1
//! Miscellaneous utilities
2

            
3
use crate::internal_prelude::*;
4

            
5
pub mod bool_indexed_array;
6
pub(crate) use bool_indexed_array::*;
7

            
8
/// What `RangeInclusive::map` ought to be
9
///
10
/// Open-coding this at the call site would risk accidental change of the range type,
11
/// changing inclusiveness, etc.  This function has the same range type as argument and return.
12
18
pub(crate) fn map_range<T, U>(
13
18
    r: &RangeInclusive<T>,
14
18
    mut f: impl FnMut(&T) -> U,
15
18
) -> RangeInclusive<U> {
16
18
    f(r.start())..=f(r.end())
17
18
}
18

            
19
#[ext(name = IteratorExtUnzip)]
20
pub(crate) impl<AI, BI, I> I
21
where
22
    I: Iterator<Item = (Option<AI>, Option<BI>)>,
23
{
24
    /// Collect and filter an iterator yielding tuples of options into two collections.
25
    ///
26
    /// Takes an iterator yielding `(Option<AI>, Option<AB>)` and collects the
27
    /// `Some`s into a tuple of the two collections, of `AI` and `BI` respectively.
28
    //
29
    // TODO DIRAUTH consider moving this to tor-basic-utils or itertools or something.
30
48
    fn filter_collect_unzip<AC, BC>(self) -> (AC, BC)
31
48
    where
32
48
        AC: Default + Extend<AI>,
33
48
        BC: Default + Extend<BI>,
34
    {
35
48
        let mut ac = AC::default();
36
48
        let mut bc = BC::default();
37
48
        for (ao, bo) in self {
38
243
            ac.extend(ao);
39
243
            bc.extend(bo);
40
        }
41
48
        (ac, bc)
42
48
    }
43
}
44

            
45
#[ext(name = IteratorExt)]
46
pub(crate) impl<I> I
47
where
48
    I: Iterator,
49
{
50
    /// Filter items using a fallible predicate
51
    ///
52
    /// Returns an iterator of `Result`.
53
    //
54
    // TODO DIRAUTH consider moving this to tor-basic-utils or itertools or something.
55
145
    fn try_filter<'r, F, E>(self, mut f: F) -> impl Iterator<Item = Result<I::Item, E>> + 'r
56
145
    where
57
145
        I: 'r,
58
145
        F: FnMut(&I::Item) -> Result<bool, E> + 'r,
59
    {
60
1485
        self.filter_map(move |item| match f(&item) {
61
505
            Ok(false) => None,
62
980
            Ok(true) => Some(Ok(item)),
63
            Err(e) => Some(Err(e)),
64
1485
        })
65
145
    }
66
}
67

            
68
#[ext(name = TryAddAssign)]
69
pub(crate) impl<T: num_traits::CheckedAdd> T {
70
    /// `+=` but throws bug on overflow.
71
    //
72
    // `try` rather than `checked` because `checked_add_assign` ought to return `Option<()>`
73
    // by analogy with `.checked_add`.
74
5916
    fn try_add_assign(&mut self, v: Self) -> Result<(), Bug> {
75
5916
        *self = self
76
5916
            .checked_add(&v)
77
            .ok_or_else(|| internal!("addition overflow"))?;
78
5916
        Ok(())
79
5916
    }
80
}
81

            
82
/// Helper for deferring handling of `None`, temporarily substituting dummy values
83
///
84
/// Our macros like things to be uniform.  For exaempl, when calculating a pair of
85
/// routerstatuses, they want us to generate both in parallel.
86
///
87
/// But sometimes we want to be able to "early exit" from calculating an md rs,
88
/// for example if we discover that voters don't agree enough on the md hash.
89
///
90
/// This utility type allows us to "defer the early exit":
91
/// instead of returning early, we make a note in the
92
/// `NoneDefer` that we ought to be returning early.
93
///
94
/// And then we can safely fill in dummy values, knowing that they won't leak.
95
///
96
/// # Correctness - manual checks needed!
97
///
98
///  * You must ensure to call `.finish()` in your return path.
99
///    There is no engineered safeguard against forgetting to do so.
100
///
101
///  * The return from every call to `handle` must *only*
102
///    go into the output value that will be fed to `.finish()`.
103
///    Again, there is no engineered safeguard against getting this wrong.
104
///
105
///  * Do not attempt to have multiple `NoneDefer` in the same function.
106
///    There is nothing stopping you using the wrong one.
107
//
108
// Still, this is better than something more ad-hoc, such as "just a local boolean".
109
// And given that there's only one call site atm, this is probably a reasonable compromise.
110
pub(crate) struct NoneDefer<O> {
111
    /// Are we live?
112
    ///
113
    /// `Some` means we can still return `Some` from `finish`,
114
    /// and no dummy values have been substituted.
115
    ///
116
    /// `None` means we've `handle`d a `Noen`.
117
    ok: Option<()>,
118

            
119
    /// Bind this to the output type.
120
    ///
121
    /// This is not strictly necessary to uphold the promised assurances,
122
    /// but it seems like a good idea.
123
    marker: PhantomData<fn(O) -> O>,
124
}
125

            
126
impl<O> NoneDefer<O> {
127
    /// Create a new `NoneDefer`, which is initialised as "all is good, we'll return `Some`"
128
71
    pub(crate) fn new() -> Self {
129
71
        NoneDefer {
130
71
            ok: Some(()),
131
71
            marker: PhantomData,
132
71
        }
133
71
    }
134

            
135
    /// Handle a value that might be `None`, deferring and substituting if necessary
136
    ///
137
    /// If `v` is `Ok(Some(_))` or `Err()`, it is passed through.
138
    ///
139
    /// If `v` is `Ok(None`, remembers in `self` that we should be returning `None`.
140
    /// and then calls `fallback` to generate a dummy value.
141
    ///
142
    /// # Correctness
143
    ///
144
    /// The returned `Ok` value must only flow into the input to `finish`.
145
    /// See the [type-level docs](NoneDefer).
146
71
    pub(crate) fn handle<V, E, F>(&mut self, v: Result<Option<V>, E>, fallback: F) -> Result<V, E>
147
71
    where
148
71
        F: FnOnce() -> V,
149
    {
150
71
        Ok(match v? {
151
71
            Some(v) => v,
152
            None => {
153
                self.ok = None;
154
                fallback()
155
            }
156
        })
157
71
    }
158

            
159
    /// End the deferral of `Noen`s
160
    ///
161
    /// If we substituted any dummy value in a `handle` call, returns `None`.
162
    ///
163
    /// Otherwise returns `Some(o)`.
164
71
    pub(crate) fn finish(self, o: O) -> Option<O> {
165
71
        self.ok.map(|()| o)
166
71
    }
167
}