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 14, 2024
1 parent 6168c5c commit 1d0a11e
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,30 +3155,23 @@ 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(),
_ => {
let mut iter = self.fuse();
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
}
}
Expand Down

0 comments on commit 1d0a11e

Please sign in to comment.