option_inspect_none/
lib.rs

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
pub trait OptionInspectNone<T> {
    fn inspect_none(self, inspector_function: impl FnOnce()) -> Self;
}

impl<T> OptionInspectNone<T> for Option<T> {
    fn inspect_none(self, inspector_function: impl FnOnce()) -> Self {
        match &self {
            Some(_) => (),
            None => inspector_function(),
        }
        self
    }
}

impl<T> OptionInspectNone<T> for &Option<T> {
    fn inspect_none(self, inspector_function: impl FnOnce()) -> Self {
        match &self {
            Some(_) => (),
            None => inspector_function(),
        }
        self
    }
}

#[cfg(test)]
mod tests {
    use crate::OptionInspectNone;

    #[test]
    fn inspect_none_on_some() {
        let mut inspector_function_called = false;
        Some(()).inspect_none(|| inspector_function_called = true);
        assert!(!inspector_function_called);
    }

    #[test]
    fn inspect_none_on_none() {
        let mut inspector_function_called = false;
        None::<()>.inspect_none(|| inspector_function_called = true);
        assert!(inspector_function_called);
    }
}