orx_meta/queue/
single.rs

1use crate::queue::{Queue, StQueue};
2
3/// A statically-typed queue containing exactly one element of type `Front`.
4///
5/// See also the other [`StQueue`] implementation [`Queue`] which can be
6/// created by pushing a second element to this queue.
7#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8pub struct QueueSingle<Front> {
9    pub(super) front: Front,
10}
11
12impl<F> StQueue for QueueSingle<F> {
13    type PushBack<Elem> = Queue<F, QueueSingle<Elem>>;
14
15    type Front = F;
16
17    type Back = Self;
18
19    const LEN: usize = 1;
20
21    #[inline(always)]
22    fn push<Elem>(self, element: Elem) -> Self::PushBack<Elem> {
23        Queue::from_fb(self.front, QueueSingle::new(element))
24    }
25
26    #[inline(always)]
27    fn front(&self) -> &Self::Front {
28        &self.front
29    }
30
31    #[inline(always)]
32    fn front_mut(&mut self) -> &mut Self::Front {
33        &mut self.front
34    }
35
36    #[inline(always)]
37    fn into_front(self) -> Self::Front {
38        self.front
39    }
40}
41
42impl<F> QueueSingle<F> {
43    /// Creates a new statically-typed queue [`StQueue`] containing exactly one `element`.
44    ///
45    /// Alternatively, we can use multiple element queue's [`new`]. This is for convenience to
46    /// allows to work with a single queue type while coding.
47    ///
48    /// [`new`]: crate::queue::Queue::new
49    ///
50    /// # Examples
51    ///
52    /// ```
53    /// use orx_meta::queue::*;
54    ///
55    /// let queue: QueueSingle<u32> = QueueSingle::new(42);
56    /// assert_eq!(queue.len(), 1);
57    /// assert_eq!(queue.front(), &42);
58    ///
59    /// // alternatively, we can use `Queue::new`:
60    /// let queue: QueueSingle<u32> = Queue::new(42);
61    /// assert_eq!(queue.len(), 1);
62    /// assert_eq!(queue.front(), &42);
63    /// ```
64    #[inline(always)]
65    pub fn new(element: F) -> Self {
66        Self { front: element }
67    }
68
69    /// Pops and returns the element in the front of this queue.
70    ///
71    /// Since this element contains only one element, there is no remaining queue once the
72    /// front is popped. Therefore, the return type is only the element rather than a tuple.
73    ///
74    /// # Examples
75    ///
76    /// ```
77    /// use orx_meta::queue::*;
78    ///
79    /// let queue: QueueSingle<u32> = QueueSingle::new(42);
80    ///
81    /// let num = queue.pop();
82    /// assert_eq!(num, 42);
83    /// ```
84    #[inline(always)]
85    pub fn pop(self) -> F {
86        self.front
87    }
88}