From 9ee5ce221501cbafd8540586ec2904063b4448d6 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Wed, 10 Jul 2013 09:50:24 -0400 Subject: [PATCH] Add a `mut_split()` method for dividing one `&mut [T]` into two --- src/libstd/cast.rs | 1 - src/libstd/vec.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/libstd/cast.rs b/src/libstd/cast.rs index 30b6b030dba..50b5b2fcd29 100644 --- a/src/libstd/cast.rs +++ b/src/libstd/cast.rs @@ -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] diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 825dc4cc187..f8f4ea0be2c 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -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); /** @@ -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 { @@ -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]); + } }