• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Open-S2 / gis-tools / #90

29 Jul 2025 06:33PM UTC coverage: 91.122% (+0.2%) from 90.968%
#90

push

Mr Martian
fix a doc error and downgrade bun for tests

90306 of 99105 relevant lines covered (91.12%)

244424.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.73
/rust/data_structures/cache.rs
1
use alloc::{collections::BTreeMap, vec::Vec};
2

3
/// Function to be called when a value is deleted from the cache
4
pub type CacheDeleteFunction<K, V> = fn(&K, &V);
5

6
/// # Cache System
7
///
8
/// ## Description
9
/// A cache of values with a max size to ensure that too much old data is not stored.
10
///
11
/// Uses the [`CacheDeleteFunction`] type
12
///
13
/// ## Usage
14
///
15
/// ```rust
16
/// extern crate alloc;
17
/// use gistools::data_structures::Cache;
18
/// use alloc::borrow::ToOwned;
19
/// use alloc::string::{String, ToString};
20
///
21
/// fn on_delete(key: &String, value: &String) {
22
///     println!("Deleted key {} with value {}", key, value);
23
/// }
24
///
25
/// let mut cache = Cache::new(10, Some(on_delete));
26
/// cache.set("key".to_owned(), "value".to_owned());
27
/// println!("{:?}", cache.get(&"key".to_string())); // Some("value")
28
/// cache.delete(&"key".to_string());
29
/// ```
30
#[derive(Debug, Clone, Default)]
31
pub struct Cache<K, V>
32
where
33
    K: Ord + Clone,
34
{
35
    map: BTreeMap<K, V>,
36
    order: Vec<K>,
37
    max_size: usize,
38
    on_delete: Option<CacheDeleteFunction<K, V>>,
39
}
40

41
impl<K, V> Cache<K, V>
42
where
43
    K: Ord + Clone,
44
{
45
    /// Creates a new cache with a given max size and an optional deletion callback.
46
    pub fn new(max_size: usize, on_delete: Option<CacheDeleteFunction<K, V>>) -> Self {
7✔
47
        Self { map: BTreeMap::new(), order: Vec::new(), max_size, on_delete }
7✔
48
    }
7✔
49

50
    /// Returns the number of elements in the cache.
51
    pub fn len(&self) -> usize {
1✔
52
        self.map.len()
1✔
53
    }
1✔
54

55
    /// Returns true if the cache is empty.
56
    pub fn is_empty(&self) -> bool {
2✔
57
        self.map.is_empty()
2✔
58
    }
2✔
59

60
    /// Inserts a key-value pair into the cache.
61
    pub fn set(&mut self, key: K, value: V) {
11✔
62
        if self.map.contains_key(&key) {
11✔
63
            self.order.retain(|k| k != &key);
5✔
64
        }
10✔
65
        self.order.insert(0, key.clone());
11✔
66
        self.map.insert(key, value);
11✔
67

68
        while self.order.len() > self.max_size {
13✔
69
            if let Some(oldest) = self.order.pop() {
2✔
70
                self.delete(&oldest);
2✔
71
            }
2✔
72
        }
73
    }
11✔
74

75
    /// Retrieves a value from the cache.
76
    pub fn get(&mut self, key: &K) -> Option<&V> {
6✔
77
        if self.map.contains_key(key) {
6✔
78
            self.order.retain(|k| k != key);
8✔
79
            self.order.insert(0, key.clone());
4✔
80
        }
2✔
81
        self.map.get(key)
6✔
82
    }
6✔
83

84
    /// Retrieves a mutable value from the cache.
85
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
1✔
86
        if self.map.contains_key(key) {
1✔
87
            self.order.retain(|k| k != key);
1✔
88
            self.order.insert(0, key.clone());
1✔
89
        }
×
90
        self.map.get_mut(key)
1✔
91
    }
1✔
92

93
    /// Removes a key from the cache.
94
    pub fn delete(&mut self, key: &K) -> bool {
5✔
95
        if let Some(value) = self.map.remove(key) {
5✔
96
            self.order.retain(|k| k != key);
12✔
97
            if let Some(ref callback) = self.on_delete {
4✔
98
                callback(key, &value);
4✔
99
            }
4✔
100
            return true;
4✔
101
        }
1✔
102
        false
1✔
103
    }
5✔
104
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc