rspace_traits/impls/
impl_apply.rs

1/*
2    Appellation: impl_apply <module>
3    Created At: 2026.01.01:21:39:28
4    Contrib: @FL03
5*/
6use crate::ops::{Apply, ApplyMut, ApplyOnce};
7
8impl<U, V, F> ApplyOnce<F> for Option<U>
9where
10    F: FnOnce(U) -> V,
11{
12    type Output = Option<V>;
13
14    fn apply_once(self, rhs: F) -> Self::Output {
15        self.map(rhs)
16    }
17}
18
19impl<U, V, F> Apply<F> for Option<U>
20where
21    F: Fn(&U) -> V,
22{
23    type Output = Option<V>;
24
25    fn apply(&self, rhs: F) -> Self::Output {
26        self.as_ref().map(rhs)
27    }
28}
29
30impl<U, V, F> ApplyMut<F> for Option<U>
31where
32    F: FnMut(&mut U) -> V,
33{
34    type Output = Option<V>;
35
36    fn apply_mut(&mut self, rhs: F) -> Self::Output {
37        self.as_mut().map(rhs)
38    }
39}
40
41impl<const N: usize, U, V, F> Apply<F> for [U; N]
42where
43    F: Fn(&U) -> V,
44{
45    type Output = [V; N];
46
47    fn apply(&self, rhs: F) -> Self::Output {
48        core::array::from_fn(|i| rhs(&self[i]))
49    }
50}
51
52#[cfg(all(feature = "alloc", feature = "nightly"))]
53mod impl_alloc {
54    use crate::ops::Apply;
55    use alloc::alloc::Allocator;
56    use alloc::boxed::Box;
57    use alloc::vec::Vec;
58
59    impl<U, V, F, A> Apply<F> for Box<U, A>
60    where
61        A: Allocator,
62        F: Fn(&U) -> V,
63    {
64        type Output = Box<V>;
65
66        fn apply(&self, rhs: F) -> Self::Output {
67            Box::new(rhs(self.as_ref()))
68        }
69    }
70
71    impl<U, V, F, A> Apply<F> for Vec<U, A>
72    where
73        A: Allocator,
74        F: Fn(&U) -> V,
75        Vec<V, A>: FromIterator<V>,
76    {
77        type Output = Vec<V, A>;
78
79        fn apply(&self, rhs: F) -> Self::Output {
80            self.iter().map(rhs).collect()
81        }
82    }
83}
84#[cfg(all(feature = "alloc", not(feature = "nightly")))]
85mod impl_alloc {
86    use crate::ops::Apply;
87    use alloc::boxed::Box;
88    use alloc::vec::Vec;
89
90    impl<U, V, F> Apply<F> for Box<U>
91    where
92        F: Fn(&U) -> V,
93    {
94        type Output = Box<V>;
95
96        fn apply(&self, rhs: F) -> Self::Output {
97            Box::new(rhs(self.as_ref()))
98        }
99    }
100
101    impl<U, V, F> Apply<F> for Vec<U>
102    where
103        F: Fn(&U) -> V,
104        Vec<V>: FromIterator<V>,
105    {
106        type Output = Vec<V>;
107
108        fn apply(&self, rhs: F) -> Self::Output {
109            self.iter().map(rhs).collect()
110        }
111    }
112}