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")]
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.
37 use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
38 use cmp::Ordering::{Less, Equal, Greater};
41 use intrinsics::assume;
43 use ops::{FnMut, self, Index};
46 use option::Option::{None, Some};
48 use result::Result::{Ok, Err};
52 use marker::{Send, Sync, self};
53 use num::wrapping::OverflowingOps;
55 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
56 use raw::Slice as RawSlice;
63 /// Extension methods for slices.
64 #[allow(missing_docs)] // docs in libcollections
66 #[unstable(feature = "core_slice_ext",
67 reason = "stable interface provided by `impl [T]` in later crates",
72 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
73 fn iter(&self) -> Iter<Self::Item>;
74 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
75 where P: FnMut(&Self::Item) -> bool;
76 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
77 where P: FnMut(&Self::Item) -> bool;
78 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
79 where P: FnMut(&Self::Item) -> bool;
80 fn windows(&self, size: usize) -> Windows<Self::Item>;
81 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
82 fn get(&self, index: usize) -> Option<&Self::Item>;
83 fn first(&self) -> Option<&Self::Item>;
84 fn tail(&self) -> &[Self::Item];
85 fn init(&self) -> &[Self::Item];
86 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
87 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
88 fn last(&self) -> Option<&Self::Item>;
89 unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
90 fn as_ptr(&self) -> *const Self::Item;
91 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
92 F: FnMut(&Self::Item) -> Ordering;
93 fn len(&self) -> usize;
94 fn is_empty(&self) -> bool { self.len() == 0 }
95 fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
96 fn iter_mut(&mut self) -> IterMut<Self::Item>;
97 fn first_mut(&mut self) -> Option<&mut Self::Item>;
98 fn tail_mut(&mut self) -> &mut [Self::Item];
99 fn init_mut(&mut self) -> &mut [Self::Item];
100 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
101 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
102 fn last_mut(&mut self) -> Option<&mut Self::Item>;
103 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
104 where P: FnMut(&Self::Item) -> bool;
105 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
106 where P: FnMut(&Self::Item) -> bool;
107 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
108 where P: FnMut(&Self::Item) -> bool;
109 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
110 fn swap(&mut self, a: usize, b: usize);
111 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
112 fn reverse(&mut self);
113 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
114 fn as_mut_ptr(&mut self) -> *mut Self::Item;
116 fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
118 fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
120 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
122 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
124 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
126 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
127 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
128 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
130 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
133 // Use macros to be generic over const/mut
134 macro_rules! slice_offset {
135 ($ptr:expr, $by:expr) => {{
137 if size_from_ptr(ptr) == 0 {
138 ::intrinsics::arith_offset(ptr as *mut i8, $by) as *mut _
145 macro_rules! slice_ref {
148 if size_from_ptr(ptr) == 0 {
149 // Use a non-null pointer value
157 impl<T> SliceExt for [T] {
161 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
162 (&self[..mid], &self[mid..])
166 fn iter(&self) -> Iter<T> {
168 let p = if mem::size_of::<T>() == 0 {
171 let p = self.as_ptr();
172 assume(!p.is_null());
178 end: slice_offset!(p, self.len() as isize),
179 _marker: marker::PhantomData
185 fn split<P>(&self, pred: P) -> Split<T, P> where P: FnMut(&T) -> bool {
194 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P> where
195 P: FnMut(&T) -> bool,
198 inner: GenericSplitN {
199 iter: self.split(pred),
207 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P> where
208 P: FnMut(&T) -> bool,
211 inner: GenericSplitN {
212 iter: self.split(pred),
220 fn windows(&self, size: usize) -> Windows<T> {
222 Windows { v: self, size: size }
226 fn chunks(&self, size: usize) -> Chunks<T> {
228 Chunks { v: self, size: size }
232 fn get(&self, index: usize) -> Option<&T> {
233 if index < self.len() { Some(&self[index]) } else { None }
237 fn first(&self) -> Option<&T> {
238 if self.is_empty() { None } else { Some(&self[0]) }
242 fn tail(&self) -> &[T] { &self[1..] }
245 fn split_first(&self) -> Option<(&T, &[T])> {
246 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
250 fn init(&self) -> &[T] { &self[..self.len() - 1] }
253 fn split_last(&self) -> Option<(&T, &[T])> {
254 let len = self.len();
255 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
259 fn last(&self) -> Option<&T> {
260 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
264 unsafe fn get_unchecked(&self, index: usize) -> &T {
265 &*(self.repr().data.offset(index as isize))
269 fn as_ptr(&self) -> *const T {
273 fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
274 F: FnMut(&T) -> Ordering
276 let mut base : usize = 0;
277 let mut lim : usize = self.len();
280 let ix = base + (lim >> 1);
282 Equal => return Ok(ix),
295 fn len(&self) -> usize { self.repr().len }
298 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
299 if index < self.len() { Some(&mut self[index]) } else { None }
303 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
304 let len = self.len();
305 let ptr = self.as_mut_ptr();
310 (from_raw_parts_mut(ptr, mid),
311 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
316 fn iter_mut(&mut self) -> IterMut<T> {
318 let p = if mem::size_of::<T>() == 0 {
321 let p = self.as_mut_ptr();
322 assume(!p.is_null());
328 end: slice_offset!(p, self.len() as isize),
329 _marker: marker::PhantomData
335 fn last_mut(&mut self) -> Option<&mut T> {
336 let len = self.len();
337 if len == 0 { return None; }
338 Some(&mut self[len - 1])
342 fn first_mut(&mut self) -> Option<&mut T> {
343 if self.is_empty() { None } else { Some(&mut self[0]) }
347 fn tail_mut(&mut self) -> &mut [T] { &mut self[1 ..] }
350 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
351 if self.is_empty() { None } else {
352 let split = self.split_at_mut(1);
353 Some((&mut split.0[0], split.1))
358 fn init_mut(&mut self) -> &mut [T] {
359 let len = self.len();
360 &mut self[.. (len - 1)]
364 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
365 let len = self.len();
366 if len == 0 { None } else {
367 let split = self.split_at_mut(len - 1);
368 Some((&mut split.1[0], split.0))
373 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P> where P: FnMut(&T) -> bool {
374 SplitMut { v: self, pred: pred, finished: false }
378 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P> where
382 inner: GenericSplitN {
383 iter: self.split_mut(pred),
391 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
392 P: FnMut(&T) -> bool,
395 inner: GenericSplitN {
396 iter: self.split_mut(pred),
404 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
405 assert!(chunk_size > 0);
406 ChunksMut { v: self, chunk_size: chunk_size }
410 fn swap(&mut self, a: usize, b: usize) {
412 // Can't take two mutable loans from one vector, so instead just cast
413 // them to their raw pointers to do the swap
414 let pa: *mut T = &mut self[a];
415 let pb: *mut T = &mut self[b];
420 fn reverse(&mut self) {
421 let mut i: usize = 0;
424 // Unsafe swap to avoid the bounds check in safe swap.
426 let pa: *mut T = self.get_unchecked_mut(i);
427 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
435 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
436 &mut *(self.repr().data as *mut T).offset(index as isize)
440 fn as_mut_ptr(&mut self) -> *mut T {
441 self.repr().data as *mut T
445 fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
446 self.iter().position(|y| *x == *y)
450 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
451 self.iter().rposition(|x| *x == *t)
455 fn contains(&self, x: &T) -> bool where T: PartialEq {
456 self.iter().any(|elt| *x == *elt)
460 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
461 let n = needle.len();
462 self.len() >= n && needle == &self[..n]
466 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
467 let (m, n) = (self.len(), needle.len());
468 m >= n && needle == &self[m-n..]
471 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
472 self.binary_search_by(|p| p.cmp(x))
475 fn next_permutation(&mut self) -> bool where T: Ord {
476 // These cases only have 1 permutation each, so we can't do anything.
477 if self.len() < 2 { return false; }
479 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
480 let mut i = self.len() - 1;
481 while i > 0 && self[i-1] >= self[i] {
485 // If that is the entire vector, this is the last-ordered permutation.
490 // Step 2: Find the rightmost element larger than the pivot (i-1)
491 let mut j = self.len() - 1;
492 while j >= i && self[j] <= self[i-1] {
496 // Step 3: Swap that element with the pivot
499 // Step 4: Reverse the (previously) weakly decreasing part
505 fn prev_permutation(&mut self) -> bool where T: Ord {
506 // These cases only have 1 permutation each, so we can't do anything.
507 if self.len() < 2 { return false; }
509 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
510 let mut i = self.len() - 1;
511 while i > 0 && self[i-1] <= self[i] {
515 // If that is the entire vector, this is the first-ordered permutation.
520 // Step 2: Reverse the weakly increasing part
523 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
524 let mut j = self.len() - 1;
525 while j >= i && self[j-1] < self[i-1] {
529 // Step 4: Swap that element with the pivot
536 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
537 let min = cmp::min(self.len(), src.len());
538 let dst = &mut self[.. min];
539 let src = &src[.. min];
541 dst[i].clone_from(&src[i]);
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl<T> ops::Index<usize> for [T] {
551 fn index(&self, index: usize) -> &T {
552 assert!(index < self.len());
553 unsafe { self.get_unchecked(index) }
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<T> ops::IndexMut<usize> for [T] {
560 fn index_mut(&mut self, index: usize) -> &mut T {
561 assert!(index < self.len());
562 unsafe { self.get_unchecked_mut(index) }
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<T> ops::Index<ops::Range<usize>> for [T] {
571 fn index(&self, index: ops::Range<usize>) -> &[T] {
572 assert!(index.start <= index.end);
573 assert!(index.end <= self.len());
576 self.as_ptr().offset(index.start as isize),
577 index.end - index.start
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
587 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
588 self.index(ops::Range{ start: 0, end: index.end })
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
596 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
597 self.index(ops::Range{ start: index.start, end: self.len() })
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl<T> ops::Index<RangeFull> for [T] {
605 fn index(&self, _index: RangeFull) -> &[T] {
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
613 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
614 assert!(index.start <= index.end);
615 assert!(index.end <= self.len());
618 self.as_mut_ptr().offset(index.start as isize),
619 index.end - index.start
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
627 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
628 self.index_mut(ops::Range{ start: 0, end: index.end })
631 #[stable(feature = "rust1", since = "1.0.0")]
632 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
634 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
635 let len = self.len();
636 self.index_mut(ops::Range{ start: index.start, end: len })
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<T> ops::IndexMut<RangeFull> for [T] {
642 fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
648 ////////////////////////////////////////////////////////////////////////////////
650 ////////////////////////////////////////////////////////////////////////////////
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl<'a, T> Default for &'a [T] {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 fn default() -> &'a [T] { &[] }
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl<'a, T> IntoIterator for &'a [T] {
665 type IntoIter = Iter<'a, T>;
667 fn into_iter(self) -> Iter<'a, T> {
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<'a, T> IntoIterator for &'a mut [T] {
674 type Item = &'a mut T;
675 type IntoIter = IterMut<'a, T>;
677 fn into_iter(self) -> IterMut<'a, T> {
683 fn size_from_ptr<T>(_: *const T) -> usize {
687 // The shared definition of the `Iter` and `IterMut` iterators
688 macro_rules! iterator {
689 (struct $name:ident -> $ptr:ty, $elem:ty) => {
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<'a, T> Iterator for $name<'a, T> {
695 fn next(&mut self) -> Option<$elem> {
696 // could be implemented with slices, but this avoids bounds checks
698 if mem::size_of::<T>() != 0 {
699 assume(!self.ptr.is_null());
700 assume(!self.end.is_null());
702 if self.ptr == self.end {
706 self.ptr = slice_offset!(self.ptr, 1);
707 Some(slice_ref!(old))
713 fn size_hint(&self) -> (usize, Option<usize>) {
714 let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
715 let size = mem::size_of::<T>();
716 let exact = diff / (if size == 0 {1} else {size});
721 fn count(self) -> usize {
726 fn nth(&mut self, n: usize) -> Option<$elem> {
727 // Call helper method. Can't put the definition here because mut versus const.
732 fn last(mut self) -> Option<$elem> {
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
740 fn next_back(&mut self) -> Option<$elem> {
741 // could be implemented with slices, but this avoids bounds checks
743 if mem::size_of::<T>() != 0 {
744 assume(!self.ptr.is_null());
745 assume(!self.end.is_null());
747 if self.end == self.ptr {
750 self.end = slice_offset!(self.end, -1);
751 Some(slice_ref!(self.end))
759 macro_rules! make_slice {
760 ($start: expr, $end: expr) => {{
762 let diff = ($end as usize).wrapping_sub(start as usize);
763 if size_from_ptr(start) == 0 {
764 // use a non-null pointer value
765 unsafe { from_raw_parts(1 as *const _, diff) }
767 let len = diff / size_from_ptr(start);
768 unsafe { from_raw_parts(start, len) }
773 macro_rules! make_mut_slice {
774 ($start: expr, $end: expr) => {{
776 let diff = ($end as usize).wrapping_sub(start as usize);
777 if size_from_ptr(start) == 0 {
778 // use a non-null pointer value
779 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
781 let len = diff / size_from_ptr(start);
782 unsafe { from_raw_parts_mut(start, len) }
787 /// Immutable slice iterator
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub struct Iter<'a, T: 'a> {
792 _marker: marker::PhantomData<&'a T>,
795 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
796 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
798 impl<'a, T> Iter<'a, T> {
799 /// View the underlying data as a subslice of the original data.
801 /// This has the same lifetime as the original slice, and so the
802 /// iterator can continue to be used while this exists.
803 #[unstable(feature = "iter_to_slice", issue = "27775")]
804 pub fn as_slice(&self) -> &'a [T] {
805 make_slice!(self.ptr, self.end)
808 // Helper function for Iter::nth
809 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
810 match self.as_slice().get(n) {
811 Some(elem_ref) => unsafe {
812 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
823 iterator!{struct Iter -> *const T, &'a T}
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<'a, T> Clone for Iter<'a, T> {
830 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
833 /// Mutable slice iterator.
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub struct IterMut<'a, T: 'a> {
838 _marker: marker::PhantomData<&'a mut T>,
841 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
842 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
844 impl<'a, T> IterMut<'a, T> {
845 /// View the underlying data as a subslice of the original data.
847 /// To avoid creating `&mut` references that alias, this is forced
848 /// to consume the iterator. Consider using the `Slice` and
849 /// `SliceMut` implementations for obtaining slices with more
850 /// restricted lifetimes that do not consume the iterator.
851 #[unstable(feature = "iter_to_slice", issue = "27775")]
852 pub fn into_slice(self) -> &'a mut [T] {
853 make_mut_slice!(self.ptr, self.end)
856 // Helper function for IterMut::nth
857 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
858 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
859 Some(elem_ref) => unsafe {
860 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
871 iterator!{struct IterMut -> *mut T, &'a mut T}
873 #[stable(feature = "rust1", since = "1.0.0")]
874 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
876 /// An internal abstraction over the splitting iterators, so that
877 /// splitn, splitn_mut etc can be implemented once.
878 trait SplitIter: DoubleEndedIterator {
879 /// Mark the underlying iterator as complete, extracting the remaining
880 /// portion of the slice.
881 fn finish(&mut self) -> Option<Self::Item>;
884 /// An iterator over subslices separated by elements that match a predicate
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
893 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
896 fn clone(&self) -> Split<'a, T, P> {
899 pred: self.pred.clone(),
900 finished: self.finished,
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
910 fn next(&mut self) -> Option<&'a [T]> {
911 if self.finished { return None; }
913 match self.v.iter().position(|x| (self.pred)(x)) {
914 None => self.finish(),
916 let ret = Some(&self.v[..idx]);
917 self.v = &self.v[idx + 1..];
924 fn size_hint(&self) -> (usize, Option<usize>) {
928 (1, Some(self.v.len() + 1))
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
936 fn next_back(&mut self) -> Option<&'a [T]> {
937 if self.finished { return None; }
939 match self.v.iter().rposition(|x| (self.pred)(x)) {
940 None => self.finish(),
942 let ret = Some(&self.v[idx + 1..]);
943 self.v = &self.v[..idx];
950 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
952 fn finish(&mut self) -> Option<&'a [T]> {
953 if self.finished { None } else { self.finished = true; Some(self.v) }
957 /// An iterator over the subslices of the vector which are separated
958 /// by elements that match `pred`.
959 #[stable(feature = "rust1", since = "1.0.0")]
960 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
966 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
968 fn finish(&mut self) -> Option<&'a mut [T]> {
972 self.finished = true;
973 Some(mem::replace(&mut self.v, &mut []))
978 #[stable(feature = "rust1", since = "1.0.0")]
979 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
980 type Item = &'a mut [T];
983 fn next(&mut self) -> Option<&'a mut [T]> {
984 if self.finished { return None; }
986 let idx_opt = { // work around borrowck limitations
987 let pred = &mut self.pred;
988 self.v.iter().position(|x| (*pred)(x))
991 None => self.finish(),
993 let tmp = mem::replace(&mut self.v, &mut []);
994 let (head, tail) = tmp.split_at_mut(idx);
995 self.v = &mut tail[1..];
1002 fn size_hint(&self) -> (usize, Option<usize>) {
1006 // if the predicate doesn't match anything, we yield one slice
1007 // if it matches every element, we yield len+1 empty slices.
1008 (1, Some(self.v.len() + 1))
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1015 P: FnMut(&T) -> bool,
1018 fn next_back(&mut self) -> Option<&'a mut [T]> {
1019 if self.finished { return None; }
1021 let idx_opt = { // work around borrowck limitations
1022 let pred = &mut self.pred;
1023 self.v.iter().rposition(|x| (*pred)(x))
1026 None => self.finish(),
1028 let tmp = mem::replace(&mut self.v, &mut []);
1029 let (head, tail) = tmp.split_at_mut(idx);
1031 Some(&mut tail[1..])
1037 /// An private iterator over subslices separated by elements that
1038 /// match a predicate function, splitting at most a fixed number of
1040 struct GenericSplitN<I> {
1046 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1050 fn next(&mut self) -> Option<T> {
1053 1 => { self.count -= 1; self.iter.finish() }
1056 if self.invert {self.iter.next_back()} else {self.iter.next()}
1062 fn size_hint(&self) -> (usize, Option<usize>) {
1063 let (lower, upper_opt) = self.iter.size_hint();
1064 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1068 /// An iterator over subslices separated by elements that match a predicate
1069 /// function, limited to a given number of splits.
1070 #[stable(feature = "rust1", since = "1.0.0")]
1071 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1072 inner: GenericSplitN<Split<'a, T, P>>
1075 /// An iterator over subslices separated by elements that match a
1076 /// predicate function, limited to a given number of splits, starting
1077 /// from the end of the slice.
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1080 inner: GenericSplitN<Split<'a, T, P>>
1083 /// An iterator over subslices separated by elements that match a predicate
1084 /// function, limited to a given number of splits.
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1087 inner: GenericSplitN<SplitMut<'a, T, P>>
1090 /// An iterator over subslices separated by elements that match a
1091 /// predicate function, limited to a given number of splits, starting
1092 /// from the end of the slice.
1093 #[stable(feature = "rust1", since = "1.0.0")]
1094 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1095 inner: GenericSplitN<SplitMut<'a, T, P>>
1098 macro_rules! forward_iterator {
1099 ($name:ident: $elem:ident, $iter_of:ty) => {
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1102 P: FnMut(&T) -> bool
1104 type Item = $iter_of;
1107 fn next(&mut self) -> Option<$iter_of> {
1112 fn size_hint(&self) -> (usize, Option<usize>) {
1113 self.inner.size_hint()
1119 forward_iterator! { SplitN: T, &'a [T] }
1120 forward_iterator! { RSplitN: T, &'a [T] }
1121 forward_iterator! { SplitNMut: T, &'a mut [T] }
1122 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1124 /// An iterator over overlapping subslices of length `size`.
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct Windows<'a, T:'a> {
1131 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<'a, T> Clone for Windows<'a, T> {
1134 fn clone(&self) -> Windows<'a, T> {
1142 #[stable(feature = "rust1", since = "1.0.0")]
1143 impl<'a, T> Iterator for Windows<'a, T> {
1144 type Item = &'a [T];
1147 fn next(&mut self) -> Option<&'a [T]> {
1148 if self.size > self.v.len() {
1151 let ret = Some(&self.v[..self.size]);
1152 self.v = &self.v[1..];
1158 fn size_hint(&self) -> (usize, Option<usize>) {
1159 if self.size > self.v.len() {
1162 let size = self.v.len() - self.size + 1;
1168 fn count(self) -> usize {
1173 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1174 let (end, overflow) = self.size.overflowing_add(n);
1175 if end > self.v.len() || overflow {
1179 let nth = &self.v[n..end];
1180 self.v = &self.v[n+1..];
1186 fn last(self) -> Option<Self::Item> {
1187 if self.size > self.v.len() {
1190 let start = self.v.len() - self.size;
1191 Some(&self.v[start..])
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1199 fn next_back(&mut self) -> Option<&'a [T]> {
1200 if self.size > self.v.len() {
1203 let ret = Some(&self.v[self.v.len()-self.size..]);
1204 self.v = &self.v[..self.v.len()-1];
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1213 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1216 /// When the slice len is not evenly divided by the chunk size, the last slice
1217 /// of the iteration will be the remainder.
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 pub struct Chunks<'a, T:'a> {
1224 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<'a, T> Clone for Chunks<'a, T> {
1227 fn clone(&self) -> Chunks<'a, T> {
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl<'a, T> Iterator for Chunks<'a, T> {
1237 type Item = &'a [T];
1240 fn next(&mut self) -> Option<&'a [T]> {
1241 if self.v.is_empty() {
1244 let chunksz = cmp::min(self.v.len(), self.size);
1245 let (fst, snd) = self.v.split_at(chunksz);
1252 fn size_hint(&self) -> (usize, Option<usize>) {
1253 if self.v.is_empty() {
1256 let n = self.v.len() / self.size;
1257 let rem = self.v.len() % self.size;
1258 let n = if rem > 0 { n+1 } else { n };
1264 fn count(self) -> usize {
1269 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1270 let (start, overflow) = n.overflowing_mul(self.size);
1271 if start >= self.v.len() || overflow {
1275 let end = match start.checked_add(self.size) {
1276 Some(sum) => cmp::min(self.v.len(), sum),
1277 None => self.v.len(),
1279 let nth = &self.v[start..end];
1280 self.v = &self.v[end..];
1286 fn last(self) -> Option<Self::Item> {
1287 if self.v.is_empty() {
1290 let start = (self.v.len() - 1) / self.size * self.size;
1291 Some(&self.v[start..])
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1299 fn next_back(&mut self) -> Option<&'a [T]> {
1300 if self.v.is_empty() {
1303 let remainder = self.v.len() % self.size;
1304 let chunksz = if remainder != 0 { remainder } else { self.size };
1305 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1315 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1316 /// elements at a time). When the slice len is not evenly divided by the chunk
1317 /// size, the last slice of the iteration will be the remainder.
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 pub struct ChunksMut<'a, T:'a> {
1324 #[stable(feature = "rust1", since = "1.0.0")]
1325 impl<'a, T> Iterator for ChunksMut<'a, T> {
1326 type Item = &'a mut [T];
1329 fn next(&mut self) -> Option<&'a mut [T]> {
1330 if self.v.is_empty() {
1333 let sz = cmp::min(self.v.len(), self.chunk_size);
1334 let tmp = mem::replace(&mut self.v, &mut []);
1335 let (head, tail) = tmp.split_at_mut(sz);
1342 fn size_hint(&self) -> (usize, Option<usize>) {
1343 if self.v.is_empty() {
1346 let n = self.v.len() / self.chunk_size;
1347 let rem = self.v.len() % self.chunk_size;
1348 let n = if rem > 0 { n + 1 } else { n };
1354 fn count(self) -> usize {
1359 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1360 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1361 if start >= self.v.len() || overflow {
1365 let end = match start.checked_add(self.chunk_size) {
1366 Some(sum) => cmp::min(self.v.len(), sum),
1367 None => self.v.len(),
1369 let tmp = mem::replace(&mut self.v, &mut []);
1370 let (head, tail) = tmp.split_at_mut(end);
1371 let (_, nth) = head.split_at_mut(start);
1378 fn last(self) -> Option<Self::Item> {
1379 if self.v.is_empty() {
1382 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1383 Some(&mut self.v[start..])
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1391 fn next_back(&mut self) -> Option<&'a mut [T]> {
1392 if self.v.is_empty() {
1395 let remainder = self.v.len() % self.chunk_size;
1396 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1397 let tmp = mem::replace(&mut self.v, &mut []);
1398 let tmp_len = tmp.len();
1399 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1413 /// Converts a pointer to A into a slice of length 1 (without copying).
1414 #[unstable(feature = "ref_slice", issue = "27774")]
1415 pub fn ref_slice<A>(s: &A) -> &[A] {
1417 from_raw_parts(s, 1)
1421 /// Converts a pointer to A into a slice of length 1 (without copying).
1422 #[unstable(feature = "ref_slice", issue = "27774")]
1423 pub fn mut_ref_slice<A>(s: &mut A) -> &mut [A] {
1425 from_raw_parts_mut(s, 1)
1429 /// Forms a slice from a pointer and a length.
1431 /// The `len` argument is the number of **elements**, not the number of bytes.
1435 /// This function is unsafe as there is no guarantee that the given pointer is
1436 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1437 /// lifetime for the returned slice.
1439 /// `p` must be non-null, even for zero-length slices.
1443 /// The lifetime for the returned slice is inferred from its usage. To
1444 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1445 /// source lifetime is safe in the context, such as by providing a helper
1446 /// function taking the lifetime of a host value for the slice, or by explicit
1454 /// // manifest a slice out of thin air!
1455 /// let ptr = 0x1234 as *const usize;
1458 /// let slice = slice::from_raw_parts(ptr, amt);
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1464 mem::transmute(RawSlice { data: p, len: len })
1467 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1468 /// slice is returned.
1470 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1471 /// as not being able to provide a non-aliasing guarantee of the returned
1474 #[stable(feature = "rust1", since = "1.0.0")]
1475 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1476 mem::transmute(RawSlice { data: p, len: len })
1483 /// Operations on `[u8]`.
1484 #[unstable(feature = "slice_bytes", reason = "needs review",
1488 use slice::SliceExt;
1490 /// A trait for operations on mutable `[u8]`s.
1491 pub trait MutableByteVector {
1492 /// Sets all bytes of the receiver to the given value.
1493 fn set_memory(&mut self, value: u8);
1496 impl MutableByteVector for [u8] {
1498 fn set_memory(&mut self, value: u8) {
1499 unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1503 /// Copies data from `src` to `dst`
1505 /// Panics if the length of `dst` is less than the length of `src`.
1507 pub fn copy_memory(src: &[u8], dst: &mut [u8]) {
1508 let len_src = src.len();
1509 assert!(dst.len() >= len_src);
1510 // `dst` is unaliasable, so we know statically it doesn't overlap
1513 ptr::copy_nonoverlapping(src.as_ptr(),
1523 // Boilerplate traits
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1528 fn eq(&self, other: &[B]) -> bool {
1529 if self.len() != other.len() {
1533 for i in 0..self.len() {
1534 if !self[i].eq(&other[i]) {
1541 fn ne(&self, other: &[B]) -> bool {
1542 if self.len() != other.len() {
1546 for i in 0..self.len() {
1547 if self[i].ne(&other[i]) {
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<T: Eq> Eq for [T] {}
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<T: Ord> Ord for [T] {
1561 fn cmp(&self, other: &[T]) -> Ordering {
1562 self.iter().cmp(other.iter())
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl<T: PartialOrd> PartialOrd for [T] {
1569 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1570 self.iter().partial_cmp(other.iter())
1573 fn lt(&self, other: &[T]) -> bool {
1574 self.iter().lt(other.iter())
1577 fn le(&self, other: &[T]) -> bool {
1578 self.iter().le(other.iter())
1581 fn ge(&self, other: &[T]) -> bool {
1582 self.iter().ge(other.iter())
1585 fn gt(&self, other: &[T]) -> bool {
1586 self.iter().gt(other.iter())