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")]
17 // How this module is organized.
19 // The library infrastructure for slices is fairly messy. There's
20 // a lot of stuff defined here. Let's keep it clean.
22 // Since slices don't support inherent methods; all operations
23 // on them are defined on traits, which are then reexported from
24 // the prelude for convenience. So there are a lot of traits here.
26 // The layout of this file is thus:
28 // * Slice-specific 'extension' traits and their implementations. This
29 // is where most of the slice API resides.
30 // * Implementations of a few common traits with important slice ops.
31 // * Definitions of a bunch of iterators.
33 // * The `raw` and `bytes` submodules.
34 // * Boilerplate trait implementations.
38 use collections::Collection;
39 use cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering, Less, Equal, Greater, Equiv};
43 use num::{CheckedAdd, Saturating, div_rem};
44 use option::{None, Option, Some};
50 use raw::{Repr, Slice};
56 /// Extension methods for vectors
57 pub trait ImmutableSlice<'a, T> {
59 * Returns a slice of self spanning the interval [`start`, `end`).
61 * Fails when the slice (or part of it) is outside the bounds of self,
62 * or when `start` > `end`.
64 fn slice(&self, start: uint, end: uint) -> &'a [T];
67 * Returns a slice of self from `start` to the end of the vec.
69 * Fails when `start` points outside the bounds of self.
71 fn slice_from(&self, start: uint) -> &'a [T];
74 * Returns a slice of self from the start of the vec to `end`.
76 * Fails when `end` points outside the bounds of self.
78 fn slice_to(&self, end: uint) -> &'a [T];
80 /// Divides one slice into two at an index.
82 /// The first will contain all indices from `[0, mid)` (excluding
83 /// the index `mid` itself) and the second will contain all
84 /// indices from `[mid, len)` (excluding the index `len` itself).
86 /// Fails if `mid > len`.
87 fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]);
89 /// Returns an iterator over the vector
90 fn iter(self) -> Items<'a, T>;
91 /// Returns an iterator over the subslices of the vector which are
92 /// separated by elements that match `pred`. The matched element
93 /// is not contained in the subslices.
94 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
95 /// Returns an iterator over the subslices of the vector which are
96 /// separated by elements that match `pred`, limited to splitting
97 /// at most `n` times. The matched element is not contained in
99 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
100 /// Returns an iterator over the subslices of the vector which are
101 /// separated by elements that match `pred` limited to splitting
102 /// at most `n` times. This starts at the end of the vector and
103 /// works backwards. The matched element is not contained in the
105 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T>;
108 * Returns an iterator over all contiguous windows of length
109 * `size`. The windows overlap. If the vector is shorter than
110 * `size`, the iterator returns no values.
114 * Fails if `size` is 0.
118 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
122 * let v = &[1i, 2, 3, 4];
123 * for win in v.windows(2) {
124 * println!("{}", win);
129 fn windows(self, size: uint) -> Windows<'a, T>;
132 * Returns an iterator over `size` elements of the vector at a
133 * time. The chunks do not overlap. If `size` does not divide the
134 * length of the vector, then the last chunk will not have length
139 * Fails if `size` is 0.
143 * Print the vector two elements at a time (i.e. `[1,2]`,
147 * let v = &[1i, 2, 3, 4, 5];
148 * for win in v.chunks(2) {
149 * println!("{}", win);
154 fn chunks(self, size: uint) -> Chunks<'a, T>;
156 /// Returns the element of a vector at the given index, or `None` if the
157 /// index is out of bounds
158 fn get(&self, index: uint) -> Option<&'a T>;
159 /// Returns the first element of a vector, or `None` if it is empty
160 fn head(&self) -> Option<&'a T>;
161 /// Returns all but the first element of a vector
162 fn tail(&self) -> &'a [T];
163 /// Returns all but the first `n' elements of a vector
164 fn tailn(&self, n: uint) -> &'a [T];
165 /// Returns all but the last element of a vector
166 fn init(&self) -> &'a [T];
167 /// Returns all but the last `n' elements of a vector
168 fn initn(&self, n: uint) -> &'a [T];
169 /// Returns the last element of a vector, or `None` if it is empty.
170 fn last(&self) -> Option<&'a T>;
172 /// Returns a pointer to the element at the given index, without doing
174 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
177 * Returns an unsafe pointer to the vector's buffer
179 * The caller must ensure that the vector outlives the pointer this
180 * function returns, or else it will end up pointing to garbage.
182 * Modifying the vector may cause its buffer to be reallocated, which
183 * would also make any pointers to it invalid.
185 fn as_ptr(&self) -> *const T;
188 * Binary search a sorted vector with a comparator function.
190 * The comparator function should implement an order consistent
191 * with the sort order of the underlying vector, returning an
192 * order code that indicates whether its argument is `Less`,
193 * `Equal` or `Greater` the desired target.
195 * Returns the index where the comparator returned `Equal`, or `None` if
198 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
201 * Returns an immutable reference to the first element in this slice
202 * and adjusts the slice in place so that it no longer contains
203 * that element. O(1).
208 * if self.len() == 0 { return None }
209 * let head = &self[0];
210 * *self = self.slice_from(1);
214 * Returns `None` if vector is empty
216 fn shift_ref(&mut self) -> Option<&'a T>;
219 * Returns an immutable reference to the last element in this slice
220 * and adjusts the slice in place so that it no longer contains
221 * that element. O(1).
226 * if self.len() == 0 { return None; }
227 * let tail = &self[self.len() - 1];
228 * *self = self.slice_to(self.len() - 1);
232 * Returns `None` if slice is empty.
234 fn pop_ref(&mut self) -> Option<&'a T>;
237 impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
239 fn slice(&self, start: uint, end: uint) -> &'a [T] {
240 assert!(start <= end);
241 assert!(end <= self.len());
244 data: self.as_ptr().offset(start as int),
251 fn slice_from(&self, start: uint) -> &'a [T] {
252 self.slice(start, self.len())
256 fn slice_to(&self, end: uint) -> &'a [T] {
261 fn split_at(&self, mid: uint) -> (&'a [T], &'a [T]) {
262 (self.slice(0, mid), self.slice(mid, self.len()))
266 fn iter(self) -> Items<'a, T> {
268 let p = self.as_ptr();
269 if mem::size_of::<T>() == 0 {
271 end: (p as uint + self.len()) as *const T,
272 marker: marker::ContravariantLifetime::<'a>}
275 end: p.offset(self.len() as int),
276 marker: marker::ContravariantLifetime::<'a>}
282 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
291 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
293 iter: self.split(pred),
300 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<'a, T> {
302 iter: self.split(pred),
309 fn windows(self, size: uint) -> Windows<'a, T> {
311 Windows { v: self, size: size }
315 fn chunks(self, size: uint) -> Chunks<'a, T> {
317 Chunks { v: self, size: size }
321 fn get(&self, index: uint) -> Option<&'a T> {
322 if index < self.len() { Some(&self[index]) } else { None }
326 fn head(&self) -> Option<&'a T> {
327 if self.len() == 0 { None } else { Some(&self[0]) }
331 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
334 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
337 fn init(&self) -> &'a [T] {
338 self.slice(0, self.len() - 1)
342 fn initn(&self, n: uint) -> &'a [T] {
343 self.slice(0, self.len() - n)
347 fn last(&self) -> Option<&'a T> {
348 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
352 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
353 transmute(self.repr().data.offset(index as int))
357 fn as_ptr(&self) -> *const T {
362 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
363 let mut base : uint = 0;
364 let mut lim : uint = self.len();
367 let ix = base + (lim >> 1);
369 Equal => return Some(ix),
381 fn shift_ref(&mut self) -> Option<&'a T> {
383 let s: &mut Slice<T> = transmute(self);
384 match raw::shift_ptr(s) {
385 Some(p) => Some(&*p),
391 fn pop_ref(&mut self) -> Option<&'a T> {
393 let s: &mut Slice<T> = transmute(self);
394 match raw::pop_ptr(s) {
395 Some(p) => Some(&*p),
402 /// Extension methods for vectors such that their elements are
404 pub trait MutableSlice<'a, T> {
405 /// Returns a mutable reference to the element at the given index,
406 /// or `None` if the index is out of bounds
407 fn get_mut(self, index: uint) -> Option<&'a mut T>;
408 /// Work with `self` as a mut slice.
409 /// Primarily intended for getting a &mut [T] from a [T, ..N].
410 fn as_mut_slice(self) -> &'a mut [T];
412 /// Return a slice that points into another slice.
413 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
416 * Returns a slice of self from `start` to the end of the vec.
418 * Fails when `start` points outside the bounds of self.
420 fn mut_slice_from(self, start: uint) -> &'a mut [T];
423 * Returns a slice of self from the start of the vec to `end`.
425 * Fails when `end` points outside the bounds of self.
427 fn mut_slice_to(self, end: uint) -> &'a mut [T];
429 /// Returns an iterator that allows modifying each value
430 fn mut_iter(self) -> MutItems<'a, T>;
432 /// Returns a mutable pointer to the last item in the vector.
433 fn mut_last(self) -> Option<&'a mut T>;
435 /// Returns an iterator over the mutable subslices of the vector
436 /// which are separated by elements that match `pred`. The
437 /// matched element is not contained in the subslices.
438 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
441 * Returns an iterator over `size` elements of the vector at a time.
442 * The chunks are mutable and do not overlap. If `size` does not divide the
443 * length of the vector, then the last chunk will not have length
448 * Fails if `size` is 0.
450 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
453 * Returns a mutable reference to the first element in this slice
454 * and adjusts the slice in place so that it no longer contains
455 * that element. O(1).
460 * if self.len() == 0 { return None; }
461 * let head = &mut self[0];
462 * *self = self.mut_slice_from(1);
466 * Returns `None` if slice is empty
468 fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
471 * Returns a mutable reference to the last element in this slice
472 * and adjusts the slice in place so that it no longer contains
473 * that element. O(1).
478 * if self.len() == 0 { return None; }
479 * let tail = &mut self[self.len() - 1];
480 * *self = self.mut_slice_to(self.len() - 1);
484 * Returns `None` if slice is empty.
486 fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
488 /// Swaps two elements in a vector.
490 /// Fails if `a` or `b` are out of bounds.
494 /// * a - The index of the first element
495 /// * b - The index of the second element
500 /// let mut v = ["a", "b", "c", "d"];
502 /// assert!(v == ["a", "d", "c", "b"]);
504 fn swap(self, a: uint, b: uint);
507 /// Divides one `&mut` into two at an index.
509 /// The first will contain all indices from `[0, mid)` (excluding
510 /// the index `mid` itself) and the second will contain all
511 /// indices from `[mid, len)` (excluding the index `len` itself).
513 /// Fails if `mid > len`.
518 /// let mut v = [1i, 2, 3, 4, 5, 6];
520 /// // scoped to restrict the lifetime of the borrows
522 /// let (left, right) = v.mut_split_at(0);
523 /// assert!(left == &mut []);
524 /// assert!(right == &mut [1i, 2, 3, 4, 5, 6]);
528 /// let (left, right) = v.mut_split_at(2);
529 /// assert!(left == &mut [1i, 2]);
530 /// assert!(right == &mut [3i, 4, 5, 6]);
534 /// let (left, right) = v.mut_split_at(6);
535 /// assert!(left == &mut [1i, 2, 3, 4, 5, 6]);
536 /// assert!(right == &mut []);
539 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
541 /// Reverse the order of elements in a vector, in place.
546 /// let mut v = [1i, 2, 3];
548 /// assert!(v == [3i, 2, 1]);
552 /// Returns an unsafe mutable pointer to the element in index
553 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
555 /// Return an unsafe mutable pointer to the vector's buffer.
557 /// The caller must ensure that the vector outlives the pointer this
558 /// function returns, or else it will end up pointing to garbage.
560 /// Modifying the vector may cause its buffer to be reallocated, which
561 /// would also make any pointers to it invalid.
563 fn as_mut_ptr(self) -> *mut T;
565 /// Unsafely sets the element in index to the value.
567 /// This performs no bounds checks, and it is undefined behaviour
568 /// if `index` is larger than the length of `self`. However, it
569 /// does run the destructor at `index`. It is equivalent to
570 /// `self[index] = val`.
575 /// let mut v = ["foo".to_string(), "bar".to_string(), "baz".to_string()];
578 /// // `"baz".to_string()` is deallocated.
579 /// v.unsafe_set(2, "qux".to_string());
581 /// // Out of bounds: could cause a crash, or overwriting
582 /// // other data, or something else.
583 /// // v.unsafe_set(10, "oops".to_string());
586 unsafe fn unsafe_set(self, index: uint, val: T);
588 /// Unchecked vector index assignment. Does not drop the
589 /// old value and hence is only suitable when the vector
590 /// is newly allocated.
595 /// let mut v = ["foo".to_string(), "bar".to_string()];
597 /// // memory leak! `"bar".to_string()` is not deallocated.
598 /// unsafe { v.init_elem(1, "baz".to_string()); }
600 unsafe fn init_elem(self, i: uint, val: T);
602 /// Copies raw bytes from `src` to `self`.
604 /// This does not run destructors on the overwritten elements, and
605 /// ignores move semantics. `self` and `src` must not
606 /// overlap. Fails if `self` is shorter than `src`.
607 unsafe fn copy_memory(self, src: &[T]);
610 impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
612 fn get_mut(self, index: uint) -> Option<&'a mut T> {
613 if index < self.len() { Some(&mut self[index]) } else { None }
617 fn as_mut_slice(self) -> &'a mut [T] { self }
619 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
620 assert!(start <= end);
621 assert!(end <= self.len());
624 data: self.as_mut_ptr().offset(start as int) as *const T,
631 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
632 let len = self.len();
633 self.mut_slice(start, len)
637 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
638 self.mut_slice(0, end)
642 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
644 let len = self.len();
645 let self2: &'a mut [T] = mem::transmute_copy(&self);
646 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
651 fn mut_iter(self) -> MutItems<'a, T> {
653 let p = self.as_mut_ptr();
654 if mem::size_of::<T>() == 0 {
656 end: (p as uint + self.len()) as *mut T,
657 marker: marker::ContravariantLifetime::<'a>,
658 marker2: marker::NoCopy}
661 end: p.offset(self.len() as int),
662 marker: marker::ContravariantLifetime::<'a>,
663 marker2: marker::NoCopy}
669 fn mut_last(self) -> Option<&'a mut T> {
670 let len = self.len();
671 if len == 0 { return None; }
672 Some(&mut self[len - 1])
676 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
677 MutSplits { v: self, pred: pred, finished: false }
681 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
682 assert!(chunk_size > 0);
683 MutChunks { v: self, chunk_size: chunk_size }
686 fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
688 let s: &mut Slice<T> = transmute(self);
689 match raw::shift_ptr(s) {
690 // FIXME #13933: this `&` -> `&mut` cast is a little
692 Some(p) => Some(&mut *(p as *mut _)),
698 fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
700 let s: &mut Slice<T> = transmute(self);
701 match raw::pop_ptr(s) {
702 // FIXME #13933: this `&` -> `&mut` cast is a little
704 Some(p) => Some(&mut *(p as *mut _)),
710 fn swap(self, a: uint, b: uint) {
712 // Can't take two mutable loans from one vector, so instead just cast
713 // them to their raw pointers to do the swap
714 let pa: *mut T = &mut self[a];
715 let pb: *mut T = &mut self[b];
724 self.swap(i, ln - i - 1);
730 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
731 transmute((self.repr().data as *mut T).offset(index as int))
735 fn as_mut_ptr(self) -> *mut T {
736 self.repr().data as *mut T
740 unsafe fn unsafe_set(self, index: uint, val: T) {
741 *self.unsafe_mut_ref(index) = val;
745 unsafe fn init_elem(self, i: uint, val: T) {
746 ptr::write(&mut (*self.as_mut_ptr().offset(i as int)), val);
750 unsafe fn copy_memory(self, src: &[T]) {
751 let len_src = src.len();
752 assert!(self.len() >= len_src);
753 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
757 /// Extension methods for vectors contain `PartialEq` elements.
758 pub trait ImmutableEqSlice<T:PartialEq> {
759 /// Find the first index containing a matching value
760 fn position_elem(&self, t: &T) -> Option<uint>;
762 /// Find the last index containing a matching value
763 fn rposition_elem(&self, t: &T) -> Option<uint>;
765 /// Return true if a vector contains an element with the given value
766 fn contains(&self, x: &T) -> bool;
768 /// Returns true if `needle` is a prefix of the vector.
769 fn starts_with(&self, needle: &[T]) -> bool;
771 /// Returns true if `needle` is a suffix of the vector.
772 fn ends_with(&self, needle: &[T]) -> bool;
775 impl<'a,T:PartialEq> ImmutableEqSlice<T> for &'a [T] {
777 fn position_elem(&self, x: &T) -> Option<uint> {
778 self.iter().position(|y| *x == *y)
782 fn rposition_elem(&self, t: &T) -> Option<uint> {
783 self.iter().rposition(|x| *x == *t)
787 fn contains(&self, x: &T) -> bool {
788 self.iter().any(|elt| *x == *elt)
792 fn starts_with(&self, needle: &[T]) -> bool {
793 let n = needle.len();
794 self.len() >= n && needle == self.slice_to(n)
798 fn ends_with(&self, needle: &[T]) -> bool {
799 let (m, n) = (self.len(), needle.len());
800 m >= n && needle == self.slice_from(m - n)
804 /// Extension methods for vectors containing `Ord` elements.
805 pub trait ImmutableOrdSlice<T: Ord> {
807 * Binary search a sorted vector for a given element.
809 * Returns the index of the element or None if not found.
811 fn bsearch_elem(&self, x: &T) -> Option<uint>;
814 impl<'a, T: Ord> ImmutableOrdSlice<T> for &'a [T] {
815 fn bsearch_elem(&self, x: &T) -> Option<uint> {
816 self.bsearch(|p| p.cmp(x))
820 /// Trait for &[T] where T is Cloneable
821 pub trait MutableCloneableSlice<T> {
822 /// Copies as many elements from `src` as it can into `self` (the
823 /// shorter of `self.len()` and `src.len()`). Returns the number
824 /// of elements copied.
829 /// use std::slice::MutableCloneableSlice;
831 /// let mut dst = [0i, 0, 0];
832 /// let src = [1i, 2];
834 /// assert!(dst.copy_from(src) == 2);
835 /// assert!(dst == [1, 2, 0]);
837 /// let src2 = [3i, 4, 5, 6];
838 /// assert!(dst.copy_from(src2) == 3);
839 /// assert!(dst == [3i, 4, 5]);
841 fn copy_from(self, &[T]) -> uint;
844 impl<'a, T:Clone> MutableCloneableSlice<T> for &'a mut [T] {
846 fn copy_from(self, src: &[T]) -> uint {
847 for (a, b) in self.mut_iter().zip(src.iter()) {
850 cmp::min(self.len(), src.len())
861 /// Any vector that can be represented as a slice.
862 pub trait Vector<T> {
863 /// Work with `self` as a slice.
864 fn as_slice<'a>(&'a self) -> &'a [T];
867 impl<'a,T> Vector<T> for &'a [T] {
869 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
872 impl<'a, T> Collection for &'a [T] {
873 /// Returns the length of a vector
875 fn len(&self) -> uint {
880 impl<'a, T> Default for &'a [T] {
881 fn default() -> &'a [T] { &[] }
891 // The shared definition of the `Item` and `MutItems` iterators
892 macro_rules! iterator {
893 (struct $name:ident -> $ptr:ty, $elem:ty) => {
894 impl<'a, T> Iterator<$elem> for $name<'a, T> {
896 fn next(&mut self) -> Option<$elem> {
897 // could be implemented with slices, but this avoids bounds checks
899 if self.ptr == self.end {
902 if mem::size_of::<T>() == 0 {
903 // purposefully don't use 'ptr.offset' because for
904 // vectors with 0-size elements this would return the
906 self.ptr = transmute(self.ptr as uint + 1);
908 // Use a non-null pointer value
912 self.ptr = self.ptr.offset(1);
921 fn size_hint(&self) -> (uint, Option<uint>) {
922 let diff = (self.end as uint) - (self.ptr as uint);
923 let size = mem::size_of::<T>();
924 let exact = diff / (if size == 0 {1} else {size});
929 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
931 fn next_back(&mut self) -> Option<$elem> {
932 // could be implemented with slices, but this avoids bounds checks
934 if self.end == self.ptr {
937 if mem::size_of::<T>() == 0 {
938 // See above for why 'ptr.offset' isn't used
939 self.end = transmute(self.end as uint - 1);
941 // Use a non-null pointer value
944 self.end = self.end.offset(-1);
946 Some(transmute(self.end))
955 /// Immutable slice iterator
956 pub struct Items<'a, T> {
959 marker: marker::ContravariantLifetime<'a>
962 iterator!{struct Items -> *const T, &'a T}
964 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
966 impl<'a, T> Clone for Items<'a, T> {
967 fn clone(&self) -> Items<'a, T> { *self }
970 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
972 fn indexable(&self) -> uint {
973 let (exact, _) = self.size_hint();
978 fn idx(&mut self, index: uint) -> Option<&'a T> {
980 if index < self.indexable() {
981 if mem::size_of::<T>() == 0 {
982 // Use a non-null pointer value
985 Some(transmute(self.ptr.offset(index as int)))
994 /// Mutable slice iterator
995 pub struct MutItems<'a, T> {
998 marker: marker::ContravariantLifetime<'a>,
999 marker2: marker::NoCopy
1002 iterator!{struct MutItems -> *mut T, &'a mut T}
1004 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
1006 /// An iterator over the slices of a vector separated by elements that
1007 /// match a predicate function.
1008 pub struct Splits<'a, T> {
1010 pred: |t: &T|: 'a -> bool,
1014 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
1016 fn next(&mut self) -> Option<&'a [T]> {
1017 if self.finished { return None; }
1019 match self.v.iter().position(|x| (self.pred)(x)) {
1021 self.finished = true;
1025 let ret = Some(self.v.slice(0, idx));
1026 self.v = self.v.slice(idx + 1, self.v.len());
1033 fn size_hint(&self) -> (uint, Option<uint>) {
1037 (1, Some(self.v.len() + 1))
1042 impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
1044 fn next_back(&mut self) -> Option<&'a [T]> {
1045 if self.finished { return None; }
1047 match self.v.iter().rposition(|x| (self.pred)(x)) {
1049 self.finished = true;
1053 let ret = Some(self.v.slice(idx + 1, self.v.len()));
1054 self.v = self.v.slice(0, idx);
1061 /// An iterator over the subslices of the vector which are separated
1062 /// by elements that match `pred`.
1063 pub struct MutSplits<'a, T> {
1065 pred: |t: &T|: 'a -> bool,
1069 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
1071 fn next(&mut self) -> Option<&'a mut [T]> {
1072 if self.finished { return None; }
1074 let pred = &mut self.pred;
1075 match self.v.iter().position(|x| (*pred)(x)) {
1077 self.finished = true;
1078 let tmp = mem::replace(&mut self.v, &mut []);
1079 let len = tmp.len();
1080 let (head, tail) = tmp.mut_split_at(len);
1085 let tmp = mem::replace(&mut self.v, &mut []);
1086 let (head, tail) = tmp.mut_split_at(idx);
1087 self.v = tail.mut_slice_from(1);
1094 fn size_hint(&self) -> (uint, Option<uint>) {
1098 // if the predicate doesn't match anything, we yield one slice
1099 // if it matches every element, we yield len+1 empty slices.
1100 (1, Some(self.v.len() + 1))
1105 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
1107 fn next_back(&mut self) -> Option<&'a mut [T]> {
1108 if self.finished { return None; }
1110 let pred = &mut self.pred;
1111 match self.v.iter().rposition(|x| (*pred)(x)) {
1113 self.finished = true;
1114 let tmp = mem::replace(&mut self.v, &mut []);
1118 let tmp = mem::replace(&mut self.v, &mut []);
1119 let (head, tail) = tmp.mut_split_at(idx);
1121 Some(tail.mut_slice_from(1))
1127 /// An iterator over the slices of a vector separated by elements that
1128 /// match a predicate function, splitting at most a fixed number of times.
1129 pub struct SplitsN<'a, T> {
1130 iter: Splits<'a, T>,
1135 impl<'a, T> Iterator<&'a [T]> for SplitsN<'a, T> {
1137 fn next(&mut self) -> Option<&'a [T]> {
1138 if self.count == 0 {
1139 if self.iter.finished {
1142 self.iter.finished = true;
1147 if self.invert { self.iter.next_back() } else { self.iter.next() }
1152 fn size_hint(&self) -> (uint, Option<uint>) {
1153 if self.iter.finished {
1156 (1, Some(cmp::min(self.count, self.iter.v.len()) + 1))
1161 /// An iterator over the (overlapping) slices of length `size` within
1164 pub struct Windows<'a, T> {
1169 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
1171 fn next(&mut self) -> Option<&'a [T]> {
1172 if self.size > self.v.len() {
1175 let ret = Some(self.v.slice(0, self.size));
1176 self.v = self.v.slice(1, self.v.len());
1182 fn size_hint(&self) -> (uint, Option<uint>) {
1183 if self.size > self.v.len() {
1186 let x = self.v.len() - self.size;
1187 (x.saturating_add(1), x.checked_add(&1u))
1192 /// An iterator over a vector in (non-overlapping) chunks (`size`
1193 /// elements at a time).
1195 /// When the vector len is not evenly divided by the chunk size,
1196 /// the last slice of the iteration will be the remainder.
1198 pub struct Chunks<'a, T> {
1203 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
1205 fn next(&mut self) -> Option<&'a [T]> {
1206 if self.v.len() == 0 {
1209 let chunksz = cmp::min(self.v.len(), self.size);
1210 let (fst, snd) = self.v.split_at(chunksz);
1217 fn size_hint(&self) -> (uint, Option<uint>) {
1218 if self.v.len() == 0 {
1221 let (n, rem) = div_rem(self.v.len(), self.size);
1222 let n = if rem > 0 { n+1 } else { n };
1228 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
1230 fn next_back(&mut self) -> Option<&'a [T]> {
1231 if self.v.len() == 0 {
1234 let remainder = self.v.len() % self.size;
1235 let chunksz = if remainder != 0 { remainder } else { self.size };
1236 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1243 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
1245 fn indexable(&self) -> uint {
1246 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1250 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1251 if index < self.indexable() {
1252 let lo = index * self.size;
1253 let mut hi = lo + self.size;
1254 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1256 Some(self.v.slice(lo, hi))
1263 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
1264 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
1266 pub struct MutChunks<'a, T> {
1271 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
1273 fn next(&mut self) -> Option<&'a mut [T]> {
1274 if self.v.len() == 0 {
1277 let sz = cmp::min(self.v.len(), self.chunk_size);
1278 let tmp = mem::replace(&mut self.v, &mut []);
1279 let (head, tail) = tmp.mut_split_at(sz);
1286 fn size_hint(&self) -> (uint, Option<uint>) {
1287 if self.v.len() == 0 {
1290 let (n, rem) = div_rem(self.v.len(), self.chunk_size);
1291 let n = if rem > 0 { n + 1 } else { n };
1297 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
1299 fn next_back(&mut self) -> Option<&'a mut [T]> {
1300 if self.v.len() == 0 {
1303 let remainder = self.v.len() % self.chunk_size;
1304 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1305 let tmp = mem::replace(&mut self.v, &mut []);
1306 let tmp_len = tmp.len();
1307 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
1322 * Converts a pointer to A into a slice of length 1 (without copying).
1324 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1326 transmute(Slice { data: s, len: 1 })
1331 * Converts a pointer to A into a slice of length 1 (without copying).
1333 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1335 let ptr: *const A = transmute(s);
1336 transmute(Slice { data: ptr, len: 1 })
1347 /// Unsafe operations
1352 use option::{None, Option, Some};
1355 * Form a slice from a pointer and length (as a number of units,
1359 pub unsafe fn buf_as_slice<T,U>(p: *const T, len: uint, f: |v: &[T]| -> U)
1368 * Form a slice from a pointer and length (as a number of units,
1372 pub unsafe fn mut_buf_as_slice<T,
1376 f: |v: &mut [T]| -> U)
1379 data: p as *const T,
1385 * Returns a pointer to first element in slice and adjusts
1386 * slice so it no longer contains that element. Returns None
1387 * if the slice is empty. O(1).
1390 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1391 if slice.len == 0 { return None; }
1392 let head: *const T = slice.data;
1393 slice.data = slice.data.offset(1);
1399 * Returns a pointer to last element in slice and adjusts
1400 * slice so it no longer contains that element. Returns None
1401 * if the slice is empty. O(1).
1404 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1405 if slice.len == 0 { return None; }
1406 let tail: *const T = slice.data.offset((slice.len - 1) as int);
1412 /// Operations on `[u8]`.
1414 use collections::Collection;
1416 use slice::MutableSlice;
1418 /// A trait for operations on mutable `[u8]`s.
1419 pub trait MutableByteVector {
1420 /// Sets all bytes of the receiver to the given value.
1421 fn set_memory(self, value: u8);
1424 impl<'a> MutableByteVector for &'a mut [u8] {
1426 #[allow(experimental)]
1427 fn set_memory(self, value: u8) {
1428 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1432 /// Copies data from `src` to `dst`
1434 /// `src` and `dst` must not overlap. Fails if the length of `dst`
1435 /// is less than the length of `src`.
1437 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1438 // Bound checks are done at .copy_memory.
1439 unsafe { dst.copy_memory(src) }
1447 // Boilerplate traits
1450 impl<'a,T:PartialEq> PartialEq for &'a [T] {
1451 fn eq(&self, other: & &'a [T]) -> bool {
1452 self.len() == other.len() &&
1453 order::eq(self.iter(), other.iter())
1455 fn ne(&self, other: & &'a [T]) -> bool {
1456 self.len() != other.len() ||
1457 order::ne(self.iter(), other.iter())
1461 impl<'a,T:Eq> Eq for &'a [T] {}
1463 impl<'a,T:PartialEq, V: Vector<T>> Equiv<V> for &'a [T] {
1465 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
1468 impl<'a,T:Ord> Ord for &'a [T] {
1469 fn cmp(&self, other: & &'a [T]) -> Ordering {
1470 order::cmp(self.iter(), other.iter())
1474 impl<'a, T: PartialOrd> PartialOrd for &'a [T] {
1476 fn partial_cmp(&self, other: &&'a [T]) -> Option<Ordering> {
1477 order::partial_cmp(self.iter(), other.iter())
1480 fn lt(&self, other: & &'a [T]) -> bool {
1481 order::lt(self.iter(), other.iter())
1484 fn le(&self, other: & &'a [T]) -> bool {
1485 order::le(self.iter(), other.iter())
1488 fn ge(&self, other: & &'a [T]) -> bool {
1489 order::ge(self.iter(), other.iter())
1492 fn gt(&self, other: & &'a [T]) -> bool {
1493 order::gt(self.iter(), other.iter())