rlibdht/utils/
linked_hashmap.rs1use std::collections::{HashMap, VecDeque};
2use std::hash::Hash;
3
4#[derive(Debug, Clone, PartialEq)]
5pub struct LinkedHashMap<K: Eq + Hash, V> {
6 map: HashMap<K, V>,
7 order: VecDeque<K>,
8 capacity: usize
9}
10
11impl<K, V> LinkedHashMap<K, V> where K: Eq + Hash + Clone, V: Clone {
12
13 pub fn new() -> Self {
14 Self {
15 map: HashMap::new(),
16 order: VecDeque::new(),
17 capacity: 0
18 }
19 }
20
21 pub fn with_capacity(capacity: usize) -> Self {
22 Self {
23 map: HashMap::with_capacity(capacity),
24 order: VecDeque::with_capacity(capacity),
25 capacity
26 }
27 }
28
29 pub fn insert(&mut self, key: K, value: V) {
30 if self.map.len() >= self.capacity {
31 if let Some(eldest) = self.order.pop_front() {
32 self.map.remove(&eldest);
33 }
34 }
35 self.order.push_back(key.clone());
36 self.map.insert(key, value);
37 }
38
39 pub fn get(&self, key: &K) -> Option<&V> {
40 self.map.get(key)
41 }
42
43 pub fn values(&self) -> Vec<V> {
44 self.order
45 .iter()
46 .filter_map(|key| self.map.get(key).cloned())
47 .collect()
48 }
49
50 pub fn len(&self) -> usize {
51 self.map.len()
52 }
53
54 pub fn is_empty(&self) -> bool {
55 self.map.is_empty()
56 }
57}