chainer/
basic.rs

1/// Enables immutable call chaining on all types.
2///
3/// # Example
4///
5/// ```rust
6/// use chainer::*;
7///
8/// struct HelloWorld;
9/// impl HelloWorld {
10///     fn print(&self) {
11///         println!("Hello, world!");
12///     }
13/// }
14///
15/// fn main() {
16///     HelloWorld
17///         .chain(HelloWorld::print)
18///         .chain(HelloWorld::print)
19///         .chain(HelloWorld::print);
20///
21///     // Hello, world!
22///     // Hello, world!
23///     // Hello, world!
24/// }
25/// ```
26pub trait CallChain {
27	/// Enables immutable call chaining on all types.
28	///
29	/// # Example
30	///
31	/// ```rust
32	/// use chainer::*;
33	///
34	/// struct HelloWorld;
35	/// impl HelloWorld {
36	///     fn print(&self) {
37	///         println!("Hello, world!");
38	///     }
39	/// }
40	///
41	/// fn main() {
42	///     HelloWorld
43	///         .chain(HelloWorld::print)
44	///         .chain(HelloWorld::print)
45	///         .chain(HelloWorld::print);
46	///
47	///     // Hello, world!
48	///     // Hello, world!
49	///     // Hello, world!
50	/// }
51	/// ```
52	fn chain<R, F: FnOnce(&Self) -> R>(&self, f: F) -> &Self {
53		f(self);
54		self
55	}
56}
57
58/// Enables mutable call chaining on all types.
59///
60/// # Example
61///
62/// ```rust
63/// use chainer::*;
64///
65/// struct Counter { value: i32 }
66/// impl Counter {
67///     fn increment(&mut self) {
68///         self.value += 1;
69///         println!("{}", self.value);
70///     }
71/// }
72///
73/// fn main() {
74///     Counter { value: 0 }
75///         .chain_mut(Counter::increment)
76///         .chain_mut(Counter::increment)
77///         .chain_mut(Counter::increment);
78///
79///     // 1
80///     // 2
81///     // 3
82/// }
83/// ```
84pub trait CallChainMut {
85	/// Enables mutable call chaining on all types.
86	///
87	/// # Example
88	///
89	/// ```rust
90	/// use chainer::*;
91	///
92	/// struct Counter { value: i32 }
93	/// impl Counter {
94	///     fn increment(&mut self) {
95	///         self.value += 1;
96	///         println!("{}", self.value);
97	///     }
98	/// }
99	///
100	/// fn main() {
101	///     Counter { value: 0 }
102	///         .chain_mut(Counter::increment)
103	///         .chain_mut(Counter::increment)
104	///         .chain_mut(Counter::increment);
105	///
106	///     // 1
107	///     // 2
108	///     // 3
109	/// }
110	/// ```
111	fn chain_mut<R, F: FnOnce(&mut Self) -> R>(&mut self, f: F) -> &mut Self {
112		f(self);
113		self
114	}
115}
116
117impl<T: ?Sized> CallChain for T {}
118impl<T: ?Sized> CallChainMut for T {}