devela/data/list/queue/destaque/
impl_traits.rs

1// devela::data::list::queue::destaque::impl_traits
2//
3//!
4//
5
6#[cfg(feature = "alloc")]
7use crate::Boxed;
8use crate::{
9    Array, Bare, ConstDefault, DataCollection, DataDeque, DataDesta, DataQueue, DataStack,
10    Destaque, DestaqueIter, NotAvailable, NotEnoughElements, NotEnoughSpace, Ordering, Storage,
11    _core::fmt,
12};
13
14// helper macro for implementing traits for a Stack depending on the custom index size.
15macro_rules! impl_destaque {
16    () => {
17        impl_destaque![
18            u8:"_destaque_u8", u16:"_destaque_u16", u32:"_destaque_u32", usize:"_destaque_usize"];
19    };
20
21    // $IDX : the index type. E.g. u8, usize
22    // $cap:  the capability feature that enables the given implementation. E.g "_destaque_u8".
23    ($( $IDX:ty: $cap:literal ),+) => {
24        $(
25            #[cfg(feature = $cap )]
26            impl_destaque![@$IDX:$cap];
27        )+
28    };
29    (@$IDX:ty : $cap:literal) => { $crate::paste! {
30        /* impl data traits */
31
32        /* collection */
33
34        #[rustfmt::skip]
35        impl<T, const LEN: usize, S: Storage> DataCollection for Destaque<T, LEN, $IDX, S> {
36            type Element = T;
37            fn collection_capacity(&self)
38                -> Result<usize, NotAvailable> { Ok(self.capacity() as usize) }
39            fn collection_len(&self)
40                -> Result<usize, NotAvailable> { Ok(self.len() as usize) }
41            fn collection_is_empty(&self)
42                -> Result<bool, NotAvailable> { Ok(self.is_empty()) }
43            fn collection_is_full(&self)
44                -> Result<bool, NotAvailable> { Ok(self.is_full()) }
45            fn collection_contains(&self, element: Self::Element)
46                -> Result<bool, NotAvailable> where T: PartialEq {
47                    Ok(self.contains(&element)) }
48            fn collection_count(&self, element: &Self::Element)
49                -> Result<usize, NotAvailable> where T: PartialEq {
50                    Ok(self.iter().filter(|&e| e == element).count()) }
51        }
52
53        /* queue, deque */
54
55        // safe alternative with T: Clone
56        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
57        impl<T: Clone, const CAP: usize, S: Storage> DataQueue
58            for crate::Destaque<T, CAP, $IDX, S> {
59            fn queue_pop(&mut self)
60                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
61                self.pop_front()
62            }
63            fn queue_push(&mut self, element: <Self as DataCollection>::Element)
64                -> Result<(), NotEnoughSpace> {
65                self.push_back(element)
66            }
67        }
68        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
69        impl<T: Clone, const CAP: usize, S: Storage> DataDeque
70            for crate::Destaque<T, CAP, $IDX, S> {
71            fn queue_pop_back(&mut self)
72                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
73                self.pop_back()
74            }
75            fn queue_push_front(&mut self, element: <Self as DataCollection>::Element)
76                -> Result<(), NotEnoughSpace> {
77                self.push_front(element)
78            }
79        }
80        // unsafe alternative without T: Clone
81        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
82        impl<T, const CAP: usize, S: Storage> DataQueue for crate::Destaque<T, CAP, $IDX, S> {
83            fn queue_pop(&mut self)
84                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
85                self.pop_front()
86            }
87            fn queue_push(&mut self, element: <Self as DataCollection>::Element)
88                -> Result<(), NotEnoughSpace> {
89                self.push_back(element)
90            }
91        }
92        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
93        impl<T, const CAP: usize, S: Storage> DataDeque for crate::Destaque<T, CAP, $IDX, S> {
94            fn queue_pop_back(&mut self)
95                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
96                self.pop_back()
97            }
98            fn queue_push_front(&mut self, element: <Self as DataCollection>::Element)
99                -> Result<(), NotEnoughSpace> {
100                self.push_front(element)
101            }
102        }
103
104        /* stack, desta */
105
106        // safe alternative with T: Clone
107        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
108        impl<T: Clone, const CAP: usize, S: Storage> DataStack for Destaque<T, CAP, $IDX, S> {
109            fn stack_pop(&mut self)
110                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
111                self.pop_back()
112            }
113            fn stack_push(&mut self, element: <Self as DataCollection>::Element)
114                -> Result<(), NotEnoughSpace> {
115                self.push_back(element)
116            }
117        }
118        #[cfg(any(feature = "safe_data", not(feature = "unsafe_ptr")))]
119        impl<T: Clone, const CAP: usize, S: Storage> DataDesta for Destaque<T, CAP, $IDX, S> {
120            fn stack_pop_front(&mut self)
121                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
122                self.pop_front()
123            }
124            fn stack_push_front(&mut self, element: <Self as DataCollection>::Element)
125                -> Result<(), NotEnoughSpace> {
126                self.push_front(element)
127            }
128        }
129        // unsafe alternative without T: Clone
130        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
131        impl<T, const CAP: usize, S: Storage> DataStack for Destaque<T, CAP, $IDX, S> {
132            fn stack_pop(&mut self)
133                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
134                self.pop_back()
135            }
136            fn stack_push(&mut self, element: <Self as DataCollection>::Element)
137                -> Result<(), NotEnoughSpace> {
138                self.push_back(element)
139            }
140        }
141        #[cfg(all(not(feature = "safe_data"), feature = "unsafe_ptr"))]
142        impl<T, const CAP: usize, S: Storage> DataDesta for Destaque<T, CAP, $IDX, S> {
143            fn stack_pop_front(&mut self)
144                -> Result<<Self as DataCollection>::Element, NotEnoughElements> {
145                self.pop_front()
146            }
147            fn stack_push_front(&mut self, element: <Self as DataCollection>::Element)
148                -> Result<(), NotEnoughSpace> {
149                self.push_front(element)
150            }
151        }
152        /* impl From<IntoIterator<Item = T>> */
153
154        impl<T: Default, I, const CAP: usize> From<I> for Destaque<T, CAP, $IDX, Bare>
155        where
156            I: IntoIterator<Item = T>,
157        {
158            /// Returns a queue filled with an iterator, in the stack.
159            /// # Examples
160            /// ```
161            #[doc = "# use devela::Destaque" $IDX:camel ";"]
162            #[doc = "let q: Destaque" $IDX:camel "<_, 3> = [1, 2, 3].into();"]
163            /// ```
164            fn from(iterator: I) -> Destaque<T, CAP, $IDX, Bare> {
165                let mut q = Destaque::<T, CAP, $IDX, Bare>::default();
166                let _ = q.extend_back(iterator);
167                q
168            }
169        }
170
171        #[cfg(feature = "alloc")]
172        impl<T: Default, I, const CAP: usize> From<I> for Destaque<T, CAP, $IDX, Boxed>
173        where
174            I: IntoIterator<Item = T>,
175        {
176            /// Returns a queue filled with an iterator, in the heap.
177            /// # Examples
178            /// ```
179            #[doc = "# use devela::{Boxed, Destaque" $IDX:camel "};"]
180            #[doc = "let q: Destaque" $IDX:camel "<_, 3, Boxed> = [1, 2, 3].into();"]
181            /// ```
182            fn from(iterator: I) -> Destaque<T, CAP, $IDX, Boxed> {
183                let mut q = Destaque::<T, CAP, $IDX, Boxed>::default();
184                let _ = q.extend_back(iterator);
185                q
186            }
187        }
188
189        /* iterators */
190
191        impl<'s, T, const CAP: usize, S: Storage> Iterator for DestaqueIter<'s, T, CAP, $IDX, S> {
192            type Item = &'s T;
193            /// Iterates over shared references.
194            /// # Example
195            /// ```
196            #[doc = "# use devela::Destaque" $IDX:camel ";"]
197            #[doc = "let mut q = Destaque" $IDX:camel "::<i32, 4>::from([1, 2]);"]
198            /// q.pop_front();
199            /// q.push_back(3);
200            /// q.pop_front();
201            /// q.push_back(4);
202            ///
203            /// let mut qi = q.iter();
204            /// assert_eq![Some(&3), qi.next()];
205            /// assert_eq![Some(&4), qi.next()];
206            /// assert_eq![None, qi.next()];
207            /// ```
208            fn next(&mut self) -> Option<Self::Item> {
209                let item = if self.idx == self.destaque.len() as usize {
210                    None
211                } else {
212                    Some(&self.destaque.data[self.destaque.idx_front(self.idx as $IDX)])
213                };
214                self.idx += 1;
215                item
216            }
217
218            fn size_hint(&self) -> (usize, Option<usize>) {
219                (self.destaque.len() as usize, Some(self.destaque.len() as usize))
220            }
221        }
222        impl<'s, T, const CAP: usize, S: Storage> ExactSizeIterator for DestaqueIter<'s, T, CAP, $IDX, S> {}
223
224        impl<'s, T, const CAP: usize, S: Storage> DoubleEndedIterator for DestaqueIter<'s, T, CAP, $IDX, S> {
225            /// Iterates over shared references.
226            /// # Example
227            /// ```
228            #[doc = "# use devela::Destaque" $IDX:camel ";"]
229            #[doc = "let mut q = Destaque" $IDX:camel "::<i32, 4>::from([1, 2]);"]
230            /// q.pop_front();
231            /// q.push_back(3);
232            /// q.pop_front();
233            /// q.push_back(4);
234            ///
235            /// let mut qi = q.iter();
236            /// assert_eq![Some(&3), qi.next()];
237            /// assert_eq![Some(&4), qi.next()];
238            /// assert_eq![None, qi.next()];
239            ///
240            /// let mut qi = q.iter();
241            /// assert_eq![Some(&4), qi.next_back()];
242            /// assert_eq![Some(&3), qi.next_back()];
243            /// assert_eq![None, qi.next_back()];
244            /// ```
245            fn next_back(&mut self) -> Option<Self::Item> {
246                let item = if self.idx == self.destaque.len() as usize {
247                    None
248                } else {
249                    Some(&self.destaque.data[self.destaque.idx_back(self.idx as $IDX)])
250                };
251                self.idx += 1;
252                item
253            }
254        }
255
256        /* PartialOrd, Ord */
257
258        // T: PartialOrd
259        impl<T: PartialOrd, const CAP: usize, S: Storage> PartialOrd for Destaque<T, CAP, $IDX, S>
260        where
261            S::Stored<[T; CAP]>: PartialOrd,
262        {
263            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
264                self.iter().partial_cmp(other.iter())
265            }
266        }
267
268        // T: Ord
269        impl<T: Ord, const CAP: usize, S: Storage> Ord for Destaque<T, CAP, $IDX, S>
270        where
271            S::Stored<[T; CAP]>: Ord,
272        {
273            fn cmp(&self, other: &Self) -> Ordering {
274                self.iter().cmp(other.iter())
275            }
276        }
277    }};
278}
279impl_destaque!();
280
281// T: Clone
282impl<T: Clone, const CAP: usize, IDX: Clone, S: Storage> Clone for Destaque<T, CAP, IDX, S>
283where
284    S::Stored<[T; CAP]>: Clone,
285{
286    fn clone(&self) -> Self {
287        Self {
288            data: self.data.clone(),
289            front: self.front.clone(),
290            back: self.back.clone(),
291            len: self.len.clone(),
292        }
293    }
294}
295
296// T: Copy
297impl<T: Copy, const CAP: usize, IDX: Copy, S: Storage> Copy for Destaque<T, CAP, IDX, S> where
298    S::Stored<[T; CAP]>: Copy
299{
300}
301
302// T: Debug
303impl<T: fmt::Debug, const CAP: usize, IDX: fmt::Debug, S: Storage> fmt::Debug
304    for Destaque<T, CAP, IDX, S>
305where
306    S::Stored<[T; CAP]>: fmt::Debug,
307{
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        f.debug_struct("Destaque")
310            .field("CAP", &CAP)
311            .field("len", &self.len)
312            .field("front", &self.front)
313            .field("back", &self.back)
314            .field("data", &self.data)
315            .finish()
316    }
317}
318
319// T: PartialEq
320impl<T: PartialEq, const CAP: usize, IDX: PartialEq, S: Storage> PartialEq
321    for Destaque<T, CAP, IDX, S>
322where
323    S::Stored<[T; CAP]>: PartialEq,
324{
325    fn eq(&self, other: &Self) -> bool {
326        self.data == other.data
327            && self.len == other.len
328            && self.front == other.front
329            && self.back == other.back
330    }
331}
332// T: Eq
333impl<T: Eq, const CAP: usize, IDX: Eq, S: Storage> Eq for Destaque<T, CAP, IDX, S> where
334    S::Stored<[T; CAP]>: Eq
335{
336}
337
338// T: Default, S: Bare
339impl<T: Default, const CAP: usize, IDX: Default> Default for Destaque<T, CAP, IDX, Bare> {
340    /// Returns an empty queue, allocated in the stack,
341    /// using the default value to fill the remaining free data.
342    fn default() -> Self {
343        Self {
344            data: Array::default(),
345            front: IDX::default(),
346            back: IDX::default(),
347            len: IDX::default(),
348        }
349    }
350}
351
352// T: ConstDefault, S: Bare
353impl<T: ConstDefault, const CAP: usize, IDX: ConstDefault> ConstDefault
354    for Destaque<T, CAP, IDX, Bare>
355{
356    /// Returns an empty stack, allocated in the stack,
357    /// using the default value to fill the remaining free data.
358    const DEFAULT: Self = Self {
359        data: Array::DEFAULT,
360        front: IDX::DEFAULT,
361        back: IDX::DEFAULT,
362        len: IDX::DEFAULT,
363    };
364}
365
366// T: Default, S: Boxed
367#[cfg(feature = "alloc")]
368impl<T: Default, const CAP: usize, IDX: Default> Default for Destaque<T, CAP, IDX, Boxed> {
369    /// Returns an empty queue, allocated in the heap,
370    /// using the default value to fill the remaining free data.
371    /// # Examples
372    /// ```
373    /// # use devela::{Boxed, DestaqueU8};
374    /// let mut q = DestaqueU8::<i32, 100, Boxed>::default();
375    /// ```
376    fn default() -> Self {
377        Self {
378            data: Array::default(),
379            front: IDX::default(),
380            back: IDX::default(),
381            len: IDX::default(),
382        }
383    }
384}