Skip to main content

trueno/brick/patterns/
bounded_queue.rs

1//! AWP-11: Bounded Message Queue
2
3use std::collections::VecDeque;
4
5/// Bounded message queue with back-pressure.
6///
7/// # Example
8/// ```rust
9/// use trueno::brick::BoundedQueue;
10///
11/// let mut queue: BoundedQueue<i32> = BoundedQueue::new(3);
12///
13/// assert!(queue.try_push(1).is_ok());
14/// assert!(queue.try_push(2).is_ok());
15/// assert!(queue.try_push(3).is_ok());
16/// assert!(queue.try_push(4).is_err()); // Queue full
17///
18/// assert_eq!(queue.pop(), Some(1));
19/// assert!(queue.try_push(4).is_ok()); // Space available
20/// ```
21#[derive(Debug)]
22pub struct BoundedQueue<T> {
23    items: VecDeque<T>,
24    capacity: usize,
25}
26
27impl<T> BoundedQueue<T> {
28    /// Create a new bounded queue.
29    pub fn new(capacity: usize) -> Self {
30        Self { items: VecDeque::with_capacity(capacity), capacity }
31    }
32
33    /// Try to push an item. Returns error if queue is full.
34    pub fn try_push(&mut self, item: T) -> Result<(), T> {
35        if self.items.len() >= self.capacity {
36            Err(item)
37        } else {
38            self.items.push_back(item);
39            Ok(())
40        }
41    }
42
43    /// Pop an item from the front.
44    pub fn pop(&mut self) -> Option<T> {
45        self.items.pop_front()
46    }
47
48    /// Peek at the front item.
49    #[must_use]
50    pub fn peek(&self) -> Option<&T> {
51        self.items.front()
52    }
53
54    /// Get the number of items in the queue.
55    #[must_use]
56    pub fn len(&self) -> usize {
57        self.items.len()
58    }
59
60    /// Check if the queue is empty.
61    #[must_use]
62    pub fn is_empty(&self) -> bool {
63        self.items.is_empty()
64    }
65
66    /// Check if the queue is full.
67    #[must_use]
68    pub fn is_full(&self) -> bool {
69        self.items.len() >= self.capacity
70    }
71
72    /// Get the capacity.
73    #[must_use]
74    pub fn capacity(&self) -> usize {
75        self.capacity
76    }
77
78    /// Get remaining capacity.
79    #[must_use]
80    pub fn remaining(&self) -> usize {
81        self.capacity.saturating_sub(self.items.len())
82    }
83
84    /// Clear all items.
85    pub fn clear(&mut self) {
86        self.items.clear();
87    }
88}
89
90impl<T> Default for BoundedQueue<T> {
91    fn default() -> Self {
92        Self::new(16)
93    }
94}