slice_utils/
fromfn.rs

1use crate::{Slice, SliceOwned};
2
3/// A slice calling a closure on index; see [`from_fn`](crate::from_fn).
4#[derive(Clone, Copy, Hash)]
5pub struct FromFn<F> {
6    /// The inner closure of the slice.
7    pub f: F,
8    len: usize,
9}
10
11impl<F, T> FromFn<F>
12where
13    F: Fn(usize) -> Option<T>,
14{
15    /// Create a slice from a closure; see [`from_fn`](crate::from_fn).
16    pub fn new(f: F, len: Option<usize>) -> Self {
17        Self {
18            f,
19            len: len.unwrap_or(usize::MAX),
20        }
21    }
22}
23
24impl<F, T> Slice for FromFn<F>
25where
26    F: Fn(usize) -> Option<T>,
27{
28    type Output = T;
29
30    fn len(&self) -> usize {
31        self.len
32    }
33
34    fn get_with<W: FnMut(&Self::Output) -> R, R>(&self, index: usize, f: &mut W) -> Option<R> {
35        Some(f(&self.get_owned(index)?))
36    }
37}
38
39impl<F, T> SliceOwned for FromFn<F>
40where
41    F: Fn(usize) -> Option<T>,
42{
43    fn get_owned(&self, index: usize) -> Option<Self::Output> {
44        (self.f)(index)
45    }
46}