@@ -840,6 +840,7 @@ pub trait ImmutableVector<'self, T> {
840
840
fn window_iter ( self , size : uint ) -> WindowIter < ' self , T > ;
841
841
fn chunk_iter ( self , size : uint ) -> ChunkIter < ' self , T > ;
842
842
843
+ fn get_opt ( & self , index : uint ) -> Option < & ' self T > ;
843
844
fn head ( & self ) -> & ' self T ;
844
845
fn head_opt ( & self ) -> Option < & ' self T > ;
845
846
fn tail ( & self ) -> & ' self [ T ] ;
@@ -1019,6 +1020,13 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
1019
1020
ChunkIter { v : self , size : size }
1020
1021
}
1021
1022
1023
+ /// Returns the element of a vector at the given index, or `None` if the
1024
+ /// index is out of bounds
1025
+ #[ inline]
1026
+ fn get_opt ( & self , index : uint ) -> Option < & ' self T > {
1027
+ if index < self . len ( ) { Some ( & self [ index] ) } else { None }
1028
+ }
1029
+
1022
1030
/// Returns the first element of a vector, failing if the vector is empty.
1023
1031
#[ inline]
1024
1032
fn head ( & self ) -> & ' self T {
@@ -2574,6 +2582,16 @@ mod tests {
2574
2582
assert_eq ! ( v2. len( ) , 2 ) ;
2575
2583
}
2576
2584
2585
+ #[ test]
2586
+ fn test_get_opt ( ) {
2587
+ let mut a = ~[ 11 ] ;
2588
+ assert_eq ! ( a. get_opt( 1 ) , None ) ;
2589
+ a = ~[ 11 , 12 ] ;
2590
+ assert_eq ! ( a. get_opt( 1 ) . unwrap( ) , & 12 ) ;
2591
+ a = ~[ 11 , 12 , 13 ] ;
2592
+ assert_eq ! ( a. get_opt( 1 ) . unwrap( ) , & 12 ) ;
2593
+ }
2594
+
2577
2595
#[ test]
2578
2596
fn test_head ( ) {
2579
2597
let mut a = ~[ 11 ] ;
0 commit comments