From 216bcfd66b63a9f60e41e4b736145f62edda4150 Mon Sep 17 00:00:00 2001 From: Jorge Aparicio Date: Wed, 3 Dec 2014 15:51:47 -0500 Subject: [PATCH] libcore: use unboxed closures in the fields of `Unfold` --- src/libcore/iter.rs | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 36b902dbee1..51ae0f47029 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -2108,19 +2108,18 @@ impl RandomAccessIterator for Inspect where /// } /// ``` #[experimental] -pub struct Unfold<'a, A, St> { - f: |&mut St|: 'a -> Option, +pub struct Unfold where F: FnMut(&mut St) -> Option { + f: F, /// Internal state that will be passed to the closure on the next iteration pub state: St, } #[experimental] -impl<'a, A, St> Unfold<'a, A, St> { +impl Unfold where F: FnMut(&mut St) -> Option { /// Creates a new iterator with the specified closure as the "iterator /// function" and an initial state to eventually pass to the closure #[inline] - pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option) - -> Unfold<'a, A, St> { + pub fn new(initial_state: St, f: F) -> Unfold { Unfold { f: f, state: initial_state @@ -2129,7 +2128,7 @@ impl<'a, A, St> Unfold<'a, A, St> { } #[experimental] -impl<'a, A, St> Iterator for Unfold<'a, A, St> { +impl Iterator for Unfold where F: FnMut(&mut St) -> Option { #[inline] fn next(&mut self) -> Option { (self.f)(&mut self.state) @@ -2456,18 +2455,24 @@ impl RandomAccessIterator for Repeat { fn idx(&mut self, _: uint) -> Option { Some(self.element.clone()) } } -type IterateState<'a, T> = (|T|: 'a -> T, Option, bool); +type IterateState = (F, Option, bool); /// An iterator that repeatedly applies a given function, starting /// from a given seed value. #[experimental] -pub type Iterate<'a, T> = Unfold<'a, T, IterateState<'a, T>>; +pub type Iterate = Unfold, fn(&mut IterateState) -> Option>; /// Create a new iterator that produces an infinite sequence of /// repeated applications of the given function `f`. #[experimental] -pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T> { - Unfold::new((f, Some(seed), true), |st| { +pub fn iterate(seed: T, f: F) -> Iterate where + T: Clone, + F: FnMut(T) -> T, +{ + fn next(st: &mut IterateState) -> Option where + T: Clone, + F: FnMut(T) -> T, + { let &(ref mut f, ref mut val, ref mut first) = st; if *first { *first = false; @@ -2480,7 +2485,9 @@ pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T> { } } val.clone() - }) + } + + Unfold::new((f, Some(seed), true), next) } /// Create a new iterator that endlessly repeats the element `elt`.