bitwarden_logging/
circular_buffer.rs1use std::{collections::VecDeque, num::NonZeroUsize, sync::Mutex};
4
5const _: () = {
9 fn _assert_send_sync<T: Send + Sync>() {}
10 fn _assert_circular_buffer<T: Send>() {
11 _assert_send_sync::<CircularBuffer<T>>();
12 }
13};
14
15pub struct CircularBuffer<T> {
20 buffer: Mutex<VecDeque<T>>,
21 capacity: usize,
22}
23
24impl<T> std::fmt::Debug for CircularBuffer<T> {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 f.debug_struct("CircularBuffer")
27 .field("capacity", &self.capacity)
28 .finish()
29 }
30}
31
32impl<T> CircularBuffer<T> {
33 pub fn new(capacity: NonZeroUsize) -> Self {
35 let capacity = capacity.get();
36 Self {
37 buffer: Mutex::new(VecDeque::with_capacity(capacity)),
38 capacity,
39 }
40 }
41
42 pub fn push(&self, item: T) -> Option<T> {
46 let mut buffer = self.buffer.lock().expect("CircularBuffer mutex poisoned");
47
48 let evicted = if buffer.len() >= self.capacity {
49 buffer.pop_front()
50 } else {
51 None
52 };
53
54 buffer.push_back(item);
55 evicted
56 }
57
58 #[inline]
60 #[must_use]
61 pub fn len(&self) -> usize {
62 self.buffer
63 .lock()
64 .expect("CircularBuffer mutex poisoned")
65 .len()
66 }
67
68 #[inline]
70 #[must_use]
71 pub fn capacity(&self) -> usize {
72 self.capacity
73 }
74
75 #[must_use]
77 pub fn take_all(&self) -> Vec<T> {
78 self.buffer
79 .lock()
80 .expect("CircularBuffer mutex poisoned")
81 .drain(..)
82 .collect()
83 }
84
85 #[inline]
87 #[must_use]
88 pub fn is_empty(&self) -> bool {
89 self.buffer
90 .lock()
91 .expect("CircularBuffer mutex poisoned")
92 .is_empty()
93 }
94}
95
96impl<T: Clone> CircularBuffer<T> {
97 #[must_use]
101 pub fn read(&self) -> Vec<T> {
102 let mut result = Vec::with_capacity(self.capacity);
103 let buffer = self.buffer.lock().expect("CircularBuffer mutex poisoned");
104 result.extend(buffer.iter().cloned());
105 result
106 }
107}
108
109#[cfg(test)]
110mod tests {
111 use std::sync::Arc;
112
113 use super::*;
114
115 #[test]
116 fn test_push_and_read() {
117 let buffer = CircularBuffer::new(NonZeroUsize::new(5).unwrap());
118 buffer.push("first".to_string());
119 buffer.push("second".to_string());
120 buffer.push("third".to_string());
121
122 let items = buffer.read();
123 assert_eq!(items, vec!["first", "second", "third"]);
124 }
125
126 #[test]
127 fn test_fifo_eviction() {
128 let buffer = CircularBuffer::new(NonZeroUsize::new(3).unwrap());
129 buffer.push("event1".to_string());
130 buffer.push("event2".to_string());
131 buffer.push("event3".to_string());
132
133 let evicted = buffer.push("event4".to_string());
135 assert_eq!(evicted, Some("event1".to_string()));
136
137 let contents = buffer.read();
138 assert_eq!(contents, vec!["event2", "event3", "event4"]);
139 }
140
141 #[test]
142 fn test_len_and_is_empty() {
143 let buffer = CircularBuffer::new(NonZeroUsize::new(10).unwrap());
144 assert!(buffer.is_empty());
145 assert_eq!(buffer.len(), 0);
146
147 buffer.push("item".to_string());
148 assert!(!buffer.is_empty());
149 assert_eq!(buffer.len(), 1);
150
151 let items = buffer.read();
152 assert_eq!(items.len(), 1);
153 }
154
155 #[test]
156 fn test_read_preserves_contents() {
157 let buffer = CircularBuffer::new(NonZeroUsize::new(5).unwrap());
158 buffer.push("a".to_string());
159 buffer.push("b".to_string());
160
161 let first_read = buffer.read();
162 let second_read = buffer.read();
163 assert_eq!(first_read, second_read);
164 }
165
166 #[test]
167 fn test_concurrent_push() {
168 let buffer = Arc::new(CircularBuffer::new(NonZeroUsize::new(1000).unwrap()));
169 let handles: Vec<_> = (0..10)
170 .map(|i| {
171 let buf = Arc::clone(&buffer);
172 std::thread::spawn(move || {
173 for j in 0..100 {
174 buf.push(format!("thread{i}-event{j}"));
175 }
176 })
177 })
178 .collect();
179
180 for h in handles {
181 h.join().expect("thread panicked");
182 }
183
184 assert_eq!(buffer.len(), 1000);
185 }
186}