1
//! General functions for use in consensus calculations
2
//!
3
//! Most functions here have signatures like [`Aggregate::aggregate`], for use with `calc!`,
4
//! for the precise types found in netstatus field(s).
5

            
6
use super::*;
7

            
8
/// Return the low median of the inputs
9
170
pub(super) fn low_median<'i, T: Ord + Clone + 'i, AC>(
10
170
    _context: ConsensusContextRefs<AC>,
11
170
    inputs: impl ComponentInVotes<&'i T>,
12
170
) -> Result<T, ConsensusError> {
13
170
    low_median_raw(inputs.votes().cloned()).ok_or(ConsensusError::NoVotes)
14
170
}
15

            
16
/// Return the low median of the inputs, without cloning, and without context
17
1856
pub(super) fn low_median_raw<'i, T: Ord + 'i>(inputs: impl Iterator<Item = T>) -> Option<T> {
18
1856
    let mut all = inputs.collect_vec();
19
1856
    all.sort();
20
1856
    let i = all.len().checked_sub(1)? / 2;
21
1855
    all.into_iter().nth(i)
22
1856
}
23

            
24
/// Return the value which is most popular, without cloning, and without context
25
///
26
/// Returns `None` iff the input iterator is empty.
27
///
28
/// See [`choose_most_popular_amongst_votes`].
29
497
pub(super) fn choose_most_popular_amongst_votes_raw<T, K>(
30
497
    inputs: impl ComponentInVotes<T>,
31
497
    ord_key: impl for<'i> Fn(&'i T) -> K,
32
497
) -> Option<T>
33
497
where
34
497
    T: Eq + Hash,
35
497
    K: Ord,
36
{
37
497
    let counts = inputs.votes().counts();
38
497
    let best = counts.values().copied().max()?;
39

            
40
497
    counts
41
497
        .into_iter()
42
499
        .filter(|(_v, count)| count == &best)
43
        .map(|(v, _count)| v)
44
        .at_most_one()
45
        .unwrap_or_else(|several| several.min_by_key(ord_key))
46
497
}
47

            
48
/// Return the value which is most popular
49
///
50
/// If there are several values which are equally most popular,
51
/// ties are broken in favour of the earliest according to `ord`.
52
/// (We avoid calling `ord` unless it is necessary.)
53
///
54
/// This is used for `v` and `pr` items in routerstatuses:
55
///  * <https://spec.torproject.org/dir-spec/computing-consensus.html>
56
///  * <https://spec.torproject.org/dir-spec/consensus-formats.html#item:pr>
57
355
pub(super) fn choose_most_popular_amongst_votes<'i, T, K, AC>(
58
355
    _context: ConsensusContextRefs<AC>,
59
355
    inputs: impl ComponentInVotes<&'i T>,
60
355
    ord_key: impl Fn(&'i T) -> K,
61
355
) -> Result<Option<T>, ConsensusError>
62
355
where
63
355
    T: Eq + Hash + Clone + 'i,
64
355
    K: Ord,
65
{
66
355
    Ok(choose_most_popular_amongst_votes_raw(inputs, |v| ord_key(v)).cloned())
67
355
}
68

            
69
/// Helper for choosing the lexically last by string representation
70
///
71
/// Pass as `ord_key` to eg [`choose_most_popular_amongst_votes`].
72
pub(super) fn ord_string_reverse_choose_lexically_latest<T: ToString>(t: &T) -> impl Ord {
73
    std::cmp::Reverse(t.to_string())
74
}
75

            
76
/// Extension trait for `ComponentInVotes<Option<_>>`
77
pub(super) trait ComponentInVotesOptionExt<'i, T: 'i> {
78
    /// Filter out the votes with opinions
79
    ///
80
    /// Convenience method equivalent to `.iter().map(|(_vnum, v)| v)`.
81
    fn with_opinions(self) -> impl Iterator<Item = (VoterNum, &'i T)> + Clone;
82
}
83
impl<'i, I, T> ComponentInVotesOptionExt<'i, T> for I
84
where
85
    I: Iterator<Item = (VoterNum, &'i Option<T>)> + Clone,
86
    T: 'i,
87
{
88
    /// Yield the votes with opinions, ie, that voted `Some`
89
284
    fn with_opinions(self) -> impl Iterator<Item = (VoterNum, &'i T)> + Clone {
90
284
        self.clone()
91
10478
            .filter_map(|(vnum, rs_v)| Some((vnum, rs_v.as_ref()?)))
92
284
    }
93
}
94

            
95
#[cfg(test)]
96
mod test {
97
    // @@ begin test lint list maintained by maint/add_warning @@
98
    #![allow(clippy::bool_assert_comparison)]
99
    #![allow(clippy::clone_on_copy)]
100
    #![allow(clippy::dbg_macro)]
101
    #![allow(clippy::mixed_attributes_style)]
102
    #![allow(clippy::print_stderr)]
103
    #![allow(clippy::print_stdout)]
104
    #![allow(clippy::single_char_pattern)]
105
    #![allow(clippy::unwrap_used)]
106
    #![allow(clippy::unchecked_time_subtraction)]
107
    #![allow(clippy::useless_vec)]
108
    #![allow(clippy::needless_pass_by_value)]
109
    #![allow(clippy::string_slice)] // See arti#2571
110
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
111
    use super::*;
112

            
113
    #[test]
114
    fn low_medians() {
115
        let check = |exp: i32, inp: &[i32]| {
116
            assert_eq!(low_median_raw(inp.iter().cloned()), Some(exp), "{inp:?}");
117
        };
118

            
119
        assert_eq!(low_median_raw::<i32>([].into_iter()), None);
120
        check(1, &[1]);
121
        check(1, &[1, 2]);
122
        check(2, &[1, 2, 3]);
123
        check(2, &[1, 2, 3, 4]);
124
        check(3, &[1, 2, 3, 4, 5]);
125
    }
126
}