use std::collections::VecDeque;
use std::sync::Mutex;
pub(crate) struct RecentRingBuffer {
buffer: Mutex<VecDeque<String>>,
capacity: usize,
}
impl RecentRingBuffer {
pub fn new(capacity: usize) -> Self {
Self {
buffer: Mutex::new(VecDeque::with_capacity(capacity)),
capacity,
}
}
pub fn push(&self, value: String) {
let mut q = self.buffer.lock().unwrap_or_else(|p| p.into_inner());
if q.len() >= self.capacity {
q.pop_front();
}
q.push_back(value);
}
pub fn push_dedup(&self, value: &str) {
let mut q = self.buffer.lock().unwrap_or_else(|p| p.into_inner());
q.retain(|existing| existing != value);
if q.len() >= self.capacity {
q.pop_front();
}
q.push_back(value.to_owned());
}
pub fn snapshot(&self) -> Vec<String> {
self.buffer
.lock()
.unwrap_or_else(|p| p.into_inner())
.iter()
.cloned()
.collect()
}
}