Skip to main content

tree_table/types/
bounded_deque.rs

1use alloc::collections::VecDeque;
2
3#[derive(Debug, Clone)]
4pub struct BoundedDeque<T> {
5    deque: VecDeque<T>,
6    maxlen: usize,
7}
8
9impl<T> BoundedDeque<T> {
10    /// Creates a new bounded deque with the given maximum length.
11    pub fn new(maxlen: usize) -> Self {
12        BoundedDeque {
13            deque: VecDeque::new(),
14            maxlen,
15        }
16    }
17
18    /// Returns the current number of items in the deque.
19    pub fn len(&self) -> usize {
20        self.deque.len()
21    }
22
23    /// Sets a new maximum length for the deque.
24    /// If the new maxlen is smaller than the current length,
25    /// elements are removed from the start until the length is within the new limit.
26    pub fn set_maxlen(&mut self, new_maxlen: usize) {
27        self.maxlen = new_maxlen;
28        while self.deque.len() > self.maxlen {
29            self.deque.pop_front();
30        }
31    }
32
33    /// Returns the current maximum length of the deque.
34    pub fn get_maxlen(&self) -> usize {
35        self.maxlen
36    }
37
38    /// Adds an item to the end. If the deque is at capacity, removes from the start first.
39    pub fn push_back(&mut self, item: T) {
40        if self.deque.len() == self.maxlen {
41            self.deque.pop_front();
42        }
43        self.deque.push_back(item);
44    }
45
46    /// Adds an item to the start. If the deque is at capacity, removes from the end first.
47    pub fn push_front(&mut self, item: T) {
48        if self.deque.len() == self.maxlen {
49            self.deque.pop_back();
50        }
51        self.deque.push_front(item);
52    }
53
54    /// Removes and returns the start item, if any.
55    pub fn pop_front(&mut self) -> Option<T> {
56        self.deque.pop_front()
57    }
58
59    /// Removes and returns the end item, if any.
60    pub fn pop_back(&mut self) -> Option<T> {
61        self.deque.pop_back()
62    }
63
64    /// Returns a reference to the start item, if any.
65    pub fn front(&self) -> Option<&T> {
66        self.deque.front()
67    }
68
69    /// Returns a reference to the end item, if any.
70    pub fn back(&self) -> Option<&T> {
71        self.deque.back()
72    }
73
74    /// Checks if the deque is empty.
75    pub fn is_empty(&self) -> bool {
76        self.deque.is_empty()
77    }
78
79    /// Clears the deque.
80    pub fn clear(&mut self) {
81        self.deque.clear();
82    }
83
84    /// Returns a reference to the last (most recently added) item, if any.
85    pub fn last(&self) -> Option<&T> {
86        self.deque.back()
87    }
88
89    /// Returns a mutable reference to the last (most recently added) item, if any.
90    pub fn last_mut(&mut self) -> Option<&mut T> {
91        self.deque.back_mut()
92    }
93}