cyfs_bdt/sn/client/
cache.rs

1use std::{
2    sync::{RwLock}, 
3    collections::{BTreeSet, BTreeMap}
4};
5use cyfs_base::*;
6use crate::{
7    types::*, 
8    dht::*
9};
10
11pub struct SnCache {
12    known_list: RwLock<BTreeSet<DeviceId>>, 
13    active_endpoints: RwLock<BTreeMap<DeviceId, EndpointPair>> 
14}
15
16impl SnCache {
17    pub fn new() -> Self {
18        Self {
19            known_list: RwLock::new(BTreeSet::new()),
20            active_endpoints: RwLock::new(BTreeMap::new())
21        }
22    }
23
24    pub fn add_known_sn(&self, sn_list: &Vec<DeviceId>) {
25        let mut known_list = self.known_list.write().unwrap();
26        for sn in sn_list {
27            known_list.insert(sn.clone());
28        }
29    }
30
31    pub fn reset_known_sn(&self, sn_list: &Vec<DeviceId>) {
32        let mut known_list = self.known_list.write().unwrap();
33        known_list.clear();
34        for sn in sn_list {
35            known_list.insert(sn.clone());
36        }
37    }
38
39    pub fn nearest_sn_of(remote: &DeviceId, sn_list: &[DeviceId]) -> Option<DeviceId> {
40        sn_list.iter().min_by(|l, r| l.object_id().distance(remote.object_id()).cmp(&r.object_id().distance(remote.object_id()))).cloned()
41    }
42
43    pub fn known_list(&self) -> Vec<DeviceId> {
44        self.known_list.read().unwrap().iter().cloned().collect()
45    }
46
47    pub fn add_active(&self, sn: &DeviceId, active: EndpointPair) {
48        self.active_endpoints.write().unwrap().insert(sn.clone(), active);
49    }
50
51    pub fn get_active(&self, sn: &DeviceId) -> Option<EndpointPair> {
52        self.active_endpoints.read().unwrap().get(sn).cloned()
53    }
54
55    pub fn remove_active(&self, sn: &DeviceId) {
56        self.active_endpoints.write().unwrap().remove(sn);
57    }
58}