1 // Copyright 2012-2017 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 see [`std::slice`].
15 //! [`std::slice`]: ../../std/slice/index.html
17 #![stable(feature = "rust1", since = "1.0.0")]
19 // How this module is organized.
21 // The library infrastructure for slices is fairly messy. There's
22 // a lot of stuff defined here. Let's keep it clean.
24 // Since slices don't support inherent methods; all operations
25 // on them are defined on traits, which are then reexported from
26 // the prelude for convenience. So there are a lot of traits here.
28 // The layout of this file is thus:
30 // * Slice-specific 'extension' traits and their implementations. This
31 // is where most of the slice API resides.
32 // * Implementations of a few common traits with important slice ops.
33 // * Definitions of a bunch of iterators.
35 // * The `raw` and `bytes` submodules.
36 // * Boilerplate trait implementations.
39 use cmp::Ordering::{self, Less, Equal, Greater};
42 use intrinsics::assume;
44 use ops::{FnMut, self};
46 use option::Option::{None, Some};
48 use result::Result::{Ok, Err};
51 use marker::{Copy, Send, Sync, Sized, self};
52 use iter_private::TrustedRandomAccess;
66 /// Extension methods for slices.
67 #[unstable(feature = "core_slice_ext",
68 reason = "stable interface provided by `impl [T]` in later crates",
70 #[allow(missing_docs)] // documented elsewhere
74 #[stable(feature = "core", since = "1.6.0")]
75 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
77 #[stable(feature = "core", since = "1.6.0")]
78 fn iter(&self) -> Iter<Self::Item>;
80 #[stable(feature = "core", since = "1.6.0")]
81 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
82 where P: FnMut(&Self::Item) -> bool;
84 #[stable(feature = "core", since = "1.6.0")]
85 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
86 where P: FnMut(&Self::Item) -> bool;
88 #[stable(feature = "core", since = "1.6.0")]
89 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
90 where P: FnMut(&Self::Item) -> bool;
92 #[stable(feature = "core", since = "1.6.0")]
93 fn windows(&self, size: usize) -> Windows<Self::Item>;
95 #[stable(feature = "core", since = "1.6.0")]
96 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
98 #[stable(feature = "core", since = "1.6.0")]
99 fn get<I>(&self, index: I) -> Option<&I::Output>
100 where I: SliceIndex<Self::Item>;
102 #[stable(feature = "core", since = "1.6.0")]
103 fn first(&self) -> Option<&Self::Item>;
105 #[stable(feature = "core", since = "1.6.0")]
106 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
108 #[stable(feature = "core", since = "1.6.0")]
109 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
111 #[stable(feature = "core", since = "1.6.0")]
112 fn last(&self) -> Option<&Self::Item>;
114 #[stable(feature = "core", since = "1.6.0")]
115 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
116 where I: SliceIndex<Self::Item>;
118 #[stable(feature = "core", since = "1.6.0")]
119 fn as_ptr(&self) -> *const Self::Item;
121 #[stable(feature = "core", since = "1.6.0")]
122 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
123 where Self::Item: Borrow<Q>,
126 #[stable(feature = "core", since = "1.6.0")]
127 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
128 where F: FnMut(&'a Self::Item) -> Ordering;
130 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
131 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result<usize, usize>
132 where F: FnMut(&'a Self::Item) -> B,
136 #[stable(feature = "core", since = "1.6.0")]
137 fn len(&self) -> usize;
139 #[stable(feature = "core", since = "1.6.0")]
140 fn is_empty(&self) -> bool { self.len() == 0 }
142 #[stable(feature = "core", since = "1.6.0")]
143 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
144 where I: SliceIndex<Self::Item>;
146 #[stable(feature = "core", since = "1.6.0")]
147 fn iter_mut(&mut self) -> IterMut<Self::Item>;
149 #[stable(feature = "core", since = "1.6.0")]
150 fn first_mut(&mut self) -> Option<&mut Self::Item>;
152 #[stable(feature = "core", since = "1.6.0")]
153 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
155 #[stable(feature = "core", since = "1.6.0")]
156 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
158 #[stable(feature = "core", since = "1.6.0")]
159 fn last_mut(&mut self) -> Option<&mut Self::Item>;
161 #[stable(feature = "core", since = "1.6.0")]
162 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
163 where P: FnMut(&Self::Item) -> bool;
165 #[stable(feature = "core", since = "1.6.0")]
166 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
167 where P: FnMut(&Self::Item) -> bool;
169 #[stable(feature = "core", since = "1.6.0")]
170 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
171 where P: FnMut(&Self::Item) -> bool;
173 #[stable(feature = "core", since = "1.6.0")]
174 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
176 #[stable(feature = "core", since = "1.6.0")]
177 fn swap(&mut self, a: usize, b: usize);
179 #[stable(feature = "core", since = "1.6.0")]
180 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
182 #[stable(feature = "core", since = "1.6.0")]
183 fn reverse(&mut self);
185 #[stable(feature = "core", since = "1.6.0")]
186 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
187 where I: SliceIndex<Self::Item>;
189 #[stable(feature = "core", since = "1.6.0")]
190 fn as_mut_ptr(&mut self) -> *mut Self::Item;
192 #[stable(feature = "core", since = "1.6.0")]
193 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
195 #[stable(feature = "core", since = "1.6.0")]
196 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
198 #[stable(feature = "core", since = "1.6.0")]
199 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
201 #[stable(feature = "clone_from_slice", since = "1.7.0")]
202 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
204 #[stable(feature = "copy_from_slice", since = "1.9.0")]
205 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
207 #[unstable(feature = "sort_unstable", issue = "40585")]
208 fn sort_unstable(&mut self)
209 where Self::Item: Ord;
211 #[unstable(feature = "sort_unstable", issue = "40585")]
212 fn sort_unstable_by<F>(&mut self, compare: F)
213 where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
215 #[unstable(feature = "sort_unstable", issue = "40585")]
216 fn sort_unstable_by_key<B, F>(&mut self, f: F)
217 where F: FnMut(&Self::Item) -> B,
221 // Use macros to be generic over const/mut
222 macro_rules! slice_offset {
223 ($ptr:expr, $by:expr) => {{
225 if size_from_ptr(ptr) == 0 {
226 (ptr as *mut i8).wrapping_offset($by) as _
233 // make a &T from a *const T
234 macro_rules! make_ref {
237 if size_from_ptr(ptr) == 0 {
238 // Use a non-null pointer value
246 // make a &mut T from a *mut T
247 macro_rules! make_ref_mut {
250 if size_from_ptr(ptr) == 0 {
251 // Use a non-null pointer value
259 #[unstable(feature = "core_slice_ext",
260 reason = "stable interface provided by `impl [T]` in later crates",
262 impl<T> SliceExt for [T] {
266 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
267 (&self[..mid], &self[mid..])
271 fn iter(&self) -> Iter<T> {
273 let p = if mem::size_of::<T>() == 0 {
276 let p = self.as_ptr();
277 assume(!p.is_null());
283 end: slice_offset!(p, self.len() as isize),
284 _marker: marker::PhantomData
290 fn split<P>(&self, pred: P) -> Split<T, P>
291 where P: FnMut(&T) -> bool
301 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
302 where P: FnMut(&T) -> bool
305 inner: GenericSplitN {
306 iter: self.split(pred),
314 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
315 where P: FnMut(&T) -> bool
318 inner: GenericSplitN {
319 iter: self.split(pred),
327 fn windows(&self, size: usize) -> Windows<T> {
329 Windows { v: self, size: size }
333 fn chunks(&self, size: usize) -> Chunks<T> {
335 Chunks { v: self, size: size }
339 fn get<I>(&self, index: I) -> Option<&I::Output>
340 where I: SliceIndex<T>
346 fn first(&self) -> Option<&T> {
347 if self.is_empty() { None } else { Some(&self[0]) }
351 fn split_first(&self) -> Option<(&T, &[T])> {
352 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
356 fn split_last(&self) -> Option<(&T, &[T])> {
357 let len = self.len();
358 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
362 fn last(&self) -> Option<&T> {
363 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
367 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
368 where I: SliceIndex<T>
370 index.get_unchecked(self)
374 fn as_ptr(&self) -> *const T {
375 self as *const [T] as *const T
378 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
379 where F: FnMut(&'a T) -> Ordering
381 let mut base = 0usize;
385 let (head, tail) = s.split_at(s.len() >> 1);
391 base += head.len() + 1;
395 Equal => return Ok(base + head.len()),
401 fn len(&self) -> usize {
403 mem::transmute::<&[T], Repr<T>>(self).len
408 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
409 where I: SliceIndex<T>
415 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
416 let len = self.len();
417 let ptr = self.as_mut_ptr();
422 (from_raw_parts_mut(ptr, mid),
423 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
428 fn iter_mut(&mut self) -> IterMut<T> {
430 let p = if mem::size_of::<T>() == 0 {
433 let p = self.as_mut_ptr();
434 assume(!p.is_null());
440 end: slice_offset!(p, self.len() as isize),
441 _marker: marker::PhantomData
447 fn last_mut(&mut self) -> Option<&mut T> {
448 let len = self.len();
449 if len == 0 { return None; }
450 Some(&mut self[len - 1])
454 fn first_mut(&mut self) -> Option<&mut T> {
455 if self.is_empty() { None } else { Some(&mut self[0]) }
459 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
460 if self.is_empty() { None } else {
461 let split = self.split_at_mut(1);
462 Some((&mut split.0[0], split.1))
467 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
468 let len = self.len();
469 if len == 0 { None } else {
470 let split = self.split_at_mut(len - 1);
471 Some((&mut split.1[0], split.0))
476 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
477 where P: FnMut(&T) -> bool
479 SplitMut { v: self, pred: pred, finished: false }
483 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
484 where P: FnMut(&T) -> bool
487 inner: GenericSplitN {
488 iter: self.split_mut(pred),
496 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
497 P: FnMut(&T) -> bool,
500 inner: GenericSplitN {
501 iter: self.split_mut(pred),
509 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
510 assert!(chunk_size > 0);
511 ChunksMut { v: self, chunk_size: chunk_size }
515 fn swap(&mut self, a: usize, b: usize) {
517 // Can't take two mutable loans from one vector, so instead just cast
518 // them to their raw pointers to do the swap
519 let pa: *mut T = &mut self[a];
520 let pb: *mut T = &mut self[b];
525 fn reverse(&mut self) {
526 let mut i: usize = 0;
529 // Unsafe swap to avoid the bounds check in safe swap.
531 let pa: *mut T = self.get_unchecked_mut(i);
532 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
540 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
541 where I: SliceIndex<T>
543 index.get_unchecked_mut(self)
547 fn as_mut_ptr(&mut self) -> *mut T {
548 self as *mut [T] as *mut T
552 fn contains(&self, x: &T) -> bool where T: PartialEq {
553 self.iter().any(|elt| *x == *elt)
557 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
558 let n = needle.len();
559 self.len() >= n && needle == &self[..n]
563 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
564 let (m, n) = (self.len(), needle.len());
565 m >= n && needle == &self[m-n..]
568 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
572 self.binary_search_by(|p| p.borrow().cmp(x))
576 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
577 assert!(self.len() == src.len(),
578 "destination and source slices have different lengths");
579 // NOTE: We need to explicitly slice them to the same length
580 // for bounds checking to be elided, and the optimizer will
581 // generate memcpy for simple cases (for example T = u8).
582 let len = self.len();
583 let src = &src[..len];
585 self[i].clone_from(&src[i]);
590 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
591 assert!(self.len() == src.len(),
592 "destination and source slices have different lengths");
594 ptr::copy_nonoverlapping(
595 src.as_ptr(), self.as_mut_ptr(), self.len());
600 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
601 where F: FnMut(&'a Self::Item) -> B,
605 self.binary_search_by(|k| f(k).borrow().cmp(b))
609 fn sort_unstable(&mut self)
610 where Self::Item: Ord
612 sort::quicksort(self, |a, b| a.lt(b));
616 fn sort_unstable_by<F>(&mut self, mut compare: F)
617 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
619 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
623 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
624 where F: FnMut(&Self::Item) -> B,
627 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
631 #[stable(feature = "rust1", since = "1.0.0")]
632 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
633 impl<T, I> ops::Index<I> for [T]
634 where I: SliceIndex<T>
636 type Output = I::Output;
639 fn index(&self, index: I) -> &I::Output {
644 #[stable(feature = "rust1", since = "1.0.0")]
645 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
646 impl<T, I> ops::IndexMut<I> for [T]
647 where I: SliceIndex<T>
650 fn index_mut(&mut self, index: I) -> &mut I::Output {
651 index.index_mut(self)
657 fn slice_index_len_fail(index: usize, len: usize) -> ! {
658 panic!("index {} out of range for slice of length {}", index, len);
663 fn slice_index_order_fail(index: usize, end: usize) -> ! {
664 panic!("slice index starts at {} but ends at {}", index, end);
667 /// A helper trait used for indexing operations.
668 #[unstable(feature = "slice_get_slice", issue = "35729")]
669 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
670 pub trait SliceIndex<T> {
671 /// The output type returned by methods.
674 /// Returns a shared reference to the output at this location, if in
676 fn get(self, slice: &[T]) -> Option<&Self::Output>;
678 /// Returns a mutable reference to the output at this location, if in
680 fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output>;
682 /// Returns a shared reference to the output at this location, without
683 /// performing any bounds checking.
684 unsafe fn get_unchecked(self, slice: &[T]) -> &Self::Output;
686 /// Returns a mutable reference to the output at this location, without
687 /// performing any bounds checking.
688 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut Self::Output;
690 /// Returns a shared reference to the output at this location, panicking
691 /// if out of bounds.
692 fn index(self, slice: &[T]) -> &Self::Output;
694 /// Returns a mutable reference to the output at this location, panicking
695 /// if out of bounds.
696 fn index_mut(self, slice: &mut [T]) -> &mut Self::Output;
699 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
700 impl<T> SliceIndex<T> for usize {
704 fn get(self, slice: &[T]) -> Option<&T> {
705 if self < slice.len() {
707 Some(self.get_unchecked(slice))
715 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
716 if self < slice.len() {
718 Some(self.get_unchecked_mut(slice))
726 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
727 &*slice.as_ptr().offset(self as isize)
731 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
732 &mut *slice.as_mut_ptr().offset(self as isize)
736 fn index(self, slice: &[T]) -> &T {
737 // NB: use intrinsic indexing
742 fn index_mut(self, slice: &mut [T]) -> &mut T {
743 // NB: use intrinsic indexing
748 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
749 impl<T> SliceIndex<T> for ops::Range<usize> {
753 fn get(self, slice: &[T]) -> Option<&[T]> {
754 if self.start > self.end || self.end > slice.len() {
758 Some(self.get_unchecked(slice))
764 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
765 if self.start > self.end || self.end > slice.len() {
769 Some(self.get_unchecked_mut(slice))
775 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
776 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
780 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
781 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
785 fn index(self, slice: &[T]) -> &[T] {
786 if self.start > self.end {
787 slice_index_order_fail(self.start, self.end);
788 } else if self.end > slice.len() {
789 slice_index_len_fail(self.end, slice.len());
792 self.get_unchecked(slice)
797 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
798 if self.start > self.end {
799 slice_index_order_fail(self.start, self.end);
800 } else if self.end > slice.len() {
801 slice_index_len_fail(self.end, slice.len());
804 self.get_unchecked_mut(slice)
809 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
810 impl<T> SliceIndex<T> for ops::RangeTo<usize> {
814 fn get(self, slice: &[T]) -> Option<&[T]> {
815 (0..self.end).get(slice)
819 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
820 (0..self.end).get_mut(slice)
824 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
825 (0..self.end).get_unchecked(slice)
829 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
830 (0..self.end).get_unchecked_mut(slice)
834 fn index(self, slice: &[T]) -> &[T] {
835 (0..self.end).index(slice)
839 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
840 (0..self.end).index_mut(slice)
844 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
845 impl<T> SliceIndex<T> for ops::RangeFrom<usize> {
849 fn get(self, slice: &[T]) -> Option<&[T]> {
850 (self.start..slice.len()).get(slice)
854 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
855 (self.start..slice.len()).get_mut(slice)
859 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
860 (self.start..slice.len()).get_unchecked(slice)
864 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
865 (self.start..slice.len()).get_unchecked_mut(slice)
869 fn index(self, slice: &[T]) -> &[T] {
870 (self.start..slice.len()).index(slice)
874 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
875 (self.start..slice.len()).index_mut(slice)
879 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
880 impl<T> SliceIndex<T> for ops::RangeFull {
884 fn get(self, slice: &[T]) -> Option<&[T]> {
889 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
894 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
899 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
904 fn index(self, slice: &[T]) -> &[T] {
909 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
915 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
916 impl<T> SliceIndex<T> for ops::RangeInclusive<usize> {
920 fn get(self, slice: &[T]) -> Option<&[T]> {
922 ops::RangeInclusive::Empty { .. } => Some(&[]),
923 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => None,
924 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get(slice),
929 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
931 ops::RangeInclusive::Empty { .. } => Some(&mut []),
932 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => None,
933 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get_mut(slice),
938 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
940 ops::RangeInclusive::Empty { .. } => &[],
941 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get_unchecked(slice),
946 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
948 ops::RangeInclusive::Empty { .. } => &mut [],
949 ops::RangeInclusive::NonEmpty { start, end } => {
950 (start..end + 1).get_unchecked_mut(slice)
956 fn index(self, slice: &[T]) -> &[T] {
958 ops::RangeInclusive::Empty { .. } => &[],
959 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => {
960 panic!("attempted to index slice up to maximum usize");
962 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).index(slice),
967 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
969 ops::RangeInclusive::Empty { .. } => &mut [],
970 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => {
971 panic!("attempted to index slice up to maximum usize");
973 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).index_mut(slice),
978 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
979 impl<T> SliceIndex<T> for ops::RangeToInclusive<usize> {
983 fn get(self, slice: &[T]) -> Option<&[T]> {
984 (0...self.end).get(slice)
988 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
989 (0...self.end).get_mut(slice)
993 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
994 (0...self.end).get_unchecked(slice)
998 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
999 (0...self.end).get_unchecked_mut(slice)
1003 fn index(self, slice: &[T]) -> &[T] {
1004 (0...self.end).index(slice)
1008 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1009 (0...self.end).index_mut(slice)
1013 ////////////////////////////////////////////////////////////////////////////////
1015 ////////////////////////////////////////////////////////////////////////////////
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a, T> Default for &'a [T] {
1019 /// Creates an empty slice.
1020 fn default() -> &'a [T] { &[] }
1023 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1024 impl<'a, T> Default for &'a mut [T] {
1025 /// Creates a mutable empty slice.
1026 fn default() -> &'a mut [T] { &mut [] }
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<'a, T> IntoIterator for &'a [T] {
1036 type IntoIter = Iter<'a, T>;
1038 fn into_iter(self) -> Iter<'a, T> {
1043 #[stable(feature = "rust1", since = "1.0.0")]
1044 impl<'a, T> IntoIterator for &'a mut [T] {
1045 type Item = &'a mut T;
1046 type IntoIter = IterMut<'a, T>;
1048 fn into_iter(self) -> IterMut<'a, T> {
1054 fn size_from_ptr<T>(_: *const T) -> usize {
1058 // The shared definition of the `Iter` and `IterMut` iterators
1059 macro_rules! iterator {
1060 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl<'a, T> Iterator for $name<'a, T> {
1066 fn next(&mut self) -> Option<$elem> {
1067 // could be implemented with slices, but this avoids bounds checks
1069 if mem::size_of::<T>() != 0 {
1070 assume(!self.ptr.is_null());
1071 assume(!self.end.is_null());
1073 if self.ptr == self.end {
1076 Some($mkref!(self.ptr.post_inc()))
1082 fn size_hint(&self) -> (usize, Option<usize>) {
1083 let exact = ptrdistance(self.ptr, self.end);
1084 (exact, Some(exact))
1088 fn count(self) -> usize {
1093 fn nth(&mut self, n: usize) -> Option<$elem> {
1094 // Call helper method. Can't put the definition here because mut versus const.
1099 fn last(mut self) -> Option<$elem> {
1103 fn all<F>(&mut self, mut predicate: F) -> bool
1104 where F: FnMut(Self::Item) -> bool,
1106 self.search_while(true, move |elt| {
1108 SearchWhile::Continue
1110 SearchWhile::Done(false)
1115 fn any<F>(&mut self, mut predicate: F) -> bool
1116 where F: FnMut(Self::Item) -> bool,
1118 !self.all(move |elt| !predicate(elt))
1121 fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1122 where F: FnMut(&Self::Item) -> bool,
1124 self.search_while(None, move |elt| {
1125 if predicate(&elt) {
1126 SearchWhile::Done(Some(elt))
1128 SearchWhile::Continue
1133 fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1134 where F: FnMut(Self::Item) -> bool,
1137 self.search_while(None, move |elt| {
1139 SearchWhile::Done(Some(index))
1142 SearchWhile::Continue
1147 fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1148 where F: FnMut(Self::Item) -> bool,
1150 let mut index = self.len();
1151 self.rsearch_while(None, move |elt| {
1154 SearchWhile::Done(Some(index))
1156 SearchWhile::Continue
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1165 fn next_back(&mut self) -> Option<$elem> {
1166 // could be implemented with slices, but this avoids bounds checks
1168 if mem::size_of::<T>() != 0 {
1169 assume(!self.ptr.is_null());
1170 assume(!self.end.is_null());
1172 if self.end == self.ptr {
1175 Some($mkref!(self.end.pre_dec()))
1181 // search_while is a generalization of the internal iteration methods.
1182 impl<'a, T> $name<'a, T> {
1183 // search through the iterator's element using the closure `g`.
1184 // if no element was found, return `default`.
1185 fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1187 G: FnMut($elem) -> SearchWhile<Acc>
1189 // manual unrolling is needed when there are conditional exits from the loop
1191 while ptrdistance(self.ptr, self.end) >= 4 {
1192 search_while!(g($mkref!(self.ptr.post_inc())));
1193 search_while!(g($mkref!(self.ptr.post_inc())));
1194 search_while!(g($mkref!(self.ptr.post_inc())));
1195 search_while!(g($mkref!(self.ptr.post_inc())));
1197 while self.ptr != self.end {
1198 search_while!(g($mkref!(self.ptr.post_inc())));
1204 fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1206 G: FnMut($elem) -> SearchWhile<Acc>
1209 while ptrdistance(self.ptr, self.end) >= 4 {
1210 search_while!(g($mkref!(self.end.pre_dec())));
1211 search_while!(g($mkref!(self.end.pre_dec())));
1212 search_while!(g($mkref!(self.end.pre_dec())));
1213 search_while!(g($mkref!(self.end.pre_dec())));
1215 while self.ptr != self.end {
1216 search_while!(g($mkref!(self.end.pre_dec())));
1225 macro_rules! make_slice {
1226 ($start: expr, $end: expr) => {{
1228 let diff = ($end as usize).wrapping_sub(start as usize);
1229 if size_from_ptr(start) == 0 {
1230 // use a non-null pointer value
1231 unsafe { from_raw_parts(1 as *const _, diff) }
1233 let len = diff / size_from_ptr(start);
1234 unsafe { from_raw_parts(start, len) }
1239 macro_rules! make_mut_slice {
1240 ($start: expr, $end: expr) => {{
1242 let diff = ($end as usize).wrapping_sub(start as usize);
1243 if size_from_ptr(start) == 0 {
1244 // use a non-null pointer value
1245 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1247 let len = diff / size_from_ptr(start);
1248 unsafe { from_raw_parts_mut(start, len) }
1253 // An enum used for controlling the execution of `.search_while()`.
1254 enum SearchWhile<T> {
1255 // Continue searching
1257 // Fold is complete and will return this value
1261 // helper macro for search while's control flow
1262 macro_rules! search_while {
1265 SearchWhile::Continue => { }
1266 SearchWhile::Done(done) => return done,
1271 /// Immutable slice iterator
1273 /// This struct is created by the [`iter`] method on [slices].
1280 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1281 /// let slice = &[1, 2, 3];
1283 /// // Then, we iterate over it:
1284 /// for element in slice.iter() {
1285 /// println!("{}", element);
1289 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1290 /// [slices]: ../../std/primitive.slice.html
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub struct Iter<'a, T: 'a> {
1295 _marker: marker::PhantomData<&'a T>,
1298 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1299 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1301 f.debug_tuple("Iter")
1302 .field(&self.as_slice())
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1312 impl<'a, T> Iter<'a, T> {
1313 /// View the underlying data as a subslice of the original data.
1315 /// This has the same lifetime as the original slice, and so the
1316 /// iterator can continue to be used while this exists.
1323 /// // First, we declare a type which has the `iter` method to get the `Iter`
1324 /// // struct (&[usize here]):
1325 /// let slice = &[1, 2, 3];
1327 /// // Then, we get the iterator:
1328 /// let mut iter = slice.iter();
1329 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1330 /// println!("{:?}", iter.as_slice());
1332 /// // Next, we move to the second element of the slice:
1334 /// // Now `as_slice` returns "[2, 3]":
1335 /// println!("{:?}", iter.as_slice());
1337 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1338 pub fn as_slice(&self) -> &'a [T] {
1339 make_slice!(self.ptr, self.end)
1342 // Helper function for Iter::nth
1343 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1344 match self.as_slice().get(n) {
1345 Some(elem_ref) => unsafe {
1346 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1350 self.ptr = self.end;
1357 iterator!{struct Iter -> *const T, &'a T, make_ref}
1359 #[stable(feature = "rust1", since = "1.0.0")]
1360 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1361 fn is_empty(&self) -> bool {
1362 self.ptr == self.end
1366 #[unstable(feature = "fused", issue = "35602")]
1367 impl<'a, T> FusedIterator for Iter<'a, T> {}
1369 #[unstable(feature = "trusted_len", issue = "37572")]
1370 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<'a, T> Clone for Iter<'a, T> {
1374 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1377 #[stable(feature = "slice_iter_as_ref", since = "1.12.0")]
1378 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1379 fn as_ref(&self) -> &[T] {
1384 /// Mutable slice iterator.
1386 /// This struct is created by the [`iter_mut`] method on [slices].
1393 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1394 /// // struct (&[usize here]):
1395 /// let mut slice = &mut [1, 2, 3];
1397 /// // Then, we iterate over it and increment each element value:
1398 /// for element in slice.iter_mut() {
1402 /// // We now have "[2, 3, 4]":
1403 /// println!("{:?}", slice);
1406 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1407 /// [slices]: ../../std/primitive.slice.html
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 pub struct IterMut<'a, T: 'a> {
1412 _marker: marker::PhantomData<&'a mut T>,
1415 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1416 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1418 f.debug_tuple("IterMut")
1419 .field(&make_slice!(self.ptr, self.end))
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1429 impl<'a, T> IterMut<'a, T> {
1430 /// View the underlying data as a subslice of the original data.
1432 /// To avoid creating `&mut` references that alias, this is forced
1433 /// to consume the iterator. Consider using the `Slice` and
1434 /// `SliceMut` implementations for obtaining slices with more
1435 /// restricted lifetimes that do not consume the iterator.
1442 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1443 /// // struct (&[usize here]):
1444 /// let mut slice = &mut [1, 2, 3];
1447 /// // Then, we get the iterator:
1448 /// let mut iter = slice.iter_mut();
1449 /// // We move to next element:
1451 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1452 /// println!("{:?}", iter.into_slice());
1455 /// // Now let's modify a value of the slice:
1457 /// // First we get back the iterator:
1458 /// let mut iter = slice.iter_mut();
1459 /// // We change the value of the first element of the slice returned by the `next` method:
1460 /// *iter.next().unwrap() += 1;
1462 /// // Now slice is "[2, 2, 3]":
1463 /// println!("{:?}", slice);
1465 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1466 pub fn into_slice(self) -> &'a mut [T] {
1467 make_mut_slice!(self.ptr, self.end)
1470 // Helper function for IterMut::nth
1471 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1472 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1473 Some(elem_ref) => unsafe {
1474 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1478 self.ptr = self.end;
1485 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1489 fn is_empty(&self) -> bool {
1490 self.ptr == self.end
1494 #[unstable(feature = "fused", issue = "35602")]
1495 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1497 #[unstable(feature = "trusted_len", issue = "37572")]
1498 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1501 // Return the number of elements of `T` from `start` to `end`.
1502 // Return the arithmetic difference if `T` is zero size.
1504 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1505 let diff = (end as usize).wrapping_sub(start as usize);
1506 let size = mem::size_of::<T>();
1507 diff / (if size == 0 { 1 } else { size })
1510 // Extension methods for raw pointers, used by the iterators
1511 trait PointerExt : Copy {
1512 unsafe fn slice_offset(self, i: isize) -> Self;
1514 /// Increments `self` by 1, but returns the old value.
1516 unsafe fn post_inc(&mut self) -> Self {
1517 let current = *self;
1518 *self = self.slice_offset(1);
1522 /// Decrements `self` by 1, and returns the new value.
1524 unsafe fn pre_dec(&mut self) -> Self {
1525 *self = self.slice_offset(-1);
1530 impl<T> PointerExt for *const T {
1532 unsafe fn slice_offset(self, i: isize) -> Self {
1533 slice_offset!(self, i)
1537 impl<T> PointerExt for *mut T {
1539 unsafe fn slice_offset(self, i: isize) -> Self {
1540 slice_offset!(self, i)
1544 /// An internal abstraction over the splitting iterators, so that
1545 /// splitn, splitn_mut etc can be implemented once.
1547 trait SplitIter: DoubleEndedIterator {
1548 /// Marks the underlying iterator as complete, extracting the remaining
1549 /// portion of the slice.
1550 fn finish(&mut self) -> Option<Self::Item>;
1553 /// An iterator over subslices separated by elements that match a predicate
1556 /// This struct is created by the [`split`] method on [slices].
1558 /// [`split`]: ../../std/primitive.slice.html#method.split
1559 /// [slices]: ../../std/primitive.slice.html
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1567 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1568 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1570 f.debug_struct("Split")
1571 .field("v", &self.v)
1572 .field("finished", &self.finished)
1577 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1580 fn clone(&self) -> Split<'a, T, P> {
1583 pred: self.pred.clone(),
1584 finished: self.finished,
1589 #[stable(feature = "rust1", since = "1.0.0")]
1590 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1591 type Item = &'a [T];
1594 fn next(&mut self) -> Option<&'a [T]> {
1595 if self.finished { return None; }
1597 match self.v.iter().position(|x| (self.pred)(x)) {
1598 None => self.finish(),
1600 let ret = Some(&self.v[..idx]);
1601 self.v = &self.v[idx + 1..];
1608 fn size_hint(&self) -> (usize, Option<usize>) {
1612 (1, Some(self.v.len() + 1))
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1620 fn next_back(&mut self) -> Option<&'a [T]> {
1621 if self.finished { return None; }
1623 match self.v.iter().rposition(|x| (self.pred)(x)) {
1624 None => self.finish(),
1626 let ret = Some(&self.v[idx + 1..]);
1627 self.v = &self.v[..idx];
1634 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1636 fn finish(&mut self) -> Option<&'a [T]> {
1637 if self.finished { None } else { self.finished = true; Some(self.v) }
1641 #[unstable(feature = "fused", issue = "35602")]
1642 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1644 /// An iterator over the subslices of the vector which are separated
1645 /// by elements that match `pred`.
1647 /// This struct is created by the [`split_mut`] method on [slices].
1649 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1650 /// [slices]: ../../std/primitive.slice.html
1651 #[stable(feature = "rust1", since = "1.0.0")]
1652 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1658 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1659 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1661 f.debug_struct("SplitMut")
1662 .field("v", &self.v)
1663 .field("finished", &self.finished)
1668 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1670 fn finish(&mut self) -> Option<&'a mut [T]> {
1674 self.finished = true;
1675 Some(mem::replace(&mut self.v, &mut []))
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1682 type Item = &'a mut [T];
1685 fn next(&mut self) -> Option<&'a mut [T]> {
1686 if self.finished { return None; }
1688 let idx_opt = { // work around borrowck limitations
1689 let pred = &mut self.pred;
1690 self.v.iter().position(|x| (*pred)(x))
1693 None => self.finish(),
1695 let tmp = mem::replace(&mut self.v, &mut []);
1696 let (head, tail) = tmp.split_at_mut(idx);
1697 self.v = &mut tail[1..];
1704 fn size_hint(&self) -> (usize, Option<usize>) {
1708 // if the predicate doesn't match anything, we yield one slice
1709 // if it matches every element, we yield len+1 empty slices.
1710 (1, Some(self.v.len() + 1))
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1717 P: FnMut(&T) -> bool,
1720 fn next_back(&mut self) -> Option<&'a mut [T]> {
1721 if self.finished { return None; }
1723 let idx_opt = { // work around borrowck limitations
1724 let pred = &mut self.pred;
1725 self.v.iter().rposition(|x| (*pred)(x))
1728 None => self.finish(),
1730 let tmp = mem::replace(&mut self.v, &mut []);
1731 let (head, tail) = tmp.split_at_mut(idx);
1733 Some(&mut tail[1..])
1739 #[unstable(feature = "fused", issue = "35602")]
1740 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1742 /// An private iterator over subslices separated by elements that
1743 /// match a predicate function, splitting at most a fixed number of
1746 struct GenericSplitN<I> {
1752 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1756 fn next(&mut self) -> Option<T> {
1759 1 => { self.count -= 1; self.iter.finish() }
1762 if self.invert {self.iter.next_back()} else {self.iter.next()}
1768 fn size_hint(&self) -> (usize, Option<usize>) {
1769 let (lower, upper_opt) = self.iter.size_hint();
1770 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1774 /// An iterator over subslices separated by elements that match a predicate
1775 /// function, limited to a given number of splits.
1777 /// This struct is created by the [`splitn`] method on [slices].
1779 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1780 /// [slices]: ../../std/primitive.slice.html
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1783 inner: GenericSplitN<Split<'a, T, P>>
1786 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1787 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1789 f.debug_struct("SplitN")
1790 .field("inner", &self.inner)
1795 /// An iterator over subslices separated by elements that match a
1796 /// predicate function, limited to a given number of splits, starting
1797 /// from the end of the slice.
1799 /// This struct is created by the [`rsplitn`] method on [slices].
1801 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1802 /// [slices]: ../../std/primitive.slice.html
1803 #[stable(feature = "rust1", since = "1.0.0")]
1804 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1805 inner: GenericSplitN<Split<'a, T, P>>
1808 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1809 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
1810 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1811 f.debug_struct("RSplitN")
1812 .field("inner", &self.inner)
1817 /// An iterator over subslices separated by elements that match a predicate
1818 /// function, limited to a given number of splits.
1820 /// This struct is created by the [`splitn_mut`] method on [slices].
1822 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
1823 /// [slices]: ../../std/primitive.slice.html
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1826 inner: GenericSplitN<SplitMut<'a, T, P>>
1829 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1830 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1831 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1832 f.debug_struct("SplitNMut")
1833 .field("inner", &self.inner)
1838 /// An iterator over subslices separated by elements that match a
1839 /// predicate function, limited to a given number of splits, starting
1840 /// from the end of the slice.
1842 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1844 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
1845 /// [slices]: ../../std/primitive.slice.html
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1848 inner: GenericSplitN<SplitMut<'a, T, P>>
1851 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1852 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1853 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1854 f.debug_struct("RSplitNMut")
1855 .field("inner", &self.inner)
1860 macro_rules! forward_iterator {
1861 ($name:ident: $elem:ident, $iter_of:ty) => {
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1864 P: FnMut(&T) -> bool
1866 type Item = $iter_of;
1869 fn next(&mut self) -> Option<$iter_of> {
1874 fn size_hint(&self) -> (usize, Option<usize>) {
1875 self.inner.size_hint()
1879 #[unstable(feature = "fused", issue = "35602")]
1880 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
1881 where P: FnMut(&T) -> bool {}
1885 forward_iterator! { SplitN: T, &'a [T] }
1886 forward_iterator! { RSplitN: T, &'a [T] }
1887 forward_iterator! { SplitNMut: T, &'a mut [T] }
1888 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1890 /// An iterator over overlapping subslices of length `size`.
1892 /// This struct is created by the [`windows`] method on [slices].
1894 /// [`windows`]: ../../std/primitive.slice.html#method.windows
1895 /// [slices]: ../../std/primitive.slice.html
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 pub struct Windows<'a, T:'a> {
1903 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl<'a, T> Clone for Windows<'a, T> {
1906 fn clone(&self) -> Windows<'a, T> {
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl<'a, T> Iterator for Windows<'a, T> {
1916 type Item = &'a [T];
1919 fn next(&mut self) -> Option<&'a [T]> {
1920 if self.size > self.v.len() {
1923 let ret = Some(&self.v[..self.size]);
1924 self.v = &self.v[1..];
1930 fn size_hint(&self) -> (usize, Option<usize>) {
1931 if self.size > self.v.len() {
1934 let size = self.v.len() - self.size + 1;
1940 fn count(self) -> usize {
1945 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1946 let (end, overflow) = self.size.overflowing_add(n);
1947 if end > self.v.len() || overflow {
1951 let nth = &self.v[n..end];
1952 self.v = &self.v[n+1..];
1958 fn last(self) -> Option<Self::Item> {
1959 if self.size > self.v.len() {
1962 let start = self.v.len() - self.size;
1963 Some(&self.v[start..])
1968 #[stable(feature = "rust1", since = "1.0.0")]
1969 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1971 fn next_back(&mut self) -> Option<&'a [T]> {
1972 if self.size > self.v.len() {
1975 let ret = Some(&self.v[self.v.len()-self.size..]);
1976 self.v = &self.v[..self.v.len()-1];
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1985 #[unstable(feature = "fused", issue = "35602")]
1986 impl<'a, T> FusedIterator for Windows<'a, T> {}
1988 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1991 /// When the slice len is not evenly divided by the chunk size, the last slice
1992 /// of the iteration will be the remainder.
1994 /// This struct is created by the [`chunks`] method on [slices].
1996 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
1997 /// [slices]: ../../std/primitive.slice.html
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 pub struct Chunks<'a, T:'a> {
2005 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2006 #[stable(feature = "rust1", since = "1.0.0")]
2007 impl<'a, T> Clone for Chunks<'a, T> {
2008 fn clone(&self) -> Chunks<'a, T> {
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 impl<'a, T> Iterator for Chunks<'a, T> {
2018 type Item = &'a [T];
2021 fn next(&mut self) -> Option<&'a [T]> {
2022 if self.v.is_empty() {
2025 let chunksz = cmp::min(self.v.len(), self.size);
2026 let (fst, snd) = self.v.split_at(chunksz);
2033 fn size_hint(&self) -> (usize, Option<usize>) {
2034 if self.v.is_empty() {
2037 let n = self.v.len() / self.size;
2038 let rem = self.v.len() % self.size;
2039 let n = if rem > 0 { n+1 } else { n };
2045 fn count(self) -> usize {
2050 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2051 let (start, overflow) = n.overflowing_mul(self.size);
2052 if start >= self.v.len() || overflow {
2056 let end = match start.checked_add(self.size) {
2057 Some(sum) => cmp::min(self.v.len(), sum),
2058 None => self.v.len(),
2060 let nth = &self.v[start..end];
2061 self.v = &self.v[end..];
2067 fn last(self) -> Option<Self::Item> {
2068 if self.v.is_empty() {
2071 let start = (self.v.len() - 1) / self.size * self.size;
2072 Some(&self.v[start..])
2077 #[stable(feature = "rust1", since = "1.0.0")]
2078 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2080 fn next_back(&mut self) -> Option<&'a [T]> {
2081 if self.v.is_empty() {
2084 let remainder = self.v.len() % self.size;
2085 let chunksz = if remainder != 0 { remainder } else { self.size };
2086 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2093 #[stable(feature = "rust1", since = "1.0.0")]
2094 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2096 #[unstable(feature = "fused", issue = "35602")]
2097 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2099 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2100 /// elements at a time). When the slice len is not evenly divided by the chunk
2101 /// size, the last slice of the iteration will be the remainder.
2103 /// This struct is created by the [`chunks_mut`] method on [slices].
2105 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2106 /// [slices]: ../../std/primitive.slice.html
2108 #[stable(feature = "rust1", since = "1.0.0")]
2109 pub struct ChunksMut<'a, T:'a> {
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<'a, T> Iterator for ChunksMut<'a, T> {
2116 type Item = &'a mut [T];
2119 fn next(&mut self) -> Option<&'a mut [T]> {
2120 if self.v.is_empty() {
2123 let sz = cmp::min(self.v.len(), self.chunk_size);
2124 let tmp = mem::replace(&mut self.v, &mut []);
2125 let (head, tail) = tmp.split_at_mut(sz);
2132 fn size_hint(&self) -> (usize, Option<usize>) {
2133 if self.v.is_empty() {
2136 let n = self.v.len() / self.chunk_size;
2137 let rem = self.v.len() % self.chunk_size;
2138 let n = if rem > 0 { n + 1 } else { n };
2144 fn count(self) -> usize {
2149 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2150 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2151 if start >= self.v.len() || overflow {
2155 let end = match start.checked_add(self.chunk_size) {
2156 Some(sum) => cmp::min(self.v.len(), sum),
2157 None => self.v.len(),
2159 let tmp = mem::replace(&mut self.v, &mut []);
2160 let (head, tail) = tmp.split_at_mut(end);
2161 let (_, nth) = head.split_at_mut(start);
2168 fn last(self) -> Option<Self::Item> {
2169 if self.v.is_empty() {
2172 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2173 Some(&mut self.v[start..])
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2181 fn next_back(&mut self) -> Option<&'a mut [T]> {
2182 if self.v.is_empty() {
2185 let remainder = self.v.len() % self.chunk_size;
2186 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2187 let tmp = mem::replace(&mut self.v, &mut []);
2188 let tmp_len = tmp.len();
2189 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2199 #[unstable(feature = "fused", issue = "35602")]
2200 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2206 /// Forms a slice from a pointer and a length.
2208 /// The `len` argument is the number of **elements**, not the number of bytes.
2212 /// This function is unsafe as there is no guarantee that the given pointer is
2213 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2214 /// lifetime for the returned slice.
2216 /// `p` must be non-null, even for zero-length slices.
2220 /// The lifetime for the returned slice is inferred from its usage. To
2221 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2222 /// source lifetime is safe in the context, such as by providing a helper
2223 /// function taking the lifetime of a host value for the slice, or by explicit
2231 /// // manifest a slice out of thin air!
2232 /// let ptr = 0x1234 as *const usize;
2235 /// let slice = slice::from_raw_parts(ptr, amt);
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2241 mem::transmute(Repr { data: p, len: len })
2244 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2245 /// slice is returned.
2247 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2248 /// as not being able to provide a non-aliasing guarantee of the returned
2251 #[stable(feature = "rust1", since = "1.0.0")]
2252 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2253 mem::transmute(Repr { data: p, len: len })
2256 // This function is public only because there is no other way to unit test heapsort.
2257 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2259 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2260 where F: FnMut(&T, &T) -> bool
2262 sort::heapsort(v, &mut is_less);
2266 // Comparison traits
2270 /// Calls implementation provided memcmp.
2272 /// Interprets the data as u8.
2274 /// Returns 0 for equal, < 0 for less than and > 0 for greater
2276 // FIXME(#32610): Return type should be c_int
2277 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2280 #[stable(feature = "rust1", since = "1.0.0")]
2281 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2282 fn eq(&self, other: &[B]) -> bool {
2283 SlicePartialEq::equal(self, other)
2286 fn ne(&self, other: &[B]) -> bool {
2287 SlicePartialEq::not_equal(self, other)
2291 #[stable(feature = "rust1", since = "1.0.0")]
2292 impl<T: Eq> Eq for [T] {}
2294 /// Implements comparison of vectors lexicographically.
2295 #[stable(feature = "rust1", since = "1.0.0")]
2296 impl<T: Ord> Ord for [T] {
2297 fn cmp(&self, other: &[T]) -> Ordering {
2298 SliceOrd::compare(self, other)
2302 /// Implements comparison of vectors lexicographically.
2303 #[stable(feature = "rust1", since = "1.0.0")]
2304 impl<T: PartialOrd> PartialOrd for [T] {
2305 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2306 SlicePartialOrd::partial_compare(self, other)
2311 // intermediate trait for specialization of slice's PartialEq
2312 trait SlicePartialEq<B> {
2313 fn equal(&self, other: &[B]) -> bool;
2315 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2318 // Generic slice equality
2319 impl<A, B> SlicePartialEq<B> for [A]
2320 where A: PartialEq<B>
2322 default fn equal(&self, other: &[B]) -> bool {
2323 if self.len() != other.len() {
2327 for i in 0..self.len() {
2328 if !self[i].eq(&other[i]) {
2337 // Use memcmp for bytewise equality when the types allow
2338 impl<A> SlicePartialEq<A> for [A]
2339 where A: PartialEq<A> + BytewiseEquality
2341 fn equal(&self, other: &[A]) -> bool {
2342 if self.len() != other.len() {
2345 if self.as_ptr() == other.as_ptr() {
2349 let size = mem::size_of_val(self);
2350 memcmp(self.as_ptr() as *const u8,
2351 other.as_ptr() as *const u8, size) == 0
2357 // intermediate trait for specialization of slice's PartialOrd
2358 trait SlicePartialOrd<B> {
2359 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2362 impl<A> SlicePartialOrd<A> for [A]
2365 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2366 let l = cmp::min(self.len(), other.len());
2368 // Slice to the loop iteration range to enable bound check
2369 // elimination in the compiler
2370 let lhs = &self[..l];
2371 let rhs = &other[..l];
2374 match lhs[i].partial_cmp(&rhs[i]) {
2375 Some(Ordering::Equal) => (),
2376 non_eq => return non_eq,
2380 self.len().partial_cmp(&other.len())
2384 impl<A> SlicePartialOrd<A> for [A]
2387 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2388 Some(SliceOrd::compare(self, other))
2393 // intermediate trait for specialization of slice's Ord
2395 fn compare(&self, other: &[B]) -> Ordering;
2398 impl<A> SliceOrd<A> for [A]
2401 default fn compare(&self, other: &[A]) -> Ordering {
2402 let l = cmp::min(self.len(), other.len());
2404 // Slice to the loop iteration range to enable bound check
2405 // elimination in the compiler
2406 let lhs = &self[..l];
2407 let rhs = &other[..l];
2410 match lhs[i].cmp(&rhs[i]) {
2411 Ordering::Equal => (),
2412 non_eq => return non_eq,
2416 self.len().cmp(&other.len())
2420 // memcmp compares a sequence of unsigned bytes lexicographically.
2421 // this matches the order we want for [u8], but no others (not even [i8]).
2422 impl SliceOrd<u8> for [u8] {
2424 fn compare(&self, other: &[u8]) -> Ordering {
2425 let order = unsafe {
2426 memcmp(self.as_ptr(), other.as_ptr(),
2427 cmp::min(self.len(), other.len()))
2430 self.len().cmp(&other.len())
2431 } else if order < 0 {
2440 /// Trait implemented for types that can be compared for equality using
2441 /// their bytewise representation
2442 trait BytewiseEquality { }
2444 macro_rules! impl_marker_for {
2445 ($traitname:ident, $($ty:ty)*) => {
2447 impl $traitname for $ty { }
2452 impl_marker_for!(BytewiseEquality,
2453 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2456 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2457 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2458 &*self.ptr.offset(i as isize)
2460 fn may_have_side_effect() -> bool { false }
2464 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2465 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2466 &mut *self.ptr.offset(i as isize)
2468 fn may_have_side_effect() -> bool { false }