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 #![stable(feature = "rust1", since = "1.0.0")]
16 #![doc(primitive = "slice")]
18 // How this module is organized.
20 // The library infrastructure for slices is fairly messy. There's
21 // a lot of stuff defined here. Let's keep it clean.
23 // Since slices don't support inherent methods; all operations
24 // on them are defined on traits, which are then reexported from
25 // the prelude for convenience. So there are a lot of traits here.
27 // The layout of this file is thus:
29 // * Slice-specific 'extension' traits and their implementations. This
30 // is where most of the slice API resides.
31 // * Implementations of a few common traits with important slice ops.
32 // * Definitions of a bunch of iterators.
34 // * The `raw` and `bytes` submodules.
35 // * Boilerplate trait implementations.
39 use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
40 use cmp::Ordering::{Less, Equal, Greater};
43 use intrinsics::assume;
45 use ops::{FnMut, self, Index};
48 use option::Option::{None, Some};
50 use result::Result::{Ok, Err};
54 use marker::{Send, Sync, self};
56 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
57 use raw::Slice as RawSlice;
64 /// Extension methods for slices.
65 #[allow(missing_docs)] // docs in libcollections
70 fn split_at<'a>(&'a self, mid: usize) -> (&'a [Self::Item], &'a [Self::Item]);
71 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
72 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
73 where P: FnMut(&Self::Item) -> bool;
74 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, Self::Item, P>
75 where P: FnMut(&Self::Item) -> bool;
76 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, Self::Item, P>
77 where P: FnMut(&Self::Item) -> bool;
78 fn windows<'a>(&'a self, size: usize) -> Windows<'a, Self::Item>;
79 fn chunks<'a>(&'a self, size: usize) -> Chunks<'a, Self::Item>;
80 fn get<'a>(&'a self, index: usize) -> Option<&'a Self::Item>;
81 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
82 fn tail<'a>(&'a self) -> &'a [Self::Item];
83 fn init<'a>(&'a self) -> &'a [Self::Item];
84 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
85 unsafe fn get_unchecked<'a>(&'a self, index: usize) -> &'a Self::Item;
86 fn as_ptr(&self) -> *const Self::Item;
87 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
88 F: FnMut(&Self::Item) -> Ordering;
89 fn len(&self) -> usize;
90 fn is_empty(&self) -> bool { self.len() == 0 }
91 fn get_mut<'a>(&'a mut self, index: usize) -> Option<&'a mut Self::Item>;
92 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
93 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
94 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
95 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
96 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
97 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
98 where P: FnMut(&Self::Item) -> bool;
99 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
100 where P: FnMut(&Self::Item) -> bool;
101 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
102 where P: FnMut(&Self::Item) -> bool;
103 fn chunks_mut<'a>(&'a mut self, chunk_size: usize) -> ChunksMut<'a, Self::Item>;
104 fn swap(&mut self, a: usize, b: usize);
105 fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
106 fn reverse(&mut self);
107 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Item;
108 fn as_mut_ptr(&mut self) -> *mut Self::Item;
110 fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
112 fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
114 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
116 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
118 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
120 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
121 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
122 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
124 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
127 // Use macros to be generic over const/mut
128 macro_rules! slice_offset {
129 ($ptr:expr, $by:expr) => {{
131 if size_from_ptr(ptr) == 0 {
132 ::intrinsics::arith_offset(ptr as *mut i8, $by) as *mut _
139 macro_rules! slice_ref {
142 if size_from_ptr(ptr) == 0 {
143 // Use a non-null pointer value
151 #[unstable(feature = "core")]
152 impl<T> SliceExt for [T] {
156 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
157 (&self[..mid], &self[mid..])
161 fn iter<'a>(&'a self) -> Iter<'a, T> {
163 let p = if mem::size_of::<T>() == 0 {
166 let p = self.as_ptr();
167 assume(!p.is_null());
173 end: slice_offset!(p, self.len() as isize),
174 _marker: marker::PhantomData
180 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
189 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, T, P> where
190 P: FnMut(&T) -> bool,
193 inner: GenericSplitN {
194 iter: self.split(pred),
202 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, T, P> where
203 P: FnMut(&T) -> bool,
206 inner: GenericSplitN {
207 iter: self.split(pred),
215 fn windows(&self, size: usize) -> Windows<T> {
217 Windows { v: self, size: size }
221 fn chunks(&self, size: usize) -> Chunks<T> {
223 Chunks { v: self, size: size }
227 fn get(&self, index: usize) -> Option<&T> {
228 if index < self.len() { Some(&self[index]) } else { None }
232 fn first(&self) -> Option<&T> {
233 if self.is_empty() { None } else { Some(&self[0]) }
237 fn tail(&self) -> &[T] { &self[1..] }
240 fn init(&self) -> &[T] {
241 &self[..self.len() - 1]
245 fn last(&self) -> Option<&T> {
246 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
250 unsafe fn get_unchecked(&self, index: usize) -> &T {
251 transmute(self.repr().data.offset(index as isize))
255 fn as_ptr(&self) -> *const T {
259 #[unstable(feature = "core")]
260 fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
261 F: FnMut(&T) -> Ordering
263 let mut base : usize = 0;
264 let mut lim : usize = self.len();
267 let ix = base + (lim >> 1);
269 Equal => return Ok(ix),
282 fn len(&self) -> usize { self.repr().len }
285 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
286 if index < self.len() { Some(&mut self[index]) } else { None }
290 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
292 let self2: &mut [T] = mem::transmute_copy(&self);
294 (ops::IndexMut::index_mut(self, ops::RangeTo { end: mid } ),
295 ops::IndexMut::index_mut(self2, ops::RangeFrom { start: mid } ))
300 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
302 let p = if mem::size_of::<T>() == 0 {
305 let p = self.as_mut_ptr();
306 assume(!p.is_null());
312 end: slice_offset!(p, self.len() as isize),
313 _marker: marker::PhantomData
319 fn last_mut(&mut self) -> Option<&mut T> {
320 let len = self.len();
321 if len == 0 { return None; }
322 Some(&mut self[len - 1])
326 fn first_mut(&mut self) -> Option<&mut T> {
327 if self.is_empty() { None } else { Some(&mut self[0]) }
331 fn tail_mut(&mut self) -> &mut [T] {
336 fn init_mut(&mut self) -> &mut [T] {
337 let len = self.len();
338 &mut self[.. (len - 1)]
342 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
343 SplitMut { v: self, pred: pred, finished: false }
347 fn splitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> SplitNMut<'a, T, P> where
351 inner: GenericSplitN {
352 iter: self.split_mut(pred),
360 fn rsplitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> RSplitNMut<'a, T, P> where
361 P: FnMut(&T) -> bool,
364 inner: GenericSplitN {
365 iter: self.split_mut(pred),
373 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
374 assert!(chunk_size > 0);
375 ChunksMut { v: self, chunk_size: chunk_size }
379 fn swap(&mut self, a: usize, b: usize) {
381 // Can't take two mutable loans from one vector, so instead just cast
382 // them to their raw pointers to do the swap
383 let pa: *mut T = &mut self[a];
384 let pb: *mut T = &mut self[b];
389 fn reverse(&mut self) {
390 let mut i: usize = 0;
393 // Unsafe swap to avoid the bounds check in safe swap.
395 let pa: *mut T = self.get_unchecked_mut(i);
396 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
404 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
405 transmute((self.repr().data as *mut T).offset(index as isize))
409 fn as_mut_ptr(&mut self) -> *mut T {
410 self.repr().data as *mut T
414 fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
415 self.iter().position(|y| *x == *y)
419 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
420 self.iter().rposition(|x| *x == *t)
424 fn contains(&self, x: &T) -> bool where T: PartialEq {
425 self.iter().any(|elt| *x == *elt)
429 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
430 let n = needle.len();
431 self.len() >= n && needle == &self[..n]
435 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
436 let (m, n) = (self.len(), needle.len());
437 m >= n && needle == &self[m-n..]
440 #[unstable(feature = "core")]
441 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
442 self.binary_search_by(|p| p.cmp(x))
445 #[unstable(feature = "core")]
446 fn next_permutation(&mut self) -> bool where T: Ord {
447 // These cases only have 1 permutation each, so we can't do anything.
448 if self.len() < 2 { return false; }
450 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
451 let mut i = self.len() - 1;
452 while i > 0 && self[i-1] >= self[i] {
456 // If that is the entire vector, this is the last-ordered permutation.
461 // Step 2: Find the rightmost element larger than the pivot (i-1)
462 let mut j = self.len() - 1;
463 while j >= i && self[j] <= self[i-1] {
467 // Step 3: Swap that element with the pivot
470 // Step 4: Reverse the (previously) weakly decreasing part
476 #[unstable(feature = "core")]
477 fn prev_permutation(&mut self) -> bool where T: Ord {
478 // These cases only have 1 permutation each, so we can't do anything.
479 if self.len() < 2 { return false; }
481 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
482 let mut i = self.len() - 1;
483 while i > 0 && self[i-1] <= self[i] {
487 // If that is the entire vector, this is the first-ordered permutation.
492 // Step 2: Reverse the weakly increasing part
495 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
496 let mut j = self.len() - 1;
497 while j >= i && self[j-1] < self[i-1] {
501 // Step 4: Swap that element with the pivot
508 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
509 let min = cmp::min(self.len(), src.len());
510 let dst = &mut self[.. min];
511 let src = &src[.. min];
513 dst[i].clone_from(&src[i]);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<T> ops::Index<usize> for [T] {
523 fn index(&self, index: usize) -> &T {
524 assert!(index < self.len());
526 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl<T> ops::IndexMut<usize> for [T] {
533 fn index_mut(&mut self, index: usize) -> &mut T {
534 assert!(index < self.len());
536 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl<T> ops::Index<ops::Range<usize>> for [T] {
545 fn index(&self, index: ops::Range<usize>) -> &[T] {
546 assert!(index.start <= index.end);
547 assert!(index.end <= self.len());
550 self.as_ptr().offset(index.start as isize),
551 index.end - index.start
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
561 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
562 self.index(ops::Range{ start: 0, end: index.end })
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
570 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
571 self.index(ops::Range{ start: index.start, end: self.len() })
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<T> ops::Index<RangeFull> for [T] {
579 fn index(&self, _index: RangeFull) -> &[T] {
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
587 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
588 assert!(index.start <= index.end);
589 assert!(index.end <= self.len());
592 self.as_mut_ptr().offset(index.start as isize),
593 index.end - index.start
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
601 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
602 self.index_mut(ops::Range{ start: 0, end: index.end })
605 #[stable(feature = "rust1", since = "1.0.0")]
606 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
608 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
609 let len = self.len();
610 self.index_mut(ops::Range{ start: index.start, end: len })
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl<T> ops::IndexMut<RangeFull> for [T] {
616 fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
622 ////////////////////////////////////////////////////////////////////////////////
624 ////////////////////////////////////////////////////////////////////////////////
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl<'a, T> Default for &'a [T] {
628 #[stable(feature = "rust1", since = "1.0.0")]
629 fn default() -> &'a [T] { &[] }
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl<'a, T> IntoIterator for &'a [T] {
639 type IntoIter = Iter<'a, T>;
641 fn into_iter(self) -> Iter<'a, T> {
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl<'a, T> IntoIterator for &'a mut [T] {
648 type Item = &'a mut T;
649 type IntoIter = IterMut<'a, T>;
651 fn into_iter(self) -> IterMut<'a, T> {
657 fn size_from_ptr<T>(_: *const T) -> usize {
661 // The shared definition of the `Iter` and `IterMut` iterators
662 macro_rules! iterator {
663 (struct $name:ident -> $ptr:ty, $elem:ty) => {
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl<'a, T> Iterator for $name<'a, T> {
669 fn next(&mut self) -> Option<$elem> {
670 // could be implemented with slices, but this avoids bounds checks
672 if mem::size_of::<T>() != 0 {
673 assume(!self.ptr.is_null());
674 assume(!self.end.is_null());
676 if self.ptr == self.end {
680 self.ptr = slice_offset!(self.ptr, 1);
681 Some(slice_ref!(old))
687 fn size_hint(&self) -> (usize, Option<usize>) {
688 let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
689 let size = mem::size_of::<T>();
690 let exact = diff / (if size == 0 {1} else {size});
695 fn count(self) -> usize {
700 fn nth(&mut self, n: usize) -> Option<$elem> {
701 // Call helper method. Can't put the definition here because mut versus const.
706 fn last(mut self) -> Option<$elem> {
711 #[stable(feature = "rust1", since = "1.0.0")]
712 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
714 fn next_back(&mut self) -> Option<$elem> {
715 // could be implemented with slices, but this avoids bounds checks
717 if mem::size_of::<T>() != 0 {
718 assume(!self.ptr.is_null());
719 assume(!self.end.is_null());
721 if self.end == self.ptr {
724 self.end = slice_offset!(self.end, -1);
725 Some(slice_ref!(self.end))
733 macro_rules! make_slice {
734 ($start: expr, $end: expr) => {{
736 let diff = ($end as usize).wrapping_sub(start as usize);
737 if size_from_ptr(start) == 0 {
738 // use a non-null pointer value
739 unsafe { from_raw_parts(1 as *const _, diff) }
741 let len = diff / size_from_ptr(start);
742 unsafe { from_raw_parts(start, len) }
747 macro_rules! make_mut_slice {
748 ($start: expr, $end: expr) => {{
750 let diff = ($end as usize).wrapping_sub(start as usize);
751 if size_from_ptr(start) == 0 {
752 // use a non-null pointer value
753 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
755 let len = diff / size_from_ptr(start);
756 unsafe { from_raw_parts_mut(start, len) }
761 /// Immutable slice iterator
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub struct Iter<'a, T: 'a> {
766 _marker: marker::PhantomData<&'a T>,
769 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
770 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
772 impl<'a, T> Iter<'a, T> {
773 /// View the underlying data as a subslice of the original data.
775 /// This has the same lifetime as the original slice, and so the
776 /// iterator can continue to be used while this exists.
777 #[unstable(feature = "core")]
778 pub fn as_slice(&self) -> &'a [T] {
779 make_slice!(self.ptr, self.end)
782 // Helper function for Iter::nth
783 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
784 match self.as_slice().get(n) {
785 Some(elem_ref) => unsafe {
786 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
797 iterator!{struct Iter -> *const T, &'a T}
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl<'a, T> Clone for Iter<'a, T> {
804 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
807 #[unstable(feature = "core", reason = "trait is experimental")]
808 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
810 fn indexable(&self) -> usize {
811 let (exact, _) = self.size_hint();
816 fn idx(&mut self, index: usize) -> Option<&'a T> {
818 if index < self.indexable() {
819 Some(slice_ref!(self.ptr.offset(index as isize)))
827 /// Mutable slice iterator.
828 #[stable(feature = "rust1", since = "1.0.0")]
829 pub struct IterMut<'a, T: 'a> {
832 _marker: marker::PhantomData<&'a mut T>,
835 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
836 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
838 impl<'a, T> IterMut<'a, T> {
839 /// View the underlying data as a subslice of the original data.
841 /// To avoid creating `&mut` references that alias, this is forced
842 /// to consume the iterator. Consider using the `Slice` and
843 /// `SliceMut` implementations for obtaining slices with more
844 /// restricted lifetimes that do not consume the iterator.
845 #[unstable(feature = "core")]
846 pub fn into_slice(self) -> &'a mut [T] {
847 make_mut_slice!(self.ptr, self.end)
850 // Helper function for IterMut::nth
851 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
852 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
853 Some(elem_ref) => unsafe {
854 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
865 iterator!{struct IterMut -> *mut T, &'a mut T}
867 #[stable(feature = "rust1", since = "1.0.0")]
868 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
870 /// An internal abstraction over the splitting iterators, so that
871 /// splitn, splitn_mut etc can be implemented once.
872 trait SplitIter: DoubleEndedIterator {
873 /// Mark the underlying iterator as complete, extracting the remaining
874 /// portion of the slice.
875 fn finish(&mut self) -> Option<Self::Item>;
878 /// An iterator over subslices separated by elements that match a predicate
880 #[stable(feature = "rust1", since = "1.0.0")]
881 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
887 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
890 fn clone(&self) -> Split<'a, T, P> {
893 pred: self.pred.clone(),
894 finished: self.finished,
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
904 fn next(&mut self) -> Option<&'a [T]> {
905 if self.finished { return None; }
907 match self.v.iter().position(|x| (self.pred)(x)) {
908 None => self.finish(),
910 let ret = Some(&self.v[..idx]);
911 self.v = &self.v[idx + 1..];
918 fn size_hint(&self) -> (usize, Option<usize>) {
922 (1, Some(self.v.len() + 1))
927 #[stable(feature = "rust1", since = "1.0.0")]
928 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
930 fn next_back(&mut self) -> Option<&'a [T]> {
931 if self.finished { return None; }
933 match self.v.iter().rposition(|x| (self.pred)(x)) {
934 None => self.finish(),
936 let ret = Some(&self.v[idx + 1..]);
937 self.v = &self.v[..idx];
944 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
946 fn finish(&mut self) -> Option<&'a [T]> {
947 if self.finished { None } else { self.finished = true; Some(self.v) }
951 /// An iterator over the subslices of the vector which are separated
952 /// by elements that match `pred`.
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
960 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
962 fn finish(&mut self) -> Option<&'a mut [T]> {
966 self.finished = true;
967 Some(mem::replace(&mut self.v, &mut []))
972 #[stable(feature = "rust1", since = "1.0.0")]
973 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
974 type Item = &'a mut [T];
977 fn next(&mut self) -> Option<&'a mut [T]> {
978 if self.finished { return None; }
980 let idx_opt = { // work around borrowck limitations
981 let pred = &mut self.pred;
982 self.v.iter().position(|x| (*pred)(x))
985 None => self.finish(),
987 let tmp = mem::replace(&mut self.v, &mut []);
988 let (head, tail) = tmp.split_at_mut(idx);
989 self.v = &mut tail[1..];
996 fn size_hint(&self) -> (usize, Option<usize>) {
1000 // if the predicate doesn't match anything, we yield one slice
1001 // if it matches every element, we yield len+1 empty slices.
1002 (1, Some(self.v.len() + 1))
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1009 P: FnMut(&T) -> bool,
1012 fn next_back(&mut self) -> Option<&'a mut [T]> {
1013 if self.finished { return None; }
1015 let idx_opt = { // work around borrowck limitations
1016 let pred = &mut self.pred;
1017 self.v.iter().rposition(|x| (*pred)(x))
1020 None => self.finish(),
1022 let tmp = mem::replace(&mut self.v, &mut []);
1023 let (head, tail) = tmp.split_at_mut(idx);
1025 Some(&mut tail[1..])
1031 /// An private iterator over subslices separated by elements that
1032 /// match a predicate function, splitting at most a fixed number of
1034 struct GenericSplitN<I> {
1040 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1044 fn next(&mut self) -> Option<T> {
1047 1 => { self.count -= 1; self.iter.finish() }
1050 if self.invert {self.iter.next_back()} else {self.iter.next()}
1056 fn size_hint(&self) -> (usize, Option<usize>) {
1057 let (lower, upper_opt) = self.iter.size_hint();
1058 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1062 /// An iterator over subslices separated by elements that match a predicate
1063 /// function, limited to a given number of splits.
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1066 inner: GenericSplitN<Split<'a, T, P>>
1069 /// An iterator over subslices separated by elements that match a
1070 /// predicate function, limited to a given number of splits, starting
1071 /// from the end of the slice.
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1074 inner: GenericSplitN<Split<'a, T, P>>
1077 /// An iterator over subslices separated by elements that match a predicate
1078 /// function, limited to a given number of splits.
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1081 inner: GenericSplitN<SplitMut<'a, T, P>>
1084 /// An iterator over subslices separated by elements that match a
1085 /// predicate function, limited to a given number of splits, starting
1086 /// from the end of the slice.
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1089 inner: GenericSplitN<SplitMut<'a, T, P>>
1092 macro_rules! forward_iterator {
1093 ($name:ident: $elem:ident, $iter_of:ty) => {
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1096 P: FnMut(&T) -> bool
1098 type Item = $iter_of;
1101 fn next(&mut self) -> Option<$iter_of> {
1106 fn size_hint(&self) -> (usize, Option<usize>) {
1107 self.inner.size_hint()
1113 forward_iterator! { SplitN: T, &'a [T] }
1114 forward_iterator! { RSplitN: T, &'a [T] }
1115 forward_iterator! { SplitNMut: T, &'a mut [T] }
1116 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1118 /// An iterator over overlapping subslices of length `size`.
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub struct Windows<'a, T:'a> {
1125 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<'a, T> Clone for Windows<'a, T> {
1128 fn clone(&self) -> Windows<'a, T> {
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<'a, T> Iterator for Windows<'a, T> {
1138 type Item = &'a [T];
1141 fn next(&mut self) -> Option<&'a [T]> {
1142 if self.size > self.v.len() {
1145 let ret = Some(&self.v[..self.size]);
1146 self.v = &self.v[1..];
1152 fn size_hint(&self) -> (usize, Option<usize>) {
1153 if self.size > self.v.len() {
1156 let size = self.v.len() - self.size + 1;
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1165 fn next_back(&mut self) -> Option<&'a [T]> {
1166 if self.size > self.v.len() {
1169 let ret = Some(&self.v[self.v.len()-self.size..]);
1170 self.v = &self.v[..self.v.len()-1];
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1179 #[unstable(feature = "core", reason = "trait is experimental")]
1180 impl<'a, T> RandomAccessIterator for Windows<'a, T> {
1182 fn indexable(&self) -> usize {
1187 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1188 if index + self.size > self.v.len() {
1191 Some(&self.v[index .. index+self.size])
1196 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1199 /// When the slice len is not evenly divided by the chunk size, the last slice
1200 /// of the iteration will be the remainder.
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 pub struct Chunks<'a, T:'a> {
1207 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl<'a, T> Clone for Chunks<'a, T> {
1210 fn clone(&self) -> Chunks<'a, T> {
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<'a, T> Iterator for Chunks<'a, T> {
1220 type Item = &'a [T];
1223 fn next(&mut self) -> Option<&'a [T]> {
1224 if self.v.is_empty() {
1227 let chunksz = cmp::min(self.v.len(), self.size);
1228 let (fst, snd) = self.v.split_at(chunksz);
1235 fn size_hint(&self) -> (usize, Option<usize>) {
1236 if self.v.is_empty() {
1239 let n = self.v.len() / self.size;
1240 let rem = self.v.len() % self.size;
1241 let n = if rem > 0 { n+1 } else { n };
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1250 fn next_back(&mut self) -> Option<&'a [T]> {
1251 if self.v.is_empty() {
1254 let remainder = self.v.len() % self.size;
1255 let chunksz = if remainder != 0 { remainder } else { self.size };
1256 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1266 #[unstable(feature = "core", reason = "trait is experimental")]
1267 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1269 fn indexable(&self) -> usize {
1270 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1274 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1275 if index < self.indexable() {
1276 let lo = index * self.size;
1277 let mut hi = lo + self.size;
1278 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1280 Some(&self.v[lo..hi])
1287 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1288 /// elements at a time). When the slice len is not evenly divided by the chunk
1289 /// size, the last slice of the iteration will be the remainder.
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 pub struct ChunksMut<'a, T:'a> {
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<'a, T> Iterator for ChunksMut<'a, T> {
1298 type Item = &'a mut [T];
1301 fn next(&mut self) -> Option<&'a mut [T]> {
1302 if self.v.is_empty() {
1305 let sz = cmp::min(self.v.len(), self.chunk_size);
1306 let tmp = mem::replace(&mut self.v, &mut []);
1307 let (head, tail) = tmp.split_at_mut(sz);
1314 fn size_hint(&self) -> (usize, Option<usize>) {
1315 if self.v.is_empty() {
1318 let n = self.v.len() / self.chunk_size;
1319 let rem = self.v.len() % self.chunk_size;
1320 let n = if rem > 0 { n + 1 } else { n };
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1329 fn next_back(&mut self) -> Option<&'a mut [T]> {
1330 if self.v.is_empty() {
1333 let remainder = self.v.len() % self.chunk_size;
1334 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1335 let tmp = mem::replace(&mut self.v, &mut []);
1336 let tmp_len = tmp.len();
1337 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1351 /// Converts a pointer to A into a slice of length 1 (without copying).
1352 #[unstable(feature = "core")]
1353 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1355 from_raw_parts(s, 1)
1359 /// Converts a pointer to A into a slice of length 1 (without copying).
1360 #[unstable(feature = "core")]
1361 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1363 from_raw_parts_mut(s, 1)
1367 /// Forms a slice from a pointer and a length.
1369 /// The `len` argument is the number of **elements**, not the number of bytes.
1371 /// This function is unsafe as there is no guarantee that the given pointer is
1372 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1373 /// lifetime for the returned slice.
1377 /// The lifetime for the returned slice is inferred from its usage. To
1378 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1379 /// source lifetime is safe in the context, such as by providing a helper
1380 /// function taking the lifetime of a host value for the slice, or by explicit
1388 /// // manifest a slice out of thin air!
1389 /// let ptr = 0x1234 as *const usize;
1392 /// let slice = slice::from_raw_parts(ptr, amt);
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1398 transmute(RawSlice { data: p, len: len })
1401 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1402 /// slice is returned.
1404 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1405 /// as not being able to provide a non-aliasing guarantee of the returned
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1410 transmute(RawSlice { data: p, len: len })
1417 /// Operations on `[u8]`.
1418 #[unstable(feature = "core", reason = "needs review")]
1421 use slice::SliceExt;
1423 /// A trait for operations on mutable `[u8]`s.
1424 pub trait MutableByteVector {
1425 /// Sets all bytes of the receiver to the given value.
1426 fn set_memory(&mut self, value: u8);
1429 impl MutableByteVector for [u8] {
1431 fn set_memory(&mut self, value: u8) {
1432 unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1436 /// Copies data from `src` to `dst`
1438 /// Panics if the length of `dst` is less than the length of `src`.
1440 pub fn copy_memory(src: &[u8], dst: &mut [u8]) {
1441 let len_src = src.len();
1442 assert!(dst.len() >= len_src);
1443 // `dst` is unaliasable, so we know statically it doesn't overlap
1446 ptr::copy_nonoverlapping(src.as_ptr(),
1456 // Boilerplate traits
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1461 fn eq(&self, other: &[B]) -> bool {
1462 self.len() == other.len() &&
1463 order::eq(self.iter(), other.iter())
1465 fn ne(&self, other: &[B]) -> bool {
1466 self.len() != other.len() ||
1467 order::ne(self.iter(), other.iter())
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<T: Eq> Eq for [T] {}
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 impl<T: Ord> Ord for [T] {
1476 fn cmp(&self, other: &[T]) -> Ordering {
1477 order::cmp(self.iter(), other.iter())
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: PartialOrd> PartialOrd for [T] {
1484 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1485 order::partial_cmp(self.iter(), other.iter())
1488 fn lt(&self, other: &[T]) -> bool {
1489 order::lt(self.iter(), other.iter())
1492 fn le(&self, other: &[T]) -> bool {
1493 order::le(self.iter(), other.iter())
1496 fn ge(&self, other: &[T]) -> bool {
1497 order::ge(self.iter(), other.iter())
1500 fn gt(&self, other: &[T]) -> bool {
1501 order::gt(self.iter(), other.iter())
1505 /// Extension methods for slices containing integers.
1506 #[unstable(feature = "core")]
1507 pub trait IntSliceExt<U, S> {
1508 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1509 fn as_unsigned<'a>(&'a self) -> &'a [U];
1510 /// Converts the slice to an immutable slice of signed integers with the same width.
1511 fn as_signed<'a>(&'a self) -> &'a [S];
1513 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1514 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1515 /// Converts the slice to a mutable slice of signed integers with the same width.
1516 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1519 macro_rules! impl_int_slice {
1520 ($u:ty, $s:ty, $t:ty) => {
1521 #[unstable(feature = "core")]
1522 impl IntSliceExt<$u, $s> for [$t] {
1524 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1526 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1528 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1530 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1535 macro_rules! impl_int_slices {
1537 impl_int_slice! { $u, $s, $u }
1538 impl_int_slice! { $u, $s, $s }
1542 impl_int_slices! { u8, i8 }
1543 impl_int_slices! { u16, i16 }
1544 impl_int_slices! { u32, i32 }
1545 impl_int_slices! { u64, i64 }
1546 impl_int_slices! { usize, isize }