@@ -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
@@ -3136,8 +3138,10 @@ pub trait Itertools: Iterator {
3136
3138
/// Consumes the iterator and return an iterator of the last `n` elements.
3137
3139
///
3138
3140
/// It allocates up to `n` elements.
3139
- /// The iterator, if directly collected to a `Vec `, is converted
3141
+ /// The iterator, if directly collected to a `VecDeque `, is converted
3140
3142
/// without any extra copying or allocation cost.
3143
+ /// If directly collected to a `Vec`, it may need some data movement
3144
+ /// but no re-allocation.
3141
3145
///
3142
3146
/// ```
3143
3147
/// use itertools::{assert_equal, Itertools};
@@ -3155,14 +3159,14 @@ pub trait Itertools: Iterator {
3155
3159
/// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
3156
3160
/// without consuming the entire iterator.
3157
3161
#[ cfg( feature = "use_alloc" ) ]
3158
- fn tail ( self , n : usize ) -> VecIntoIter < Self :: Item >
3162
+ fn tail ( self , n : usize ) -> VecDequeIntoIter < Self :: Item >
3159
3163
where
3160
3164
Self : Sized ,
3161
3165
{
3162
3166
match n {
3163
3167
0 => {
3164
3168
self . last ( ) ;
3165
- Vec :: new ( )
3169
+ VecDeque :: new ( )
3166
3170
}
3167
3171
1 => self . last ( ) . into_iter ( ) . collect ( ) ,
3168
3172
_ => {
@@ -3179,7 +3183,8 @@ pub trait Itertools: Iterator {
3179
3183
i + 1
3180
3184
}
3181
3185
} ) ;
3182
- // Respect the insertion order.
3186
+ // Respect the insertion order, efficiently.
3187
+ let mut data = VecDeque :: from ( data) ;
3183
3188
data. rotate_left ( idx) ;
3184
3189
data
3185
3190
}
0 commit comments