1414
1515use core:: prelude:: * ;
1616
17+ use alloc:: boxed:: Box ;
1718use alloc:: heap:: { EMPTY , allocate, reallocate, deallocate} ;
1819use core:: cmp:: max;
1920use core:: default:: Default ;
@@ -757,6 +758,20 @@ impl<T> Vec<T> {
757758 }
758759 }
759760
761+ /// Convert the vector into Box<[T]>.
762+ ///
763+ /// Note that this will drop any excess capacity. Calling this and converting back to a vector
764+ /// with `into_vec()` is equivalent to calling `shrink_to_fit()`.
765+ #[ experimental]
766+ pub fn into_boxed_slice ( mut self ) -> Box < [ T ] > {
767+ self . shrink_to_fit ( ) ;
768+ unsafe {
769+ let xs: Box < [ T ] > = mem:: transmute ( self . as_mut_slice ( ) ) ;
770+ mem:: forget ( self ) ;
771+ xs
772+ }
773+ }
774+
760775 /// Deprecated, call `push` instead
761776 #[ inline]
762777 #[ deprecated = "call .push() instead" ]
@@ -1734,7 +1749,7 @@ impl<T> MutableSeq<T> for Vec<T> {
17341749 let size = max ( old_size, 2 * mem:: size_of :: < T > ( ) ) * 2 ;
17351750 if old_size > size { fail ! ( "capacity overflow" ) }
17361751 unsafe {
1737- self . ptr = alloc_or_realloc ( self . ptr , self . cap * mem :: size_of :: < T > ( ) , size) ;
1752+ self . ptr = alloc_or_realloc ( self . ptr , old_size , size) ;
17381753 }
17391754 self . cap = max ( self . cap , 2 ) * 2 ;
17401755 }
@@ -1758,7 +1773,6 @@ impl<T> MutableSeq<T> for Vec<T> {
17581773 }
17591774 }
17601775 }
1761-
17621776}
17631777
17641778/// An iterator that moves out of a vector.
@@ -2632,6 +2646,13 @@ mod tests {
26322646 assert ! ( vec2 == vec!( ( ) , ( ) , ( ) ) ) ;
26332647 }
26342648
2649+ #[ test]
2650+ fn test_into_boxed_slice ( ) {
2651+ let xs = vec ! [ 1 u, 2 , 3 ] ;
2652+ let ys = xs. into_boxed_slice ( ) ;
2653+ assert_eq ! ( ys. as_slice( ) , [ 1 u, 2 , 3 ] . as_slice( ) ) ;
2654+ }
2655+
26352656 #[ bench]
26362657 fn bench_new ( b : & mut Bencher ) {
26372658 b. iter ( || {
0 commit comments