result_inspect/
lib.rs

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