@@ -3133,6 +3133,56 @@ pub trait Itertools: Iterator {
3133
3133
self . k_largest_by ( k, k_smallest:: key_to_cmp ( key) )
3134
3134
}
3135
3135
3136
+ /// Consumes the iterator and return an iterator of the last `n` elements.
3137
+ ///
3138
+ /// It allocates up to `n` elements.
3139
+ /// The iterator, if directly collected to a `Vec`, is converted
3140
+ /// without any extra copying or allocation cost.
3141
+ ///
3142
+ /// ```
3143
+ /// use itertools::{assert_equal, Itertools};
3144
+ ///
3145
+ /// let v = vec![5, 9, 8, 4, 2, 12, 0];
3146
+ /// assert_equal(v.iter().tail(3), &[2, 12, 0]);
3147
+ /// assert_equal(v.iter().tail(10), &v);
3148
+ ///
3149
+ /// assert_equal((0..100).tail(10), 90..100);
3150
+ /// ```
3151
+ ///
3152
+ /// For double ended iterators without side-effects, you might prefer
3153
+ /// `.rev().take(n).rev()` to have a similar result (lazy and non-allocating)
3154
+ /// without consuming the entire iterator.
3155
+ #[ cfg( feature = "use_alloc" ) ]
3156
+ fn tail ( self , n : usize ) -> VecIntoIter < Self :: Item >
3157
+ where
3158
+ Self : Sized ,
3159
+ {
3160
+ match n {
3161
+ 0 => {
3162
+ self . last ( ) ;
3163
+ Vec :: new ( )
3164
+ }
3165
+ 1 => self . last ( ) . into_iter ( ) . collect ( ) ,
3166
+ _ => {
3167
+ let mut iter = self . fuse ( ) ;
3168
+ let mut data: Vec < _ > = iter. by_ref ( ) . take ( n) . collect ( ) ;
3169
+ // Update `data` cyclically.
3170
+ let idx = iter. fold ( 0 , |i, val| {
3171
+ data[ i] = val;
3172
+ if i + 1 == n {
3173
+ 0
3174
+ } else {
3175
+ i + 1
3176
+ }
3177
+ } ) ;
3178
+ // Respect the insertion order.
3179
+ data. rotate_left ( idx) ;
3180
+ data
3181
+ }
3182
+ }
3183
+ . into_iter ( )
3184
+ }
3185
+
3136
3186
/// Collect all iterator elements into one of two
3137
3187
/// partitions. Unlike [`Iterator::partition`], each partition may
3138
3188
/// have a distinct type.
0 commit comments