Skip to main content

vector_core/i2p/
names.rs

1//! Human-readable `.i2p` names, resolved through the router's own address book and remembered
2//! for an hour. Per instance, so a new router connection starts with nothing cached.
3
4use std::collections::HashMap;
5use std::sync::Mutex;
6use std::time::Duration;
7
8use web_time::Instant;
9
10const TTL: Duration = Duration::from_secs(3600);
11const CAP: usize = 256;
12
13#[derive(Default)]
14pub struct NameCache {
15    map: Mutex<HashMap<String, (String, Instant)>>,
16}
17
18impl NameCache {
19    pub fn get(&self, name: &str) -> Option<String> {
20        let map = self.map.lock().unwrap_or_else(|e| e.into_inner());
21        map.get(name).filter(|(_, at)| at.elapsed() < TTL).map(|(v, _)| v.clone())
22    }
23
24    pub fn put(&self, name: &str, dest: String) {
25        let mut map = self.map.lock().unwrap_or_else(|e| e.into_inner());
26        if map.len() >= CAP && !map.contains_key(name) {
27            map.retain(|_, (_, at)| at.elapsed() < TTL);
28            if map.len() >= CAP {
29                if let Some(oldest) = map.iter().min_by_key(|(_, (_, at))| *at).map(|(k, _)| k.clone()) {
30                    map.remove(&oldest);
31                }
32            }
33        }
34        map.insert(name.to_string(), (dest, Instant::now()));
35    }
36
37    /// A cached destination the router no longer accepts.
38    pub fn forget(&self, name: &str) {
39        self.map.lock().unwrap_or_else(|e| e.into_inner()).remove(name);
40    }
41
42    #[cfg(test)]
43    pub(crate) fn age_for_test(&self, by: Duration) {
44        for (_, at) in self.map.lock().unwrap_or_else(|e| e.into_inner()).values_mut() {
45            *at = at.checked_sub(by).unwrap_or(*at);
46        }
47    }
48}