Skip to content

Commit ea470e7

Browse files
New Itertools::tail
Note that for `n=0`, I consume the iterator with `for_each` to have a similar behavior to `n>0`. It could alternatively return a vector and not `VecIntoIter` but most of our methods do this (and immediately collect to a vector won't reallocate). I don't think we should write a non-lazy `head` method (`.take(n)` is a lazy one) but it would be easy: `.take(n).collect_vec().into_iter()`.
1 parent 8ed734b commit ea470e7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/lib.rs

+41
Original file line numberDiff line numberDiff line change
@@ -3133,6 +3133,47 @@ pub trait Itertools: Iterator {
31333133
self.k_largest_by(k, k_smallest::key_to_cmp(key))
31343134
}
31353135

3136+
/// Consumes the iterator and return an iterator of the last `n` elements.
3137+
///
3138+
/// It allocates up to `n` elements.
3139+
/// The iterator, if directly collected to a `Vec`, is converted
3140+
/// without any extra copying or allocation cost.
3141+
///
3142+
/// ```
3143+
/// use itertools::{assert_equal, Itertools};
3144+
///
3145+
/// let v = vec![5, 9, 8, 4, 2, 12, 0];
3146+
/// assert_equal(v.iter().tail(3), &[2, 12, 0]);
3147+
/// assert_equal(v.iter().tail(10), &v);
3148+
///
3149+
/// assert_equal((0..100).tail(10), 90..100);
3150+
/// ```
3151+
///
3152+
/// For double ended iterators without side-effects, you might prefer
3153+
/// `.rev().take(n).collect_vec().into_iter().rev()`
3154+
/// to have the same result without consuming the entire iterator.
3155+
#[cfg(feature = "use_alloc")]
3156+
fn tail(mut self, n: usize) -> VecIntoIter<Self::Item>
3157+
where
3158+
Self: Sized,
3159+
{
3160+
if n == 0 {
3161+
self.for_each(|_| {});
3162+
return Vec::new().into_iter();
3163+
}
3164+
let mut data: Vec<_> = self.by_ref().take(n).collect();
3165+
// If the iterator is not exhausted yet, update the data cyclically and
3166+
// finally rotate the data so that the order of the tail is respected.
3167+
if data.len() == n {
3168+
let idx = self.fold(0, |i, val| {
3169+
data[i] = val;
3170+
(i + 1) % n
3171+
});
3172+
data.rotate_left(idx);
3173+
}
3174+
data.into_iter()
3175+
}
3176+
31363177
/// Collect all iterator elements into one of two
31373178
/// partitions. Unlike [`Iterator::partition`], each partition may
31383179
/// have a distinct type.

tests/quick.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1949,4 +1949,9 @@ quickcheck! {
19491949
result_set.is_empty()
19501950
}
19511951
}
1952+
1953+
fn tail(v: Vec<i32>, n: u8) -> bool {
1954+
let n = n as usize;
1955+
itertools::equal(v.iter().tail(n), &v[v.len().saturating_sub(n)..])
1956+
}
19521957
}

0 commit comments

Comments
 (0)