devela/data/collections/destaque/
impl_traits.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// devela::data::collections::destaque::impl_traits
//
//!
//

#[cfg(feature = "alloc")]
use crate::Boxed;
use crate::{
    Array, Bare, ConstDefault, DataCollection, DataDeque, DataDesta, DataQueue, DataStack,
    Destaque, DestaqueIter, NotAvailable, NotEnoughElements, NotEnoughSpace, Ordering, Storage,
    _core::fmt,
};

// helper macro for implementing traits for a Stack depending on the custom index size.
macro_rules! impl_destaque {
    () => {
        impl_destaque![
            u8:"_destaque_u8", u16:"_destaque_u16", u32:"_destaque_u32", usize:"_destaque_usize"];
    };

    // $IDX : the index type. E.g. u8, usize
    // $cap:  the capability feature that enables the given implementation. E.g "_destaque_u8".
    ($( $IDX:ty: $cap:literal ),+) => {
        $(
            #[cfg(feature = $cap )]
            impl_destaque![@$IDX:$cap];
        )+
    };
    (@$IDX:ty : $cap:literal) => { crate::paste! {
        /* impl data traits */

        /* collection */

        #[rustfmt::skip]
        impl<T, const LEN: usize, S: Storage> DataCollection for Destaque<T, LEN, $IDX, S> {
            type Element = T;
            fn collection_capacity(&self)
                -> Result<usize, NotAvailable> { Ok(self.capacity() as usize) }
            fn collection_len(&self)
                -> Result<usize, NotAvailable> { Ok(self.len() as usize) }
            fn collection_is_empty(&self)
                -> Result<bool, NotAvailable> { Ok(self.is_empty()) }
            fn collection_is_full(&self)
                -> Result<bool, NotAvailable> { Ok(self.is_full()) }
            fn collection_contains(&self, element: Self::Element)
                -> Result<bool, NotAvailable> where T: PartialEq {
                    Ok(self.contains(&element)) }
            fn collection_count(&self, element: &Self::Element)
                -> Result<usize, NotAvailable> where T: PartialEq {
                    Ok(self.iter().filter(|&e| e == element).count()) }
        }

        /* queue, deque */

        // safe alternative with T: Clone
        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
        impl<T: Clone, const CAP: usize, S: Storage> DataQueue
            for crate::Destaque<T, CAP, $IDX, S> {
            fn queue_pop(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_front()
            }
            fn queue_push(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_back(element)
            }
        }
        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
        impl<T: Clone, const CAP: usize, S: Storage> DataDeque
            for crate::Destaque<T, CAP, $IDX, S> {
            fn queue_pop_back(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_back()
            }
            fn queue_push_front(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_front(element)
            }
        }
        // unsafe alternative without T: Clone
        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
        impl<T, const CAP: usize, S: Storage> DataQueue for crate::Destaque<T, CAP, $IDX, S> {
            fn queue_pop(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_front()
            }
            fn queue_push(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_back(element)
            }
        }
        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
        impl<T, const CAP: usize, S: Storage> DataDeque for crate::Destaque<T, CAP, $IDX, S> {
            fn queue_pop_back(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_back()
            }
            fn queue_push_front(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_front(element)
            }
        }

        /* stack, desta */

        // safe alternative with T: Clone
        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
        impl<T: Clone, const CAP: usize, S: Storage> DataStack for Destaque<T, CAP, $IDX, S> {
            fn stack_pop(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_back()
            }
            fn stack_push(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_back(element)
            }
        }
        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
        impl<T: Clone, const CAP: usize, S: Storage> DataDesta for Destaque<T, CAP, $IDX, S> {
            fn stack_pop_front(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_front()
            }
            fn stack_push_front(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_front(element)
            }
        }
        // unsafe alternative without T: Clone
        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
        impl<T, const CAP: usize, S: Storage> DataStack for Destaque<T, CAP, $IDX, S> {
            fn stack_pop(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_back()
            }
            fn stack_push(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_back(element)
            }
        }
        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
        impl<T, const CAP: usize, S: Storage> DataDesta for Destaque<T, CAP, $IDX, S> {
            fn stack_pop_front(&mut self)
                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
                self.pop_front()
            }
            fn stack_push_front(&mut self, element: <Self as DataCollection>::Element)
                -> Result<(), NotEnoughSpace> {
                self.push_front(element)
            }
        }
        /* impl From<IntoIterator<Item = T>> */

        impl<T: Default, I, const CAP: usize> From<I> for Destaque<T, CAP, $IDX, Bare>
        where
            I: IntoIterator<Item = T>,
        {
            /// Returns a queue filled with an iterator, in the stack.
            /// # Examples
            /// ```
            #[doc = "# use devela::Destaque" $IDX:camel ";"]
            #[doc = "let q: Destaque" $IDX:camel "<_, 3> = [1, 2, 3].into();"]
            /// ```
            fn from(iterator: I) -> Destaque<T, CAP, $IDX, Bare> {
                let mut q = Destaque::<T, CAP, $IDX, Bare>::default();
                let _ = q.extend_back(iterator);
                q
            }
        }

        #[cfg(feature = "alloc")]
        impl<T: Default, I, const CAP: usize> From<I> for Destaque<T, CAP, $IDX, Boxed>
        where
            I: IntoIterator<Item = T>,
        {
            /// Returns a queue filled with an iterator, in the heap.
            /// # Examples
            /// ```
            #[doc = "# use devela::{Boxed, Destaque" $IDX:camel "};"]
            #[doc = "let q: Destaque" $IDX:camel "<_, 3, Boxed> = [1, 2, 3].into();"]
            /// ```
            fn from(iterator: I) -> Destaque<T, CAP, $IDX, Boxed> {
                let mut q = Destaque::<T, CAP, $IDX, Boxed>::default();
                let _ = q.extend_back(iterator);
                q
            }
        }

        /* iterators */

        impl<'s, T, const CAP: usize, S: Storage> Iterator for DestaqueIter<'s, T, CAP, $IDX, S> {
            type Item = &'s T;
            /// Iterates over shared references.
            /// # Example
            /// ```
            #[doc = "# use devela::Destaque" $IDX:camel ";"]
            #[doc = "let mut q = Destaque" $IDX:camel "::<i32, 4>::from([1, 2]);"]
            /// q.pop_front();
            /// q.push_back(3);
            /// q.pop_front();
            /// q.push_back(4);
            ///
            /// let mut qi = q.iter();
            /// assert_eq![Some(&3), qi.next()];
            /// assert_eq![Some(&4), qi.next()];
            /// assert_eq![None, qi.next()];
            /// ```
            fn next(&mut self) -> Option<Self::Item> {
                let item = if self.idx == self.destaque.len() as usize {
                    None
                } else {
                    Some(&self.destaque.data[self.destaque.idx_front(self.idx as $IDX)])
                };
                self.idx += 1;
                item
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                (self.destaque.len() as usize, Some(self.destaque.len() as usize))
            }
        }
        impl<'s, T, const CAP: usize, S: Storage> ExactSizeIterator for DestaqueIter<'s, T, CAP, $IDX, S> {}

        impl<'s, T, const CAP: usize, S: Storage> DoubleEndedIterator for DestaqueIter<'s, T, CAP, $IDX, S> {
            /// Iterates over shared references.
            /// # Example
            /// ```
            #[doc = "# use devela::Destaque" $IDX:camel ";"]
            #[doc = "let mut q = Destaque" $IDX:camel "::<i32, 4>::from([1, 2]);"]
            /// q.pop_front();
            /// q.push_back(3);
            /// q.pop_front();
            /// q.push_back(4);
            ///
            /// let mut qi = q.iter();
            /// assert_eq![Some(&3), qi.next()];
            /// assert_eq![Some(&4), qi.next()];
            /// assert_eq![None, qi.next()];
            ///
            /// let mut qi = q.iter();
            /// assert_eq![Some(&4), qi.next_back()];
            /// assert_eq![Some(&3), qi.next_back()];
            /// assert_eq![None, qi.next_back()];
            /// ```
            fn next_back(&mut self) -> Option<Self::Item> {
                let item = if self.idx == self.destaque.len() as usize {
                    None
                } else {
                    Some(&self.destaque.data[self.destaque.idx_back(self.idx as $IDX)])
                };
                self.idx += 1;
                item
            }
        }

        /* PartialOrd, Ord */

        // T: PartialOrd
        impl<T: PartialOrd, const CAP: usize, S: Storage> PartialOrd for Destaque<T, CAP, $IDX, S>
        where
            S::Stored<[T; CAP]>: PartialOrd,
        {
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                self.iter().partial_cmp(other.iter())
            }
        }

        // T: Ord
        impl<T: Ord, const CAP: usize, S: Storage> Ord for Destaque<T, CAP, $IDX, S>
        where
            S::Stored<[T; CAP]>: Ord,
        {
            fn cmp(&self, other: &Self) -> Ordering {
                self.iter().cmp(other.iter())
            }
        }
    }};
}
impl_destaque!();

// T: Clone
impl<T: Clone, const CAP: usize, IDX: Clone, S: Storage> Clone for Destaque<T, CAP, IDX, S>
where
    S::Stored<[T; CAP]>: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            front: self.front.clone(),
            back: self.back.clone(),
            len: self.len.clone(),
        }
    }
}

// T: Copy
impl<T: Copy, const CAP: usize, IDX: Copy, S: Storage> Copy for Destaque<T, CAP, IDX, S> where
    S::Stored<[T; CAP]>: Copy
{
}

// T: Debug
impl<T: fmt::Debug, const CAP: usize, IDX: fmt::Debug, S: Storage> fmt::Debug
    for Destaque<T, CAP, IDX, S>
where
    S::Stored<[T; CAP]>: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Destaque")
            .field("CAP", &CAP)
            .field("len", &self.len)
            .field("front", &self.front)
            .field("back", &self.back)
            .field("data", &self.data)
            .finish()
    }
}

// T: PartialEq
impl<T: PartialEq, const CAP: usize, IDX: PartialEq, S: Storage> PartialEq
    for Destaque<T, CAP, IDX, S>
where
    S::Stored<[T; CAP]>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
            && self.len == other.len
            && self.front == other.front
            && self.back == other.back
    }
}
// T: Eq
impl<T: Eq, const CAP: usize, IDX: Eq, S: Storage> Eq for Destaque<T, CAP, IDX, S> where
    S::Stored<[T; CAP]>: Eq
{
}

// T: Default, S: Bare
impl<T: Default, const CAP: usize, IDX: Default> Default for Destaque<T, CAP, IDX, Bare> {
    /// Returns an empty queue, allocated in the stack,
    /// using the default value to fill the remaining free data.
    fn default() -> Self {
        Self {
            data: Array::default(),
            front: IDX::default(),
            back: IDX::default(),
            len: IDX::default(),
        }
    }
}

// T: ConstDefault, S: Bare
impl<T: ConstDefault, const CAP: usize, IDX: ConstDefault> ConstDefault
    for Destaque<T, CAP, IDX, Bare>
{
    /// Returns an empty stack, allocated in the stack,
    /// using the default value to fill the remaining free data.
    const DEFAULT: Self = Self {
        data: Array::DEFAULT,
        front: IDX::DEFAULT,
        back: IDX::DEFAULT,
        len: IDX::DEFAULT,
    };
}

// T: Default, S: Boxed
#[cfg(feature = "alloc")]
impl<T: Default, const CAP: usize, IDX: Default> Default for Destaque<T, CAP, IDX, Boxed> {
    /// Returns an empty queue, allocated in the heap,
    /// using the default value to fill the remaining free data.
    /// # Examples
    /// ```
    /// # use devela::{Boxed, DestaqueU8};
    /// let mut q = DestaqueU8::<i32, 100, Boxed>::default();
    /// ```
    fn default() -> Self {
        Self {
            data: Array::default(),
            front: IDX::default(),
            back: IDX::default(),
            len: IDX::default(),
        }
    }
}