Skip to content

Commit 34d5624

Browse files
author
Clar Fon
committed
Move DoubleEndedIterator to own module
1 parent c40450c commit 34d5624

File tree

2 files changed

+300
-298
lines changed

2 files changed

+300
-298
lines changed
Lines changed: 297 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,297 @@
1+
use ops::Try;
2+
use iter::LoopState;
3+
4+
/// An iterator able to yield elements from both ends.
5+
///
6+
/// Something that implements `DoubleEndedIterator` has one extra capability
7+
/// over something that implements [`Iterator`]: the ability to also take
8+
/// `Item`s from the back, as well as the front.
9+
///
10+
/// It is important to note that both back and forth work on the same range,
11+
/// and do not cross: iteration is over when they meet in the middle.
12+
///
13+
/// In a similar fashion to the [`Iterator`] protocol, once a
14+
/// `DoubleEndedIterator` returns `None` from a `next_back()`, calling it again
15+
/// may or may not ever return `Some` again. `next()` and `next_back()` are
16+
/// interchangeable for this purpose.
17+
///
18+
/// [`Iterator`]: trait.Iterator.html
19+
///
20+
/// # Examples
21+
///
22+
/// Basic usage:
23+
///
24+
/// ```
25+
/// let numbers = vec![1, 2, 3, 4, 5, 6];
26+
///
27+
/// let mut iter = numbers.iter();
28+
///
29+
/// assert_eq!(Some(&1), iter.next());
30+
/// assert_eq!(Some(&6), iter.next_back());
31+
/// assert_eq!(Some(&5), iter.next_back());
32+
/// assert_eq!(Some(&2), iter.next());
33+
/// assert_eq!(Some(&3), iter.next());
34+
/// assert_eq!(Some(&4), iter.next());
35+
/// assert_eq!(None, iter.next());
36+
/// assert_eq!(None, iter.next_back());
37+
/// ```
38+
#[stable(feature = "rust1", since = "1.0.0")]
39+
pub trait DoubleEndedIterator: Iterator {
40+
/// Removes and returns an element from the end of the iterator.
41+
///
42+
/// Returns `None` when there are no more elements.
43+
///
44+
/// The [trait-level] docs contain more details.
45+
///
46+
/// [trait-level]: trait.DoubleEndedIterator.html
47+
///
48+
/// # Examples
49+
///
50+
/// Basic usage:
51+
///
52+
/// ```
53+
/// let numbers = vec![1, 2, 3, 4, 5, 6];
54+
///
55+
/// let mut iter = numbers.iter();
56+
///
57+
/// assert_eq!(Some(&1), iter.next());
58+
/// assert_eq!(Some(&6), iter.next_back());
59+
/// assert_eq!(Some(&5), iter.next_back());
60+
/// assert_eq!(Some(&2), iter.next());
61+
/// assert_eq!(Some(&3), iter.next());
62+
/// assert_eq!(Some(&4), iter.next());
63+
/// assert_eq!(None, iter.next());
64+
/// assert_eq!(None, iter.next_back());
65+
/// ```
66+
#[stable(feature = "rust1", since = "1.0.0")]
67+
fn next_back(&mut self) -> Option<Self::Item>;
68+
69+
/// Returns the `n`th element from the end of the iterator.
70+
///
71+
/// This is essentially the reversed version of [`nth`]. Although like most indexing
72+
/// operations, the count starts from zero, so `nth_back(0)` returns the first value fro
73+
/// the end, `nth_back(1)` the second, and so on.
74+
///
75+
/// Note that all elements between the end and the returned element will be
76+
/// consumed, including the returned element. This also means that calling
77+
/// `nth_back(0)` multiple times on the same iterator will return different
78+
/// elements.
79+
///
80+
/// `nth_back()` will return [`None`] if `n` is greater than or equal to the length of the
81+
/// iterator.
82+
///
83+
/// [`None`]: ../../std/option/enum.Option.html#variant.None
84+
/// [`nth`]: ../../std/iter/trait.Iterator.html#method.nth
85+
///
86+
/// # Examples
87+
///
88+
/// Basic usage:
89+
///
90+
/// ```
91+
/// #![feature(iter_nth_back)]
92+
/// let a = [1, 2, 3];
93+
/// assert_eq!(a.iter().nth_back(2), Some(&1));
94+
/// ```
95+
///
96+
/// Calling `nth_back()` multiple times doesn't rewind the iterator:
97+
///
98+
/// ```
99+
/// #![feature(iter_nth_back)]
100+
/// let a = [1, 2, 3];
101+
///
102+
/// let mut iter = a.iter();
103+
///
104+
/// assert_eq!(iter.nth_back(1), Some(&2));
105+
/// assert_eq!(iter.nth_back(1), None);
106+
/// ```
107+
///
108+
/// Returning `None` if there are less than `n + 1` elements:
109+
///
110+
/// ```
111+
/// #![feature(iter_nth_back)]
112+
/// let a = [1, 2, 3];
113+
/// assert_eq!(a.iter().nth_back(10), None);
114+
/// ```
115+
#[inline]
116+
#[unstable(feature = "iter_nth_back", issue = "56995")]
117+
fn nth_back(&mut self, mut n: usize) -> Option<Self::Item> {
118+
for x in self.rev() {
119+
if n == 0 { return Some(x) }
120+
n -= 1;
121+
}
122+
None
123+
}
124+
125+
/// This is the reverse version of [`try_fold()`]: it takes elements
126+
/// starting from the back of the iterator.
127+
///
128+
/// [`try_fold()`]: trait.Iterator.html#method.try_fold
129+
///
130+
/// # Examples
131+
///
132+
/// Basic usage:
133+
///
134+
/// ```
135+
/// let a = ["1", "2", "3"];
136+
/// let sum = a.iter()
137+
/// .map(|&s| s.parse::<i32>())
138+
/// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
139+
/// assert_eq!(sum, Ok(6));
140+
/// ```
141+
///
142+
/// Short-circuiting:
143+
///
144+
/// ```
145+
/// let a = ["1", "rust", "3"];
146+
/// let mut it = a.iter();
147+
/// let sum = it
148+
/// .by_ref()
149+
/// .map(|&s| s.parse::<i32>())
150+
/// .try_rfold(0, |acc, x| x.and_then(|y| Ok(acc + y)));
151+
/// assert!(sum.is_err());
152+
///
153+
/// // Because it short-circuited, the remaining elements are still
154+
/// // available through the iterator.
155+
/// assert_eq!(it.next_back(), Some(&"1"));
156+
/// ```
157+
#[inline]
158+
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
159+
fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
160+
where
161+
Self: Sized,
162+
F: FnMut(B, Self::Item) -> R,
163+
R: Try<Ok=B>
164+
{
165+
let mut accum = init;
166+
while let Some(x) = self.next_back() {
167+
accum = f(accum, x)?;
168+
}
169+
Try::from_ok(accum)
170+
}
171+
172+
/// An iterator method that reduces the iterator's elements to a single,
173+
/// final value, starting from the back.
174+
///
175+
/// This is the reverse version of [`fold()`]: it takes elements starting from
176+
/// the back of the iterator.
177+
///
178+
/// `rfold()` takes two arguments: an initial value, and a closure with two
179+
/// arguments: an 'accumulator', and an element. The closure returns the value that
180+
/// the accumulator should have for the next iteration.
181+
///
182+
/// The initial value is the value the accumulator will have on the first
183+
/// call.
184+
///
185+
/// After applying this closure to every element of the iterator, `rfold()`
186+
/// returns the accumulator.
187+
///
188+
/// This operation is sometimes called 'reduce' or 'inject'.
189+
///
190+
/// Folding is useful whenever you have a collection of something, and want
191+
/// to produce a single value from it.
192+
///
193+
/// [`fold()`]: trait.Iterator.html#method.fold
194+
///
195+
/// # Examples
196+
///
197+
/// Basic usage:
198+
///
199+
/// ```
200+
/// let a = [1, 2, 3];
201+
///
202+
/// // the sum of all of the elements of a
203+
/// let sum = a.iter()
204+
/// .rfold(0, |acc, &x| acc + x);
205+
///
206+
/// assert_eq!(sum, 6);
207+
/// ```
208+
///
209+
/// This example builds a string, starting with an initial value
210+
/// and continuing with each element from the back until the front:
211+
///
212+
/// ```
213+
/// let numbers = [1, 2, 3, 4, 5];
214+
///
215+
/// let zero = "0".to_string();
216+
///
217+
/// let result = numbers.iter().rfold(zero, |acc, &x| {
218+
/// format!("({} + {})", x, acc)
219+
/// });
220+
///
221+
/// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");
222+
/// ```
223+
#[inline]
224+
#[stable(feature = "iter_rfold", since = "1.27.0")]
225+
fn rfold<B, F>(mut self, accum: B, mut f: F) -> B
226+
where
227+
Self: Sized,
228+
F: FnMut(B, Self::Item) -> B,
229+
{
230+
self.try_rfold(accum, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
231+
}
232+
233+
/// Searches for an element of an iterator from the back that satisfies a predicate.
234+
///
235+
/// `rfind()` takes a closure that returns `true` or `false`. It applies
236+
/// this closure to each element of the iterator, starting at the end, and if any
237+
/// of them return `true`, then `rfind()` returns [`Some(element)`]. If they all return
238+
/// `false`, it returns [`None`].
239+
///
240+
/// `rfind()` is short-circuiting; in other words, it will stop processing
241+
/// as soon as the closure returns `true`.
242+
///
243+
/// Because `rfind()` takes a reference, and many iterators iterate over
244+
/// references, this leads to a possibly confusing situation where the
245+
/// argument is a double reference. You can see this effect in the
246+
/// examples below, with `&&x`.
247+
///
248+
/// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
249+
/// [`None`]: ../../std/option/enum.Option.html#variant.None
250+
///
251+
/// # Examples
252+
///
253+
/// Basic usage:
254+
///
255+
/// ```
256+
/// let a = [1, 2, 3];
257+
///
258+
/// assert_eq!(a.iter().rfind(|&&x| x == 2), Some(&2));
259+
///
260+
/// assert_eq!(a.iter().rfind(|&&x| x == 5), None);
261+
/// ```
262+
///
263+
/// Stopping at the first `true`:
264+
///
265+
/// ```
266+
/// let a = [1, 2, 3];
267+
///
268+
/// let mut iter = a.iter();
269+
///
270+
/// assert_eq!(iter.rfind(|&&x| x == 2), Some(&2));
271+
///
272+
/// // we can still use `iter`, as there are more elements.
273+
/// assert_eq!(iter.next_back(), Some(&1));
274+
/// ```
275+
#[inline]
276+
#[stable(feature = "iter_rfind", since = "1.27.0")]
277+
fn rfind<P>(&mut self, mut predicate: P) -> Option<Self::Item>
278+
where
279+
Self: Sized,
280+
P: FnMut(&Self::Item) -> bool
281+
{
282+
self.try_rfold((), move |(), x| {
283+
if predicate(&x) { LoopState::Break(x) }
284+
else { LoopState::Continue(()) }
285+
}).break_value()
286+
}
287+
}
288+
289+
#[stable(feature = "rust1", since = "1.0.0")]
290+
impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
291+
fn next_back(&mut self) -> Option<I::Item> {
292+
(**self).next_back()
293+
}
294+
fn nth_back(&mut self, n: usize) -> Option<I::Item> {
295+
(**self).nth_back(n)
296+
}
297+
}

0 commit comments

Comments
 (0)