Skip to content

Commit

Permalink
Itertools::tail with VecDeque rather than Vec
Browse files Browse the repository at this point in the history
  • Loading branch information
Philippe-Cholet committed Mar 15, 2024
1 parent 740a62a commit d61185a
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ extern crate core as std;
extern crate alloc;

#[cfg(feature = "use_alloc")]
use alloc::{string::String, vec::Vec};
use alloc::{collections::VecDeque, string::String, vec::Vec};

pub use either::Either;

Expand All @@ -72,6 +72,8 @@ use std::fmt::Write;
use std::hash::Hash;
use std::iter::{once, IntoIterator};
#[cfg(feature = "use_alloc")]
type VecDequeIntoIter<T> = alloc::collections::vec_deque::IntoIter<T>;
#[cfg(feature = "use_alloc")]
type VecIntoIter<T> = alloc::vec::IntoIter<T>;
use std::iter::FromIterator;

Expand Down Expand Up @@ -3153,32 +3155,25 @@ pub trait Itertools: Iterator {
/// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
/// without consuming the entire iterator.
#[cfg(feature = "use_alloc")]
fn tail(self, n: usize) -> VecIntoIter<Self::Item>
fn tail(self, n: usize) -> VecDequeIntoIter<Self::Item>
where
Self: Sized,
{
match n {
0 => {
self.last();
Vec::new()
VecDeque::new()
}
1 => self.last().into_iter().collect(),
_ => {
// Skip the starting part of iterator if possible.
let (low, _) = self.size_hint();
let mut iter = self.fuse().skip(low.saturating_sub(n));
let mut data: Vec<_> = iter.by_ref().take(n).collect();
// Update `data` cyclically.
let idx = iter.fold(0, |i, val| {
data[i] = val;
if i + 1 == n {
0
} else {
i + 1
}
let mut data: VecDeque<_> = iter.by_ref().take(n).collect();
iter.for_each(|value| {
data.pop_front();
data.push_back(value);
});
// Respect the insertion order.
data.rotate_left(idx);
data
}

Check warning on line 3178 in src/lib.rs

View check run for this annotation

Codecov / codecov/patch

src/lib.rs#L3178

Added line #L3178 was not covered by tests
}
Expand Down

0 comments on commit d61185a

Please sign in to comment.