melvin_ob/scheduling/
linked_box.rs

1use std::collections::VecDeque;
2
3/// A fixed-size linked list data structure.
4/// This structure uses a `VecDeque` internally and maintains a maximum size.
5/// When the maximum size is exceeded, the oldest element (at the back) is removed.
6pub struct LinkedBox<T> {
7    /// `VecDeque` holding the actual data
8    list: VecDeque<T>,
9    /// `max_size` represents the maximum length of the queue
10    size: usize,
11}
12
13impl<T> LinkedBox<T> {
14    /// Creates a new `LinkedBox` with the specified maximum size.
15    ///
16    /// # Arguments
17    ///
18    /// * `max_size` - The maximum number of elements that the linked list can hold.
19    ///
20    /// # Returns
21    /// A new, empty `LinkedBox` instance.
22    pub fn new(size: usize) -> Self { Self { list: VecDeque::new(), size } }
23
24    /// Pushes an element to the front of the list.
25    ///
26    /// If the size limit is exceeded, the element at the back of the list is removed.
27    ///
28    /// # Arguments
29    /// * `item` - The element to be added to the front of the list.
30    pub fn push(&mut self, item: T) {
31        self.list.push_front(item);
32        if self.len() > self.size {
33            self.list.pop_back();
34        }
35    }
36
37    /// Returns a reference to the first element in the list, if present.
38    ///
39    /// # Returns
40    /// An `Option` containing a reference to the first element, or `None` if the list is empty.
41    pub fn front(&self) -> Option<&T> { self.list.front() }
42
43    /// Returns a reference to the last element in the list, if present.
44    ///
45    /// # Returns
46    /// An `Option` containing a reference to the last element, or `None` if the list is empty.
47    pub fn back(&self) -> Option<&T> { self.list.back() }
48
49    /// Returns the current number of elements in the list.
50    ///
51    /// # Returns
52    /// The number of elements in the list as a `usize`.
53    pub fn len(&self) -> usize { self.list.len() }
54
55    /// Returns the maximum number of elements in the list.
56    ///
57    /// # Returns
58    /// The capacity of the list as a `usize`.
59    pub fn size(&self) -> usize { self.size }
60
61    /// Checks if the list is empty.
62    ///
63    /// # Returns
64    /// A boolean value, `true` if the list is empty, `false` otherwise.
65    pub fn is_empty(&self) -> bool { self.list.is_empty() }
66}