1
Fork 0

auto merge of #17494 : aturon/rust/stabilize-mutable-slices, r=alexcrichton

This commit is another in the series of vector slice API stabilization. The focus here is the *mutable* slice API.

Largely, this API inherits the stability attributes [previously assigned](rust-lang#16332) to the analogous methods on immutable slides. It also adds comments to a few `unstable` attributes that were previously missing them.

In addition, the commit adds several `_mut` variants of APIs that were missing:

- `init_mut`
- `head_mut`
- `tail_mut`
- `splitn_mut`
- `rsplitn_mut`

Some of the unsafe APIs -- `unsafe_set`, `init_elem`, and `copy_memory` -- were deprecated in favor of working through `as_mut_ptr`, to simplify the API surface.

Due to deprecations, this is a:

[breaking-change]
This commit is contained in:
bors 2014-09-26 11:44:01 +00:00
commit 5d653c17a6
3 changed files with 348 additions and 243 deletions

View file

@ -844,6 +844,7 @@ mod tests {
} }
#[test] #[test]
#[allow(deprecated)]
fn test_append() { fn test_append() {
{ {
let mut m = DList::new(); let mut m = DList::new();

View file

@ -850,6 +850,16 @@ mod tests {
assert_eq!(a.as_slice().head().unwrap(), &11); assert_eq!(a.as_slice().head().unwrap(), &11);
} }
#[test]
fn test_head_mut() {
let mut a = vec![];
assert_eq!(a.as_mut_slice().head_mut(), None);
a = vec![11i];
assert_eq!(*a.as_mut_slice().head_mut().unwrap(), 11);
a = vec![11i, 12];
assert_eq!(*a.as_mut_slice().head_mut().unwrap(), 11);
}
#[test] #[test]
fn test_tail() { fn test_tail() {
let mut a = vec![11i]; let mut a = vec![11i];
@ -860,6 +870,16 @@ mod tests {
assert_eq!(a.tail(), b); assert_eq!(a.tail(), b);
} }
#[test]
fn test_tail_mut() {
let mut a = vec![11i];
let b: &mut [int] = &mut [];
assert!(a.as_mut_slice().tail_mut() == b);
a = vec![11i, 12];
let b: &mut [int] = &mut [12];
assert!(a.as_mut_slice().tail_mut() == b);
}
#[test] #[test]
#[should_fail] #[should_fail]
fn test_tail_empty() { fn test_tail_empty() {
@ -867,15 +887,22 @@ mod tests {
a.tail(); a.tail();
} }
#[test]
#[should_fail]
fn test_tail_mut_empty() {
let mut a: Vec<int> = vec![];
a.as_mut_slice().tail_mut();
}
#[test] #[test]
#[allow(deprecated)] #[allow(deprecated)]
fn test_tailn() { fn test_tailn() {
let mut a = vec![11i, 12, 13]; let mut a = vec![11i, 12, 13];
let b: &[int] = &[11, 12, 13]; let b: &mut [int] = &mut [11, 12, 13];
assert_eq!(a.tailn(0), b); assert!(a.tailn(0) == b);
a = vec![11i, 12, 13]; a = vec![11i, 12, 13];
let b: &[int] = &[13]; let b: &mut [int] = &mut [13];
assert_eq!(a.tailn(2), b); assert!(a.tailn(2) == b);
} }
#[test] #[test]
@ -896,6 +923,16 @@ mod tests {
assert_eq!(a.init(), b); assert_eq!(a.init(), b);
} }
#[test]
fn test_init_mut() {
let mut a = vec![11i];
let b: &mut [int] = &mut [];
assert!(a.as_mut_slice().init_mut() == b);
a = vec![11i, 12];
let b: &mut [int] = &mut [11];
assert!(a.as_mut_slice().init_mut() == b);
}
#[test] #[test]
#[should_fail] #[should_fail]
fn test_init_empty() { fn test_init_empty() {
@ -903,6 +940,13 @@ mod tests {
a.init(); a.init();
} }
#[test]
#[should_fail]
fn test_init_mut_empty() {
let mut a: Vec<int> = vec![];
a.as_mut_slice().init_mut();
}
#[test] #[test]
#[allow(deprecated)] #[allow(deprecated)]
fn test_initn() { fn test_initn() {
@ -932,6 +976,16 @@ mod tests {
assert_eq!(a.as_slice().last().unwrap(), &12); assert_eq!(a.as_slice().last().unwrap(), &12);
} }
#[test]
fn test_last_mut() {
let mut a = vec![];
assert_eq!(a.as_mut_slice().last_mut(), None);
a = vec![11i];
assert_eq!(*a.as_mut_slice().last_mut().unwrap(), 11);
a = vec![11i, 12];
assert_eq!(*a.as_mut_slice().last_mut().unwrap(), 12);
}
#[test] #[test]
fn test_slice() { fn test_slice() {
// Test fixed length vector. // Test fixed length vector.
@ -1077,6 +1131,7 @@ mod tests {
} }
#[test] #[test]
#[allow(deprecated)]
fn test_grow_set() { fn test_grow_set() {
let mut v = vec![1i, 2, 3]; let mut v = vec![1i, 2, 3];
v.grow_set(4u, &4, 5); v.grow_set(4u, &4, 5);
@ -1610,6 +1665,7 @@ mod tests {
#[test] #[test]
#[should_fail] #[should_fail]
#[allow(deprecated)]
fn test_copy_memory_oob() { fn test_copy_memory_oob() {
unsafe { unsafe {
let mut a = [1i, 2, 3, 4]; let mut a = [1i, 2, 3, 4];
@ -1793,6 +1849,26 @@ mod tests {
assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits); assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), splits);
} }
#[test]
fn test_splitnator_mut() {
let xs = &mut [1i,2,3,4,5];
let splits: &[&mut [int]] = &[&mut [1,2,3,4,5]];
assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>().as_slice(),
splits);
let splits: &[&mut [int]] = &[&mut [1], &mut [3,4,5]];
assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>().as_slice(),
splits);
let splits: &[&mut [int]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<&mut [int]>>().as_slice(),
splits);
let xs: &mut [int] = &mut [];
let splits: &[&mut [int]] = &[&mut []];
assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<&mut [int]>>().as_slice(),
splits);
}
#[test] #[test]
fn test_rsplitator() { fn test_rsplitator() {
let xs = &[1i,2,3,4,5]; let xs = &[1i,2,3,4,5];

View file

@ -67,7 +67,7 @@ pub trait ImmutableSlice<'a, T> {
/// original slice (i.e. when `end > self.len()`) or when `start > end`. /// original slice (i.e. when `end > self.len()`) or when `start > end`.
/// ///
/// Slicing with `start` equal to `end` yields an empty slice. /// Slicing with `start` equal to `end` yields an empty slice.
#[unstable] #[unstable = "waiting on final error conventions"]
fn slice(&self, start: uint, end: uint) -> &'a [T]; fn slice(&self, start: uint, end: uint) -> &'a [T];
/// Returns a subslice from `start` to the end of the slice. /// Returns a subslice from `start` to the end of the slice.
@ -75,7 +75,7 @@ pub trait ImmutableSlice<'a, T> {
/// Fails when `start` is strictly greater than the length of the original slice. /// Fails when `start` is strictly greater than the length of the original slice.
/// ///
/// Slicing from `self.len()` yields an empty slice. /// Slicing from `self.len()` yields an empty slice.
#[unstable] #[unstable = "waiting on final error conventions"]
fn slice_from(&self, start: uint) -> &'a [T]; fn slice_from(&self, start: uint) -> &'a [T];
/// Returns a subslice from the start of the slice to `end`. /// Returns a subslice from the start of the slice to `end`.
@ -83,7 +83,7 @@ pub trait ImmutableSlice<'a, T> {
/// Fails when `end` is strictly greater than the length of the original slice. /// Fails when `end` is strictly greater than the length of the original slice.
/// ///
/// Slicing to `0` yields an empty slice. /// Slicing to `0` yields an empty slice.
#[unstable] #[unstable = "waiting on final error conventions"]
fn slice_to(&self, end: uint) -> &'a [T]; fn slice_to(&self, end: uint) -> &'a [T];
/// Divides one slice into two at an index. /// Divides one slice into two at an index.
@ -93,102 +93,102 @@ pub trait ImmutableSlice<'a, T> {
/// indices from `[mid, len)` (excluding the index `len` itself). /// indices from `[mid, len)` (excluding the index `len` itself).
/// ///
/// Fails if `mid > len`. /// Fails if `mid > len`.
#[unstable] #[unstable = "waiting on final error conventions"]
fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]); fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);
/// Returns an iterator over the vector /// Returns an iterator over the slice
#[unstable = "iterator type may change"] #[unstable = "iterator type may change"]
fn iter(self) -> Items<'a, T>; fn iter(self) -> Items<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`. The matched element /// Returns an iterator over subslices separated by elements that match
/// is not contained in the subslices. /// `pred`. The matched element is not contained in the subslices.
#[unstable = "iterator type may change"] #[unstable = "iterator type may change, waiting on unboxed closures"]
fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>; fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred`, limited to splitting /// Returns an iterator over subslices separated by elements that match
/// at most `n` times. The matched element is not contained in /// `pred`, limited to splitting at most `n` times. The matched element is
/// not contained in the subslices.
#[unstable = "iterator type may change"]
fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;
/// Returns an iterator over subslices separated by elements that match
/// `pred` limited to splitting at most `n` times. This starts at the end of
/// the slice and works backwards. The matched element is not contained in
/// the subslices. /// the subslices.
#[unstable = "iterator type may change"] #[unstable = "iterator type may change"]
fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>; fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;
/// Returns an iterator over the subslices of the vector which are
/// separated by elements that match `pred` limited to splitting
/// at most `n` times. This starts at the end of the vector and
/// works backwards. The matched element is not contained in the
/// subslices.
#[unstable = "iterator type may change"]
fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
/** /// Returns an iterator over all contiguous windows of length
* Returns an iterator over all contiguous windows of length /// `size`. The windows overlap. If the slice is shorter than
* `size`. The windows overlap. If the vector is shorter than /// `size`, the iterator returns no values.
* `size`, the iterator returns no values. ///
* /// # Failure
* # Failure ///
* /// Fails if `size` is 0.
* Fails if `size` is 0. ///
* /// # Example
* # Example ///
* /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
* Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`, /// `[3,4]`):
* `[3,4]`): ///
* /// ```rust
* ```rust /// let v = &[1i, 2, 3, 4];
* let v = &[1i, 2, 3, 4]; /// for win in v.windows(2) {
* for win in v.windows(2) { /// println!("{}", win);
* println!("{}", win); /// }
* } /// ```
* ```
*
*/
#[unstable = "iterator type may change"] #[unstable = "iterator type may change"]
fn windows(self, size: uint) -> Windows<'a, T>; fn windows(self, size: uint) -> Windows<'a, T>;
/**
* /// Returns an iterator over `size` elements of the slice at a
* Returns an iterator over `size` elements of the vector at a /// time. The chunks do not overlap. If `size` does not divide the
* time. The chunks do not overlap. If `size` does not divide the /// length of the slice, then the last chunk will not have length
* length of the vector, then the last chunk will not have length /// `size`.
* `size`. ///
* /// # Failure
* # Failure ///
* /// Fails if `size` is 0.
* Fails if `size` is 0. ///
* /// # Example
* # Example ///
* /// Print the slice two elements at a time (i.e. `[1,2]`,
* Print the vector two elements at a time (i.e. `[1,2]`, /// `[3,4]`, `[5]`):
* `[3,4]`, `[5]`): ///
* /// ```rust
* ```rust /// let v = &[1i, 2, 3, 4, 5];
* let v = &[1i, 2, 3, 4, 5]; /// for win in v.chunks(2) {
* for win in v.chunks(2) { /// println!("{}", win);
* println!("{}", win); /// }
* } /// ```
* ```
*
*/
#[unstable = "iterator type may change"] #[unstable = "iterator type may change"]
fn chunks(self, size: uint) -> Chunks<'a, T>; fn chunks(self, size: uint) -> Chunks<'a, T>;
/// Returns the element of a vector at the given index, or `None` if the /// Returns the element of a slice at the given index, or `None` if the
/// index is out of bounds /// index is out of bounds.
#[unstable] #[unstable = "waiting on final collection conventions"]
fn get(&self, index: uint) -> Option<&'a T>; fn get(&self, index: uint) -> Option<&'a T>;
/// Returns the first element of a vector, or `None` if it is empty
/// Returns the first element of a slice, or `None` if it is empty.
#[unstable = "name may change"] #[unstable = "name may change"]
fn head(&self) -> Option<&'a T>; fn head(&self) -> Option<&'a T>;
/// Returns all but the first element of a vector
/// Returns all but the first element of a slice.
#[unstable = "name may change"] #[unstable = "name may change"]
fn tail(&self) -> &'a [T]; fn tail(&self) -> &'a [T];
/// Returns all but the first `n' elements of a vector
/// Returns all but the first `n' elements of a slice.
#[deprecated = "use slice_from"] #[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T]; fn tailn(&self, n: uint) -> &'a [T];
/// Returns all but the last element of a vector
/// Returns all but the last element of a slice.
#[unstable = "name may change"] #[unstable = "name may change"]
fn init(&self) -> &'a [T]; fn init(&self) -> &'a [T];
/// Returns all but the last `n' elements of a vector
/// Returns all but the last `n' elements of a slice.
#[deprecated = "use slice_to but note the arguments are different"] #[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T]; fn initn(&self, n: uint) -> &'a [T];
/// Returns the last element of a vector, or `None` if it is empty.
/// Returns the last element of a slice, or `None` if it is empty.
#[unstable = "name may change"] #[unstable = "name may change"]
fn last(&self) -> Option<&'a T>; fn last(&self) -> Option<&'a T>;
@ -202,36 +202,24 @@ pub trait ImmutableSlice<'a, T> {
#[unstable] #[unstable]
unsafe fn unsafe_get(self, index: uint) -> &'a T; unsafe fn unsafe_get(self, index: uint) -> &'a T;
/** /// Returns an unsafe pointer to the slice's buffer
* Returns an unsafe pointer to the vector's buffer ///
* /// The caller must ensure that the slice outlives the pointer this
* The caller must ensure that the vector outlives the pointer this /// function returns, or else it will end up pointing to garbage.
* function returns, or else it will end up pointing to garbage. ///
* /// Modifying the slice may cause its buffer to be reallocated, which
* Modifying the vector may cause its buffer to be reallocated, which /// would also make any pointers to it invalid.
* would also make any pointers to it invalid.
*/
#[unstable] #[unstable]
fn as_ptr(&self) -> *const T; fn as_ptr(&self) -> *const T;
/** /// Deprecated: use `binary_search`.
* Binary search a sorted vector with a comparator function.
*
* The comparator function should implement an order consistent
* with the sort order of the underlying vector, returning an
* order code that indicates whether its argument is `Less`,
* `Equal` or `Greater` the desired target.
*
* Returns the index where the comparator returned `Equal`, or `None` if
* not found.
*/
#[deprecated = "use binary_search"] #[deprecated = "use binary_search"]
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>; fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
/// Binary search a sorted vector with a comparator function. /// Binary search a sorted slice with a comparator function.
/// ///
/// The comparator function should implement an order consistent /// The comparator function should implement an order consistent
/// with the sort order of the underlying vector, returning an /// with the sort order of the underlying slice, returning an
/// order code that indicates whether its argument is `Less`, /// order code that indicates whether its argument is `Less`,
/// `Equal` or `Greater` the desired target. /// `Equal` or `Greater` the desired target.
/// ///
@ -239,7 +227,7 @@ pub trait ImmutableSlice<'a, T> {
/// index of the matching element; if the value is not found then /// index of the matching element; if the value is not found then
/// `NotFound` is returned, containing the index where a matching /// `NotFound` is returned, containing the index where a matching
/// element could be inserted while maintaining sorted order. /// element could be inserted while maintaining sorted order.
#[unstable] #[unstable = "waiting on unboxed closures"]
fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult; fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult;
/** /**
@ -336,7 +324,7 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
} }
#[inline] #[inline]
fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> { fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
SplitsN { SplitsN {
iter: self.split(pred), iter: self.split(pred),
count: n, count: n,
@ -345,7 +333,7 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
} }
#[inline] #[inline]
fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> { fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
SplitsN { SplitsN {
iter: self.split(pred), iter: self.split(pred),
count: n, count: n,
@ -533,12 +521,13 @@ impl<T> ops::SliceMut<uint, [T]> for [T] {
} }
} }
/// Extension methods for vectors such that their elements are /// Extension methods for slices such that their elements are
/// mutable. /// mutable.
#[experimental = "may merge with other traits; may lose region param; needs review"] #[experimental = "may merge with other traits; may lose region param; needs review"]
pub trait MutableSlice<'a, T> { pub trait MutableSlice<'a, T> {
/// Returns a mutable reference to the element at the given index, /// Returns a mutable reference to the element at the given index,
/// or `None` if the index is out of bounds /// or `None` if the index is out of bounds
#[unstable = "waiting on final error conventions"]
fn get_mut(self, index: uint) -> Option<&'a mut T>; fn get_mut(self, index: uint) -> Option<&'a mut T>;
/// Work with `self` as a mut slice. /// Work with `self` as a mut slice.
/// Primarily intended for getting a &mut [T] from a [T, ..N]. /// Primarily intended for getting a &mut [T] from a [T, ..N].
@ -556,6 +545,7 @@ pub trait MutableSlice<'a, T> {
/// original slice (i.e. when `end > self.len()`) or when `start > end`. /// original slice (i.e. when `end > self.len()`) or when `start > end`.
/// ///
/// Slicing with `start` equal to `end` yields an empty slice. /// Slicing with `start` equal to `end` yields an empty slice.
#[unstable = "waiting on final error conventions"]
fn slice_mut(self, start: uint, end: uint) -> &'a mut [T]; fn slice_mut(self, start: uint, end: uint) -> &'a mut [T];
/// Deprecated: use `slice_from_mut`. /// Deprecated: use `slice_from_mut`.
@ -569,6 +559,7 @@ pub trait MutableSlice<'a, T> {
/// Fails when `start` is strictly greater than the length of the original slice. /// Fails when `start` is strictly greater than the length of the original slice.
/// ///
/// Slicing from `self.len()` yields an empty slice. /// Slicing from `self.len()` yields an empty slice.
#[unstable = "waiting on final error conventions"]
fn slice_from_mut(self, start: uint) -> &'a mut [T]; fn slice_from_mut(self, start: uint) -> &'a mut [T];
/// Deprecated: use `slice_to_mut`. /// Deprecated: use `slice_to_mut`.
@ -582,6 +573,7 @@ pub trait MutableSlice<'a, T> {
/// Fails when `end` is strictly greater than the length of the original slice. /// Fails when `end` is strictly greater than the length of the original slice.
/// ///
/// Slicing to `0` yields an empty slice. /// Slicing to `0` yields an empty slice.
#[unstable = "waiting on final error conventions"]
fn slice_to_mut(self, end: uint) -> &'a mut [T]; fn slice_to_mut(self, end: uint) -> &'a mut [T];
/// Deprecated: use `iter_mut`. /// Deprecated: use `iter_mut`.
@ -591,15 +583,29 @@ pub trait MutableSlice<'a, T> {
} }
/// Returns an iterator that allows modifying each value /// Returns an iterator that allows modifying each value
#[unstable = "waiting on iterator type name conventions"]
fn iter_mut(self) -> MutItems<'a, T>; fn iter_mut(self) -> MutItems<'a, T>;
/// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
#[unstable = "name may change"]
fn head_mut(self) -> Option<&'a mut T>;
/// Returns all but the first element of a mutable slice
#[unstable = "name may change"]
fn tail_mut(self) -> &'a mut [T];
/// Returns all but the last element of a mutable slice
#[unstable = "name may change"]
fn init_mut(self) -> &'a mut [T];
/// Deprecated: use `last_mut`. /// Deprecated: use `last_mut`.
#[deprecated = "use last_mut"] #[deprecated = "use last_mut"]
fn mut_last(self) -> Option<&'a mut T> { fn mut_last(self) -> Option<&'a mut T> {
self.last_mut() self.last_mut()
} }
/// Returns a mutable pointer to the last item in the vector. /// Returns a mutable pointer to the last item in the slice.
#[unstable = "name may change"]
fn last_mut(self) -> Option<&'a mut T>; fn last_mut(self) -> Option<&'a mut T>;
/// Deprecated: use `split_mut`. /// Deprecated: use `split_mut`.
@ -608,27 +614,39 @@ pub trait MutableSlice<'a, T> {
self.split_mut(pred) self.split_mut(pred)
} }
/// Returns an iterator over the mutable subslices of the vector /// Returns an iterator over mutable subslices separated by elements that
/// which are separated by elements that match `pred`. The /// match `pred`. The matched element is not contained in the subslices.
/// matched element is not contained in the subslices. #[unstable = "waiting on unboxed closures, iterator type name conventions"]
fn split_mut(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>; fn split_mut(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
/// Returns an iterator over subslices separated by elements that match
/// `pred`, limited to splitting at most `n` times. The matched element is
/// not contained in the subslices.
#[unstable = "waiting on unboxed closures, iterator type name conventions"]
fn splitn_mut(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;
/// Returns an iterator over subslices separated by elements that match
/// `pred` limited to splitting at most `n` times. This starts at the end of
/// the slice and works backwards. The matched element is not contained in
/// the subslices.
#[unstable = "waiting on unboxed closures, iterator type name conventions"]
fn rsplitn_mut(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;
/// Deprecated: use `chunks_mut`. /// Deprecated: use `chunks_mut`.
#[deprecated = "use chunks_mut"] #[deprecated = "use chunks_mut"]
fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> { fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
self.chunks_mut(chunk_size) self.chunks_mut(chunk_size)
} }
/** /// Returns an iterator over `chunk_size` elements of the slice at a time.
* Returns an iterator over `chunk_size` elements of the vector at a time. /// The chunks are mutable and do not overlap. If `chunk_size` does
* The chunks are mutable and do not overlap. If `chunk_size` does /// not divide the length of the slice, then the last chunk will not
* not divide the length of the vector, then the last chunk will not /// have length `chunk_size`.
* have length `chunk_size`. ///
* /// # Failure
* # Failure ///
* /// Fails if `chunk_size` is 0.
* Fails if `chunk_size` is 0. #[unstable = "waiting on iterator type name conventions"]
*/
fn chunks_mut(self, chunk_size: uint) -> MutChunks<'a, T>; fn chunks_mut(self, chunk_size: uint) -> MutChunks<'a, T>;
/** /**
@ -647,7 +665,7 @@ pub trait MutableSlice<'a, T> {
* *
* Returns `None` if slice is empty * Returns `None` if slice is empty
*/ */
#[deprecated = "find some other way. sorry"] #[deprecated = "use iter_mut"]
fn mut_shift_ref(&mut self) -> Option<&'a mut T>; fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
/** /**
@ -666,10 +684,10 @@ pub trait MutableSlice<'a, T> {
* *
* Returns `None` if slice is empty. * Returns `None` if slice is empty.
*/ */
#[deprecated = "find some other way. sorry"] #[deprecated = "use iter_mut"]
fn mut_pop_ref(&mut self) -> Option<&'a mut T>; fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
/// Swaps two elements in a vector. /// Swaps two elements in a slice.
/// ///
/// Fails if `a` or `b` are out of bounds. /// Fails if `a` or `b` are out of bounds.
/// ///
@ -685,6 +703,7 @@ pub trait MutableSlice<'a, T> {
/// v.swap(1, 3); /// v.swap(1, 3);
/// assert!(v == ["a", "d", "c", "b"]); /// assert!(v == ["a", "d", "c", "b"]);
/// ``` /// ```
#[unstable = "waiting on final error conventions"]
fn swap(self, a: uint, b: uint); fn swap(self, a: uint, b: uint);
/// Deprecated: use `split_at_mut`. /// Deprecated: use `split_at_mut`.
@ -725,9 +744,10 @@ pub trait MutableSlice<'a, T> {
/// assert!(right == &mut []); /// assert!(right == &mut []);
/// } /// }
/// ``` /// ```
#[unstable = "waiting on final error conventions"]
fn split_at_mut(self, mid: uint) -> (&'a mut [T], &'a mut [T]); fn split_at_mut(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
/// Reverse the order of elements in a vector, in place. /// Reverse the order of elements in a slice, in place.
/// ///
/// # Example /// # Example
/// ///
@ -736,6 +756,7 @@ pub trait MutableSlice<'a, T> {
/// v.reverse(); /// v.reverse();
/// assert!(v == [3i, 2, 1]); /// assert!(v == [3i, 2, 1]);
/// ``` /// ```
#[experimental = "may be moved to iterators instead"]
fn reverse(self); fn reverse(self);
/// Deprecated: use `unsafe_mut`. /// Deprecated: use `unsafe_mut`.
@ -745,60 +766,30 @@ pub trait MutableSlice<'a, T> {
} }
/// Returns an unsafe mutable pointer to the element in index /// Returns an unsafe mutable pointer to the element in index
#[experimental = "waiting on unsafe conventions"]
unsafe fn unsafe_mut(self, index: uint) -> &'a mut T; unsafe fn unsafe_mut(self, index: uint) -> &'a mut T;
/// Return an unsafe mutable pointer to the vector's buffer. /// Return an unsafe mutable pointer to the slice's buffer.
/// ///
/// The caller must ensure that the vector outlives the pointer this /// The caller must ensure that the slice outlives the pointer this
/// function returns, or else it will end up pointing to garbage. /// function returns, or else it will end up pointing to garbage.
/// ///
/// Modifying the vector may cause its buffer to be reallocated, which /// Modifying the slice may cause its buffer to be reallocated, which
/// would also make any pointers to it invalid. /// would also make any pointers to it invalid.
#[inline] #[inline]
#[unstable]
fn as_mut_ptr(self) -> *mut T; fn as_mut_ptr(self) -> *mut T;
/// Unsafely sets the element in index to the value. /// Deprecated: use `*foo.as_mut_ptr().offset(index) = val` instead.
/// #[deprecated = "use `*foo.as_mut_ptr().offset(index) = val`"]
/// This performs no bounds checks, and it is undefined behaviour
/// if `index` is larger than the length of `self`. However, it
/// does run the destructor at `index`. It is equivalent to
/// `self[index] = val`.
///
/// # Example
///
/// ```rust
/// let mut v = ["foo".to_string(), "bar".to_string(), "baz".to_string()];
///
/// unsafe {
/// // `"baz".to_string()` is deallocated.
/// v.unsafe_set(2, "qux".to_string());
///
/// // Out of bounds: could cause a crash, or overwriting
/// // other data, or something else.
/// // v.unsafe_set(10, "oops".to_string());
/// }
/// ```
unsafe fn unsafe_set(self, index: uint, val: T); unsafe fn unsafe_set(self, index: uint, val: T);
/// Unchecked vector index assignment. Does not drop the /// Deprecated: use `ptr::write(foo.as_mut_ptr().offset(i), val)` instead.
/// old value and hence is only suitable when the vector #[deprecated = "use `ptr::write(foo.as_mut_ptr().offset(i), val)`"]
/// is newly allocated.
///
/// # Example
///
/// ```rust
/// let mut v = ["foo".to_string(), "bar".to_string()];
///
/// // memory leak! `"bar".to_string()` is not deallocated.
/// unsafe { v.init_elem(1, "baz".to_string()); }
/// ```
unsafe fn init_elem(self, i: uint, val: T); unsafe fn init_elem(self, i: uint, val: T);
/// Copies raw bytes from `src` to `self`. /// Deprecated: use `as_mut_ptr` and `ptr::copy_memory` instead.
/// #[deprecated = "use as_mut_ptr and ptr::copy_memory"]
/// This does not run destructors on the overwritten elements, and
/// ignores move semantics. `self` and `src` must not
/// overlap. Fails if `self` is shorter than `src`.
unsafe fn copy_memory(self, src: &[T]); unsafe fn copy_memory(self, src: &[T]);
} }
@ -868,11 +859,46 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
Some(&mut self[len - 1]) Some(&mut self[len - 1])
} }
#[inline]
fn head_mut(self) -> Option<&'a mut T> {
if self.len() == 0 { None } else { Some(&mut self[0]) }
}
#[inline]
fn tail_mut(self) -> &'a mut [T] {
let len = self.len();
self.slice_mut(1, len)
}
#[inline]
fn init_mut(self) -> &'a mut [T] {
let len = self.len();
self.slice_mut(0, len - 1)
}
#[inline] #[inline]
fn split_mut(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> { fn split_mut(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
MutSplits { v: self, pred: pred, finished: false } MutSplits { v: self, pred: pred, finished: false }
} }
#[inline]
fn splitn_mut(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
SplitsN {
iter: self.split_mut(pred),
count: n,
invert: false
}
}
#[inline]
fn rsplitn_mut(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
SplitsN {
iter: self.split_mut(pred),
count: n,
invert: true
}
}
#[inline] #[inline]
fn chunks_mut(self, chunk_size: uint) -> MutChunks<'a, T> { fn chunks_mut(self, chunk_size: uint) -> MutChunks<'a, T> {
assert!(chunk_size > 0); assert!(chunk_size > 0);
@ -955,22 +981,22 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
} }
} }
/// Extension methods for vectors contain `PartialEq` elements. /// Extension methods for slices containing `PartialEq` elements.
#[unstable = "may merge with other traits"] #[unstable = "may merge with other traits"]
pub trait ImmutablePartialEqSlice<T:PartialEq> { pub trait ImmutablePartialEqSlice<T:PartialEq> {
/// Find the first index containing a matching value /// Find the first index containing a matching value.
fn position_elem(&self, t: &T) -> Option<uint>; fn position_elem(&self, t: &T) -> Option<uint>;
/// Find the last index containing a matching value /// Find the last index containing a matching value.
fn rposition_elem(&self, t: &T) -> Option<uint>; fn rposition_elem(&self, t: &T) -> Option<uint>;
/// Return true if a vector contains an element with the given value /// Return true if the slice contains an element with the given value.
fn contains(&self, x: &T) -> bool; fn contains(&self, x: &T) -> bool;
/// Returns true if `needle` is a prefix of the vector. /// Returns true if `needle` is a prefix of the slice.
fn starts_with(&self, needle: &[T]) -> bool; fn starts_with(&self, needle: &[T]) -> bool;
/// Returns true if `needle` is a suffix of the vector. /// Returns true if `needle` is a suffix of the slice.
fn ends_with(&self, needle: &[T]) -> bool; fn ends_with(&self, needle: &[T]) -> bool;
} }
@ -1004,26 +1030,20 @@ impl<'a,T:PartialEq> ImmutablePartialEqSlice<T> for &'a [T] {
} }
} }
/// Extension methods for vectors containing `Ord` elements. /// Extension methods for slices containing `Ord` elements.
#[unstable = "may merge with other traits"] #[unstable = "may merge with other traits"]
pub trait ImmutableOrdSlice<T: Ord> { pub trait ImmutableOrdSlice<T: Ord> {
/** /// Deprecated: use `binary_search_elem`.
* Binary search a sorted vector for a given element.
*
* Returns the index of the element or None if not found.
*/
#[deprecated = "use binary_search_elem"] #[deprecated = "use binary_search_elem"]
fn bsearch_elem(&self, x: &T) -> Option<uint>; fn bsearch_elem(&self, x: &T) -> Option<uint>;
/** /// Binary search a sorted slice for a given element.
* Binary search a sorted vector for a given element. ///
* /// If the value is found then `Found` is returned, containing the
* If the value is found then `Found` is returned, containing the /// index of the matching element; if the value is not found then
* index of the matching element; if the value is not found then /// `NotFound` is returned, containing the index where a matching
* `NotFound` is returned, containing the index where a matching /// element could be inserted while maintaining sorted order.
* element could be inserted while maintaining sorted order. #[unstable = "name likely to change"]
*/
#[unstable]
fn binary_search_elem(&self, x: &T) -> BinarySearchResult; fn binary_search_elem(&self, x: &T) -> BinarySearchResult;
} }
@ -1090,7 +1110,7 @@ impl<'a, T:Clone> MutableCloneableSlice<T> for &'a mut [T] {
// Common traits // Common traits
// //
/// Any vector that can be represented as a slice. /// Data that is viewable as a slice.
#[unstable = "may merge with other traits"] #[unstable = "may merge with other traits"]
pub trait Slice<T> { pub trait Slice<T> {
/// Work with `self` as a slice. /// Work with `self` as a slice.
@ -1105,7 +1125,7 @@ impl<'a,T> Slice<T> for &'a [T] {
#[experimental = "trait is experimental"] #[experimental = "trait is experimental"]
impl<'a, T> Collection for &'a [T] { impl<'a, T> Collection for &'a [T] {
/// Returns the length of a vector /// Returns the length of a slice.
#[inline] #[inline]
fn len(&self) -> uint { fn len(&self) -> uint {
self.repr().len self.repr().len
@ -1114,7 +1134,7 @@ impl<'a, T> Collection for &'a [T] {
#[experimental = "trait is experimental"] #[experimental = "trait is experimental"]
impl<'a, T> Collection for &'a mut [T] { impl<'a, T> Collection for &'a mut [T] {
/// Returns the length of a vector /// Returns the length of a slice.
#[inline] #[inline]
fn len(&self) -> uint { fn len(&self) -> uint {
self.repr().len self.repr().len
@ -1239,7 +1259,7 @@ impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
} }
} }
/// Mutable slice iterator /// Mutable slice iterator.
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct MutItems<'a, T> { pub struct MutItems<'a, T> {
ptr: *mut T, ptr: *mut T,
@ -1253,8 +1273,16 @@ iterator!{struct MutItems -> *mut T, &'a mut T}
#[experimental = "needs review"] #[experimental = "needs review"]
impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {} impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
/// An iterator over the slices of a vector separated by elements that /// An abstraction over the splitting iterators, so that splitn, splitn_mut etc
/// match a predicate function. /// can be implemented once.
trait SplitsIter<E>: DoubleEndedIterator<E> {
/// Mark the underlying iterator as complete, extracting the remaining
/// portion of the slice.
fn finish(&mut self) -> Option<E>;
}
/// An iterator over subslices separated by elements that match a predicate
/// function.
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct Splits<'a, T:'a> { pub struct Splits<'a, T:'a> {
v: &'a [T], v: &'a [T],
@ -1269,10 +1297,7 @@ impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
if self.finished { return None; } if self.finished { return None; }
match self.v.iter().position(|x| (self.pred)(x)) { match self.v.iter().position(|x| (self.pred)(x)) {
None => { None => self.finish(),
self.finished = true;
Some(self.v)
}
Some(idx) => { Some(idx) => {
let ret = Some(self.v.slice(0, idx)); let ret = Some(self.v.slice(0, idx));
self.v = self.v.slice(idx + 1, self.v.len()); self.v = self.v.slice(idx + 1, self.v.len());
@ -1298,10 +1323,7 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
if self.finished { return None; } if self.finished { return None; }
match self.v.iter().rposition(|x| (self.pred)(x)) { match self.v.iter().rposition(|x| (self.pred)(x)) {
None => { None => self.finish(),
self.finished = true;
Some(self.v)
}
Some(idx) => { Some(idx) => {
let ret = Some(self.v.slice(idx + 1, self.v.len())); let ret = Some(self.v.slice(idx + 1, self.v.len()));
self.v = self.v.slice(0, idx); self.v = self.v.slice(0, idx);
@ -1311,6 +1333,13 @@ impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
} }
} }
impl<'a, T> SplitsIter<&'a [T]> for Splits<'a, T> {
#[inline]
fn finish(&mut self) -> Option<&'a [T]> {
if self.finished { None } else { self.finished = true; Some(self.v) }
}
}
/// An iterator over the subslices of the vector which are separated /// An iterator over the subslices of the vector which are separated
/// by elements that match `pred`. /// by elements that match `pred`.
#[experimental = "needs review"] #[experimental = "needs review"]
@ -1320,22 +1349,30 @@ pub struct MutSplits<'a, T:'a> {
finished: bool finished: bool
} }
impl<'a, T> SplitsIter<&'a mut [T]> for MutSplits<'a, T> {
#[inline]
fn finish(&mut self) -> Option<&'a mut [T]> {
if self.finished {
None
} else {
self.finished = true;
Some(mem::replace(&mut self.v, &mut []))
}
}
}
#[experimental = "needs review"] #[experimental = "needs review"]
impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> { impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
#[inline] #[inline]
fn next(&mut self) -> Option<&'a mut [T]> { fn next(&mut self) -> Option<&'a mut [T]> {
if self.finished { return None; } if self.finished { return None; }
let idx_opt = { // work around borrowck limitations
let pred = &mut self.pred; let pred = &mut self.pred;
match self.v.iter().position(|x| (*pred)(x)) { self.v.iter().position(|x| (*pred)(x))
None => { };
self.finished = true; match idx_opt {
let tmp = mem::replace(&mut self.v, &mut []); None => self.finish(),
let len = tmp.len();
let (head, tail) = tmp.split_at_mut(len);
self.v = tail;
Some(head)
}
Some(idx) => { Some(idx) => {
let tmp = mem::replace(&mut self.v, &mut []); let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.split_at_mut(idx); let (head, tail) = tmp.split_at_mut(idx);
@ -1363,13 +1400,12 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
fn next_back(&mut self) -> Option<&'a mut [T]> { fn next_back(&mut self) -> Option<&'a mut [T]> {
if self.finished { return None; } if self.finished { return None; }
let idx_opt = { // work around borrowck limitations
let pred = &mut self.pred; let pred = &mut self.pred;
match self.v.iter().rposition(|x| (*pred)(x)) { self.v.iter().rposition(|x| (*pred)(x))
None => { };
self.finished = true; match idx_opt {
let tmp = mem::replace(&mut self.v, &mut []); None => self.finish(),
Some(tmp)
}
Some(idx) => { Some(idx) => {
let tmp = mem::replace(&mut self.v, &mut []); let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.split_at_mut(idx); let (head, tail) = tmp.split_at_mut(idx);
@ -1380,26 +1416,21 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
} }
} }
/// An iterator over the slices of a vector separated by elements that /// An iterator over subslices separated by elements that match a predicate
/// match a predicate function, splitting at most a fixed number of times. /// function, splitting at most a fixed number of times.
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct SplitsN<'a, T:'a> { pub struct SplitsN<I> {
iter: Splits<'a, T>, iter: I,
count: uint, count: uint,
invert: bool invert: bool
} }
#[experimental = "needs review"] #[experimental = "needs review"]
impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> { impl<E, I: SplitsIter<E>> Iterator<E> for SplitsN<I> {
#[inline] #[inline]
fn next(&mut self) -> Option<&'a [T]> { fn next(&mut self) -> Option<E> {
if self.count == 0 { if self.count == 0 {
if self.iter.finished { self.iter.finish()
None
} else {
self.iter.finished = true;
Some(self.iter.v)
}
} else { } else {
self.count -= 1; self.count -= 1;
if self.invert { self.iter.next_back() } else { self.iter.next() } if self.invert { self.iter.next_back() } else { self.iter.next() }
@ -1408,16 +1439,12 @@ impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
#[inline] #[inline]
fn size_hint(&self) -> (uint, Option<uint>) { fn size_hint(&self) -> (uint, Option<uint>) {
if self.iter.finished { let (lower, upper_opt) = self.iter.size_hint();
(0, Some(0)) (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
} else {
(1, Some(cmp::min(self.count, self.iter.v.len()) + 1))
}
} }
} }
/// An iterator over the (overlapping) slices of length `size` within /// An iterator over overlapping subslices of length `size`.
/// a vector.
#[deriving(Clone)] #[deriving(Clone)]
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct Windows<'a, T:'a> { pub struct Windows<'a, T:'a> {
@ -1448,11 +1475,11 @@ impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
} }
} }
/// An iterator over a vector in (non-overlapping) chunks (`size` /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
/// elements at a time). /// time).
/// ///
/// When the vector len is not evenly divided by the chunk size, /// When the slice len is not evenly divided by the chunk size, the last slice
/// the last slice of the iteration will be the remainder. /// of the iteration will be the remainder.
#[deriving(Clone)] #[deriving(Clone)]
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct Chunks<'a, T:'a> { pub struct Chunks<'a, T:'a> {
@ -1523,9 +1550,9 @@ impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
} }
} }
/// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
/// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be /// elements at a time). When the slice len is not evenly divided by the chunk
/// the remainder. /// size, the last slice of the iteration will be the remainder.
#[experimental = "needs review"] #[experimental = "needs review"]
pub struct MutChunks<'a, T:'a> { pub struct MutChunks<'a, T:'a> {
v: &'a mut [T], v: &'a mut [T],
@ -1741,6 +1768,7 @@ pub mod bytes {
/// `src` and `dst` must not overlap. Fails if the length of `dst` /// `src` and `dst` must not overlap. Fails if the length of `dst`
/// is less than the length of `src`. /// is less than the length of `src`.
#[inline] #[inline]
#[allow(deprecated)]
pub fn copy_memory(dst: &mut [u8], src: &[u8]) { pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
// Bound checks are done at .copy_memory. // Bound checks are done at .copy_memory.
unsafe { dst.copy_memory(src) } unsafe { dst.copy_memory(src) }