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`.
15 #![doc(primitive = "slice")]
19 use collections::Collection;
20 use cmp::{PartialEq, Ord, Ordering, Less, Equal, Greater};
24 use num::{CheckedAdd, Saturating, div_rem};
25 use option::{None, Option, Some};
31 use raw::{Repr, Slice};
34 * Converts a pointer to A into a slice of length 1 (without copying).
36 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
38 transmute(Slice { data: s, len: 1 })
43 * Converts a pointer to A into a slice of length 1 (without copying).
45 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
47 let ptr: *A = transmute(s);
48 transmute(Slice { data: ptr, len: 1 })
52 /// An iterator over the slices of a vector separated by elements that
53 /// match a predicate function.
54 pub struct Splits<'a, T> {
56 pred: |t: &T|: 'a -> bool,
60 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
62 fn next(&mut self) -> Option<&'a [T]> {
63 if self.finished { return None; }
65 match self.v.iter().position(|x| (self.pred)(x)) {
71 let ret = Some(self.v.slice(0, idx));
72 self.v = self.v.slice(idx + 1, self.v.len());
79 fn size_hint(&self) -> (uint, Option<uint>) {
83 (1, Some(self.v.len() + 1))
88 impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
90 fn next_back(&mut self) -> Option<&'a [T]> {
91 if self.finished { return None; }
93 match self.v.iter().rposition(|x| (self.pred)(x)) {
99 let ret = Some(self.v.slice(idx + 1, self.v.len()));
100 self.v = self.v.slice(0, idx);
107 /// An iterator over the slices of a vector separated by elements that
108 /// match a predicate function, splitting at most a fixed number of times.
109 pub struct SplitsN<'a, T> {
115 impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
117 fn next(&mut self) -> Option<&'a [T]> {
119 if self.iter.finished {
122 self.iter.finished = true;
127 if self.invert { self.iter.next_back() } else { self.iter.next() }
132 fn size_hint(&self) -> (uint, Option<uint>) {
133 if self.iter.finished {
136 (1, Some(cmp::min(self.count, self.iter.v.len()) + 1))
141 // Functional utilities
143 /// An iterator over the (overlapping) slices of length `size` within
146 pub struct Windows<'a, T> {
151 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
153 fn next(&mut self) -> Option<&'a [T]> {
154 if self.size > self.v.len() {
157 let ret = Some(self.v.slice(0, self.size));
158 self.v = self.v.slice(1, self.v.len());
164 fn size_hint(&self) -> (uint, Option<uint>) {
165 if self.size > self.v.len() {
168 let x = self.v.len() - self.size;
169 (x.saturating_add(1), x.checked_add(&1u))
174 /// An iterator over a vector in (non-overlapping) chunks (`size`
175 /// elements at a time).
177 /// When the vector len is not evenly divided by the chunk size,
178 /// the last slice of the iteration will be the remainder.
180 pub struct Chunks<'a, T> {
185 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
187 fn next(&mut self) -> Option<&'a [T]> {
188 if self.v.len() == 0 {
191 let chunksz = cmp::min(self.v.len(), self.size);
192 let (fst, snd) = (self.v.slice_to(chunksz),
193 self.v.slice_from(chunksz));
200 fn size_hint(&self) -> (uint, Option<uint>) {
201 if self.v.len() == 0 {
204 let (n, rem) = div_rem(self.v.len(), self.size);
205 let n = if rem > 0 { n+1 } else { n };
211 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
213 fn next_back(&mut self) -> Option<&'a [T]> {
214 if self.v.len() == 0 {
217 let remainder = self.v.len() % self.size;
218 let chunksz = if remainder != 0 { remainder } else { self.size };
219 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
220 self.v.slice_from(self.v.len() - chunksz));
227 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
229 fn indexable(&self) -> uint {
230 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
234 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
235 if index < self.indexable() {
236 let lo = index * self.size;
237 let mut hi = lo + self.size;
238 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
240 Some(self.v.slice(lo, hi))
250 #[allow(missing_doc)]
254 use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Equiv};
256 use collections::Collection;
258 impl<'a,T:PartialEq> PartialEq for &'a [T] {
259 fn eq(&self, other: & &'a [T]) -> bool {
260 self.len() == other.len() &&
261 order::eq(self.iter(), other.iter())
263 fn ne(&self, other: & &'a [T]) -> bool {
264 self.len() != other.len() ||
265 order::ne(self.iter(), other.iter())
269 impl<'a,T:Eq> Eq for &'a [T] {}
271 impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] {
273 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
276 impl<'a,T:Ord> Ord for &'a [T] {
277 fn cmp(&self, other: & &'a [T]) -> Ordering {
278 order::cmp(self.iter(), other.iter())
282 impl<'a, T: PartialOrd> PartialOrd for &'a [T] {
283 fn lt(&self, other: & &'a [T]) -> bool {
284 order::lt(self.iter(), other.iter())
287 fn le(&self, other: & &'a [T]) -> bool {
288 order::le(self.iter(), other.iter())
291 fn ge(&self, other: & &'a [T]) -> bool {
292 order::ge(self.iter(), other.iter())
295 fn gt(&self, other: & &'a [T]) -> bool {
296 order::gt(self.iter(), other.iter())
304 /// Any vector that can be represented as a slice.
305 pub trait Vector<T> {
306 /// Work with `self` as a slice.
307 fn as_slice<'a>(&'a self) -> &'a [T];
310 impl<'a,T> Vector<T> for &'a [T] {
312 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
315 impl<'a, T> Collection for &'a [T] {
316 /// Returns the length of a vector
318 fn len(&self) -> uint {
323 /// Extension methods for vectors
324 pub trait ImmutableVector<'a, T> {
326 * Returns a slice of self spanning the interval [`start`, `end`).
328 * Fails when the slice (or part of it) is outside the bounds of self,
329 * or when `start` > `end`.
331 fn slice(&self, start: uint, end: uint) -> &'a [T];
334 * Returns a slice of self from `start` to the end of the vec.
336 * Fails when `start` points outside the bounds of self.
338 fn slice_from(&self, start: uint) -> &'a [T];
341 * Returns a slice of self from the start of the vec to `end`.
343 * Fails when `end` points outside the bounds of self.
345 fn slice_to(&self, end: uint) -> &'a [T];
346 /// Returns an iterator over the vector
347 fn iter(self) -> Items<'a, T>;
348 /// Returns an iterator over the subslices of the vector which are
349 /// separated by elements that match `pred`. The matched element
350 /// is not contained in the subslices.
351 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
352 /// Returns an iterator over the subslices of the vector which are
353 /// separated by elements that match `pred`, limited to splitting
354 /// at most `n` times. The matched element is not contained in
356 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
357 /// Returns an iterator over the subslices of the vector which are
358 /// separated by elements that match `pred` limited to splitting
359 /// at most `n` times. This starts at the end of the vector and
360 /// works backwards. The matched element is not contained in the
362 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
365 * Returns an iterator over all contiguous windows of length
366 * `size`. The windows overlap. If the vector is shorter than
367 * `size`, the iterator returns no values.
371 * Fails if `size` is 0.
375 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
379 * let v = &[1i, 2, 3, 4];
380 * for win in v.windows(2) {
381 * println!("{}", win);
386 fn windows(self, size: uint) -> Windows<'a, T>;
389 * Returns an iterator over `size` elements of the vector at a
390 * time. The chunks do not overlap. If `size` does not divide the
391 * length of the vector, then the last chunk will not have length
396 * Fails if `size` is 0.
400 * Print the vector two elements at a time (i.e. `[1,2]`,
404 * let v = &[1i, 2, 3, 4, 5];
405 * for win in v.chunks(2) {
406 * println!("{}", win);
411 fn chunks(self, size: uint) -> Chunks<'a, T>;
413 /// Returns the element of a vector at the given index, or `None` if the
414 /// index is out of bounds
415 fn get(&self, index: uint) -> Option<&'a T>;
416 /// Returns the first element of a vector, or `None` if it is empty
417 fn head(&self) -> Option<&'a T>;
418 /// Returns all but the first element of a vector
419 fn tail(&self) -> &'a [T];
420 /// Returns all but the first `n' elements of a vector
421 fn tailn(&self, n: uint) -> &'a [T];
422 /// Returns all but the last element of a vector
423 fn init(&self) -> &'a [T];
424 /// Returns all but the last `n' elements of a vector
425 fn initn(&self, n: uint) -> &'a [T];
426 /// Returns the last element of a vector, or `None` if it is empty.
427 fn last(&self) -> Option<&'a T>;
429 /// Returns a pointer to the element at the given index, without doing
431 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
434 * Returns an unsafe pointer to the vector's buffer
436 * The caller must ensure that the vector outlives the pointer this
437 * function returns, or else it will end up pointing to garbage.
439 * Modifying the vector may cause its buffer to be reallocated, which
440 * would also make any pointers to it invalid.
442 fn as_ptr(&self) -> *T;
445 * Binary search a sorted vector with a comparator function.
447 * The comparator function should implement an order consistent
448 * with the sort order of the underlying vector, returning an
449 * order code that indicates whether its argument is `Less`,
450 * `Equal` or `Greater` the desired target.
452 * Returns the index where the comparator returned `Equal`, or `None` if
455 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
458 * Returns an immutable reference to the first element in this slice
459 * and adjusts the slice in place so that it no longer contains
460 * that element. O(1).
465 * if self.len() == 0 { return None }
466 * let head = &self[0];
467 * *self = self.slice_from(1);
471 * Returns `None` if vector is empty
473 fn shift_ref(&mut self) -> Option<&'a T>;
476 * Returns an immutable reference to the last element in this slice
477 * and adjusts the slice in place so that it no longer contains
478 * that element. O(1).
483 * if self.len() == 0 { return None; }
484 * let tail = &self[self.len() - 1];
485 * *self = self.slice_to(self.len() - 1);
489 * Returns `None` if slice is empty.
491 fn pop_ref(&mut self) -> Option<&'a T>;
494 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
496 fn slice(&self, start: uint, end: uint) -> &'a [T] {
497 assert!(start <= end);
498 assert!(end <= self.len());
501 data: self.as_ptr().offset(start as int),
508 fn slice_from(&self, start: uint) -> &'a [T] {
509 self.slice(start, self.len())
513 fn slice_to(&self, end: uint) -> &'a [T] {
518 fn iter(self) -> Items<'a, T> {
520 let p = self.as_ptr();
521 if mem::size_of::<T>() == 0 {
523 end: (p as uint + self.len()) as *T,
524 marker: marker::ContravariantLifetime::<'a>}
527 end: p.offset(self.len() as int),
528 marker: marker::ContravariantLifetime::<'a>}
534 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
543 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
545 iter: self.split(pred),
552 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
554 iter: self.split(pred),
561 fn windows(self, size: uint) -> Windows<'a, T> {
563 Windows { v: self, size: size }
567 fn chunks(self, size: uint) -> Chunks<'a, T> {
569 Chunks { v: self, size: size }
573 fn get(&self, index: uint) -> Option<&'a T> {
574 if index < self.len() { Some(&self[index]) } else { None }
578 fn head(&self) -> Option<&'a T> {
579 if self.len() == 0 { None } else { Some(&self[0]) }
583 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
586 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
589 fn init(&self) -> &'a [T] {
590 self.slice(0, self.len() - 1)
594 fn initn(&self, n: uint) -> &'a [T] {
595 self.slice(0, self.len() - n)
599 fn last(&self) -> Option<&'a T> {
600 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
604 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
605 transmute(self.repr().data.offset(index as int))
609 fn as_ptr(&self) -> *T {
614 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
615 let mut base : uint = 0;
616 let mut lim : uint = self.len();
619 let ix = base + (lim >> 1);
621 Equal => return Some(ix),
633 fn shift_ref(&mut self) -> Option<&'a T> {
635 let s: &mut Slice<T> = transmute(self);
636 match raw::shift_ptr(s) {
637 Some(p) => Some(&*p),
643 fn pop_ref(&mut self) -> Option<&'a T> {
645 let s: &mut Slice<T> = transmute(self);
646 match raw::pop_ptr(s) {
647 Some(p) => Some(&*p),
654 /// Extension methods for vectors contain `PartialEq` elements.
655 pub trait ImmutableEqVector<T:PartialEq> {
656 /// Find the first index containing a matching value
657 fn position_elem(&self, t: &T) -> Option<uint>;
659 /// Find the last index containing a matching value
660 fn rposition_elem(&self, t: &T) -> Option<uint>;
662 /// Return true if a vector contains an element with the given value
663 fn contains(&self, x: &T) -> bool;
665 /// Returns true if `needle` is a prefix of the vector.
666 fn starts_with(&self, needle: &[T]) -> bool;
668 /// Returns true if `needle` is a suffix of the vector.
669 fn ends_with(&self, needle: &[T]) -> bool;
672 impl<'a,T:PartialEq> ImmutableEqVector<T> for &'a [T] {
674 fn position_elem(&self, x: &T) -> Option<uint> {
675 self.iter().position(|y| *x == *y)
679 fn rposition_elem(&self, t: &T) -> Option<uint> {
680 self.iter().rposition(|x| *x == *t)
684 fn contains(&self, x: &T) -> bool {
685 self.iter().any(|elt| *x == *elt)
689 fn starts_with(&self, needle: &[T]) -> bool {
690 let n = needle.len();
691 self.len() >= n && needle == self.slice_to(n)
695 fn ends_with(&self, needle: &[T]) -> bool {
696 let (m, n) = (self.len(), needle.len());
697 m >= n && needle == self.slice_from(m - n)
701 /// Extension methods for vectors containing `Ord` elements.
702 pub trait ImmutableOrdVector<T: Ord> {
704 * Binary search a sorted vector for a given element.
706 * Returns the index of the element or None if not found.
708 fn bsearch_elem(&self, x: &T) -> Option<uint>;
711 impl<'a, T: Ord> ImmutableOrdVector<T> for &'a [T] {
712 fn bsearch_elem(&self, x: &T) -> Option<uint> {
713 self.bsearch(|p| p.cmp(x))
717 /// Extension methods for vectors such that their elements are
719 pub trait MutableVector<'a, T> {
720 /// Returns a mutable reference to the element at the given index,
721 /// or `None` if the index is out of bounds
722 fn get_mut(self, index: uint) -> Option<&'a mut T>;
723 /// Work with `self` as a mut slice.
724 /// Primarily intended for getting a &mut [T] from a [T, ..N].
725 fn as_mut_slice(self) -> &'a mut [T];
727 /// Return a slice that points into another slice.
728 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
731 * Returns a slice of self from `start` to the end of the vec.
733 * Fails when `start` points outside the bounds of self.
735 fn mut_slice_from(self, start: uint) -> &'a mut [T];
738 * Returns a slice of self from the start of the vec to `end`.
740 * Fails when `end` points outside the bounds of self.
742 fn mut_slice_to(self, end: uint) -> &'a mut [T];
744 /// Returns an iterator that allows modifying each value
745 fn mut_iter(self) -> MutItems<'a, T>;
747 /// Returns a mutable pointer to the last item in the vector.
748 fn mut_last(self) -> Option<&'a mut T>;
750 /// Returns an iterator over the mutable subslices of the vector
751 /// which are separated by elements that match `pred`. The
752 /// matched element is not contained in the subslices.
753 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
756 * Returns an iterator over `size` elements of the vector at a time.
757 * The chunks are mutable and do not overlap. If `size` does not divide the
758 * length of the vector, then the last chunk will not have length
763 * Fails if `size` is 0.
765 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
768 * Returns a mutable reference to the first element in this slice
769 * and adjusts the slice in place so that it no longer contains
770 * that element. O(1).
775 * if self.len() == 0 { return None; }
776 * let head = &mut self[0];
777 * *self = self.mut_slice_from(1);
781 * Returns `None` if slice is empty
783 fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
786 * Returns a mutable reference to the last element in this slice
787 * and adjusts the slice in place so that it no longer contains
788 * that element. O(1).
793 * if self.len() == 0 { return None; }
794 * let tail = &mut self[self.len() - 1];
795 * *self = self.mut_slice_to(self.len() - 1);
799 * Returns `None` if slice is empty.
801 fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
803 /// Swaps two elements in a vector.
805 /// Fails if `a` or `b` are out of bounds.
809 /// * a - The index of the first element
810 /// * b - The index of the second element
815 /// let mut v = ["a", "b", "c", "d"];
817 /// assert!(v == ["a", "d", "c", "b"]);
819 fn swap(self, a: uint, b: uint);
822 /// Divides one `&mut` into two at an index.
824 /// The first will contain all indices from `[0, mid)` (excluding
825 /// the index `mid` itself) and the second will contain all
826 /// indices from `[mid, len)` (excluding the index `len` itself).
828 /// Fails if `mid > len`.
833 /// let mut v = [1i, 2, 3, 4, 5, 6];
835 /// // scoped to restrict the lifetime of the borrows
837 /// let (left, right) = v.mut_split_at(0);
838 /// assert!(left == &mut []);
839 /// assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
843 /// let (left, right) = v.mut_split_at(2);
844 /// assert!(left == &mut [1i, 2]);
845 /// assert!(right == &mut [3i, 4, 5, 6]);
849 /// let (left, right) = v.mut_split_at(6);
850 /// assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
851 /// assert!(right == &mut []);
854 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
856 /// Reverse the order of elements in a vector, in place.
861 /// let mut v = [1i, 2, 3];
863 /// assert!(v == [3i, 2, 1]);
867 /// Returns an unsafe mutable pointer to the element in index
868 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
870 /// Return an unsafe mutable pointer to the vector's buffer.
872 /// The caller must ensure that the vector outlives the pointer this
873 /// function returns, or else it will end up pointing to garbage.
875 /// Modifying the vector may cause its buffer to be reallocated, which
876 /// would also make any pointers to it invalid.
878 fn as_mut_ptr(self) -> *mut T;
880 /// Unsafely sets the element in index to the value.
882 /// This performs no bounds checks, and it is undefined behaviour
883 /// if `index` is larger than the length of `self`. However, it
884 /// does run the destructor at `index`. It is equivalent to
885 /// `self[index] = val`.
890 /// let mut v = ["foo".to_string(), "bar".to_string(), "baz".to_string()];
893 /// // `"baz".to_string()` is deallocated.
894 /// v.unsafe_set(2, "qux".to_string());
896 /// // Out of bounds: could cause a crash, or overwriting
897 /// // other data, or something else.
898 /// // v.unsafe_set(10, "oops".to_string());
901 unsafe fn unsafe_set(self, index: uint, val: T);
903 /// Unchecked vector index assignment. Does not drop the
904 /// old value and hence is only suitable when the vector
905 /// is newly allocated.
910 /// let mut v = ["foo".to_string(), "bar".to_string()];
912 /// // memory leak! `"bar".to_string()` is not deallocated.
913 /// unsafe { v.init_elem(1, "baz".to_string()); }
915 unsafe fn init_elem(self, i: uint, val: T);
917 /// Copies raw bytes from `src` to `self`.
919 /// This does not run destructors on the overwritten elements, and
920 /// ignores move semantics. `self` and `src` must not
921 /// overlap. Fails if `self` is shorter than `src`.
922 unsafe fn copy_memory(self, src: &[T]);
925 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
927 fn get_mut(self, index: uint) -> Option<&'a mut T> {
928 if index < self.len() { Some(&mut self[index]) } else { None }
932 fn as_mut_slice(self) -> &'a mut [T] { self }
934 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
935 assert!(start <= end);
936 assert!(end <= self.len());
939 data: self.as_mut_ptr().offset(start as int) as *T,
946 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
947 let len = self.len();
948 self.mut_slice(start, len)
952 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
953 self.mut_slice(0, end)
957 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
959 let len = self.len();
960 let self2: &'a mut [T] = mem::transmute_copy(&self);
961 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
966 fn mut_iter(self) -> MutItems<'a, T> {
968 let p = self.as_mut_ptr();
969 if mem::size_of::<T>() == 0 {
971 end: (p as uint + self.len()) as *mut T,
972 marker: marker::ContravariantLifetime::<'a>,
973 marker2: marker::NoCopy}
976 end: p.offset(self.len() as int),
977 marker: marker::ContravariantLifetime::<'a>,
978 marker2: marker::NoCopy}
984 fn mut_last(self) -> Option<&'a mut T> {
985 let len = self.len();
986 if len == 0 { return None; }
987 Some(&mut self[len - 1])
991 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
992 MutSplits { v: self, pred: pred, finished: false }
996 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
997 assert!(chunk_size > 0);
998 MutChunks { v: self, chunk_size: chunk_size }
1001 fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
1003 let s: &mut Slice<T> = transmute(self);
1004 match raw::shift_ptr(s) {
1005 // FIXME #13933: this `&` -> `&mut` cast is a little
1007 Some(p) => Some(&mut *(p as *mut _)),
1013 fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
1015 let s: &mut Slice<T> = transmute(self);
1016 match raw::pop_ptr(s) {
1017 // FIXME #13933: this `&` -> `&mut` cast is a little
1019 Some(p) => Some(&mut *(p as *mut _)),
1025 fn swap(self, a: uint, b: uint) {
1027 // Can't take two mutable loans from one vector, so instead just cast
1028 // them to their raw pointers to do the swap
1029 let pa: *mut T = &mut self[a];
1030 let pb: *mut T = &mut self[b];
1036 let mut i: uint = 0;
1037 let ln = self.len();
1039 self.swap(i, ln - i - 1);
1045 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
1046 transmute((self.repr().data as *mut T).offset(index as int))
1050 fn as_mut_ptr(self) -> *mut T {
1051 self.repr().data as *mut T
1055 unsafe fn unsafe_set(self, index: uint, val: T) {
1056 *self.unsafe_mut_ref(index) = val;
1060 unsafe fn init_elem(self, i: uint, val: T) {
1061 ptr::write(&mut (*self.as_mut_ptr().offset(i as int)), val);
1065 unsafe fn copy_memory(self, src: &[T]) {
1066 let len_src = src.len();
1067 assert!(self.len() >= len_src);
1068 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
1072 /// Trait for &[T] where T is Cloneable
1073 pub trait MutableCloneableVector<T> {
1074 /// Copies as many elements from `src` as it can into `self` (the
1075 /// shorter of `self.len()` and `src.len()`). Returns the number
1076 /// of elements copied.
1081 /// use std::slice::MutableCloneableVector;
1083 /// let mut dst = [0i, 0, 0];
1084 /// let src = [1i, 2];
1086 /// assert!(dst.copy_from(src) == 2);
1087 /// assert!(dst == [1, 2, 0]);
1089 /// let src2 = [3i, 4, 5, 6];
1090 /// assert!(dst.copy_from(src2) == 3);
1091 /// assert!(dst == [3i, 4, 5]);
1093 fn copy_from(self, &[T]) -> uint;
1096 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
1098 fn copy_from(self, src: &[T]) -> uint {
1099 for (a, b) in self.mut_iter().zip(src.iter()) {
1102 cmp::min(self.len(), src.len())
1106 /// Unsafe operations
1111 use option::{None, Option, Some};
1114 * Form a slice from a pointer and length (as a number of units,
1118 pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
1127 * Form a slice from a pointer and length (as a number of units,
1131 pub unsafe fn mut_buf_as_slice<T,
1135 f: |v: &mut [T]| -> U)
1144 * Returns a pointer to first element in slice and adjusts
1145 * slice so it no longer contains that element. Returns None
1146 * if the slice is empty. O(1).
1149 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*T> {
1150 if slice.len == 0 { return None; }
1151 let head: *T = slice.data;
1152 slice.data = slice.data.offset(1);
1158 * Returns a pointer to last element in slice and adjusts
1159 * slice so it no longer contains that element. Returns None
1160 * if the slice is empty. O(1).
1163 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*T> {
1164 if slice.len == 0 { return None; }
1165 let tail: *T = slice.data.offset((slice.len - 1) as int);
1171 /// Operations on `[u8]`.
1173 use collections::Collection;
1175 use slice::MutableVector;
1177 /// A trait for operations on mutable `[u8]`s.
1178 pub trait MutableByteVector {
1179 /// Sets all bytes of the receiver to the given value.
1180 fn set_memory(self, value: u8);
1183 impl<'a> MutableByteVector for &'a mut [u8] {
1185 #[allow(experimental)]
1186 fn set_memory(self, value: u8) {
1187 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1191 /// Copies data from `src` to `dst`
1193 /// `src` and `dst` must not overlap. Fails if the length of `dst`
1194 /// is less than the length of `src`.
1196 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1197 // Bound checks are done at .copy_memory.
1198 unsafe { dst.copy_memory(src) }
1202 /// Immutable slice iterator
1203 pub struct Items<'a, T> {
1206 marker: marker::ContravariantLifetime<'a>
1209 /// Mutable slice iterator
1210 pub struct MutItems<'a, T> {
1213 marker: marker::ContravariantLifetime<'a>,
1214 marker2: marker::NoCopy
1217 macro_rules! iterator {
1218 (struct $name:ident -> $ptr:ty, $elem:ty) => {
1219 impl<'a, T> Iterator<$elem> for $name<'a, T> {
1221 fn next(&mut self) -> Option<$elem> {
1222 // could be implemented with slices, but this avoids bounds checks
1224 if self.ptr == self.end {
1228 self.ptr = if mem::size_of::<T>() == 0 {
1229 // purposefully don't use 'ptr.offset' because for
1230 // vectors with 0-size elements this would return the
1232 transmute(self.ptr as uint + 1)
1237 Some(transmute(old))
1243 fn size_hint(&self) -> (uint, Option<uint>) {
1244 let diff = (self.end as uint) - (self.ptr as uint);
1245 let size = mem::size_of::<T>();
1246 let exact = diff / (if size == 0 {1} else {size});
1247 (exact, Some(exact))
1251 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
1253 fn next_back(&mut self) -> Option<$elem> {
1254 // could be implemented with slices, but this avoids bounds checks
1256 if self.end == self.ptr {
1259 self.end = if mem::size_of::<T>() == 0 {
1260 // See above for why 'ptr.offset' isn't used
1261 transmute(self.end as uint - 1)
1265 Some(transmute(self.end))
1273 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
1275 fn indexable(&self) -> uint {
1276 let (exact, _) = self.size_hint();
1281 fn idx(&mut self, index: uint) -> Option<&'a T> {
1283 if index < self.indexable() {
1284 transmute(self.ptr.offset(index as int))
1292 iterator!{struct Items -> *T, &'a T}
1294 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
1295 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
1297 impl<'a, T> Clone for Items<'a, T> {
1298 fn clone(&self) -> Items<'a, T> { *self }
1301 iterator!{struct MutItems -> *mut T, &'a mut T}
1303 /// An iterator over the subslices of the vector which are separated
1304 /// by elements that match `pred`.
1305 pub struct MutSplits<'a, T> {
1307 pred: |t: &T|: 'a -> bool,
1311 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
1313 fn next(&mut self) -> Option<&'a mut [T]> {
1314 if self.finished { return None; }
1316 let pred = &mut self.pred;
1317 match self.v.iter().position(|x| (*pred)(x)) {
1319 self.finished = true;
1320 let tmp = mem::replace(&mut self.v, &mut []);
1321 let len = tmp.len();
1322 let (head, tail) = tmp.mut_split_at(len);
1327 let tmp = mem::replace(&mut self.v, &mut []);
1328 let (head, tail) = tmp.mut_split_at(idx);
1329 self.v = tail.mut_slice_from(1);
1336 fn size_hint(&self) -> (uint, Option<uint>) {
1340 // if the predicate doesn't match anything, we yield one slice
1341 // if it matches every element, we yield len+1 empty slices.
1342 (1, Some(self.v.len() + 1))
1347 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
1349 fn next_back(&mut self) -> Option<&'a mut [T]> {
1350 if self.finished { return None; }
1352 let pred = &mut self.pred;
1353 match self.v.iter().rposition(|x| (*pred)(x)) {
1355 self.finished = true;
1356 let tmp = mem::replace(&mut self.v, &mut []);
1360 let tmp = mem::replace(&mut self.v, &mut []);
1361 let (head, tail) = tmp.mut_split_at(idx);
1363 Some(tail.mut_slice_from(1))
1369 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
1370 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
1372 pub struct MutChunks<'a, T> {
1377 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
1379 fn next(&mut self) -> Option<&'a mut [T]> {
1380 if self.v.len() == 0 {
1383 let sz = cmp::min(self.v.len(), self.chunk_size);
1384 let tmp = mem::replace(&mut self.v, &mut []);
1385 let (head, tail) = tmp.mut_split_at(sz);
1392 fn size_hint(&self) -> (uint, Option<uint>) {
1393 if self.v.len() == 0 {
1396 let (n, rem) = div_rem(self.v.len(), self.chunk_size);
1397 let n = if rem > 0 { n + 1 } else { n };
1403 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
1405 fn next_back(&mut self) -> Option<&'a mut [T]> {
1406 if self.v.len() == 0 {
1409 let remainder = self.v.len() % self.chunk_size;
1410 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1411 let tmp = mem::replace(&mut self.v, &mut []);
1412 let tmp_len = tmp.len();
1413 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
1420 impl<'a, T> Default for &'a [T] {
1421 fn default() -> &'a [T] { &[] }