Skip to main content

snap_coin/
bounded_set.rs

1use std::collections::{HashSet, VecDeque};
2
3pub struct BoundedSet<T> {
4    capacity: usize,
5    set: HashSet<T>,
6    order: VecDeque<T>,
7}
8
9impl<T: std::hash::Hash + Eq + Clone> BoundedSet<T> {
10    pub fn new(capacity: usize) -> Self {
11        Self {
12            capacity,
13            set: HashSet::new(),
14            order: VecDeque::new(),
15        }
16    }
17
18    pub fn insert(&mut self, value: T) {
19        if self.set.contains(&value) {
20            return;
21        }
22
23        if self.set.len() == self.capacity {
24            if let Some(old) = self.order.pop_front() {
25                self.set.remove(&old);
26            }
27        }
28
29        self.order.push_back(value.clone());
30        self.set.insert(value);
31    }
32
33    pub fn contains(&self, value: &T) -> bool {
34        self.set.contains(value)
35    }
36}