@@ -350,6 +350,31 @@ impl<T> CircularQueue<T> {
350
350
let ( a, b) = self . data . split_at_mut ( self . insertion_index ) ;
351
351
b. iter_mut ( ) . chain ( a. iter_mut ( ) )
352
352
}
353
+
354
+ /// Converts the queue into a `Vec<T>` going from the most recently pushed items to the oldest
355
+ /// ones.
356
+ ///
357
+ /// # Examples
358
+ ///
359
+ /// ```
360
+ /// use circular_queue::CircularQueue;
361
+ ///
362
+ /// let mut queue = CircularQueue::with_capacity(3);
363
+ /// queue.push(1);
364
+ /// queue.push(2);
365
+ /// queue.push(3);
366
+ /// queue.push(4);
367
+ ///
368
+ /// let v = queue.into_vec();
369
+ ///
370
+ /// assert_eq!(v, vec![4, 3, 2]);
371
+ /// ```
372
+ #[ inline]
373
+ pub fn into_vec ( mut self ) -> Vec < T > {
374
+ self . data [ self . insertion_index ..] . reverse ( ) ; // Reverse the upper part.
375
+ self . data [ ..self . insertion_index ] . reverse ( ) ; // Reverse the lower part.
376
+ self . data
377
+ }
353
378
}
354
379
355
380
impl < T : PartialEq > PartialEq for CircularQueue < T > {
@@ -361,9 +386,19 @@ impl<T: PartialEq> PartialEq for CircularQueue<T> {
361
386
362
387
impl < T : Eq > Eq for CircularQueue < T > { }
363
388
389
+ #[ cfg( has_relaxed_orphan_rule) ]
390
+ impl < T > From < CircularQueue < T > > for Vec < T > {
391
+ #[ inline]
392
+ fn from ( queue : CircularQueue < T > ) -> Self {
393
+ queue. into_vec ( )
394
+ }
395
+ }
396
+
364
397
#[ cfg( test) ]
365
398
mod tests {
366
399
use super :: * ;
400
+ #[ cfg( has_extern_crate_alloc) ]
401
+ use alloc:: vec;
367
402
368
403
#[ test]
369
404
fn zero_capacity ( ) {
@@ -628,4 +663,37 @@ mod tests {
628
663
q2. push ( ( ) ) ;
629
664
assert_eq ! ( q1, q2) ;
630
665
}
666
+
667
+ #[ test]
668
+ fn into_vec ( ) {
669
+ let mut q = CircularQueue :: with_capacity ( 4 ) ;
670
+ q. push ( 1 ) ;
671
+ q. push ( 2 ) ;
672
+ q. push ( 3 ) ;
673
+
674
+ let v = q. clone ( ) . into_vec ( ) ;
675
+ assert_eq ! ( v, vec![ 3 , 2 , 1 ] ) ;
676
+
677
+ q. push ( 4 ) ;
678
+ q. push ( 5 ) ;
679
+ let v = q. clone ( ) . into_vec ( ) ;
680
+ assert_eq ! ( v, vec![ 5 , 4 , 3 , 2 ] ) ;
681
+
682
+ q. push ( 6 ) ;
683
+ let v = q. into_vec ( ) ;
684
+ assert_eq ! ( v, vec![ 6 , 5 , 4 , 3 ] ) ;
685
+ }
686
+
687
+ #[ cfg( has_relaxed_orphan_rule) ]
688
+ #[ test]
689
+ fn vec_from ( ) {
690
+ let mut q = CircularQueue :: with_capacity ( 3 ) ;
691
+ q. push ( 1 ) ;
692
+ q. push ( 2 ) ;
693
+ q. push ( 3 ) ;
694
+ q. push ( 4 ) ;
695
+
696
+ let v = Vec :: from ( q) ;
697
+ assert_eq ! ( v, vec![ 4 , 3 , 2 ] ) ;
698
+ }
631
699
}
0 commit comments