Skip to content

Commit

Permalink
Itertools::tail: return VecDeque rather than Vec
Browse files Browse the repository at this point in the history
`rotate_left` is more efficient on `VecDeque` than on a slice.
`VecDeque::from(vec)` is O(1) on recent rust.
Thanks to scottmcm!
  • Loading branch information
Philippe-Cholet committed Mar 15, 2024
1 parent 740a62a commit 7ca66fd
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 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,14 +3155,14 @@ 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(),
_ => {
Expand All @@ -3177,7 +3179,8 @@ pub trait Itertools: Iterator {
i + 1
}
});
// Respect the insertion order.
// Respect the insertion order, efficiently.
let mut data = VecDeque::from(data);
data.rotate_left(idx);
data
}
Expand Down

0 comments on commit 7ca66fd

Please sign in to comment.