Skip to content

Commit 3851d68

Browse files
committed
auto merge of #14750 : bachm/rust/master, r=alexcrichton
This adds the missing `get_mut` method to the `MutableVector` trait, and implements it for `&'a mut [T]`.
2 parents 63dcc9a + 78053f0 commit 3851d68

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/libcollections/slice.rs

+10
Original file line numberDiff line numberDiff line change
@@ -2034,6 +2034,16 @@ mod tests {
20342034
assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
20352035
}
20362036

2037+
#[test]
2038+
fn test_get_mut() {
2039+
let mut v = [0,1,2];
2040+
assert_eq!(v.get_mut(3), None);
2041+
v.get_mut(1).map(|e| *e = 7);
2042+
assert_eq!(v[1], 7);
2043+
let mut x = 2;
2044+
assert_eq!(v.get_mut(2), Some(&mut x));
2045+
}
2046+
20372047
#[test]
20382048
fn test_mut_chunks() {
20392049
let mut v = [0u8, 1, 2, 3, 4, 5, 6];

src/libcore/slice.rs

+8
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,9 @@ impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] {
717717
/// Extension methods for vectors such that their elements are
718718
/// mutable.
719719
pub trait MutableVector<'a, T> {
720+
/// Returns a mutable reference to the element at the given index,
721+
/// or `None` if the index is out of bounds
722+
fn get_mut(self, index: uint) -> Option<&'a mut T>;
720723
/// Work with `self` as a mut slice.
721724
/// Primarily intended for getting a &mut [T] from a [T, ..N].
722725
fn as_mut_slice(self) -> &'a mut [T];
@@ -920,6 +923,11 @@ pub trait MutableVector<'a, T> {
920923
}
921924

922925
impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
926+
#[inline]
927+
fn get_mut(self, index: uint) -> Option<&'a mut T> {
928+
if index < self.len() { Some(&mut self[index]) } else { None }
929+
}
930+
923931
#[inline]
924932
fn as_mut_slice(self) -> &'a mut [T] { self }
925933

0 commit comments

Comments
 (0)