Skip to content

Add a mut_split() method for dividing one &mut [T] into two #7691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 11, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/libstd/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use sys;
use unstable::intrinsics;

/// Casts the value at `src` to U. The two types must have the same length.
/// Casts the value at `src` to U. The two types must have the same length.
#[cfg(target_word_size = "32")]
#[inline]
Expand Down
37 changes: 37 additions & 0 deletions src/libstd/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1671,6 +1671,15 @@ pub trait MutableVector<'self, T> {

fn swap(self, a: uint, b: uint);

/**
* Divides one `&mut` into two. The first will
* contain all indices from `0..mid` (excluding the index `mid`
* itself) and the second will contain all indices from
* `mid..len` (excluding the index `len` itself).
*/
fn mut_split(self, mid: uint) -> (&'self mut [T],
&'self mut [T]);

fn reverse(self);

/**
Expand Down Expand Up @@ -1708,6 +1717,15 @@ impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
}
}

#[inline]
fn mut_split(self, mid: uint) -> (&'self mut [T], &'self mut [T]) {
unsafe {
let len = self.len();
let self2: &'self mut [T] = cast::transmute_copy(&self);
(self.mut_slice(0, mid), self2.mut_slice(mid, len))
}
}

#[inline]
fn mut_iter(self) -> VecMutIterator<'self, T> {
unsafe {
Expand Down Expand Up @@ -3355,4 +3373,23 @@ mod tests {
v.push(1);
v.push(2);
}

#[test]
fn test_mut_split() {
let mut values = [1u8,2,3,4,5];
{
let (left, right) = values.mut_split(2);
assert_eq!(left.slice(0, left.len()), [1, 2]);
for left.mut_iter().advance |p| {
*p += 1;
}

assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
for right.mut_iter().advance |p| {
*p += 2;
}
}

assert_eq!(values, [2, 3, 5, 6, 7]);
}
}