1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Slice management and manipulation
13 //! For more details `std::slice`.
17 use container::Container;
18 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
22 use num::{CheckedAdd, Saturating, div_rem};
23 use option::{None, Option, Some};
29 use raw::{Repr, Slice};
32 * Converts a pointer to A into a slice of length 1 (without copying).
34 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
36 transmute(Slice { data: s, len: 1 })
41 * Converts a pointer to A into a slice of length 1 (without copying).
43 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
45 let ptr: *A = transmute(s);
46 transmute(Slice { data: ptr, len: 1 })
50 /// An iterator over the slices of a vector separated by elements that
51 /// match a predicate function.
52 pub struct Splits<'a, T> {
54 pred: |t: &T|: 'a -> bool,
58 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
60 fn next(&mut self) -> Option<&'a [T]> {
61 if self.finished { return None; }
63 match self.v.iter().position(|x| (self.pred)(x)) {
69 let ret = Some(self.v.slice(0, idx));
70 self.v = self.v.slice(idx + 1, self.v.len());
77 fn size_hint(&self) -> (uint, Option<uint>) {
81 (1, Some(self.v.len() + 1))
86 impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
88 fn next_back(&mut self) -> Option<&'a [T]> {
89 if self.finished { return None; }
91 match self.v.iter().rposition(|x| (self.pred)(x)) {
97 let ret = Some(self.v.slice(idx + 1, self.v.len()));
98 self.v = self.v.slice(0, idx);
105 /// An iterator over the slices of a vector separated by elements that
106 /// match a predicate function, splitting at most a fixed number of times.
107 pub struct SplitsN<'a, T> {
113 impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
115 fn next(&mut self) -> Option<&'a [T]> {
117 if self.iter.finished {
120 self.iter.finished = true;
125 if self.invert { self.iter.next_back() } else { self.iter.next() }
130 fn size_hint(&self) -> (uint, Option<uint>) {
131 if self.iter.finished {
134 (1, Some(cmp::min(self.count, self.iter.v.len()) + 1))
139 // Functional utilities
141 /// An iterator over the (overlapping) slices of length `size` within
144 pub struct Windows<'a, T> {
149 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
151 fn next(&mut self) -> Option<&'a [T]> {
152 if self.size > self.v.len() {
155 let ret = Some(self.v.slice(0, self.size));
156 self.v = self.v.slice(1, self.v.len());
162 fn size_hint(&self) -> (uint, Option<uint>) {
163 if self.size > self.v.len() {
166 let x = self.v.len() - self.size;
167 (x.saturating_add(1), x.checked_add(&1u))
172 /// An iterator over a vector in (non-overlapping) chunks (`size`
173 /// elements at a time).
175 /// When the vector len is not evenly divided by the chunk size,
176 /// the last slice of the iteration will be the remainder.
178 pub struct Chunks<'a, T> {
183 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
185 fn next(&mut self) -> Option<&'a [T]> {
186 if self.v.len() == 0 {
189 let chunksz = cmp::min(self.v.len(), self.size);
190 let (fst, snd) = (self.v.slice_to(chunksz),
191 self.v.slice_from(chunksz));
198 fn size_hint(&self) -> (uint, Option<uint>) {
199 if self.v.len() == 0 {
202 let (n, rem) = div_rem(self.v.len(), self.size);
203 let n = if rem > 0 { n+1 } else { n };
209 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
211 fn next_back(&mut self) -> Option<&'a [T]> {
212 if self.v.len() == 0 {
215 let remainder = self.v.len() % self.size;
216 let chunksz = if remainder != 0 { remainder } else { self.size };
217 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
218 self.v.slice_from(self.v.len() - chunksz));
225 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
227 fn indexable(&self) -> uint {
228 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
232 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
233 if index < self.indexable() {
234 let lo = index * self.size;
235 let mut hi = lo + self.size;
236 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
238 Some(self.v.slice(lo, hi))
248 #[allow(missing_doc)]
252 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
253 use iter::{order, Iterator};
254 use container::Container;
256 impl<'a,T:Eq> Eq for &'a [T] {
257 fn eq(&self, other: & &'a [T]) -> bool {
258 self.len() == other.len() &&
259 order::eq(self.iter(), other.iter())
261 fn ne(&self, other: & &'a [T]) -> bool {
262 self.len() != other.len() ||
263 order::ne(self.iter(), other.iter())
267 impl<T:Eq> Eq for ~[T] {
269 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
271 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
274 impl<'a,T:TotalEq> TotalEq for &'a [T] {}
276 impl<T:TotalEq> TotalEq for ~[T] {}
278 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
280 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
283 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
285 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
288 impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
289 fn cmp(&self, other: & &'a [T]) -> Ordering {
290 order::cmp(self.iter(), other.iter())
294 impl<T: TotalOrd> TotalOrd for ~[T] {
296 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
299 impl<'a, T: Ord> Ord for &'a [T] {
300 fn lt(&self, other: & &'a [T]) -> bool {
301 order::lt(self.iter(), other.iter())
304 fn le(&self, other: & &'a [T]) -> bool {
305 order::le(self.iter(), other.iter())
308 fn ge(&self, other: & &'a [T]) -> bool {
309 order::ge(self.iter(), other.iter())
312 fn gt(&self, other: & &'a [T]) -> bool {
313 order::gt(self.iter(), other.iter())
317 impl<T: Ord> Ord for ~[T] {
319 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
321 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
323 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
325 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
332 /// Any vector that can be represented as a slice.
333 pub trait Vector<T> {
334 /// Work with `self` as a slice.
335 fn as_slice<'a>(&'a self) -> &'a [T];
338 impl<'a,T> Vector<T> for &'a [T] {
340 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
343 impl<T> Vector<T> for ~[T] {
345 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
348 impl<'a, T> Container for &'a [T] {
349 /// Returns the length of a vector
351 fn len(&self) -> uint {
356 impl<T> Container for ~[T] {
357 /// Returns the length of a vector
359 fn len(&self) -> uint {
360 self.as_slice().len()
364 /// Extension methods for vectors
365 pub trait ImmutableVector<'a, T> {
367 * Returns a slice of self between `start` and `end`.
369 * Fails when `start` or `end` point outside the bounds of self,
370 * or when `start` > `end`.
372 fn slice(&self, start: uint, end: uint) -> &'a [T];
375 * Returns a slice of self from `start` to the end of the vec.
377 * Fails when `start` points outside the bounds of self.
379 fn slice_from(&self, start: uint) -> &'a [T];
382 * Returns a slice of self from the start of the vec to `end`.
384 * Fails when `end` points outside the bounds of self.
386 fn slice_to(&self, end: uint) -> &'a [T];
387 /// Returns an iterator over the vector
388 fn iter(self) -> Items<'a, T>;
389 /// Returns an iterator over the subslices of the vector which are
390 /// separated by elements that match `pred`. The matched element
391 /// is not contained in the subslices.
392 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
393 /// Returns an iterator over the subslices of the vector which are
394 /// separated by elements that match `pred`, limited to splitting
395 /// at most `n` times. The matched element is not contained in
397 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
398 /// Returns an iterator over the subslices of the vector which are
399 /// separated by elements that match `pred` limited to splitting
400 /// at most `n` times. This starts at the end of the vector and
401 /// works backwards. The matched element is not contained in the
403 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
406 * Returns an iterator over all contiguous windows of length
407 * `size`. The windows overlap. If the vector is shorter than
408 * `size`, the iterator returns no values.
412 * Fails if `size` is 0.
416 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
420 * let v = &[1,2,3,4];
421 * for win in v.windows(2) {
422 * println!("{:?}", win);
427 fn windows(self, size: uint) -> Windows<'a, T>;
430 * Returns an iterator over `size` elements of the vector at a
431 * time. The chunks do not overlap. If `size` does not divide the
432 * length of the vector, then the last chunk will not have length
437 * Fails if `size` is 0.
441 * Print the vector two elements at a time (i.e. `[1,2]`,
445 * let v = &[1,2,3,4,5];
446 * for win in v.chunks(2) {
447 * println!("{:?}", win);
452 fn chunks(self, size: uint) -> Chunks<'a, T>;
454 /// Returns the element of a vector at the given index, or `None` if the
455 /// index is out of bounds
456 fn get(&self, index: uint) -> Option<&'a T>;
457 /// Returns the first element of a vector, or `None` if it is empty
458 fn head(&self) -> Option<&'a T>;
459 /// Returns all but the first element of a vector
460 fn tail(&self) -> &'a [T];
461 /// Returns all but the first `n' elements of a vector
462 fn tailn(&self, n: uint) -> &'a [T];
463 /// Returns all but the last element of a vector
464 fn init(&self) -> &'a [T];
465 /// Returns all but the last `n' elements of a vector
466 fn initn(&self, n: uint) -> &'a [T];
467 /// Returns the last element of a vector, or `None` if it is empty.
468 fn last(&self) -> Option<&'a T>;
470 /// Returns a pointer to the element at the given index, without doing
472 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
475 * Returns an unsafe pointer to the vector's buffer
477 * The caller must ensure that the vector outlives the pointer this
478 * function returns, or else it will end up pointing to garbage.
480 * Modifying the vector may cause its buffer to be reallocated, which
481 * would also make any pointers to it invalid.
483 fn as_ptr(&self) -> *T;
486 * Binary search a sorted vector with a comparator function.
488 * The comparator function should implement an order consistent
489 * with the sort order of the underlying vector, returning an
490 * order code that indicates whether its argument is `Less`,
491 * `Equal` or `Greater` the desired target.
493 * Returns the index where the comparator returned `Equal`, or `None` if
496 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
499 * Returns an immutable reference to the first element in this slice
500 * and adjusts the slice in place so that it no longer contains
501 * that element. O(1).
506 * if self.len() == 0 { return None }
507 * let head = &self[0];
508 * *self = self.slice_from(1);
512 * Returns `None` if vector is empty
514 fn shift_ref(&mut self) -> Option<&'a T>;
517 * Returns an immutable reference to the last element in this slice
518 * and adjusts the slice in place so that it no longer contains
519 * that element. O(1).
524 * if self.len() == 0 { return None; }
525 * let tail = &self[self.len() - 1];
526 * *self = self.slice_to(self.len() - 1);
530 * Returns `None` if slice is empty.
532 fn pop_ref(&mut self) -> Option<&'a T>;
535 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
537 fn slice(&self, start: uint, end: uint) -> &'a [T] {
538 assert!(start <= end);
539 assert!(end <= self.len());
542 data: self.as_ptr().offset(start as int),
549 fn slice_from(&self, start: uint) -> &'a [T] {
550 self.slice(start, self.len())
554 fn slice_to(&self, end: uint) -> &'a [T] {
559 fn iter(self) -> Items<'a, T> {
561 let p = self.as_ptr();
562 if mem::size_of::<T>() == 0 {
564 end: (p as uint + self.len()) as *T,
565 marker: marker::ContravariantLifetime::<'a>}
568 end: p.offset(self.len() as int),
569 marker: marker::ContravariantLifetime::<'a>}
575 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
584 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
586 iter: self.split(pred),
593 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
595 iter: self.split(pred),
602 fn windows(self, size: uint) -> Windows<'a, T> {
604 Windows { v: self, size: size }
608 fn chunks(self, size: uint) -> Chunks<'a, T> {
610 Chunks { v: self, size: size }
614 fn get(&self, index: uint) -> Option<&'a T> {
615 if index < self.len() { Some(&self[index]) } else { None }
619 fn head(&self) -> Option<&'a T> {
620 if self.len() == 0 { None } else { Some(&self[0]) }
624 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
627 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
630 fn init(&self) -> &'a [T] {
631 self.slice(0, self.len() - 1)
635 fn initn(&self, n: uint) -> &'a [T] {
636 self.slice(0, self.len() - n)
640 fn last(&self) -> Option<&'a T> {
641 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
645 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
646 transmute(self.repr().data.offset(index as int))
650 fn as_ptr(&self) -> *T {
655 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
656 let mut base : uint = 0;
657 let mut lim : uint = self.len();
660 let ix = base + (lim >> 1);
662 Equal => return Some(ix),
674 fn shift_ref(&mut self) -> Option<&'a T> {
676 let s: &mut Slice<T> = transmute(self);
677 match raw::shift_ptr(s) {
678 Some(p) => Some(&*p),
684 fn pop_ref(&mut self) -> Option<&'a T> {
686 let s: &mut Slice<T> = transmute(self);
687 match raw::pop_ptr(s) {
688 Some(p) => Some(&*p),
695 /// Extension methods for vectors contain `Eq` elements.
696 pub trait ImmutableEqVector<T:Eq> {
697 /// Find the first index containing a matching value
698 fn position_elem(&self, t: &T) -> Option<uint>;
700 /// Find the last index containing a matching value
701 fn rposition_elem(&self, t: &T) -> Option<uint>;
703 /// Return true if a vector contains an element with the given value
704 fn contains(&self, x: &T) -> bool;
706 /// Returns true if `needle` is a prefix of the vector.
707 fn starts_with(&self, needle: &[T]) -> bool;
709 /// Returns true if `needle` is a suffix of the vector.
710 fn ends_with(&self, needle: &[T]) -> bool;
713 impl<'a,T:Eq> ImmutableEqVector<T> for &'a [T] {
715 fn position_elem(&self, x: &T) -> Option<uint> {
716 self.iter().position(|y| *x == *y)
720 fn rposition_elem(&self, t: &T) -> Option<uint> {
721 self.iter().rposition(|x| *x == *t)
725 fn contains(&self, x: &T) -> bool {
726 self.iter().any(|elt| *x == *elt)
730 fn starts_with(&self, needle: &[T]) -> bool {
731 let n = needle.len();
732 self.len() >= n && needle == self.slice_to(n)
736 fn ends_with(&self, needle: &[T]) -> bool {
737 let (m, n) = (self.len(), needle.len());
738 m >= n && needle == self.slice_from(m - n)
742 /// Extension methods for vectors containing `TotalOrd` elements.
743 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
745 * Binary search a sorted vector for a given element.
747 * Returns the index of the element or None if not found.
749 fn bsearch_elem(&self, x: &T) -> Option<uint>;
752 impl<'a, T: TotalOrd> ImmutableTotalOrdVector<T> for &'a [T] {
753 fn bsearch_elem(&self, x: &T) -> Option<uint> {
754 self.bsearch(|p| p.cmp(x))
758 /// Extension methods for vectors such that their elements are
760 pub trait MutableVector<'a, T> {
761 /// Work with `self` as a mut slice.
762 /// Primarily intended for getting a &mut [T] from a [T, ..N].
763 fn as_mut_slice(self) -> &'a mut [T];
765 /// Return a slice that points into another slice.
766 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
769 * Returns a slice of self from `start` to the end of the vec.
771 * Fails when `start` points outside the bounds of self.
773 fn mut_slice_from(self, start: uint) -> &'a mut [T];
776 * Returns a slice of self from the start of the vec to `end`.
778 * Fails when `end` points outside the bounds of self.
780 fn mut_slice_to(self, end: uint) -> &'a mut [T];
782 /// Returns an iterator that allows modifying each value
783 fn mut_iter(self) -> MutItems<'a, T>;
785 /// Returns a mutable pointer to the last item in the vector.
786 fn mut_last(self) -> Option<&'a mut T>;
788 /// Returns an iterator over the mutable subslices of the vector
789 /// which are separated by elements that match `pred`. The
790 /// matched element is not contained in the subslices.
791 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
794 * Returns an iterator over `size` elements of the vector at a time.
795 * The chunks are mutable and do not overlap. If `size` does not divide the
796 * length of the vector, then the last chunk will not have length
801 * Fails if `size` is 0.
803 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
806 * Returns a mutable reference to the first element in this slice
807 * and adjusts the slice in place so that it no longer contains
808 * that element. O(1).
813 * if self.len() == 0 { return None; }
814 * let head = &mut self[0];
815 * *self = self.mut_slice_from(1);
819 * Returns `None` if slice is empty
821 fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
824 * Returns a mutable reference to the last element in this slice
825 * and adjusts the slice in place so that it no longer contains
826 * that element. O(1).
831 * if self.len() == 0 { return None; }
832 * let tail = &mut self[self.len() - 1];
833 * *self = self.mut_slice_to(self.len() - 1);
837 * Returns `None` if slice is empty.
839 fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
841 /// Swaps two elements in a vector.
843 /// Fails if `a` or `b` are out of bounds.
847 /// * a - The index of the first element
848 /// * b - The index of the second element
853 /// let mut v = ["a", "b", "c", "d"];
855 /// assert!(v == ["a", "d", "c", "b"]);
857 fn swap(self, a: uint, b: uint);
860 /// Divides one `&mut` into two at an index.
862 /// The first will contain all indices from `[0, mid)` (excluding
863 /// the index `mid` itself) and the second will contain all
864 /// indices from `[mid, len)` (excluding the index `len` itself).
866 /// Fails if `mid > len`.
871 /// let mut v = [1, 2, 3, 4, 5, 6];
873 /// // scoped to restrict the lifetime of the borrows
875 /// let (left, right) = v.mut_split_at(0);
876 /// assert!(left == &mut []);
877 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
881 /// let (left, right) = v.mut_split_at(2);
882 /// assert!(left == &mut [1, 2]);
883 /// assert!(right == &mut [3, 4, 5, 6]);
887 /// let (left, right) = v.mut_split_at(6);
888 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
889 /// assert!(right == &mut []);
892 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
894 /// Reverse the order of elements in a vector, in place.
899 /// let mut v = [1, 2, 3];
901 /// assert!(v == [3, 2, 1]);
905 /// Returns an unsafe mutable pointer to the element in index
906 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
908 /// Return an unsafe mutable pointer to the vector's buffer.
910 /// The caller must ensure that the vector outlives the pointer this
911 /// function returns, or else it will end up pointing to garbage.
913 /// Modifying the vector may cause its buffer to be reallocated, which
914 /// would also make any pointers to it invalid.
916 fn as_mut_ptr(self) -> *mut T;
918 /// Unsafely sets the element in index to the value.
920 /// This performs no bounds checks, and it is undefined behaviour
921 /// if `index` is larger than the length of `self`. However, it
922 /// does run the destructor at `index`. It is equivalent to
923 /// `self[index] = val`.
928 /// let mut v = ~["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
931 /// // `"baz".to_owned()` is deallocated.
932 /// v.unsafe_set(2, "qux".to_owned());
934 /// // Out of bounds: could cause a crash, or overwriting
935 /// // other data, or something else.
936 /// // v.unsafe_set(10, "oops".to_owned());
939 unsafe fn unsafe_set(self, index: uint, val: T);
941 /// Unchecked vector index assignment. Does not drop the
942 /// old value and hence is only suitable when the vector
943 /// is newly allocated.
948 /// let mut v = ["foo".to_owned(), "bar".to_owned()];
950 /// // memory leak! `"bar".to_owned()` is not deallocated.
951 /// unsafe { v.init_elem(1, "baz".to_owned()); }
953 unsafe fn init_elem(self, i: uint, val: T);
955 /// Copies raw bytes from `src` to `self`.
957 /// This does not run destructors on the overwritten elements, and
958 /// ignores move semantics. `self` and `src` must not
959 /// overlap. Fails if `self` is shorter than `src`.
960 unsafe fn copy_memory(self, src: &[T]);
963 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
965 fn as_mut_slice(self) -> &'a mut [T] { self }
967 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
968 assert!(start <= end);
969 assert!(end <= self.len());
972 data: self.as_mut_ptr().offset(start as int) as *T,
979 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
980 let len = self.len();
981 self.mut_slice(start, len)
985 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
986 self.mut_slice(0, end)
990 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
992 let len = self.len();
993 let self2: &'a mut [T] = mem::transmute_copy(&self);
994 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
999 fn mut_iter(self) -> MutItems<'a, T> {
1001 let p = self.as_mut_ptr();
1002 if mem::size_of::<T>() == 0 {
1004 end: (p as uint + self.len()) as *mut T,
1005 marker: marker::ContravariantLifetime::<'a>,
1006 marker2: marker::NoCopy}
1009 end: p.offset(self.len() as int),
1010 marker: marker::ContravariantLifetime::<'a>,
1011 marker2: marker::NoCopy}
1017 fn mut_last(self) -> Option<&'a mut T> {
1018 let len = self.len();
1019 if len == 0 { return None; }
1020 Some(&mut self[len - 1])
1024 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
1025 MutSplits { v: self, pred: pred, finished: false }
1029 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
1030 assert!(chunk_size > 0);
1031 MutChunks { v: self, chunk_size: chunk_size }
1034 fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
1036 let s: &mut Slice<T> = transmute(self);
1037 match raw::shift_ptr(s) {
1038 // FIXME #13933: this `&` -> `&mut` cast is a little
1040 Some(p) => Some(&mut *(p as *mut _)),
1046 fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
1048 let s: &mut Slice<T> = transmute(self);
1049 match raw::pop_ptr(s) {
1050 // FIXME #13933: this `&` -> `&mut` cast is a little
1052 Some(p) => Some(&mut *(p as *mut _)),
1058 fn swap(self, a: uint, b: uint) {
1060 // Can't take two mutable loans from one vector, so instead just cast
1061 // them to their raw pointers to do the swap
1062 let pa: *mut T = &mut self[a];
1063 let pb: *mut T = &mut self[b];
1069 let mut i: uint = 0;
1070 let ln = self.len();
1072 self.swap(i, ln - i - 1);
1078 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
1079 transmute((self.repr().data as *mut T).offset(index as int))
1083 fn as_mut_ptr(self) -> *mut T {
1084 self.repr().data as *mut T
1088 unsafe fn unsafe_set(self, index: uint, val: T) {
1089 *self.unsafe_mut_ref(index) = val;
1093 unsafe fn init_elem(self, i: uint, val: T) {
1094 mem::overwrite(&mut (*self.as_mut_ptr().offset(i as int)), val);
1098 unsafe fn copy_memory(self, src: &[T]) {
1099 let len_src = src.len();
1100 assert!(self.len() >= len_src);
1101 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
1105 /// Trait for &[T] where T is Cloneable
1106 pub trait MutableCloneableVector<T> {
1107 /// Copies as many elements from `src` as it can into `self` (the
1108 /// shorter of `self.len()` and `src.len()`). Returns the number
1109 /// of elements copied.
1114 /// use std::slice::MutableCloneableVector;
1116 /// let mut dst = [0, 0, 0];
1117 /// let src = [1, 2];
1119 /// assert!(dst.copy_from(src) == 2);
1120 /// assert!(dst == [1, 2, 0]);
1122 /// let src2 = [3, 4, 5, 6];
1123 /// assert!(dst.copy_from(src2) == 3);
1124 /// assert!(dst == [3, 4, 5]);
1126 fn copy_from(self, &[T]) -> uint;
1129 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
1131 fn copy_from(self, src: &[T]) -> uint {
1132 for (a, b) in self.mut_iter().zip(src.iter()) {
1135 cmp::min(self.len(), src.len())
1139 /// Unsafe operations
1145 use option::{None, Option, Some};
1148 * Form a slice from a pointer and length (as a number of units,
1152 pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
1161 * Form a slice from a pointer and length (as a number of units,
1165 pub unsafe fn mut_buf_as_slice<T,
1169 f: |v: &mut [T]| -> U)
1178 * Returns a pointer to first element in slice and adjusts
1179 * slice so it no longer contains that element. Returns None
1180 * if the slice is empty. O(1).
1183 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*T> {
1184 if slice.len == 0 { return None; }
1185 let head: *T = slice.data;
1186 slice.data = slice.data.offset(1);
1192 * Returns a pointer to last element in slice and adjusts
1193 * slice so it no longer contains that element. Returns None
1194 * if the slice is empty. O(1).
1197 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*T> {
1198 if slice.len == 0 { return None; }
1199 let tail: *T = slice.data.offset((slice.len - 1) as int);
1205 /// Operations on `[u8]`.
1207 use container::Container;
1209 use slice::MutableVector;
1211 /// A trait for operations on mutable `[u8]`s.
1212 pub trait MutableByteVector {
1213 /// Sets all bytes of the receiver to the given value.
1214 fn set_memory(self, value: u8);
1217 impl<'a> MutableByteVector for &'a mut [u8] {
1219 fn set_memory(self, value: u8) {
1220 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1224 /// Copies data from `src` to `dst`
1226 /// `src` and `dst` must not overlap. Fails if the length of `dst`
1227 /// is less than the length of `src`.
1229 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1230 // Bound checks are done at .copy_memory.
1231 unsafe { dst.copy_memory(src) }
1235 /// Immutable slice iterator
1236 pub struct Items<'a, T> {
1239 marker: marker::ContravariantLifetime<'a>
1242 /// Mutable slice iterator
1243 pub struct MutItems<'a, T> {
1246 marker: marker::ContravariantLifetime<'a>,
1247 marker2: marker::NoCopy
1250 macro_rules! iterator {
1251 (struct $name:ident -> $ptr:ty, $elem:ty) => {
1252 impl<'a, T> Iterator<$elem> for $name<'a, T> {
1254 fn next(&mut self) -> Option<$elem> {
1255 // could be implemented with slices, but this avoids bounds checks
1257 if self.ptr == self.end {
1261 self.ptr = if mem::size_of::<T>() == 0 {
1262 // purposefully don't use 'ptr.offset' because for
1263 // vectors with 0-size elements this would return the
1265 transmute(self.ptr as uint + 1)
1270 Some(transmute(old))
1276 fn size_hint(&self) -> (uint, Option<uint>) {
1277 let diff = (self.end as uint) - (self.ptr as uint);
1278 let size = mem::size_of::<T>();
1279 let exact = diff / (if size == 0 {1} else {size});
1280 (exact, Some(exact))
1284 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
1286 fn next_back(&mut self) -> Option<$elem> {
1287 // could be implemented with slices, but this avoids bounds checks
1289 if self.end == self.ptr {
1292 self.end = if mem::size_of::<T>() == 0 {
1293 // See above for why 'ptr.offset' isn't used
1294 transmute(self.end as uint - 1)
1298 Some(transmute(self.end))
1306 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
1308 fn indexable(&self) -> uint {
1309 let (exact, _) = self.size_hint();
1314 fn idx(&mut self, index: uint) -> Option<&'a T> {
1316 if index < self.indexable() {
1317 transmute(self.ptr.offset(index as int))
1325 iterator!{struct Items -> *T, &'a T}
1327 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
1328 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
1330 impl<'a, T> Clone for Items<'a, T> {
1331 fn clone(&self) -> Items<'a, T> { *self }
1334 iterator!{struct MutItems -> *mut T, &'a mut T}
1336 /// An iterator over the subslices of the vector which are separated
1337 /// by elements that match `pred`.
1338 pub struct MutSplits<'a, T> {
1340 pred: |t: &T|: 'a -> bool,
1344 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
1346 fn next(&mut self) -> Option<&'a mut [T]> {
1347 if self.finished { return None; }
1349 let pred = &mut self.pred;
1350 match self.v.iter().position(|x| (*pred)(x)) {
1352 self.finished = true;
1353 let tmp = mem::replace(&mut self.v, &mut []);
1354 let len = tmp.len();
1355 let (head, tail) = tmp.mut_split_at(len);
1360 let tmp = mem::replace(&mut self.v, &mut []);
1361 let (head, tail) = tmp.mut_split_at(idx);
1362 self.v = tail.mut_slice_from(1);
1369 fn size_hint(&self) -> (uint, Option<uint>) {
1373 // if the predicate doesn't match anything, we yield one slice
1374 // if it matches every element, we yield len+1 empty slices.
1375 (1, Some(self.v.len() + 1))
1380 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
1382 fn next_back(&mut self) -> Option<&'a mut [T]> {
1383 if self.finished { return None; }
1385 let pred = &mut self.pred;
1386 match self.v.iter().rposition(|x| (*pred)(x)) {
1388 self.finished = true;
1389 let tmp = mem::replace(&mut self.v, &mut []);
1393 let tmp = mem::replace(&mut self.v, &mut []);
1394 let (head, tail) = tmp.mut_split_at(idx);
1396 Some(tail.mut_slice_from(1))
1402 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
1403 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
1405 pub struct MutChunks<'a, T> {
1410 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
1412 fn next(&mut self) -> Option<&'a mut [T]> {
1413 if self.v.len() == 0 {
1416 let sz = cmp::min(self.v.len(), self.chunk_size);
1417 let tmp = mem::replace(&mut self.v, &mut []);
1418 let (head, tail) = tmp.mut_split_at(sz);
1425 fn size_hint(&self) -> (uint, Option<uint>) {
1426 if self.v.len() == 0 {
1429 let (n, rem) = div_rem(self.v.len(), self.chunk_size);
1430 let n = if rem > 0 { n + 1 } else { n };
1436 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
1438 fn next_back(&mut self) -> Option<&'a mut [T]> {
1439 if self.v.len() == 0 {
1442 let remainder = self.v.len() % self.chunk_size;
1443 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1444 let tmp = mem::replace(&mut self.v, &mut []);
1445 let tmp_len = tmp.len();
1446 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
1453 impl<'a, T> Default for &'a [T] {
1454 fn default() -> &'a [T] { &[] }
1457 impl<T> Default for ~[T] {
1458 fn default() -> ~[T] { ~[] }