@@ -55,7 +55,7 @@ extern crate core as std;
5555extern 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
6060pub use either:: Either ;
6161
@@ -72,6 +72,8 @@ use std::fmt::Write;
7272use std:: hash:: Hash ;
7373use std:: iter:: { once, IntoIterator } ;
7474#[ cfg( feature = "use_alloc" ) ]
75+ type VecDequeIntoIter < T > = alloc:: collections:: vec_deque:: IntoIter < T > ;
76+ #[ cfg( feature = "use_alloc" ) ]
7577type VecIntoIter < T > = alloc:: vec:: IntoIter < T > ;
7678use std:: iter:: FromIterator ;
7779
@@ -3135,8 +3137,10 @@ pub trait Itertools: Iterator {
31353137
31363138 /// Consumes the iterator and return an iterator of the last `n` elements.
31373139 ///
3138- /// The iterator, if directly collected to a `Vec `, is converted
3140+ /// The iterator, if directly collected to a `VecDeque `, is converted
31393141 /// 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.
31403144 ///
31413145 /// ```
31423146 /// use itertools::{assert_equal, Itertools};
@@ -3154,20 +3158,22 @@ pub trait Itertools: Iterator {
31543158 /// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
31553159 /// without consuming the entire iterator.
31563160 #[ cfg( feature = "use_alloc" ) ]
3157- fn tail ( self , n : usize ) -> VecIntoIter < Self :: Item >
3161+ fn tail ( self , n : usize ) -> VecDequeIntoIter < Self :: Item >
31583162 where
31593163 Self : Sized ,
31603164 {
31613165 match n {
31623166 0 => {
31633167 self . last ( ) ;
3164- Vec :: new ( )
3168+ VecDeque :: new ( )
31653169 }
31663170 1 => self . last ( ) . into_iter ( ) . collect ( ) ,
31673171 _ => {
31683172 // Skip the starting part of the iterator if possible.
31693173 let ( low, _) = self . size_hint ( ) ;
31703174 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.
31713177 let mut data: Vec < _ > = iter. by_ref ( ) . take ( n) . collect ( ) ;
31723178 // Update `data` cyclically.
31733179 let idx = iter. fold ( 0 , |i, val| {
@@ -3178,7 +3184,8 @@ pub trait Itertools: Iterator {
31783184 i + 1
31793185 }
31803186 } ) ;
3181- // Respect the insertion order.
3187+ // Respect the insertion order, efficiently.
3188+ let mut data = VecDeque :: from ( data) ;
31823189 data. rotate_left ( idx) ;
31833190 data
31843191 }
0 commit comments