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
81
82
83
84
85
86
87
88
89
90
91
92
//! This crate adds the missing Result::inspect function via an extension trait
//!

/// Extension trait for adding Result::inspect
pub trait ResultInspect<F, T>
where
    F: FnOnce(&T),
    T: Sized,
{
    /// Call `f` on T if the Result is a Ok(T), or do nothing if the Result is an Err
    fn inspect(self, f: F) -> Self;
}

pub trait ResultInspectRef<F, T>
where
    F: FnOnce(&T),
    T: Sized,
{
    fn inspect(&self, f: F);
}

impl<F, T, E> ResultInspect<F, T> for Result<T, E>
where
    F: FnOnce(&T),
    T: Sized,
{
    /// Call `f` on T if the Result is a Ok(T), or do nothing if the Result is an Err
    fn inspect(self, f: F) -> Self {
        if let Ok(o) = self.as_ref() {
            (f)(o);
        }

        self
    }
}

impl<F, T, E> ResultInspectRef<F, T> for Result<T, E>
where
    F: FnOnce(&T),
    T: Sized,
{
    fn inspect(&self, f: F) {
        if let Ok(ref o) = self {
            (f)(o);
        }
    }
}

/// Extension trait for adding Result::inspect_err
pub trait ResultInspectErr<F, E>
where
    F: FnOnce(&E),
    E: Sized,
{
    /// Call `f` on T if the Result is a Err(E), or do nothing if the Result is an Ok
    fn inspect_err(self, f: F) -> Self;
}

pub trait ResultInspectErrRef<F, E>
where
    F: FnOnce(&E),
    E: Sized,
{
    fn inspect_err(&self, f: F);
}

impl<F, T, E> ResultInspectErr<F, E> for Result<T, E>
where
    F: FnOnce(&E),
    E: Sized,
{
    /// Call `f` on T if the Result is a Err(E), or do nothing if the Result is an Ok
    fn inspect_err(self, f: F) -> Self {
        if let Err(e) = self.as_ref() {
            (f)(e);
        }

        self
    }
}

impl<F, T, E> ResultInspectErrRef<F, E> for Result<T, E>
where
    F: FnOnce(&E),
    E: Sized,
{
    fn inspect_err(&self, f: F) {
        if let Err(ref e) = self {
            (f)(e);
        }
    }
}