Skip to content

Commit

Permalink
added get_mut() for [T]
Browse files Browse the repository at this point in the history
  • Loading branch information
bachm authored and bachm committed Jun 13, 2014
1 parent 5d9bceb commit 78053f0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/libcollections/slice.rs
Expand Up @@ -2034,6 +2034,16 @@ mod tests {
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];
Expand Down
8 changes: 8 additions & 0 deletions src/libcore/slice.rs
Expand Up @@ -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];
Expand Down Expand Up @@ -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 }

Expand Down

5 comments on commit 78053f0

@bors
Copy link
Contributor

@bors bors commented on 78053f0 Jun 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bors
Copy link
Contributor

@bors bors commented on 78053f0 Jun 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merging bachm/rust/master = 78053f0 into auto

@bors
Copy link
Contributor

@bors bors commented on 78053f0 Jun 13, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bachm/rust/master = 78053f0 merged ok, testing candidate = 3851d68

@bors
Copy link
Contributor

@bors bors commented on 78053f0 Jun 14, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fast-forwarding master to auto = 3851d68

Please sign in to comment.