cell_map/iterators/
positioned.rs

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