about summary refs log tree commit diff
diff options
context:
space:
mode:
authorHarry Marr <harry.marr@gmail.com>2013-09-29 16:59:00 +0100
committerHarry Marr <harry.marr@gmail.com>2013-09-29 16:59:00 +0100
commit21b24e148bd350c6f4945c35a7a30268ccf7d3cb (patch)
tree8827da4f4882129e40d3d0ad57352bc98dd18fca
parent9883a6250b61eb4bb715684f9b25304f4f0d437e (diff)
downloadrust-21b24e148bd350c6f4945c35a7a30268ccf7d3cb.tar.gz
rust-21b24e148bd350c6f4945c35a7a30268ccf7d3cb.zip
Add get_opt to std::vec
-rw-r--r--src/libstd/vec.rs18
1 files changed, 18 insertions, 0 deletions
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 {
@@ -2575,6 +2583,16 @@ mod tests {
     }
 
     #[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];
         assert_eq!(a.head(), &11);