option_inspect/
lib.rs

1//! This crate adds the missing Option::inspect function via an extension trait
2//!
3
4/// Extension trait for adding Option::inspect
5pub trait OptionInspect<F, T>
6where
7    F: FnOnce(&T),
8    T: Sized,
9{
10    /// Inspect the Option
11    ///
12    /// Either call `f` on the value in `Some` or do nothing if this Option is a None.
13    fn inspect(self, f: F) -> Self;
14}
15
16pub trait OptionInspectRef<F, T>
17where
18    F: FnOnce(&T),
19    T: Sized,
20{
21    fn inspect(&self, f: F);
22}
23
24impl<F, T> OptionInspect<F, T> for Option<T>
25where
26    F: FnOnce(&T),
27    T: Sized,
28{
29    fn inspect(self, f: F) -> Self {
30        if let Some(o) = self.as_ref() {
31            (f)(o);
32        }
33
34        self
35    }
36}
37
38impl<F, T> OptionInspectRef<F, T> for Option<T>
39where
40    F: FnOnce(&T),
41    T: Sized,
42{
43    fn inspect(&self, f: F) {
44        if let Some(ref o) = self {
45            (f)(o);
46        }
47    }
48}
49
50/// Extension trait for adding Option::inspect_none
51pub trait OptionInspectNone<F>
52where
53    F: FnOnce(),
54{
55    /// Call `f` if the Option this is called on is a None
56    fn inspect_none(self, f: F) -> Self;
57}
58
59pub trait OptionInspectNoneRef<F>
60where
61    F: FnOnce(),
62{
63    fn inspect_none(&self, f: F);
64}
65
66impl<F, T> OptionInspectNone<F> for Option<T>
67where
68    F: FnOnce(),
69{
70    fn inspect_none(self, f: F) -> Self {
71        if self.is_none() {
72            (f)();
73        }
74
75        self
76    }
77}
78
79impl<F, T> OptionInspectNoneRef<F> for Option<T>
80where
81    F: FnOnce(),
82{
83    fn inspect_none(&self, f: F) {
84        if self.is_none() {
85            (f)();
86        }
87    }
88}