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
// devela::apply
//
// Based on the code by George Burton, Unlicense licensed.
// https://crates.io/crates/apply/0.3.0
/// Allows to chain free functions into method call chains.
///
/// # Examples
/// ```
/// use devela::Apply;
///
/// let s = 1
/// .apply(|s| s * 2)
/// .apply(|s| s + 1)
/// .apply(|s: i32| s.to_string());
/// assert_eq![s, 3.to_string()];
/// ```
///
/// ```compile_fail
/// use devela::Apply;
///
/// // We can sort it, but we don't receive the new vec.
/// let v: Vec<i32> = vec![3, 2, 1, 5].apply_mut(|it| it.sort());
/// ```
pub trait Apply<Res> {
/// Apply a function which takes the parameter by value.
fn apply<F: FnOnce(Self) -> Res>(self, f: F) -> Res
where
Self: Sized,
{
f(self)
}
/// Apply a function which takes the parameter by shared reference.
fn apply_ref<F: FnOnce(&Self) -> Res>(&self, f: F) -> Res {
f(self)
}
/// Apply a function which takes the parameter by exclusive reference.
fn apply_mut<F: FnOnce(&mut Self) -> Res>(&mut self, f: F) -> Res {
f(self)
}
}
impl<T: ?Sized, Res> Apply<Res> for T {}
/// Represents a type that you can apply arbitrary functions to.
///
/// Useful for when a method doesn't return the receiver
/// but you want to apply several of them to the object.
///
/// It assumes that each function in the chain modifies the value by exclusive
/// reference and returns the modified value.
///
/// ```
/// use devela::Also;
///
/// let v = vec![3, 2, 1, 5]
/// .also_mut(|v| v.sort())
/// .also_ref(|v| assert_eq![v, &[1, 2, 3, 5]])
/// .also_mut(|v| v.push(7));
/// assert_eq![v, vec![1, 2, 3, 5, 7]];
/// ```
///
pub trait Also: Sized {
/// Applies a function which takes the parameter by exclusive reference,
/// and then returns the (possibly) modified owned value.
///
/// Similar to [`apply`], but instead of returning self directly from `f`,
/// since it has a different signature, returns it indirectly.
fn also_mut<F: FnOnce(&mut Self)>(mut self, f: F) -> Self {
f(&mut self);
self
}
/// Applies a function which takes the parameter by shared reference,
/// and then returns the (possibly) modified owned value.
///
/// Similar to [`apply`], but instead of returning self directly from `f`,
/// since it has a different signature, returns it indirectly.
fn also_ref<F: FnOnce(&Self)>(self, f: F) -> Self {
f(&self);
self
}
}
impl<T: Sized> Also for T {}