1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use crate::{supermajority, ELDER_SIZE};
use lru_time_cache::{Entry, LruCache};
use std::{collections::BTreeSet, iter, time::Duration};
use xor_name::XorName;
const COMPLAINT_EXPIRY_DURATION: Duration = Duration::from_secs(60);
pub(crate) struct ConnectivityComplaints {
    complaints: LruCache<XorName, (BTreeSet<XorName>, bool)>,
}
impl ConnectivityComplaints {
    pub fn new() -> Self {
        Self {
            complaints: LruCache::with_expiry_duration_and_capacity(
                COMPLAINT_EXPIRY_DURATION,
                ELDER_SIZE,
            ),
        }
    }
    
    pub fn add_complaint(&mut self, adult_name: XorName, elder_name: XorName) {
        match self.complaints.entry(elder_name) {
            Entry::Vacant(entry) => {
                let _ = entry.insert((iter::once(adult_name).collect(), false));
            }
            Entry::Occupied(entry) => {
                let _ = entry.into_mut().0.insert(adult_name);
            }
        }
    }
    
    pub fn is_complained(
        &mut self,
        elder_name: XorName,
        weighing_adults: &BTreeSet<XorName>,
    ) -> bool {
        let threshold = supermajority(weighing_adults.len());
        match self.complaints.entry(elder_name) {
            Entry::Vacant(_) => false,
            Entry::Occupied(entry) => {
                let mut records = entry.into_mut();
                if records.1 {
                    
                    false
                } else {
                    let complained_adults = records
                        .0
                        .iter()
                        .filter(|name| weighing_adults.contains(name))
                        .count();
                    if complained_adults >= threshold {
                        records.1 = true;
                        true
                    } else {
                        false
                    }
                }
            }
        }
    }
}
impl Default for ConnectivityComplaints {
    fn default() -> Self {
        Self::new()
    }
}