Skip to content

Commit 2071e2a

Browse files
New Itertools::tail
1 parent 8ed734b commit 2071e2a

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/lib.rs

+49
Original file line numberDiff line numberDiff line change
@@ -3133,6 +3133,55 @@ 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+
/// The iterator, if directly collected to a `Vec`, is converted
3139+
/// without any extra copying or allocation cost.
3140+
///
3141+
/// ```
3142+
/// use itertools::{assert_equal, Itertools};
3143+
///
3144+
/// let v = vec![5, 9, 8, 4, 2, 12, 0];
3145+
/// assert_equal(v.iter().tail(3), &[2, 12, 0]);
3146+
/// assert_equal(v.iter().tail(10), &v);
3147+
///
3148+
/// assert_equal((0..100).tail(10), 90..100);
3149+
/// ```
3150+
///
3151+
/// For double ended iterators without side-effects, you might prefer
3152+
/// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
3153+
/// without consuming the entire iterator.
3154+
#[cfg(feature = "use_alloc")]
3155+
fn tail(self, n: usize) -> VecIntoIter<Self::Item>
3156+
where
3157+
Self: Sized,
3158+
{
3159+
match n {
3160+
0 => {
3161+
self.last();
3162+
Vec::new()
3163+
}
3164+
1 => self.last().into_iter().collect(),
3165+
_ => {
3166+
let mut iter = self.fuse();
3167+
let mut data: Vec<_> = iter.by_ref().take(n).collect();
3168+
// Update `data` cyclically.
3169+
let idx = iter.fold(0, |i, val| {
3170+
data[i] = val;
3171+
if i + 1 == n {
3172+
0
3173+
} else {
3174+
i + 1
3175+
}
3176+
});
3177+
// Respect the insertion order.
3178+
data.rotate_left(idx);
3179+
data
3180+
}
3181+
}
3182+
.into_iter()
3183+
}
3184+
31363185
/// Collect all iterator elements into one of two
31373186
/// partitions. Unlike [`Iterator::partition`], each partition may
31383187
/// 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)