Skip to content

Commit 7ca66fd

Browse files
Itertools::tail: return VecDeque rather than Vec
`rotate_left` is more efficient on `VecDeque` than on a slice. `VecDeque::from(vec)` is O(1) on recent rust. Thanks to scottmcm!
1 parent 740a62a commit 7ca66fd

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

src/lib.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ extern crate core as std;
5555
extern crate alloc;
5656

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

6060
pub use either::Either;
6161

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

@@ -3153,14 +3155,14 @@ pub trait Itertools: Iterator {
31533155
/// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
31543156
/// without consuming the entire iterator.
31553157
#[cfg(feature = "use_alloc")]
3156-
fn tail(self, n: usize) -> VecIntoIter<Self::Item>
3158+
fn tail(self, n: usize) -> VecDequeIntoIter<Self::Item>
31573159
where
31583160
Self: Sized,
31593161
{
31603162
match n {
31613163
0 => {
31623164
self.last();
3163-
Vec::new()
3165+
VecDeque::new()
31643166
}
31653167
1 => self.last().into_iter().collect(),
31663168
_ => {
@@ -3177,7 +3179,8 @@ pub trait Itertools: Iterator {
31773179
i + 1
31783180
}
31793181
});
3180-
// Respect the insertion order.
3182+
// Respect the insertion order, efficiently.
3183+
let mut data = VecDeque::from(data);
31813184
data.rotate_left(idx);
31823185
data
31833186
}

0 commit comments

Comments
 (0)