From 21b24e148bd350c6f4945c35a7a30268ccf7d3cb Mon Sep 17 00:00:00 2001 From: Harry Marr Date: Sun, 29 Sep 2013 16:59:00 +0100 Subject: [PATCH] Add get_opt to std::vec --- src/libstd/vec.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 409aa919252..58dcc7d58b0 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -840,6 +840,7 @@ pub trait ImmutableVector<'self, T> { fn window_iter(self, size: uint) -> WindowIter<'self, T>; fn chunk_iter(self, size: uint) -> ChunkIter<'self, T>; + fn get_opt(&self, index: uint) -> Option<&'self T>; fn head(&self) -> &'self T; fn head_opt(&self) -> Option<&'self T>; fn tail(&self) -> &'self [T]; @@ -1019,6 +1020,13 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] { ChunkIter { v: self, size: size } } + /// Returns the element of a vector at the given index, or `None` if the + /// index is out of bounds + #[inline] + fn get_opt(&self, index: uint) -> Option<&'self T> { + if index < self.len() { Some(&self[index]) } else { None } + } + /// Returns the first element of a vector, failing if the vector is empty. #[inline] fn head(&self) -> &'self T { @@ -2574,6 +2582,16 @@ mod tests { assert_eq!(v2.len(), 2); } + #[test] + fn test_get_opt() { + let mut a = ~[11]; + assert_eq!(a.get_opt(1), None); + a = ~[11, 12]; + assert_eq!(a.get_opt(1).unwrap(), &12); + a = ~[11, 12, 13]; + assert_eq!(a.get_opt(1).unwrap(), &12); + } + #[test] fn test_head() { let mut a = ~[11];