slice_utils/
map.rs

1use crate::{Slice, SliceBorrowed, SliceOwned};
2
3macro_rules! map {
4    ($owned:ident, $in:ty, $fn:ident) => {
5        paste::paste! {
6            #[doc = "Maps using a closure on index; see [`" [<Slice $owned>] "::map`]."]
7            #[derive(Clone, Copy, Hash)]
8            pub struct [<Map $owned>]<S, F>(pub S, pub F);
9
10            impl<S, F, U> Slice for [<Map $owned>]<S, F>
11            where
12                S: [<Slice $owned>],
13                F: Fn($in) -> U,
14            {
15                type Output = U;
16
17                fn len(&self) -> usize {
18                    self.0.len()
19                }
20
21                fn get_with<W: FnMut(&Self::Output) -> R, R>(&self, index: usize, f: &mut W) -> Option<R> {
22                    Some(f(&self.get_owned(index)?))
23                }
24            }
25
26            impl<S, F, U> SliceOwned for [<Map $owned>]<S, F>
27            where
28                S: [<Slice $owned>],
29                F: Fn($in) -> U,
30            {
31                fn get_owned(&self, index: usize) -> Option<U> {
32                    self.0.$fn(index).map(&self.1)
33                }
34            }
35        }
36    };
37}
38
39map!(Owned, S::Output, get_owned);
40map!(Borrowed, &S::Output, get);
41// map!(MapMut, &mut S::Output, SliceMut, get_mut);