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.
38 use cmp::Ordering::{self, Less, Equal, Greater};
41 use intrinsics::assume;
43 use ops::{FnMut, Try, self};
45 use option::Option::{None, Some};
47 use result::Result::{Ok, Err};
50 use marker::{Copy, Send, Sync, Sized, self};
51 use iter_private::TrustedRandomAccess;
53 #[unstable(feature = "slice_internals", issue = "0",
54 reason = "exposed from core to be reused in std; use the memchr crate")]
55 /// Pure rust memchr implementation, taken from rust-memchr
71 /// Extension methods for slices.
72 #[unstable(feature = "core_slice_ext",
73 reason = "stable interface provided by `impl [T]` in later crates",
75 #[allow(missing_docs)] // documented elsewhere
79 #[stable(feature = "core", since = "1.6.0")]
80 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
82 #[stable(feature = "core", since = "1.6.0")]
83 fn iter(&self) -> Iter<Self::Item>;
85 #[stable(feature = "core", since = "1.6.0")]
86 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
87 where P: FnMut(&Self::Item) -> bool;
89 #[unstable(feature = "slice_rsplit", issue = "41020")]
90 fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
91 where P: FnMut(&Self::Item) -> bool;
93 #[stable(feature = "core", since = "1.6.0")]
94 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
95 where P: FnMut(&Self::Item) -> bool;
97 #[stable(feature = "core", since = "1.6.0")]
98 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
99 where P: FnMut(&Self::Item) -> bool;
101 #[stable(feature = "core", since = "1.6.0")]
102 fn windows(&self, size: usize) -> Windows<Self::Item>;
104 #[stable(feature = "core", since = "1.6.0")]
105 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
107 #[stable(feature = "core", since = "1.6.0")]
108 fn get<I>(&self, index: I) -> Option<&I::Output>
109 where I: SliceIndex<Self>;
110 #[stable(feature = "core", since = "1.6.0")]
111 fn first(&self) -> Option<&Self::Item>;
113 #[stable(feature = "core", since = "1.6.0")]
114 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
116 #[stable(feature = "core", since = "1.6.0")]
117 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
119 #[stable(feature = "core", since = "1.6.0")]
120 fn last(&self) -> Option<&Self::Item>;
122 #[stable(feature = "core", since = "1.6.0")]
123 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
124 where I: SliceIndex<Self>;
125 #[stable(feature = "core", since = "1.6.0")]
126 fn as_ptr(&self) -> *const Self::Item;
128 #[stable(feature = "core", since = "1.6.0")]
129 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
130 where Self::Item: Ord;
132 #[stable(feature = "core", since = "1.6.0")]
133 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
134 where F: FnMut(&'a Self::Item) -> Ordering;
136 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
137 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
138 where F: FnMut(&'a Self::Item) -> B,
141 #[stable(feature = "core", since = "1.6.0")]
142 fn len(&self) -> usize;
144 #[stable(feature = "core", since = "1.6.0")]
145 fn is_empty(&self) -> bool { self.len() == 0 }
147 #[stable(feature = "core", since = "1.6.0")]
148 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
149 where I: SliceIndex<Self>;
150 #[stable(feature = "core", since = "1.6.0")]
151 fn iter_mut(&mut self) -> IterMut<Self::Item>;
153 #[stable(feature = "core", since = "1.6.0")]
154 fn first_mut(&mut self) -> Option<&mut Self::Item>;
156 #[stable(feature = "core", since = "1.6.0")]
157 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
159 #[stable(feature = "core", since = "1.6.0")]
160 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
162 #[stable(feature = "core", since = "1.6.0")]
163 fn last_mut(&mut self) -> Option<&mut Self::Item>;
165 #[stable(feature = "core", since = "1.6.0")]
166 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
167 where P: FnMut(&Self::Item) -> bool;
169 #[unstable(feature = "slice_rsplit", issue = "41020")]
170 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
171 where P: FnMut(&Self::Item) -> bool;
173 #[stable(feature = "core", since = "1.6.0")]
174 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
175 where P: FnMut(&Self::Item) -> bool;
177 #[stable(feature = "core", since = "1.6.0")]
178 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
179 where P: FnMut(&Self::Item) -> bool;
181 #[stable(feature = "core", since = "1.6.0")]
182 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
184 #[stable(feature = "core", since = "1.6.0")]
185 fn swap(&mut self, a: usize, b: usize);
187 #[stable(feature = "core", since = "1.6.0")]
188 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
190 #[stable(feature = "core", since = "1.6.0")]
191 fn reverse(&mut self);
193 #[stable(feature = "core", since = "1.6.0")]
194 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
195 where I: SliceIndex<Self>;
196 #[stable(feature = "core", since = "1.6.0")]
197 fn as_mut_ptr(&mut self) -> *mut Self::Item;
199 #[stable(feature = "core", since = "1.6.0")]
200 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
202 #[stable(feature = "core", since = "1.6.0")]
203 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
205 #[stable(feature = "core", since = "1.6.0")]
206 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
208 #[unstable(feature = "slice_rotate", issue = "41891")]
209 fn rotate(&mut self, mid: usize);
211 #[stable(feature = "clone_from_slice", since = "1.7.0")]
212 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
214 #[stable(feature = "copy_from_slice", since = "1.9.0")]
215 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
217 #[unstable(feature = "swap_with_slice", issue = "44030")]
218 fn swap_with_slice(&mut self, src: &mut [Self::Item]);
220 #[stable(feature = "sort_unstable", since = "1.20.0")]
221 fn sort_unstable(&mut self)
222 where Self::Item: Ord;
224 #[stable(feature = "sort_unstable", since = "1.20.0")]
225 fn sort_unstable_by<F>(&mut self, compare: F)
226 where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
228 #[stable(feature = "sort_unstable", since = "1.20.0")]
229 fn sort_unstable_by_key<B, F>(&mut self, f: F)
230 where F: FnMut(&Self::Item) -> B,
234 // Use macros to be generic over const/mut
235 macro_rules! slice_offset {
236 ($ptr:expr, $by:expr) => {{
238 if size_from_ptr(ptr) == 0 {
239 (ptr as *mut i8).wrapping_offset($by) as _
246 // make a &T from a *const T
247 macro_rules! make_ref {
250 if size_from_ptr(ptr) == 0 {
251 // Use a non-null pointer value
259 // make a &mut T from a *mut T
260 macro_rules! make_ref_mut {
263 if size_from_ptr(ptr) == 0 {
264 // Use a non-null pointer value
272 #[unstable(feature = "core_slice_ext",
273 reason = "stable interface provided by `impl [T]` in later crates",
275 impl<T> SliceExt for [T] {
279 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
280 (&self[..mid], &self[mid..])
284 fn iter(&self) -> Iter<T> {
286 let p = if mem::size_of::<T>() == 0 {
289 let p = self.as_ptr();
290 assume(!p.is_null());
296 end: slice_offset!(p, self.len() as isize),
297 _marker: marker::PhantomData
303 fn split<P>(&self, pred: P) -> Split<T, P>
304 where P: FnMut(&T) -> bool
314 fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
315 where P: FnMut(&T) -> bool
317 RSplit { inner: self.split(pred) }
321 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
322 where P: FnMut(&T) -> bool
325 inner: GenericSplitN {
326 iter: self.split(pred),
333 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
334 where P: FnMut(&T) -> bool
337 inner: GenericSplitN {
338 iter: self.rsplit(pred),
345 fn windows(&self, size: usize) -> Windows<T> {
347 Windows { v: self, size: size }
351 fn chunks(&self, chunk_size: usize) -> Chunks<T> {
352 assert!(chunk_size != 0);
353 Chunks { v: self, chunk_size: chunk_size }
357 fn get<I>(&self, index: I) -> Option<&I::Output>
358 where I: SliceIndex<[T]>
364 fn first(&self) -> Option<&T> {
365 if self.is_empty() { None } else { Some(&self[0]) }
369 fn split_first(&self) -> Option<(&T, &[T])> {
370 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
374 fn split_last(&self) -> Option<(&T, &[T])> {
375 let len = self.len();
376 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
380 fn last(&self) -> Option<&T> {
381 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
385 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
386 where I: SliceIndex<[T]>
388 index.get_unchecked(self)
392 fn as_ptr(&self) -> *const T {
393 self as *const [T] as *const T
396 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
397 where F: FnMut(&'a T) -> Ordering
400 let mut size = s.len();
404 let mut base = 0usize;
407 let mid = base + half;
408 // mid is always in [0, size), that means mid is >= 0 and < size.
409 // mid >= 0: by definition
410 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
411 let cmp = f(unsafe { s.get_unchecked(mid) });
412 base = if cmp == Greater { base } else { mid };
415 // base is always in [0, size) because base <= mid.
416 let cmp = f(unsafe { s.get_unchecked(base) });
417 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
421 fn len(&self) -> usize {
423 mem::transmute::<&[T], Repr<T>>(self).len
428 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
429 where I: SliceIndex<[T]>
435 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
436 let len = self.len();
437 let ptr = self.as_mut_ptr();
442 (from_raw_parts_mut(ptr, mid),
443 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
448 fn iter_mut(&mut self) -> IterMut<T> {
450 let p = if mem::size_of::<T>() == 0 {
453 let p = self.as_mut_ptr();
454 assume(!p.is_null());
460 end: slice_offset!(p, self.len() as isize),
461 _marker: marker::PhantomData
467 fn last_mut(&mut self) -> Option<&mut T> {
468 let len = self.len();
469 if len == 0 { return None; }
470 Some(&mut self[len - 1])
474 fn first_mut(&mut self) -> Option<&mut T> {
475 if self.is_empty() { None } else { Some(&mut self[0]) }
479 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
480 if self.is_empty() { None } else {
481 let split = self.split_at_mut(1);
482 Some((&mut split.0[0], split.1))
487 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
488 let len = self.len();
489 if len == 0 { None } else {
490 let split = self.split_at_mut(len - 1);
491 Some((&mut split.1[0], split.0))
496 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
497 where P: FnMut(&T) -> bool
499 SplitMut { v: self, pred: pred, finished: false }
503 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
504 where P: FnMut(&T) -> bool
506 RSplitMut { inner: self.split_mut(pred) }
510 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
511 where P: FnMut(&T) -> bool
514 inner: GenericSplitN {
515 iter: self.split_mut(pred),
522 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
523 P: FnMut(&T) -> bool,
526 inner: GenericSplitN {
527 iter: self.rsplit_mut(pred),
534 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
535 assert!(chunk_size != 0);
536 ChunksMut { v: self, chunk_size: chunk_size }
540 fn swap(&mut self, a: usize, b: usize) {
542 // Can't take two mutable loans from one vector, so instead just cast
543 // them to their raw pointers to do the swap
544 let pa: *mut T = &mut self[a];
545 let pb: *mut T = &mut self[b];
550 fn reverse(&mut self) {
551 let mut i: usize = 0;
554 // For very small types, all the individual reads in the normal
555 // path perform poorly. We can do better, given efficient unaligned
556 // load/store, by loading a larger chunk and reversing a register.
558 // Ideally LLVM would do this for us, as it knows better than we do
559 // whether unaligned reads are efficient (since that changes between
560 // different ARM versions, for example) and what the best chunk size
561 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
562 // the loop, so we need to do this ourselves. (Hypothesis: reverse
563 // is troublesome because the sides can be aligned differently --
564 // will be, when the length is odd -- so there's no way of emitting
565 // pre- and postludes to use fully-aligned SIMD in the middle.)
568 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
570 if fast_unaligned && mem::size_of::<T>() == 1 {
571 // Use the llvm.bswap intrinsic to reverse u8s in a usize
572 let chunk = mem::size_of::<usize>();
573 while i + chunk - 1 < ln / 2 {
575 let pa: *mut T = self.get_unchecked_mut(i);
576 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
577 let va = ptr::read_unaligned(pa as *mut usize);
578 let vb = ptr::read_unaligned(pb as *mut usize);
579 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
580 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
586 if fast_unaligned && mem::size_of::<T>() == 2 {
587 // Use rotate-by-16 to reverse u16s in a u32
588 let chunk = mem::size_of::<u32>() / 2;
589 while i + chunk - 1 < ln / 2 {
591 let pa: *mut T = self.get_unchecked_mut(i);
592 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
593 let va = ptr::read_unaligned(pa as *mut u32);
594 let vb = ptr::read_unaligned(pb as *mut u32);
595 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
596 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
603 // Unsafe swap to avoid the bounds check in safe swap.
605 let pa: *mut T = self.get_unchecked_mut(i);
606 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
614 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
615 where I: SliceIndex<[T]>
617 index.get_unchecked_mut(self)
621 fn as_mut_ptr(&mut self) -> *mut T {
622 self as *mut [T] as *mut T
626 fn contains(&self, x: &T) -> bool where T: PartialEq {
627 x.slice_contains(self)
631 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
632 let n = needle.len();
633 self.len() >= n && needle == &self[..n]
637 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
638 let (m, n) = (self.len(), needle.len());
639 m >= n && needle == &self[m-n..]
642 fn binary_search(&self, x: &T) -> Result<usize, usize>
645 self.binary_search_by(|p| p.cmp(x))
648 fn rotate(&mut self, mid: usize) {
649 assert!(mid <= self.len());
650 let k = self.len() - mid;
653 let p = self.as_mut_ptr();
654 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
659 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
660 assert!(self.len() == src.len(),
661 "destination and source slices have different lengths");
662 // NOTE: We need to explicitly slice them to the same length
663 // for bounds checking to be elided, and the optimizer will
664 // generate memcpy for simple cases (for example T = u8).
665 let len = self.len();
666 let src = &src[..len];
668 self[i].clone_from(&src[i]);
673 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
674 assert!(self.len() == src.len(),
675 "destination and source slices have different lengths");
677 ptr::copy_nonoverlapping(
678 src.as_ptr(), self.as_mut_ptr(), self.len());
683 fn swap_with_slice(&mut self, src: &mut [T]) {
684 assert!(self.len() == src.len(),
685 "destination and source slices have different lengths");
687 ptr::swap_nonoverlapping(
688 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
693 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
694 where F: FnMut(&'a Self::Item) -> B,
697 self.binary_search_by(|k| f(k).cmp(b))
701 fn sort_unstable(&mut self)
702 where Self::Item: Ord
704 sort::quicksort(self, |a, b| a.lt(b));
708 fn sort_unstable_by<F>(&mut self, mut compare: F)
709 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
711 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
715 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
716 where F: FnMut(&Self::Item) -> B,
719 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
723 #[stable(feature = "rust1", since = "1.0.0")]
724 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
725 impl<T, I> ops::Index<I> for [T]
726 where I: SliceIndex<[T]>
728 type Output = I::Output;
731 fn index(&self, index: I) -> &I::Output {
736 #[stable(feature = "rust1", since = "1.0.0")]
737 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
738 impl<T, I> ops::IndexMut<I> for [T]
739 where I: SliceIndex<[T]>
742 fn index_mut(&mut self, index: I) -> &mut I::Output {
743 index.index_mut(self)
749 fn slice_index_len_fail(index: usize, len: usize) -> ! {
750 panic!("index {} out of range for slice of length {}", index, len);
755 fn slice_index_order_fail(index: usize, end: usize) -> ! {
756 panic!("slice index starts at {} but ends at {}", index, end);
759 /// A helper trait used for indexing operations.
760 #[unstable(feature = "slice_get_slice", issue = "35729")]
761 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
762 pub trait SliceIndex<T: ?Sized> {
763 /// The output type returned by methods.
766 /// Returns a shared reference to the output at this location, if in
768 fn get(self, slice: &T) -> Option<&Self::Output>;
770 /// Returns a mutable reference to the output at this location, if in
772 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
774 /// Returns a shared reference to the output at this location, without
775 /// performing any bounds checking.
776 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
778 /// Returns a mutable reference to the output at this location, without
779 /// performing any bounds checking.
780 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
782 /// Returns a shared reference to the output at this location, panicking
783 /// if out of bounds.
784 fn index(self, slice: &T) -> &Self::Output;
786 /// Returns a mutable reference to the output at this location, panicking
787 /// if out of bounds.
788 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
791 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
792 impl<T> SliceIndex<[T]> for usize {
796 fn get(self, slice: &[T]) -> Option<&T> {
797 if self < slice.len() {
799 Some(self.get_unchecked(slice))
807 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
808 if self < slice.len() {
810 Some(self.get_unchecked_mut(slice))
818 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
819 &*slice.as_ptr().offset(self as isize)
823 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
824 &mut *slice.as_mut_ptr().offset(self as isize)
828 fn index(self, slice: &[T]) -> &T {
829 // NB: use intrinsic indexing
834 fn index_mut(self, slice: &mut [T]) -> &mut T {
835 // NB: use intrinsic indexing
840 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
841 impl<T> SliceIndex<[T]> for ops::Range<usize> {
845 fn get(self, slice: &[T]) -> Option<&[T]> {
846 if self.start > self.end || self.end > slice.len() {
850 Some(self.get_unchecked(slice))
856 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
857 if self.start > self.end || self.end > slice.len() {
861 Some(self.get_unchecked_mut(slice))
867 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
868 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
872 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
873 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
877 fn index(self, slice: &[T]) -> &[T] {
878 if self.start > self.end {
879 slice_index_order_fail(self.start, self.end);
880 } else if self.end > slice.len() {
881 slice_index_len_fail(self.end, slice.len());
884 self.get_unchecked(slice)
889 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
890 if self.start > self.end {
891 slice_index_order_fail(self.start, self.end);
892 } else if self.end > slice.len() {
893 slice_index_len_fail(self.end, slice.len());
896 self.get_unchecked_mut(slice)
901 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
902 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
906 fn get(self, slice: &[T]) -> Option<&[T]> {
907 (0..self.end).get(slice)
911 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
912 (0..self.end).get_mut(slice)
916 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
917 (0..self.end).get_unchecked(slice)
921 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
922 (0..self.end).get_unchecked_mut(slice)
926 fn index(self, slice: &[T]) -> &[T] {
927 (0..self.end).index(slice)
931 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
932 (0..self.end).index_mut(slice)
936 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
937 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
941 fn get(self, slice: &[T]) -> Option<&[T]> {
942 (self.start..slice.len()).get(slice)
946 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
947 (self.start..slice.len()).get_mut(slice)
951 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
952 (self.start..slice.len()).get_unchecked(slice)
956 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
957 (self.start..slice.len()).get_unchecked_mut(slice)
961 fn index(self, slice: &[T]) -> &[T] {
962 (self.start..slice.len()).index(slice)
966 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
967 (self.start..slice.len()).index_mut(slice)
971 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
972 impl<T> SliceIndex<[T]> for ops::RangeFull {
976 fn get(self, slice: &[T]) -> Option<&[T]> {
981 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
986 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
991 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
996 fn index(self, slice: &[T]) -> &[T] {
1001 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1007 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1008 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1012 fn get(self, slice: &[T]) -> Option<&[T]> {
1013 if self.end == usize::max_value() { None }
1014 else { (self.start..self.end + 1).get(slice) }
1018 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1019 if self.end == usize::max_value() { None }
1020 else { (self.start..self.end + 1).get_mut(slice) }
1024 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1025 (self.start..self.end + 1).get_unchecked(slice)
1029 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1030 (self.start..self.end + 1).get_unchecked_mut(slice)
1034 fn index(self, slice: &[T]) -> &[T] {
1035 assert!(self.end != usize::max_value(),
1036 "attempted to index slice up to maximum usize");
1037 (self.start..self.end + 1).index(slice)
1041 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1042 assert!(self.end != usize::max_value(),
1043 "attempted to index slice up to maximum usize");
1044 (self.start..self.end + 1).index_mut(slice)
1048 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1049 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1053 fn get(self, slice: &[T]) -> Option<&[T]> {
1054 (0..=self.end).get(slice)
1058 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1059 (0..=self.end).get_mut(slice)
1063 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1064 (0..=self.end).get_unchecked(slice)
1068 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1069 (0..=self.end).get_unchecked_mut(slice)
1073 fn index(self, slice: &[T]) -> &[T] {
1074 (0..=self.end).index(slice)
1078 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1079 (0..=self.end).index_mut(slice)
1083 ////////////////////////////////////////////////////////////////////////////////
1085 ////////////////////////////////////////////////////////////////////////////////
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<'a, T> Default for &'a [T] {
1089 /// Creates an empty slice.
1090 fn default() -> &'a [T] { &[] }
1093 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1094 impl<'a, T> Default for &'a mut [T] {
1095 /// Creates a mutable empty slice.
1096 fn default() -> &'a mut [T] { &mut [] }
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 impl<'a, T> IntoIterator for &'a [T] {
1106 type IntoIter = Iter<'a, T>;
1108 fn into_iter(self) -> Iter<'a, T> {
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 impl<'a, T> IntoIterator for &'a mut [T] {
1115 type Item = &'a mut T;
1116 type IntoIter = IterMut<'a, T>;
1118 fn into_iter(self) -> IterMut<'a, T> {
1124 fn size_from_ptr<T>(_: *const T) -> usize {
1128 // The shared definition of the `Iter` and `IterMut` iterators
1129 macro_rules! iterator {
1130 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 impl<'a, T> Iterator for $name<'a, T> {
1136 fn next(&mut self) -> Option<$elem> {
1137 // could be implemented with slices, but this avoids bounds checks
1139 if mem::size_of::<T>() != 0 {
1140 assume(!self.ptr.is_null());
1141 assume(!self.end.is_null());
1143 if self.ptr == self.end {
1146 Some($mkref!(self.ptr.post_inc()))
1152 fn size_hint(&self) -> (usize, Option<usize>) {
1153 let exact = ptrdistance(self.ptr, self.end);
1154 (exact, Some(exact))
1158 fn count(self) -> usize {
1163 fn nth(&mut self, n: usize) -> Option<$elem> {
1164 // Call helper method. Can't put the definition here because mut versus const.
1169 fn last(mut self) -> Option<$elem> {
1174 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1175 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1177 // manual unrolling is needed when there are conditional exits from the loop
1178 let mut accum = init;
1180 while ptrdistance(self.ptr, self.end) >= 4 {
1181 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1182 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1183 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1184 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1186 while self.ptr != self.end {
1187 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
1194 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
1195 where Fold: FnMut(Acc, Self::Item) -> Acc,
1197 // Let LLVM unroll this, rather than using the default
1198 // impl that would force the manual unrolling above
1199 let mut accum = init;
1200 while let Some(x) = self.next() {
1201 accum = f(accum, x);
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1210 fn next_back(&mut self) -> Option<$elem> {
1211 // could be implemented with slices, but this avoids bounds checks
1213 if mem::size_of::<T>() != 0 {
1214 assume(!self.ptr.is_null());
1215 assume(!self.end.is_null());
1217 if self.end == self.ptr {
1220 Some($mkref!(self.end.pre_dec()))
1226 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
1227 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
1229 // manual unrolling is needed when there are conditional exits from the loop
1230 let mut accum = init;
1232 while ptrdistance(self.ptr, self.end) >= 4 {
1233 accum = f(accum, $mkref!(self.end.pre_dec()))?;
1234 accum = f(accum, $mkref!(self.end.pre_dec()))?;
1235 accum = f(accum, $mkref!(self.end.pre_dec()))?;
1236 accum = f(accum, $mkref!(self.end.pre_dec()))?;
1238 while self.ptr != self.end {
1239 accum = f(accum, $mkref!(self.end.pre_dec()))?;
1246 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
1247 where Fold: FnMut(Acc, Self::Item) -> Acc,
1249 // Let LLVM unroll this, rather than using the default
1250 // impl that would force the manual unrolling above
1251 let mut accum = init;
1252 while let Some(x) = self.next_back() {
1253 accum = f(accum, x);
1261 macro_rules! make_slice {
1262 ($start: expr, $end: expr) => {{
1264 let diff = ($end as usize).wrapping_sub(start as usize);
1265 if size_from_ptr(start) == 0 {
1266 // use a non-null pointer value
1267 unsafe { from_raw_parts(1 as *const _, diff) }
1269 let len = diff / size_from_ptr(start);
1270 unsafe { from_raw_parts(start, len) }
1275 macro_rules! make_mut_slice {
1276 ($start: expr, $end: expr) => {{
1278 let diff = ($end as usize).wrapping_sub(start as usize);
1279 if size_from_ptr(start) == 0 {
1280 // use a non-null pointer value
1281 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1283 let len = diff / size_from_ptr(start);
1284 unsafe { from_raw_parts_mut(start, len) }
1289 /// Immutable slice iterator
1291 /// This struct is created by the [`iter`] method on [slices].
1298 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1299 /// let slice = &[1, 2, 3];
1301 /// // Then, we iterate over it:
1302 /// for element in slice.iter() {
1303 /// println!("{}", element);
1307 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1308 /// [slices]: ../../std/primitive.slice.html
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub struct Iter<'a, T: 'a> {
1313 _marker: marker::PhantomData<&'a T>,
1316 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1317 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1318 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1319 f.debug_tuple("Iter")
1320 .field(&self.as_slice())
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1330 impl<'a, T> Iter<'a, T> {
1331 /// View the underlying data as a subslice of the original data.
1333 /// This has the same lifetime as the original slice, and so the
1334 /// iterator can continue to be used while this exists.
1341 /// // First, we declare a type which has the `iter` method to get the `Iter`
1342 /// // struct (&[usize here]):
1343 /// let slice = &[1, 2, 3];
1345 /// // Then, we get the iterator:
1346 /// let mut iter = slice.iter();
1347 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1348 /// println!("{:?}", iter.as_slice());
1350 /// // Next, we move to the second element of the slice:
1352 /// // Now `as_slice` returns "[2, 3]":
1353 /// println!("{:?}", iter.as_slice());
1355 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1356 pub fn as_slice(&self) -> &'a [T] {
1357 make_slice!(self.ptr, self.end)
1360 // Helper function for Iter::nth
1361 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1362 match self.as_slice().get(n) {
1363 Some(elem_ref) => unsafe {
1364 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1368 self.ptr = self.end;
1375 iterator!{struct Iter -> *const T, &'a T, make_ref}
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1379 fn is_empty(&self) -> bool {
1380 self.ptr == self.end
1384 #[unstable(feature = "fused", issue = "35602")]
1385 impl<'a, T> FusedIterator for Iter<'a, T> {}
1387 #[unstable(feature = "trusted_len", issue = "37572")]
1388 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<'a, T> Clone for Iter<'a, T> {
1392 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1395 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1396 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1397 fn as_ref(&self) -> &[T] {
1402 /// Mutable slice iterator.
1404 /// This struct is created by the [`iter_mut`] method on [slices].
1411 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1412 /// // struct (&[usize here]):
1413 /// let mut slice = &mut [1, 2, 3];
1415 /// // Then, we iterate over it and increment each element value:
1416 /// for element in slice.iter_mut() {
1420 /// // We now have "[2, 3, 4]":
1421 /// println!("{:?}", slice);
1424 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1425 /// [slices]: ../../std/primitive.slice.html
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 pub struct IterMut<'a, T: 'a> {
1430 _marker: marker::PhantomData<&'a mut T>,
1433 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1434 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1436 f.debug_tuple("IterMut")
1437 .field(&make_slice!(self.ptr, self.end))
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1447 impl<'a, T> IterMut<'a, T> {
1448 /// View the underlying data as a subslice of the original data.
1450 /// To avoid creating `&mut` references that alias, this is forced
1451 /// to consume the iterator. Consider using the `Slice` and
1452 /// `SliceMut` implementations for obtaining slices with more
1453 /// restricted lifetimes that do not consume the iterator.
1460 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1461 /// // struct (&[usize here]):
1462 /// let mut slice = &mut [1, 2, 3];
1465 /// // Then, we get the iterator:
1466 /// let mut iter = slice.iter_mut();
1467 /// // We move to next element:
1469 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1470 /// println!("{:?}", iter.into_slice());
1473 /// // Now let's modify a value of the slice:
1475 /// // First we get back the iterator:
1476 /// let mut iter = slice.iter_mut();
1477 /// // We change the value of the first element of the slice returned by the `next` method:
1478 /// *iter.next().unwrap() += 1;
1480 /// // Now slice is "[2, 2, 3]":
1481 /// println!("{:?}", slice);
1483 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1484 pub fn into_slice(self) -> &'a mut [T] {
1485 make_mut_slice!(self.ptr, self.end)
1488 // Helper function for IterMut::nth
1489 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1490 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1491 Some(elem_ref) => unsafe {
1492 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1496 self.ptr = self.end;
1503 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1507 fn is_empty(&self) -> bool {
1508 self.ptr == self.end
1512 #[unstable(feature = "fused", issue = "35602")]
1513 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1515 #[unstable(feature = "trusted_len", issue = "37572")]
1516 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1519 // Return the number of elements of `T` from `start` to `end`.
1520 // Return the arithmetic difference if `T` is zero size.
1522 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1523 match start.offset_to(end) {
1524 Some(x) => x as usize,
1525 None => (end as usize).wrapping_sub(start as usize),
1529 // Extension methods for raw pointers, used by the iterators
1530 trait PointerExt : Copy {
1531 unsafe fn slice_offset(self, i: isize) -> Self;
1533 /// Increments `self` by 1, but returns the old value.
1535 unsafe fn post_inc(&mut self) -> Self {
1536 let current = *self;
1537 *self = self.slice_offset(1);
1541 /// Decrements `self` by 1, and returns the new value.
1543 unsafe fn pre_dec(&mut self) -> Self {
1544 *self = self.slice_offset(-1);
1549 impl<T> PointerExt for *const T {
1551 unsafe fn slice_offset(self, i: isize) -> Self {
1552 slice_offset!(self, i)
1556 impl<T> PointerExt for *mut T {
1558 unsafe fn slice_offset(self, i: isize) -> Self {
1559 slice_offset!(self, i)
1563 /// An internal abstraction over the splitting iterators, so that
1564 /// splitn, splitn_mut etc can be implemented once.
1566 trait SplitIter: DoubleEndedIterator {
1567 /// Marks the underlying iterator as complete, extracting the remaining
1568 /// portion of the slice.
1569 fn finish(&mut self) -> Option<Self::Item>;
1572 /// An iterator over subslices separated by elements that match a predicate
1575 /// This struct is created by the [`split`] method on [slices].
1577 /// [`split`]: ../../std/primitive.slice.html#method.split
1578 /// [slices]: ../../std/primitive.slice.html
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1586 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1587 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1589 f.debug_struct("Split")
1590 .field("v", &self.v)
1591 .field("finished", &self.finished)
1596 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1599 fn clone(&self) -> Split<'a, T, P> {
1602 pred: self.pred.clone(),
1603 finished: self.finished,
1608 #[stable(feature = "rust1", since = "1.0.0")]
1609 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1610 type Item = &'a [T];
1613 fn next(&mut self) -> Option<&'a [T]> {
1614 if self.finished { return None; }
1616 match self.v.iter().position(|x| (self.pred)(x)) {
1617 None => self.finish(),
1619 let ret = Some(&self.v[..idx]);
1620 self.v = &self.v[idx + 1..];
1627 fn size_hint(&self) -> (usize, Option<usize>) {
1631 (1, Some(self.v.len() + 1))
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1639 fn next_back(&mut self) -> Option<&'a [T]> {
1640 if self.finished { return None; }
1642 match self.v.iter().rposition(|x| (self.pred)(x)) {
1643 None => self.finish(),
1645 let ret = Some(&self.v[idx + 1..]);
1646 self.v = &self.v[..idx];
1653 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1655 fn finish(&mut self) -> Option<&'a [T]> {
1656 if self.finished { None } else { self.finished = true; Some(self.v) }
1660 #[unstable(feature = "fused", issue = "35602")]
1661 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1663 /// An iterator over the subslices of the vector which are separated
1664 /// by elements that match `pred`.
1666 /// This struct is created by the [`split_mut`] method on [slices].
1668 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1669 /// [slices]: ../../std/primitive.slice.html
1670 #[stable(feature = "rust1", since = "1.0.0")]
1671 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1677 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1678 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1679 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1680 f.debug_struct("SplitMut")
1681 .field("v", &self.v)
1682 .field("finished", &self.finished)
1687 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1689 fn finish(&mut self) -> Option<&'a mut [T]> {
1693 self.finished = true;
1694 Some(mem::replace(&mut self.v, &mut []))
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1701 type Item = &'a mut [T];
1704 fn next(&mut self) -> Option<&'a mut [T]> {
1705 if self.finished { return None; }
1707 let idx_opt = { // work around borrowck limitations
1708 let pred = &mut self.pred;
1709 self.v.iter().position(|x| (*pred)(x))
1712 None => self.finish(),
1714 let tmp = mem::replace(&mut self.v, &mut []);
1715 let (head, tail) = tmp.split_at_mut(idx);
1716 self.v = &mut tail[1..];
1723 fn size_hint(&self) -> (usize, Option<usize>) {
1727 // if the predicate doesn't match anything, we yield one slice
1728 // if it matches every element, we yield len+1 empty slices.
1729 (1, Some(self.v.len() + 1))
1734 #[stable(feature = "rust1", since = "1.0.0")]
1735 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1736 P: FnMut(&T) -> bool,
1739 fn next_back(&mut self) -> Option<&'a mut [T]> {
1740 if self.finished { return None; }
1742 let idx_opt = { // work around borrowck limitations
1743 let pred = &mut self.pred;
1744 self.v.iter().rposition(|x| (*pred)(x))
1747 None => self.finish(),
1749 let tmp = mem::replace(&mut self.v, &mut []);
1750 let (head, tail) = tmp.split_at_mut(idx);
1752 Some(&mut tail[1..])
1758 #[unstable(feature = "fused", issue = "35602")]
1759 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1761 /// An iterator over subslices separated by elements that match a predicate
1762 /// function, starting from the end of the slice.
1764 /// This struct is created by the [`rsplit`] method on [slices].
1766 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1767 /// [slices]: ../../std/primitive.slice.html
1768 #[unstable(feature = "slice_rsplit", issue = "41020")]
1769 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1770 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1771 inner: Split<'a, T, P>
1774 #[unstable(feature = "slice_rsplit", issue = "41020")]
1775 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1777 f.debug_struct("RSplit")
1778 .field("v", &self.inner.v)
1779 .field("finished", &self.inner.finished)
1784 #[unstable(feature = "slice_rsplit", issue = "41020")]
1785 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1786 type Item = &'a [T];
1789 fn next(&mut self) -> Option<&'a [T]> {
1790 self.inner.next_back()
1794 fn size_hint(&self) -> (usize, Option<usize>) {
1795 self.inner.size_hint()
1799 #[unstable(feature = "slice_rsplit", issue = "41020")]
1800 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1802 fn next_back(&mut self) -> Option<&'a [T]> {
1807 #[unstable(feature = "slice_rsplit", issue = "41020")]
1808 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1810 fn finish(&mut self) -> Option<&'a [T]> {
1815 //#[unstable(feature = "fused", issue = "35602")]
1816 #[unstable(feature = "slice_rsplit", issue = "41020")]
1817 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1819 /// An iterator over the subslices of the vector which are separated
1820 /// by elements that match `pred`, starting from the end of the slice.
1822 /// This struct is created by the [`rsplit_mut`] method on [slices].
1824 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1825 /// [slices]: ../../std/primitive.slice.html
1826 #[unstable(feature = "slice_rsplit", issue = "41020")]
1827 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1828 inner: SplitMut<'a, T, P>
1831 #[unstable(feature = "slice_rsplit", issue = "41020")]
1832 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1834 f.debug_struct("RSplitMut")
1835 .field("v", &self.inner.v)
1836 .field("finished", &self.inner.finished)
1841 #[unstable(feature = "slice_rsplit", issue = "41020")]
1842 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1844 fn finish(&mut self) -> Option<&'a mut [T]> {
1849 #[unstable(feature = "slice_rsplit", issue = "41020")]
1850 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1851 type Item = &'a mut [T];
1854 fn next(&mut self) -> Option<&'a mut [T]> {
1855 self.inner.next_back()
1859 fn size_hint(&self) -> (usize, Option<usize>) {
1860 self.inner.size_hint()
1864 #[unstable(feature = "slice_rsplit", issue = "41020")]
1865 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1866 P: FnMut(&T) -> bool,
1869 fn next_back(&mut self) -> Option<&'a mut [T]> {
1874 //#[unstable(feature = "fused", issue = "35602")]
1875 #[unstable(feature = "slice_rsplit", issue = "41020")]
1876 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1878 /// An private iterator over subslices separated by elements that
1879 /// match a predicate function, splitting at most a fixed number of
1882 struct GenericSplitN<I> {
1887 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1891 fn next(&mut self) -> Option<T> {
1894 1 => { self.count -= 1; self.iter.finish() }
1895 _ => { self.count -= 1; self.iter.next() }
1900 fn size_hint(&self) -> (usize, Option<usize>) {
1901 let (lower, upper_opt) = self.iter.size_hint();
1902 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1906 /// An iterator over subslices separated by elements that match a predicate
1907 /// function, limited to a given number of splits.
1909 /// This struct is created by the [`splitn`] method on [slices].
1911 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1912 /// [slices]: ../../std/primitive.slice.html
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1915 inner: GenericSplitN<Split<'a, T, P>>
1918 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1919 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1921 f.debug_struct("SplitN")
1922 .field("inner", &self.inner)
1927 /// An iterator over subslices separated by elements that match a
1928 /// predicate function, limited to a given number of splits, starting
1929 /// from the end of the slice.
1931 /// This struct is created by the [`rsplitn`] method on [slices].
1933 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1934 /// [slices]: ../../std/primitive.slice.html
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1937 inner: GenericSplitN<RSplit<'a, T, P>>
1940 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1941 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
1942 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1943 f.debug_struct("RSplitN")
1944 .field("inner", &self.inner)
1949 /// An iterator over subslices separated by elements that match a predicate
1950 /// function, limited to a given number of splits.
1952 /// This struct is created by the [`splitn_mut`] method on [slices].
1954 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
1955 /// [slices]: ../../std/primitive.slice.html
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1958 inner: GenericSplitN<SplitMut<'a, T, P>>
1961 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1962 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1963 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1964 f.debug_struct("SplitNMut")
1965 .field("inner", &self.inner)
1970 /// An iterator over subslices separated by elements that match a
1971 /// predicate function, limited to a given number of splits, starting
1972 /// from the end of the slice.
1974 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1976 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
1977 /// [slices]: ../../std/primitive.slice.html
1978 #[stable(feature = "rust1", since = "1.0.0")]
1979 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1980 inner: GenericSplitN<RSplitMut<'a, T, P>>
1983 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1984 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1985 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1986 f.debug_struct("RSplitNMut")
1987 .field("inner", &self.inner)
1992 macro_rules! forward_iterator {
1993 ($name:ident: $elem:ident, $iter_of:ty) => {
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1996 P: FnMut(&T) -> bool
1998 type Item = $iter_of;
2001 fn next(&mut self) -> Option<$iter_of> {
2006 fn size_hint(&self) -> (usize, Option<usize>) {
2007 self.inner.size_hint()
2011 #[unstable(feature = "fused", issue = "35602")]
2012 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2013 where P: FnMut(&T) -> bool {}
2017 forward_iterator! { SplitN: T, &'a [T] }
2018 forward_iterator! { RSplitN: T, &'a [T] }
2019 forward_iterator! { SplitNMut: T, &'a mut [T] }
2020 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2022 /// An iterator over overlapping subslices of length `size`.
2024 /// This struct is created by the [`windows`] method on [slices].
2026 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2027 /// [slices]: ../../std/primitive.slice.html
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 pub struct Windows<'a, T:'a> {
2035 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 impl<'a, T> Clone for Windows<'a, T> {
2038 fn clone(&self) -> Windows<'a, T> {
2046 #[stable(feature = "rust1", since = "1.0.0")]
2047 impl<'a, T> Iterator for Windows<'a, T> {
2048 type Item = &'a [T];
2051 fn next(&mut self) -> Option<&'a [T]> {
2052 if self.size > self.v.len() {
2055 let ret = Some(&self.v[..self.size]);
2056 self.v = &self.v[1..];
2062 fn size_hint(&self) -> (usize, Option<usize>) {
2063 if self.size > self.v.len() {
2066 let size = self.v.len() - self.size + 1;
2072 fn count(self) -> usize {
2077 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2078 let (end, overflow) = self.size.overflowing_add(n);
2079 if end > self.v.len() || overflow {
2083 let nth = &self.v[n..end];
2084 self.v = &self.v[n+1..];
2090 fn last(self) -> Option<Self::Item> {
2091 if self.size > self.v.len() {
2094 let start = self.v.len() - self.size;
2095 Some(&self.v[start..])
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2103 fn next_back(&mut self) -> Option<&'a [T]> {
2104 if self.size > self.v.len() {
2107 let ret = Some(&self.v[self.v.len()-self.size..]);
2108 self.v = &self.v[..self.v.len()-1];
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2117 #[unstable(feature = "fused", issue = "35602")]
2118 impl<'a, T> FusedIterator for Windows<'a, T> {}
2121 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
2122 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
2123 from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
2125 fn may_have_side_effect() -> bool { false }
2128 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
2131 /// When the slice len is not evenly divided by the chunk size, the last slice
2132 /// of the iteration will be the remainder.
2134 /// This struct is created by the [`chunks`] method on [slices].
2136 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2137 /// [slices]: ../../std/primitive.slice.html
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 pub struct Chunks<'a, T:'a> {
2145 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2146 #[stable(feature = "rust1", since = "1.0.0")]
2147 impl<'a, T> Clone for Chunks<'a, T> {
2148 fn clone(&self) -> Chunks<'a, T> {
2151 chunk_size: self.chunk_size,
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<'a, T> Iterator for Chunks<'a, T> {
2158 type Item = &'a [T];
2161 fn next(&mut self) -> Option<&'a [T]> {
2162 if self.v.is_empty() {
2165 let chunksz = cmp::min(self.v.len(), self.chunk_size);
2166 let (fst, snd) = self.v.split_at(chunksz);
2173 fn size_hint(&self) -> (usize, Option<usize>) {
2174 if self.v.is_empty() {
2177 let n = self.v.len() / self.chunk_size;
2178 let rem = self.v.len() % self.chunk_size;
2179 let n = if rem > 0 { n+1 } else { n };
2185 fn count(self) -> usize {
2190 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2191 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2192 if start >= self.v.len() || overflow {
2196 let end = match start.checked_add(self.chunk_size) {
2197 Some(sum) => cmp::min(self.v.len(), sum),
2198 None => self.v.len(),
2200 let nth = &self.v[start..end];
2201 self.v = &self.v[end..];
2207 fn last(self) -> Option<Self::Item> {
2208 if self.v.is_empty() {
2211 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2212 Some(&self.v[start..])
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2220 fn next_back(&mut self) -> Option<&'a [T]> {
2221 if self.v.is_empty() {
2224 let remainder = self.v.len() % self.chunk_size;
2225 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
2226 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2233 #[stable(feature = "rust1", since = "1.0.0")]
2234 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2236 #[unstable(feature = "fused", issue = "35602")]
2237 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2240 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
2241 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
2242 let start = i * self.chunk_size;
2243 let end = match start.checked_add(self.chunk_size) {
2244 None => self.v.len(),
2245 Some(end) => cmp::min(end, self.v.len()),
2247 from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
2249 fn may_have_side_effect() -> bool { false }
2252 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
2253 /// elements at a time). When the slice len is not evenly divided by the chunk
2254 /// size, the last slice of the iteration will be the remainder.
2256 /// This struct is created by the [`chunks_mut`] method on [slices].
2258 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2259 /// [slices]: ../../std/primitive.slice.html
2261 #[stable(feature = "rust1", since = "1.0.0")]
2262 pub struct ChunksMut<'a, T:'a> {
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<'a, T> Iterator for ChunksMut<'a, T> {
2269 type Item = &'a mut [T];
2272 fn next(&mut self) -> Option<&'a mut [T]> {
2273 if self.v.is_empty() {
2276 let sz = cmp::min(self.v.len(), self.chunk_size);
2277 let tmp = mem::replace(&mut self.v, &mut []);
2278 let (head, tail) = tmp.split_at_mut(sz);
2285 fn size_hint(&self) -> (usize, Option<usize>) {
2286 if self.v.is_empty() {
2289 let n = self.v.len() / self.chunk_size;
2290 let rem = self.v.len() % self.chunk_size;
2291 let n = if rem > 0 { n + 1 } else { n };
2297 fn count(self) -> usize {
2302 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2303 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2304 if start >= self.v.len() || overflow {
2308 let end = match start.checked_add(self.chunk_size) {
2309 Some(sum) => cmp::min(self.v.len(), sum),
2310 None => self.v.len(),
2312 let tmp = mem::replace(&mut self.v, &mut []);
2313 let (head, tail) = tmp.split_at_mut(end);
2314 let (_, nth) = head.split_at_mut(start);
2321 fn last(self) -> Option<Self::Item> {
2322 if self.v.is_empty() {
2325 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2326 Some(&mut self.v[start..])
2331 #[stable(feature = "rust1", since = "1.0.0")]
2332 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2334 fn next_back(&mut self) -> Option<&'a mut [T]> {
2335 if self.v.is_empty() {
2338 let remainder = self.v.len() % self.chunk_size;
2339 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2340 let tmp = mem::replace(&mut self.v, &mut []);
2341 let tmp_len = tmp.len();
2342 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2349 #[stable(feature = "rust1", since = "1.0.0")]
2350 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2352 #[unstable(feature = "fused", issue = "35602")]
2353 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2356 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
2357 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
2358 let start = i * self.chunk_size;
2359 let end = match start.checked_add(self.chunk_size) {
2360 None => self.v.len(),
2361 Some(end) => cmp::min(end, self.v.len()),
2363 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
2365 fn may_have_side_effect() -> bool { false }
2372 /// Forms a slice from a pointer and a length.
2374 /// The `len` argument is the number of **elements**, not the number of bytes.
2378 /// This function is unsafe as there is no guarantee that the given pointer is
2379 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2380 /// lifetime for the returned slice.
2382 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2383 /// are required to distinguish between a zero-length slice within `Some()`
2384 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2385 /// for zero-length slices, though.
2389 /// The lifetime for the returned slice is inferred from its usage. To
2390 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2391 /// source lifetime is safe in the context, such as by providing a helper
2392 /// function taking the lifetime of a host value for the slice, or by explicit
2400 /// // manifest a slice out of thin air!
2401 /// let ptr = 0x1234 as *const usize;
2404 /// let slice = slice::from_raw_parts(ptr, amt);
2408 #[stable(feature = "rust1", since = "1.0.0")]
2409 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2410 mem::transmute(Repr { data: p, len: len })
2413 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2414 /// slice is returned.
2416 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2417 /// as not being able to provide a non-aliasing guarantee of the returned
2418 /// mutable slice. `p` must be non-null even for zero-length slices as with
2419 /// `from_raw_parts`.
2421 #[stable(feature = "rust1", since = "1.0.0")]
2422 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2423 mem::transmute(Repr { data: p, len: len })
2426 /// Converts a reference to T into a slice of length 1 (without copying).
2427 #[unstable(feature = "from_ref", issue = "45703")]
2428 pub fn from_ref<T>(s: &T) -> &[T] {
2430 from_raw_parts(s, 1)
2434 /// Converts a reference to T into a slice of length 1 (without copying).
2435 #[unstable(feature = "from_ref", issue = "45703")]
2436 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
2438 from_raw_parts_mut(s, 1)
2442 // This function is public only because there is no other way to unit test heapsort.
2443 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2445 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2446 where F: FnMut(&T, &T) -> bool
2448 sort::heapsort(v, &mut is_less);
2452 // Comparison traits
2456 /// Calls implementation provided memcmp.
2458 /// Interprets the data as u8.
2460 /// Returns 0 for equal, < 0 for less than and > 0 for greater
2462 // FIXME(#32610): Return type should be c_int
2463 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2466 #[stable(feature = "rust1", since = "1.0.0")]
2467 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2468 fn eq(&self, other: &[B]) -> bool {
2469 SlicePartialEq::equal(self, other)
2472 fn ne(&self, other: &[B]) -> bool {
2473 SlicePartialEq::not_equal(self, other)
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<T: Eq> Eq for [T] {}
2480 /// Implements comparison of vectors lexicographically.
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl<T: Ord> Ord for [T] {
2483 fn cmp(&self, other: &[T]) -> Ordering {
2484 SliceOrd::compare(self, other)
2488 /// Implements comparison of vectors lexicographically.
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<T: PartialOrd> PartialOrd for [T] {
2491 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2492 SlicePartialOrd::partial_compare(self, other)
2497 // intermediate trait for specialization of slice's PartialEq
2498 trait SlicePartialEq<B> {
2499 fn equal(&self, other: &[B]) -> bool;
2501 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2504 // Generic slice equality
2505 impl<A, B> SlicePartialEq<B> for [A]
2506 where A: PartialEq<B>
2508 default fn equal(&self, other: &[B]) -> bool {
2509 if self.len() != other.len() {
2513 for i in 0..self.len() {
2514 if !self[i].eq(&other[i]) {
2523 // Use memcmp for bytewise equality when the types allow
2524 impl<A> SlicePartialEq<A> for [A]
2525 where A: PartialEq<A> + BytewiseEquality
2527 fn equal(&self, other: &[A]) -> bool {
2528 if self.len() != other.len() {
2531 if self.as_ptr() == other.as_ptr() {
2535 let size = mem::size_of_val(self);
2536 memcmp(self.as_ptr() as *const u8,
2537 other.as_ptr() as *const u8, size) == 0
2543 // intermediate trait for specialization of slice's PartialOrd
2544 trait SlicePartialOrd<B> {
2545 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2548 impl<A> SlicePartialOrd<A> for [A]
2551 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2552 let l = cmp::min(self.len(), other.len());
2554 // Slice to the loop iteration range to enable bound check
2555 // elimination in the compiler
2556 let lhs = &self[..l];
2557 let rhs = &other[..l];
2560 match lhs[i].partial_cmp(&rhs[i]) {
2561 Some(Ordering::Equal) => (),
2562 non_eq => return non_eq,
2566 self.len().partial_cmp(&other.len())
2570 impl<A> SlicePartialOrd<A> for [A]
2573 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2574 Some(SliceOrd::compare(self, other))
2579 // intermediate trait for specialization of slice's Ord
2581 fn compare(&self, other: &[B]) -> Ordering;
2584 impl<A> SliceOrd<A> for [A]
2587 default fn compare(&self, other: &[A]) -> Ordering {
2588 let l = cmp::min(self.len(), other.len());
2590 // Slice to the loop iteration range to enable bound check
2591 // elimination in the compiler
2592 let lhs = &self[..l];
2593 let rhs = &other[..l];
2596 match lhs[i].cmp(&rhs[i]) {
2597 Ordering::Equal => (),
2598 non_eq => return non_eq,
2602 self.len().cmp(&other.len())
2606 // memcmp compares a sequence of unsigned bytes lexicographically.
2607 // this matches the order we want for [u8], but no others (not even [i8]).
2608 impl SliceOrd<u8> for [u8] {
2610 fn compare(&self, other: &[u8]) -> Ordering {
2611 let order = unsafe {
2612 memcmp(self.as_ptr(), other.as_ptr(),
2613 cmp::min(self.len(), other.len()))
2616 self.len().cmp(&other.len())
2617 } else if order < 0 {
2626 /// Trait implemented for types that can be compared for equality using
2627 /// their bytewise representation
2628 trait BytewiseEquality { }
2630 macro_rules! impl_marker_for {
2631 ($traitname:ident, $($ty:ty)*) => {
2633 impl $traitname for $ty { }
2638 impl_marker_for!(BytewiseEquality,
2639 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2642 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2643 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2644 &*self.ptr.offset(i as isize)
2646 fn may_have_side_effect() -> bool { false }
2650 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2651 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2652 &mut *self.ptr.offset(i as isize)
2654 fn may_have_side_effect() -> bool { false }
2657 trait SliceContains: Sized {
2658 fn slice_contains(&self, x: &[Self]) -> bool;
2661 impl<T> SliceContains for T where T: PartialEq {
2662 default fn slice_contains(&self, x: &[Self]) -> bool {
2663 x.iter().any(|y| *y == *self)
2667 impl SliceContains for u8 {
2668 fn slice_contains(&self, x: &[Self]) -> bool {
2669 memchr::memchr(*self, x).is_some()
2673 impl SliceContains for i8 {
2674 fn slice_contains(&self, x: &[Self]) -> bool {
2675 let byte = *self as u8;
2676 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
2677 memchr::memchr(byte, bytes).is_some()