diff options
| author | bachm <Ab@vapor.com> | 2014-06-08 17:05:32 +0200 |
|---|---|---|
| committer | bachm <Ab@vapor.com> | 2014-06-13 09:55:36 +0200 |
| commit | 78053f08253de974ea6e8a6ee8bb1f4c082daeab (patch) | |
| tree | ba6d35bc8bcd5d990b075239a93705f7789e66ff | |
| parent | 5d9bceb1440b6bb5759bc3c1e5ad2170a199d0ce (diff) | |
| download | rust-78053f08253de974ea6e8a6ee8bb1f4c082daeab.tar.gz rust-78053f08253de974ea6e8a6ee8bb1f4c082daeab.zip | |
added get_mut() for [T]
| -rw-r--r-- | src/libcollections/slice.rs | 10 | ||||
| -rw-r--r-- | src/libcore/slice.rs | 8 |
2 files changed, 18 insertions, 0 deletions
diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 865da9eff13..ff00ca58e8c 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -2035,6 +2035,16 @@ mod tests { } #[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]; for (i, chunk) in v.mut_chunks(3).enumerate() { diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index d579d044892..bb24d53458c 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -717,6 +717,9 @@ impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] { /// 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]; @@ -921,6 +924,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 } fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] { |
