From 8f579c17fd731233e6c3da45730899a880261a11 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Sat, 21 Nov 2020 01:20:36 +0000 Subject: [PATCH] introduce MutateReturn trait, nfc Signed-off-by: Ian Jackson --- zcoord/zcoord.rs | 52 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/zcoord/zcoord.rs b/zcoord/zcoord.rs index 424f76b7..d256178a 100644 --- a/zcoord/zcoord.rs +++ b/zcoord/zcoord.rs @@ -281,12 +281,37 @@ impl Mutable { } } -pub type RangeIterator = std::iter::Take>; +pub type RangeIterator = std::iter::Take< + IteratorCore + >; + +pub trait MutateReturn { + fn op U> + (x: &mut T, + m: M, + o: O) -> U; +} + +#[derive(Debug)] +pub struct MutateFirst; +impl MutateReturn for MutateFirst { + fn op U> + (x: &mut T, m: M, o: O) -> U + { + m(x); + o(x) + } +} #[derive(Debug)] -pub struct IteratorCore { +pub struct IteratorCore { current: Mutable, aso: ASO, + mr: MR, } #[derive(Debug)] @@ -319,7 +344,7 @@ impl Mutable { #[throws(RangeBackwards)] fn range_core(a: &Mutable, b: &Mutable, count: RangeCount) - -> IteratorCore { + -> (Mutable, AddSubRangeDelta) { type ASRD = AddSubRangeDelta; let count = count as RawLimbVal; let mut current = a.clone(); @@ -370,21 +395,26 @@ impl Mutable { current.limbs[i] = init; break 'ok ASRD { i, step: step.into() }; } }; - IteratorCore { current, aso } + (current, aso) } #[throws(RangeBackwards)] pub fn range_upto(&self, other: &Mutable, count: RangeCount) -> RangeIterator { - Mutable::range_core(self, other, count)?.take(count as usize) + let (current, aso) = Mutable::range_core(self, other, count)?; + IteratorCore { current, aso, mr: MutateFirst }.take(count as usize) } } -impl Iterator for IteratorCore { +impl Iterator for IteratorCore { type Item = ZCoord; fn next(&mut self) -> Option { - self.current.addsub(&self.aso).unwrap(); - Some(self.current.repack().unwrap()) + let aso = &self.aso; + Some(MR::op( + &mut self.current, + |current| { current.addsub(aso).unwrap(); }, + |current| { current.repack().unwrap() }, + )) } } @@ -393,8 +423,10 @@ pub type BoxedIterator = Box; impl BoxedIteratorTrait for T where T : Iterator + Debug { } impl Mutable { - pub fn iter(self, aso: ASO) -> IteratorCore { - IteratorCore { current: self, aso } + pub fn iter(self, aso: ASO) + -> IteratorCore + { + IteratorCore { current: self, aso, mr: MutateFirst } } #[throws(LogicError)] pub fn some_range(a: Option<&Mutable>, b: Option<&Mutable>, -- 2.30.2