cell_map/iterators/
indexed.rs

1//! Provides the [`Indexed`] wrapper type which modifies a [`Slicer`] to produce the current index
2//! as well as the value.
3
4// ------------------------------------------------------------------------------------------------
5// IMPORTS
6// ------------------------------------------------------------------------------------------------
7
8use std::marker::PhantomData;
9
10use nalgebra::Point2;
11
12use crate::{iterators::Slicer, Layer};
13
14// ------------------------------------------------------------------------------------------------
15// STRUCTS
16// ------------------------------------------------------------------------------------------------
17
18/// A [`Slicer`] which wrapps another [`Slicer`] and modifies it to produce the index of the item
19/// as well as the item itself.
20#[derive(Debug, Clone, Copy)]
21pub struct Indexed<'a, L, T, S>
22where
23    L: Layer,
24    S: Slicer<'a, L, T>,
25{
26    slicer: S,
27    layer: L,
28    _phantom: PhantomData<(L, &'a T)>,
29}
30
31// ------------------------------------------------------------------------------------------------
32// IMPLS
33// ------------------------------------------------------------------------------------------------
34
35impl<'a, L, T, S> Indexed<'a, L, T, S>
36where
37    L: Layer,
38    S: Slicer<'a, L, T>,
39{
40    pub(crate) fn new(slicer: S, layer: L) -> Self {
41        Self {
42            slicer,
43            layer,
44            _phantom: PhantomData,
45        }
46    }
47}
48
49impl<'a, L, T, S> Slicer<'a, L, T> for Indexed<'a, L, T, S>
50where
51    L: Layer,
52    S: Slicer<'a, L, T>,
53{
54    type Output = ((L, Point2<usize>), S::Output);
55
56    type OutputMut = ((L, Point2<usize>), S::OutputMut);
57
58    fn slice(&self, data: &'a ndarray::Array2<T>) -> Option<Self::Output> {
59        let item = self.slicer.slice(data)?;
60
61        Some(((self.layer.clone(), self.slicer.index().unwrap()), item))
62    }
63
64    fn slice_mut(&self, data: &'a mut ndarray::Array2<T>) -> Option<Self::OutputMut> {
65        let item = self.slicer.slice_mut(data)?;
66
67        Some(((self.layer.clone(), self.slicer.index().unwrap()), item))
68    }
69
70    fn advance(&mut self) {
71        self.slicer.advance()
72    }
73
74    fn index(&self) -> Option<nalgebra::Point2<usize>> {
75        self.slicer.index()
76    }
77
78    fn reset(&mut self, layer: Option<L>) {
79        if let Some(ref l) = layer {
80            self.layer = l.clone()
81        }
82
83        self.slicer.reset(layer)
84    }
85}