From 891fcc73b8bb7c162077512191c68d727f3c9db5 Mon Sep 17 00:00:00 2001 From: Christophe Troestler Date: Tue, 2 Apr 2024 17:35:17 +0200 Subject: [PATCH] Add an iterator over owned data held by the sampling --- src/lib.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index c5e07f6..bdb76c6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -291,6 +291,15 @@ impl Sampling { } } + /// Consumes the sampling and return an iterator on the curve + /// points and (owned) associated data. + pub fn into_iter_data(self) -> SamplingIntoIterData { + SamplingIntoIterData { + path: self.path.into_iter(), + guess_len: self.guess_len.get(), + } + } + /// Iterator on the x-coordinates of the sampling. /// See [`Self::iter`] for more information. #[inline] @@ -406,8 +415,37 @@ impl<'a, D> Iterator for SamplingIterMut<'a, D> { } } } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.guess_len)) + } +} + +/// Iterator returning the curve points and owned data. +pub struct SamplingIntoIterData { + path: list::IntoIter>, + guess_len: usize, } +impl Iterator for SamplingIntoIterData { + type Item = ([f64; 2], D); + + fn next(&mut self) -> Option { + match self.path.next() { + None => None, + Some(p) => { + self.guess_len -= 1; + Some((p.xy, p.data)) + } + } + } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(self.guess_len)) + } +} + + /// Intersection of a segment with the bounding box. #[derive(Debug)] enum Intersection { @@ -1817,6 +1855,18 @@ mod tests { } } + #[test] + fn into_iter_data() { + let s = Sampling::uniform(|x| (x, x as i32), 0., 4.).n(3) + .init(&[1.]).init_pt([(3., (0., -1))]).build(); + let expected = vec![ + ([0.,0.], 0), ([1.,1.], 1), ([2.,2.], 2), ([3., 0.], -1), + ([4.,4.], 4)]; + for (i, d) in s.into_iter_data().enumerate() { + assert_eq!(d, expected[i]); + } + } + /// In order the judge the quality of the sampling, we save it /// with the internal cost data. fn write_with_point_costs(