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
93
94
95
96
97
98
#[cfg(feature = "future")]
pub use self::future::TapFutureOps;
#[cfg(feature = "future")]
mod future;
#[cfg(test)]
#[cfg_attr(test, macro_use)]
extern crate matches;
pub trait TapResultOps<T, E> {
fn tap_ok<R, F: FnOnce(&T) -> R>(self, f: F) -> Self;
fn tap_err<R, F: FnOnce(&E) -> R>(self, f: F) -> Self;
}
impl<T, E> TapResultOps<T, E> for Result<T, E> {
fn tap_ok<R, F: FnOnce(&T) -> R>(self, f: F) -> Self {
if let Ok(val) = self.as_ref() {
let _ = f(val);
}
self
}
fn tap_err<R, F: FnOnce(&E) -> R>(self, f: F) -> Self {
if let Err(val) = self.as_ref() {
let _ = f(val);
}
self
}
}
pub trait TapOptionOps<T> {
fn tap_some<R, F: FnOnce(&T) -> R>(self, f: F) -> Self;
fn tap_none<R, F: FnOnce() -> R>(self, f: F) -> Self;
}
impl<T> TapOptionOps<T> for Option<T> {
fn tap_some<R, F: FnOnce(&T) -> R>(self, f: F) -> Self {
if let Some(val) = self.as_ref() {
let _ = f(val);
}
self
}
fn tap_none<R, F: FnOnce() -> R>(self, f: F) -> Self {
if self.is_none() {
let _ = f();
}
self
}
}
pub trait TapOps {
fn tap<R, F: FnOnce(&Self) -> R>(self, f: F) -> Self where Self: Sized {
let _ = f(&self);
self
}
}
impl<T> TapOps for T {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn option() {
let mut foo = 0;
let option = Some(5);
assert_eq!(option.tap_some(|x| foo += *x), Some(5));
assert_eq!(foo, 5);
}
#[test]
fn result() {
let mut foo = 0;
let option: Result<i32, i32> = Ok(5);
assert_eq!(option.tap_ok(|x| foo += *x), Ok(5));
assert_eq!(foo, 5);
}
#[test]
fn tap() {
let mut foo = 0;
assert_eq!(5.tap(|x| foo += *x), 5);
assert_eq!(foo, 5);
}
}