Skip to content

Commit d17aae5

Browse files
committed
Forward nth(), nth_back() and last() in exhaust::Iter.
1 parent a91464c commit d17aae5

3 files changed

Lines changed: 45 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
* Iterators for several standard library enums now implement `ExactSizeIterator`.
88
* `NonZero` iterators now have an improved but not perfect `size_hint()`.
9+
* `exhaust::Iter` now forwards `nth()`, `nth_back()`, and `last()` to the underlying iterator,
10+
which may improve performance.
911

1012
### Fixed
1113

src/lib.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,17 @@ impl<T: Exhaust> Iterator for Iter<T> {
411411
f(state, T::from_factory(item_factory))
412412
})
413413
}
414+
415+
// Ideally we would forward `try_fold()`, but that is not possible until the `Try` trait
416+
// is stabilized.
417+
418+
fn nth(&mut self, n: usize) -> Option<Self::Item> {
419+
self.0.nth(n).map(T::from_factory)
420+
}
421+
422+
fn last(self) -> Option<Self::Item> {
423+
self.0.last().map(T::from_factory)
424+
}
414425
}
415426

416427
impl<T: Exhaust<Iter: DoubleEndedIterator>> DoubleEndedIterator for Iter<T> {
@@ -427,6 +438,10 @@ impl<T: Exhaust<Iter: DoubleEndedIterator>> DoubleEndedIterator for Iter<T> {
427438
f(state, T::from_factory(item_factory))
428439
})
429440
}
441+
442+
fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
443+
self.0.nth_back(n).map(T::from_factory)
444+
}
430445
}
431446

432447
impl<T: Exhaust> FusedIterator for Iter<T> {

tests/core_impls_and_misc/iter.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,31 @@ fn clone() {
1616
assert_eq!(it2.len(), 1);
1717
assert_eq!(it2.next(), Some(true));
1818
}
19+
20+
#[test]
21+
fn nth() {
22+
let mut it = exhaust::Iter::<u8>::default();
23+
assert_eq!(it.nth(100), Some(100));
24+
assert_eq!(it.next(), Some(101));
25+
assert_eq!(it.nth(1000), None);
26+
}
27+
28+
#[test]
29+
fn nth_back() {
30+
let mut it = exhaust::Iter::<u8>::default();
31+
assert_eq!(it.nth_back(10), Some(245));
32+
assert_eq!(it.next_back(), Some(244));
33+
assert_eq!(it.nth_back(1000), None);
34+
}
35+
36+
#[test]
37+
fn last_simple() {
38+
assert_eq!(exhaust::Iter::<u8>::default().last(), Some(255));
39+
}
40+
41+
#[test]
42+
fn last_mutated() {
43+
let mut it = exhaust::Iter::<u8>::default();
44+
it.next_back();
45+
assert_eq!(it.last(), Some(254));
46+
}

0 commit comments

Comments
 (0)