rspace_traits/ops/
map.rs

1/*
2    Appellation: map <module>
3    Created At: 2026.01.01:21:31:12
4    Contrib: @FL03
5*/
6/// [`MapInto`] defines an interface for containers capable of applying a given function onto
7/// each of their elements and consuming the container in the process, producing a new
8/// container containing the captured results of each invocation. The trait's design allows
9/// implementors to specify the exact function signature and output type, utilizing associated
10/// type parameters to define the container and its _current_ element type.
11pub trait MapInto<F, T>
12where
13    F: FnOnce(Self::Elem) -> T,
14{
15    type Cont<_T>: ?Sized;
16    /// the current type of element associated with the contained
17    type Elem;
18
19    fn apply(self, f: F) -> Self::Cont<T>;
20}
21
22/// The [`MapTo`] trait is similar to [`MapInto`], but it operates on references to the
23/// container rather than consuming it. This allows for mapping functions over the elements
24/// of a container while retaining ownership of the original container.  
25pub trait MapTo<F, X>
26where
27    F: FnOnce(Self::Elem) -> X,
28{
29    type Cont<T>: ?Sized;
30    type Elem;
31
32    fn apply(&self, f: F) -> Self::Cont<X>;
33}
34
35/*
36 ************* Implementations *************
37*/
38
39#[cfg(test)]
40mod tests {
41
42    #[test]
43    fn test_map_into_on_option() {
44        use super::MapInto;
45        fn sample_once(input: u8) -> f32 {
46            input as f32 + 1.25
47        }
48        let exp = Some(43.25f32);
49        assert_eq! { Some(42u8).apply(sample_once), exp }
50    }
51
52    #[test]
53    fn test_map_to_on_option() {
54        use super::MapTo;
55        fn sample_ref(input: &u8) -> f32 {
56            *input as f32 + 1.25
57        }
58        let exp = Some(43.25f32);
59        assert_eq! { Some(&42u8).apply(sample_ref), exp }
60    }
61}