]> git.lizzy.rs Git - rust.git/commitdiff
added get_mut() for [T]
authorbachm <Ab@vapor.com>
Sun, 8 Jun 2014 15:05:32 +0000 (17:05 +0200)
committerbachm <Ab@vapor.com>
Fri, 13 Jun 2014 07:55:36 +0000 (09:55 +0200)
src/libcollections/slice.rs
src/libcore/slice.rs

index 865da9eff136a1a6527965bb427ae0dcf104b04a..ff00ca58e8c7668b014105a3c0eaeb388bf37c36 100644 (file)
@@ -2034,6 +2034,16 @@ fn test_mut_splitator_rev() {
         assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
     }
 
+    #[test]
+    fn test_get_mut() {
+        let mut v = [0,1,2];
+        assert_eq!(v.get_mut(3), None);
+        v.get_mut(1).map(|e| *e = 7);
+        assert_eq!(v[1], 7);
+        let mut x = 2;
+        assert_eq!(v.get_mut(2), Some(&mut x));
+    }
+
     #[test]
     fn test_mut_chunks() {
         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
index d579d04489240abed234aaa410fc6d8f2948bc4e..bb24d53458c24044df6ebf82fdbcbb89a89ab03f 100644 (file)
@@ -717,6 +717,9 @@ fn bsearch_elem(&self, x: &T) -> Option<uint> {
 /// Extension methods for vectors such that their elements are
 /// mutable.
 pub trait MutableVector<'a, T> {
+    /// Returns a mutable reference to the element at the given index,
+    /// or `None` if the index is out of bounds
+    fn get_mut(self, index: uint) -> Option<&'a mut T>;
     /// Work with `self` as a mut slice.
     /// Primarily intended for getting a &mut [T] from a [T, ..N].
     fn as_mut_slice(self) -> &'a mut [T];
@@ -920,6 +923,11 @@ pub trait MutableVector<'a, T> {
 }
 
 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
+    #[inline]
+    fn get_mut(self, index: uint) -> Option<&'a mut T> {
+        if index < self.len() { Some(&mut self[index]) } else { None }
+    }
+
     #[inline]
     fn as_mut_slice(self) -> &'a mut [T] { self }