rspace_traits/ops/
apply.rs

1/*
2    Appellation: apply <module>
3    Created At: 2025.12.24:17:20:29
4    Contrib: @FL03
5*/
6/// [`Apply`] defines an interface for objects capable of _applying_ the given function onto
7/// itself or its elements to produce some output.
8pub trait Apply<Rhs> {
9    type Output;
10
11    fn apply(&self, rhs: Rhs) -> Self::Output;
12}
13/// The [`ApplyOnce`] trait defines an interface for objects capable of consuming themselves
14/// to apply the given function onto themselves or their elements to produce some output.
15pub trait ApplyOnce<Rhs> {
16    type Output;
17
18    fn apply_once(self, rhs: Rhs) -> Self::Output;
19}
20/// The [`ApplyMut`] trait defines an interface for objects capable of mutably borrowing themselves
21/// to apply the given function onto themselves or their elements to produce some output.
22pub trait ApplyMut<Rhs> {
23    type Output;
24
25    fn apply_mut(&mut self, rhs: Rhs) -> Self::Output;
26}
27
28pub trait TryApply<Rhs> {
29    type Output;
30    type Error;
31
32    fn try_apply(&self, rhs: Rhs) -> Result<Self::Output, Self::Error>;
33}
34
35pub trait TryApplyOnce<Rhs> {
36    type Output;
37    type Error;
38
39    fn try_apply_once(self, rhs: Rhs) -> Result<Self::Output, Self::Error>;
40}
41
42pub trait TryApplyMut<Rhs> {
43    type Output;
44    type Error;
45
46    fn try_apply_mut(&mut self, rhs: Rhs) -> Result<Self::Output, Self::Error>;
47}
48
49/*
50 ************* Implementations *************
51*/
52impl<U, V, F> ApplyOnce<F> for Option<U>
53where
54    F: FnOnce(U) -> V,
55{
56    type Output = Option<V>;
57
58    fn apply_once(self, rhs: F) -> Self::Output {
59        self.map(rhs)
60    }
61}
62
63impl<U, V, F> Apply<F> for Option<U>
64where
65    F: Fn(&U) -> V,
66{
67    type Output = Option<V>;
68
69    fn apply(&self, rhs: F) -> Self::Output {
70        self.as_ref().map(rhs)
71    }
72}
73
74impl<A, X, Y> TryApplyOnce<X> for A
75where
76    A: ApplyOnce<X, Output = Y>,
77{
78    type Output = A::Output;
79    type Error = core::convert::Infallible;
80
81    fn try_apply_once(self, rhs: X) -> Result<Self::Output, Self::Error> {
82        Ok(self.apply_once(rhs))
83    }
84}
85
86impl<A, X, Y> TryApply<X> for A
87where
88    A: Apply<X, Output = Y>,
89{
90    type Output = A::Output;
91    type Error = core::convert::Infallible;
92
93    fn try_apply(&self, rhs: X) -> Result<Self::Output, Self::Error> {
94        Ok(self.apply(rhs))
95    }
96}