@@ -55,7 +55,7 @@ extern crate core as std;
55
55
extern crate alloc;
56
56
57
57
#[ cfg( feature = "use_alloc" ) ]
58
- use alloc:: { string:: String , vec:: Vec } ;
58
+ use alloc:: { collections :: VecDeque , string:: String , vec:: Vec } ;
59
59
60
60
pub use either:: Either ;
61
61
@@ -72,6 +72,8 @@ use std::fmt::Write;
72
72
use std:: hash:: Hash ;
73
73
use std:: iter:: { once, IntoIterator } ;
74
74
#[ cfg( feature = "use_alloc" ) ]
75
+ type VecDequeIntoIter < T > = alloc:: collections:: vec_deque:: IntoIter < T > ;
76
+ #[ cfg( feature = "use_alloc" ) ]
75
77
type VecIntoIter < T > = alloc:: vec:: IntoIter < T > ;
76
78
use std:: iter:: FromIterator ;
77
79
@@ -3135,8 +3137,10 @@ pub trait Itertools: Iterator {
3135
3137
3136
3138
/// Consumes the iterator and return an iterator of the last `n` elements.
3137
3139
///
3138
- /// The iterator, if directly collected to a `Vec `, is converted
3140
+ /// The iterator, if directly collected to a `VecDeque `, is converted
3139
3141
/// without any extra copying or allocation cost.
3142
+ /// If directly collected to a `Vec`, it may need some data movement
3143
+ /// but no re-allocation.
3140
3144
///
3141
3145
/// ```
3142
3146
/// use itertools::{assert_equal, Itertools};
@@ -3154,20 +3158,22 @@ pub trait Itertools: Iterator {
3154
3158
/// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
3155
3159
/// without consuming the entire iterator.
3156
3160
#[ cfg( feature = "use_alloc" ) ]
3157
- fn tail ( self , n : usize ) -> VecIntoIter < Self :: Item >
3161
+ fn tail ( self , n : usize ) -> VecDequeIntoIter < Self :: Item >
3158
3162
where
3159
3163
Self : Sized ,
3160
3164
{
3161
3165
match n {
3162
3166
0 => {
3163
3167
self . last ( ) ;
3164
- Vec :: new ( )
3168
+ VecDeque :: new ( )
3165
3169
}
3166
3170
1 => self . last ( ) . into_iter ( ) . collect ( ) ,
3167
3171
_ => {
3168
3172
// Skip the starting part of the iterator if possible.
3169
3173
let ( low, _) = self . size_hint ( ) ;
3170
3174
let mut iter = self . fuse ( ) . skip ( low. saturating_sub ( n) ) ;
3175
+ // TODO: If VecDeque has a more efficient method than
3176
+ // `.pop_front();.push_back(val)` in the future then maybe revisit this.
3171
3177
let mut data: Vec < _ > = iter. by_ref ( ) . take ( n) . collect ( ) ;
3172
3178
// Update `data` cyclically.
3173
3179
let idx = iter. fold ( 0 , |i, val| {
@@ -3178,7 +3184,8 @@ pub trait Itertools: Iterator {
3178
3184
i + 1
3179
3185
}
3180
3186
} ) ;
3181
- // Respect the insertion order.
3187
+ // Respect the insertion order, efficiently.
3188
+ let mut data = VecDeque :: from ( data) ;
3182
3189
data. rotate_left ( idx) ;
3183
3190
data
3184
3191
}
0 commit comments