stry_common/utils/fenn/
wrap.rs

1/// A trait that allows for creating 'builder' like chains of function calls.
2///
3/// This is a rough 'open' version of what
4/// [`StringExt`](./trait.StringExt.html) and [`VecExt`](./trait.VecExt.html)
5/// do, but is made for situations where theres no extension trait.
6pub trait Wrap: Sized {
7    /// Turns a self reference function call into an 'inline'/'builder' call.
8    ///
9    /// This function normally isn't needed, if you need to access a value
10    /// you can use [`Peep`](./trait.Peep.html).
11    /// Theres normally something wrong with the library if you need to use
12    /// this.
13    fn wrap_ref<F>(self, wrap: F) -> Self
14    where
15        F: FnOnce(&Self),
16    {
17        wrap(&self);
18
19        self
20    }
21
22    /// Turns a self mutable reference function call into an 'inline'/'builder'
23    /// call.
24    ///
25    /// # Examples
26    ///
27    /// If you didn't want to use [`VecExt`](./trait.VecExt.html) for some
28    /// reason you could do this.
29    ///
30    /// ```
31    /// use fenn::Wrap;
32    ///
33    /// let ex = vec![1, 1, 3, 5, 5, 5, 7].wrap_mut(Vec::dedup);
34    ///
35    /// assert_eq!(vec![1, 3, 5, 7], ex);
36    /// ```
37    fn wrap_mut<F>(mut self, wrap: F) -> Self
38    where
39        F: FnOnce(&mut Self),
40    {
41        wrap(&mut self);
42
43        self
44    }
45
46    /// Turns a consuming function call into an 'inline'/'builder' call.
47    ///
48    /// # Examples
49    ///
50    /// ```
51    /// use fenn::Wrap;
52    ///
53    /// let ex = 4.wrap_map(|n| n * 2);
54    ///
55    /// assert_eq!(8, ex);
56    /// ```
57    fn wrap_map<F, R>(self, wrap: F) -> R
58    where
59        F: FnOnce(Self) -> R,
60    {
61        wrap(self)
62    }
63}
64
65impl<T> Wrap for T {}