@@ -1093,6 +1093,7 @@ pub trait OwnedVector<T> {
1093
1093
fn pop( & mut self ) -> T ;
1094
1094
fn pop_opt( & mut self ) -> Option <T >;
1095
1095
fn shift( & mut self ) -> T ;
1096
+ fn shift_opt( & mut self ) -> Option <T >;
1096
1097
fn unshift( & mut self , x: T ) ;
1097
1098
fn insert( & mut self , i: uint, x: T ) ;
1098
1099
fn remove( & mut self , i: uint) -> T ;
@@ -1305,20 +1306,26 @@ impl<T> OwnedVector<T> for ~[T] {
1305
1306
}
1306
1307
1307
1308
/// Removes the first element from a vector and return it
1309
+ #[ inline]
1308
1310
fn shift( & mut self ) -> T {
1309
- unsafe {
1310
- assert!( !self . is_empty( ) ) ;
1311
-
1312
- if self . len( ) == 1 { return self . pop( ) }
1311
+ self . shift_opt( ) . expect( "shift: empty vector")
1312
+ }
1313
1313
1314
- if self . len( ) == 2 {
1315
- let last = self . pop( ) ;
1316
- let first = self . pop( ) ;
1317
- self . push( last) ;
1318
- return first;
1319
- }
1314
+ /// Removes the first element from a vector and return it, or `None` if it is empty
1315
+ fn shift_opt( & mut self ) -> Option <T > {
1316
+ unsafe {
1317
+ let ln = match self . len( ) {
1318
+ 0 => return None ,
1319
+ 1 => return self . pop_opt( ) ,
1320
+ 2 => {
1321
+ let last = self . pop( ) ;
1322
+ let first = self . pop_opt( ) ;
1323
+ self . push( last) ;
1324
+ return first;
1325
+ }
1326
+ x => x
1327
+ } ;
1320
1328
1321
- let ln = self . len( ) ;
1322
1329
let next_ln = self . len( ) - 1 ;
1323
1330
1324
1331
// Save the last element. We're going to overwrite its position
@@ -1354,7 +1361,7 @@ impl<T> OwnedVector<T> for ~[T] {
1354
1361
let vp = raw :: to_mut_ptr( * self ) ;
1355
1362
let vp = ptr:: mut_offset( vp, next_ln - 1 ) ;
1356
1363
1357
- ptr:: replace_ptr( vp, work_elt)
1364
+ Some ( ptr:: replace_ptr( vp, work_elt) )
1358
1365
}
1359
1366
}
1360
1367
@@ -2763,6 +2770,27 @@ mod tests {
2763
2770
assert_eq ! ( [ & [ 1 ] , & [ 2 ] , & [ 3 ] ] . connect_vec( & 0 ) , ~[ 1 , 0 , 2 , 0 , 3 ] ) ;
2764
2771
}
2765
2772
2773
+ #[ test]
2774
+ fn test_shift ( ) {
2775
+ let mut x = ~[ 1 , 2 , 3 ] ;
2776
+ assert_eq ! ( x. shift( ) , 1 ) ;
2777
+ assert_eq ! ( & x, & ~[ 2 , 3 ] ) ;
2778
+ assert_eq ! ( x. shift( ) , 2 ) ;
2779
+ assert_eq ! ( x. shift( ) , 3 ) ;
2780
+ assert_eq ! ( x. len( ) , 0 ) ;
2781
+ }
2782
+
2783
+ #[ test]
2784
+ fn test_shift_opt ( ) {
2785
+ let mut x = ~[ 1 , 2 , 3 ] ;
2786
+ assert_eq ! ( x. shift_opt( ) , Some ( 1 ) ) ;
2787
+ assert_eq ! ( & x, & ~[ 2 , 3 ] ) ;
2788
+ assert_eq ! ( x. shift_opt( ) , Some ( 2 ) ) ;
2789
+ assert_eq ! ( x. shift_opt( ) , Some ( 3 ) ) ;
2790
+ assert_eq ! ( x. shift_opt( ) , None ) ;
2791
+ assert_eq ! ( x. len( ) , 0 ) ;
2792
+ }
2793
+
2766
2794
#[ test]
2767
2795
fn test_unshift ( ) {
2768
2796
let mut x = ~[ 1 , 2 , 3 ] ;
0 commit comments