1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
impl<T> RingBuffer<T> {
/// Creates a new ring buffer with the specified capacity.
///
/// The ring buffer maintains a fixed-size circular buffer that automatically
/// evicts the oldest items when capacity is exceeded, following FIFO semantics.
///
/// # Performance
///
/// - Time: O(1) for initialization
/// - Space: O(capacity) for initial allocation
/// - Push: O(1) amortized
///
/// # Examples
///
/// ```no_run
/// use pmat::services::refactor_engine::RingBuffer;
///
/// let buffer: RingBuffer<i32> = RingBuffer::new(3);
///
/// assert_eq!(buffer.len(), 0);
/// assert!(buffer.is_empty());
/// ```
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
buffer: VecDeque::with_capacity(capacity),
capacity,
}
}
/// Pushes an item to the back of the ring buffer.
///
/// If the buffer is at capacity, the oldest item (front) is automatically
/// removed to make space for the new item.
///
/// # Examples
///
/// ```no_run
/// use pmat::services::refactor_engine::RingBuffer;
///
/// let mut buffer = RingBuffer::new(2);
///
/// buffer.push(1);
/// buffer.push(2);
/// assert_eq!(buffer.len(), 2);
///
/// // Adding third item evicts the first
/// buffer.push(3);
/// assert_eq!(buffer.len(), 2);
///
/// let items = buffer.drain();
/// assert_eq!(items, vec![2, 3]); // First item (1) was evicted
/// ```
pub fn push(&mut self, item: T) {
if self.buffer.len() >= self.capacity {
self.buffer.pop_front();
}
self.buffer.push_back(item);
}
/// Drains all items from the buffer and returns them as a vector.
///
/// After this operation, the buffer will be empty. Items are returned
/// in the order they were added (oldest first).
///
/// # Examples
///
/// ```no_run
/// use pmat::services::refactor_engine::RingBuffer;
///
/// let mut buffer = RingBuffer::new(5);
/// buffer.push("first");
/// buffer.push("second");
/// buffer.push("third");
///
/// let items = buffer.drain();
/// assert_eq!(items, vec!["first", "second", "third"]);
/// assert!(buffer.is_empty());
/// ```
pub fn drain(&mut self) -> Vec<T> {
self.buffer.drain(..).collect()
}
#[must_use]
pub fn len(&self) -> usize {
self.buffer.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.buffer.is_empty()
}
}