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;
67 /// Extension methods for slices.
68 #[unstable(feature = "core_slice_ext",
69 reason = "stable interface provided by `impl [T]` in later crates",
71 #[allow(missing_docs)] // documented elsewhere
75 #[stable(feature = "core", since = "1.6.0")]
76 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
78 #[stable(feature = "core", since = "1.6.0")]
79 fn iter(&self) -> Iter<Self::Item>;
81 #[stable(feature = "core", since = "1.6.0")]
82 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
83 where P: FnMut(&Self::Item) -> bool;
85 #[unstable(feature = "slice_rsplit", issue = "41020")]
86 fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
87 where P: FnMut(&Self::Item) -> bool;
89 #[stable(feature = "core", since = "1.6.0")]
90 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
91 where P: FnMut(&Self::Item) -> bool;
93 #[stable(feature = "core", since = "1.6.0")]
94 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
95 where P: FnMut(&Self::Item) -> bool;
97 #[stable(feature = "core", since = "1.6.0")]
98 fn windows(&self, size: usize) -> Windows<Self::Item>;
100 #[stable(feature = "core", since = "1.6.0")]
101 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
103 #[stable(feature = "core", since = "1.6.0")]
104 fn get<I>(&self, index: I) -> Option<&I::Output>
105 where I: SliceIndex<Self>;
106 #[stable(feature = "core", since = "1.6.0")]
107 fn first(&self) -> Option<&Self::Item>;
109 #[stable(feature = "core", since = "1.6.0")]
110 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
112 #[stable(feature = "core", since = "1.6.0")]
113 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
115 #[stable(feature = "core", since = "1.6.0")]
116 fn last(&self) -> Option<&Self::Item>;
118 #[stable(feature = "core", since = "1.6.0")]
119 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
120 where I: SliceIndex<Self>;
121 #[stable(feature = "core", since = "1.6.0")]
122 fn as_ptr(&self) -> *const Self::Item;
124 #[stable(feature = "core", since = "1.6.0")]
125 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
126 where Self::Item: Borrow<Q>,
129 #[stable(feature = "core", since = "1.6.0")]
130 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
131 where F: FnMut(&'a Self::Item) -> Ordering;
133 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
134 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result<usize, usize>
135 where F: FnMut(&'a Self::Item) -> B,
139 #[stable(feature = "core", since = "1.6.0")]
140 fn len(&self) -> usize;
142 #[stable(feature = "core", since = "1.6.0")]
143 fn is_empty(&self) -> bool { self.len() == 0 }
145 #[stable(feature = "core", since = "1.6.0")]
146 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
147 where I: SliceIndex<Self>;
148 #[stable(feature = "core", since = "1.6.0")]
149 fn iter_mut(&mut self) -> IterMut<Self::Item>;
151 #[stable(feature = "core", since = "1.6.0")]
152 fn first_mut(&mut self) -> Option<&mut Self::Item>;
154 #[stable(feature = "core", since = "1.6.0")]
155 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
157 #[stable(feature = "core", since = "1.6.0")]
158 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
160 #[stable(feature = "core", since = "1.6.0")]
161 fn last_mut(&mut self) -> Option<&mut Self::Item>;
163 #[stable(feature = "core", since = "1.6.0")]
164 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
165 where P: FnMut(&Self::Item) -> bool;
167 #[unstable(feature = "slice_rsplit", issue = "41020")]
168 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
169 where P: FnMut(&Self::Item) -> bool;
171 #[stable(feature = "core", since = "1.6.0")]
172 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
173 where P: FnMut(&Self::Item) -> bool;
175 #[stable(feature = "core", since = "1.6.0")]
176 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
177 where P: FnMut(&Self::Item) -> bool;
179 #[stable(feature = "core", since = "1.6.0")]
180 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
182 #[stable(feature = "core", since = "1.6.0")]
183 fn swap(&mut self, a: usize, b: usize);
185 #[stable(feature = "core", since = "1.6.0")]
186 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
188 #[stable(feature = "core", since = "1.6.0")]
189 fn reverse(&mut self);
191 #[stable(feature = "core", since = "1.6.0")]
192 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
193 where I: SliceIndex<Self>;
194 #[stable(feature = "core", since = "1.6.0")]
195 fn as_mut_ptr(&mut self) -> *mut Self::Item;
197 #[stable(feature = "core", since = "1.6.0")]
198 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
200 #[stable(feature = "core", since = "1.6.0")]
201 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
203 #[stable(feature = "core", since = "1.6.0")]
204 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
206 #[unstable(feature = "slice_rotate", issue = "41891")]
207 fn rotate(&mut self, mid: usize);
209 #[stable(feature = "clone_from_slice", since = "1.7.0")]
210 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
212 #[stable(feature = "copy_from_slice", since = "1.9.0")]
213 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
215 #[unstable(feature = "swap_with_slice", issue = "44030")]
216 fn swap_with_slice(&mut self, src: &mut [Self::Item]);
218 #[stable(feature = "sort_unstable", since = "1.20.0")]
219 fn sort_unstable(&mut self)
220 where Self::Item: Ord;
222 #[stable(feature = "sort_unstable", since = "1.20.0")]
223 fn sort_unstable_by<F>(&mut self, compare: F)
224 where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
226 #[stable(feature = "sort_unstable", since = "1.20.0")]
227 fn sort_unstable_by_key<B, F>(&mut self, f: F)
228 where F: FnMut(&Self::Item) -> B,
232 // Use macros to be generic over const/mut
233 macro_rules! slice_offset {
234 ($ptr:expr, $by:expr) => {{
236 if size_from_ptr(ptr) == 0 {
237 (ptr as *mut i8).wrapping_offset($by) as _
244 // make a &T from a *const T
245 macro_rules! make_ref {
248 if size_from_ptr(ptr) == 0 {
249 // Use a non-null pointer value
257 // make a &mut T from a *mut T
258 macro_rules! make_ref_mut {
261 if size_from_ptr(ptr) == 0 {
262 // Use a non-null pointer value
270 #[unstable(feature = "core_slice_ext",
271 reason = "stable interface provided by `impl [T]` in later crates",
273 impl<T> SliceExt for [T] {
277 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
278 (&self[..mid], &self[mid..])
282 fn iter(&self) -> Iter<T> {
284 let p = if mem::size_of::<T>() == 0 {
287 let p = self.as_ptr();
288 assume(!p.is_null());
294 end: slice_offset!(p, self.len() as isize),
295 _marker: marker::PhantomData
301 fn split<P>(&self, pred: P) -> Split<T, P>
302 where P: FnMut(&T) -> bool
312 fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
313 where P: FnMut(&T) -> bool
315 RSplit { inner: self.split(pred) }
319 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
320 where P: FnMut(&T) -> bool
323 inner: GenericSplitN {
324 iter: self.split(pred),
331 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
332 where P: FnMut(&T) -> bool
335 inner: GenericSplitN {
336 iter: self.rsplit(pred),
343 fn windows(&self, size: usize) -> Windows<T> {
345 Windows { v: self, size: size }
349 fn chunks(&self, size: usize) -> Chunks<T> {
351 Chunks { v: self, size: size }
355 fn get<I>(&self, index: I) -> Option<&I::Output>
356 where I: SliceIndex<[T]>
362 fn first(&self) -> Option<&T> {
363 if self.is_empty() { None } else { Some(&self[0]) }
367 fn split_first(&self) -> Option<(&T, &[T])> {
368 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
372 fn split_last(&self) -> Option<(&T, &[T])> {
373 let len = self.len();
374 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
378 fn last(&self) -> Option<&T> {
379 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
383 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
384 where I: SliceIndex<[T]>
386 index.get_unchecked(self)
390 fn as_ptr(&self) -> *const T {
391 self as *const [T] as *const T
394 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
395 where F: FnMut(&'a T) -> Ordering
397 let mut base = 0usize;
401 let (head, tail) = s.split_at(s.len() >> 1);
407 base += head.len() + 1;
411 Equal => return Ok(base + head.len()),
417 fn len(&self) -> usize {
419 mem::transmute::<&[T], Repr<T>>(self).len
424 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
425 where I: SliceIndex<[T]>
431 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
432 let len = self.len();
433 let ptr = self.as_mut_ptr();
438 (from_raw_parts_mut(ptr, mid),
439 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
444 fn iter_mut(&mut self) -> IterMut<T> {
446 let p = if mem::size_of::<T>() == 0 {
449 let p = self.as_mut_ptr();
450 assume(!p.is_null());
456 end: slice_offset!(p, self.len() as isize),
457 _marker: marker::PhantomData
463 fn last_mut(&mut self) -> Option<&mut T> {
464 let len = self.len();
465 if len == 0 { return None; }
466 Some(&mut self[len - 1])
470 fn first_mut(&mut self) -> Option<&mut T> {
471 if self.is_empty() { None } else { Some(&mut self[0]) }
475 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
476 if self.is_empty() { None } else {
477 let split = self.split_at_mut(1);
478 Some((&mut split.0[0], split.1))
483 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
484 let len = self.len();
485 if len == 0 { None } else {
486 let split = self.split_at_mut(len - 1);
487 Some((&mut split.1[0], split.0))
492 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
493 where P: FnMut(&T) -> bool
495 SplitMut { v: self, pred: pred, finished: false }
499 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
500 where P: FnMut(&T) -> bool
502 RSplitMut { inner: self.split_mut(pred) }
506 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
507 where P: FnMut(&T) -> bool
510 inner: GenericSplitN {
511 iter: self.split_mut(pred),
518 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
519 P: FnMut(&T) -> bool,
522 inner: GenericSplitN {
523 iter: self.rsplit_mut(pred),
530 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
531 assert!(chunk_size > 0);
532 ChunksMut { v: self, chunk_size: chunk_size }
536 fn swap(&mut self, a: usize, b: usize) {
538 // Can't take two mutable loans from one vector, so instead just cast
539 // them to their raw pointers to do the swap
540 let pa: *mut T = &mut self[a];
541 let pb: *mut T = &mut self[b];
546 fn reverse(&mut self) {
547 let mut i: usize = 0;
550 // For very small types, all the individual reads in the normal
551 // path perform poorly. We can do better, given efficient unaligned
552 // load/store, by loading a larger chunk and reversing a register.
554 // Ideally LLVM would do this for us, as it knows better than we do
555 // whether unaligned reads are efficient (since that changes between
556 // different ARM versions, for example) and what the best chunk size
557 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
558 // the loop, so we need to do this ourselves. (Hypothesis: reverse
559 // is troublesome because the sides can be aligned differently --
560 // will be, when the length is odd -- so there's no way of emitting
561 // pre- and postludes to use fully-aligned SIMD in the middle.)
564 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
566 if fast_unaligned && mem::size_of::<T>() == 1 {
567 // Use the llvm.bswap intrinsic to reverse u8s in a usize
568 let chunk = mem::size_of::<usize>();
569 while i + chunk - 1 < ln / 2 {
571 let pa: *mut T = self.get_unchecked_mut(i);
572 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
573 let va = ptr::read_unaligned(pa as *mut usize);
574 let vb = ptr::read_unaligned(pb as *mut usize);
575 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
576 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
582 if fast_unaligned && mem::size_of::<T>() == 2 {
583 // Use rotate-by-16 to reverse u16s in a u32
584 let chunk = mem::size_of::<u32>() / 2;
585 while i + chunk - 1 < ln / 2 {
587 let pa: *mut T = self.get_unchecked_mut(i);
588 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
589 let va = ptr::read_unaligned(pa as *mut u32);
590 let vb = ptr::read_unaligned(pb as *mut u32);
591 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
592 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
599 // Unsafe swap to avoid the bounds check in safe swap.
601 let pa: *mut T = self.get_unchecked_mut(i);
602 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
610 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
611 where I: SliceIndex<[T]>
613 index.get_unchecked_mut(self)
617 fn as_mut_ptr(&mut self) -> *mut T {
618 self as *mut [T] as *mut T
622 fn contains(&self, x: &T) -> bool where T: PartialEq {
623 self.iter().any(|elt| *x == *elt)
627 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
628 let n = needle.len();
629 self.len() >= n && needle == &self[..n]
633 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
634 let (m, n) = (self.len(), needle.len());
635 m >= n && needle == &self[m-n..]
638 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
642 self.binary_search_by(|p| p.borrow().cmp(x))
645 fn rotate(&mut self, mid: usize) {
646 assert!(mid <= self.len());
647 let k = self.len() - mid;
650 let p = self.as_mut_ptr();
651 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
656 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
657 assert!(self.len() == src.len(),
658 "destination and source slices have different lengths");
659 // NOTE: We need to explicitly slice them to the same length
660 // for bounds checking to be elided, and the optimizer will
661 // generate memcpy for simple cases (for example T = u8).
662 let len = self.len();
663 let src = &src[..len];
665 self[i].clone_from(&src[i]);
670 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
671 assert!(self.len() == src.len(),
672 "destination and source slices have different lengths");
674 ptr::copy_nonoverlapping(
675 src.as_ptr(), self.as_mut_ptr(), self.len());
680 fn swap_with_slice(&mut self, src: &mut [T]) {
681 assert!(self.len() == src.len(),
682 "destination and source slices have different lengths");
684 ptr::swap_nonoverlapping(
685 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
690 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
691 where F: FnMut(&'a Self::Item) -> B,
695 self.binary_search_by(|k| f(k).borrow().cmp(b))
699 fn sort_unstable(&mut self)
700 where Self::Item: Ord
702 sort::quicksort(self, |a, b| a.lt(b));
706 fn sort_unstable_by<F>(&mut self, mut compare: F)
707 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
709 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
713 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
714 where F: FnMut(&Self::Item) -> B,
717 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
721 #[stable(feature = "rust1", since = "1.0.0")]
722 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
723 impl<T, I> ops::Index<I> for [T]
724 where I: SliceIndex<[T]>
726 type Output = I::Output;
729 fn index(&self, index: I) -> &I::Output {
734 #[stable(feature = "rust1", since = "1.0.0")]
735 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
736 impl<T, I> ops::IndexMut<I> for [T]
737 where I: SliceIndex<[T]>
740 fn index_mut(&mut self, index: I) -> &mut I::Output {
741 index.index_mut(self)
747 fn slice_index_len_fail(index: usize, len: usize) -> ! {
748 panic!("index {} out of range for slice of length {}", index, len);
753 fn slice_index_order_fail(index: usize, end: usize) -> ! {
754 panic!("slice index starts at {} but ends at {}", index, end);
757 /// A helper trait used for indexing operations.
758 #[unstable(feature = "slice_get_slice", issue = "35729")]
759 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
760 pub trait SliceIndex<T: ?Sized> {
761 /// The output type returned by methods.
764 /// Returns a shared reference to the output at this location, if in
766 fn get(self, slice: &T) -> Option<&Self::Output>;
768 /// Returns a mutable reference to the output at this location, if in
770 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
772 /// Returns a shared reference to the output at this location, without
773 /// performing any bounds checking.
774 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
776 /// Returns a mutable reference to the output at this location, without
777 /// performing any bounds checking.
778 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
780 /// Returns a shared reference to the output at this location, panicking
781 /// if out of bounds.
782 fn index(self, slice: &T) -> &Self::Output;
784 /// Returns a mutable reference to the output at this location, panicking
785 /// if out of bounds.
786 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
789 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
790 impl<T> SliceIndex<[T]> for usize {
794 fn get(self, slice: &[T]) -> Option<&T> {
795 if self < slice.len() {
797 Some(self.get_unchecked(slice))
805 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
806 if self < slice.len() {
808 Some(self.get_unchecked_mut(slice))
816 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
817 &*slice.as_ptr().offset(self as isize)
821 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
822 &mut *slice.as_mut_ptr().offset(self as isize)
826 fn index(self, slice: &[T]) -> &T {
827 // NB: use intrinsic indexing
832 fn index_mut(self, slice: &mut [T]) -> &mut T {
833 // NB: use intrinsic indexing
838 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
839 impl<T> SliceIndex<[T]> for ops::Range<usize> {
843 fn get(self, slice: &[T]) -> Option<&[T]> {
844 if self.start > self.end || self.end > slice.len() {
848 Some(self.get_unchecked(slice))
854 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
855 if self.start > self.end || self.end > slice.len() {
859 Some(self.get_unchecked_mut(slice))
865 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
866 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
870 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
871 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
875 fn index(self, slice: &[T]) -> &[T] {
876 if self.start > self.end {
877 slice_index_order_fail(self.start, self.end);
878 } else if self.end > slice.len() {
879 slice_index_len_fail(self.end, slice.len());
882 self.get_unchecked(slice)
887 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
888 if self.start > self.end {
889 slice_index_order_fail(self.start, self.end);
890 } else if self.end > slice.len() {
891 slice_index_len_fail(self.end, slice.len());
894 self.get_unchecked_mut(slice)
899 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
900 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
904 fn get(self, slice: &[T]) -> Option<&[T]> {
905 (0..self.end).get(slice)
909 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
910 (0..self.end).get_mut(slice)
914 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
915 (0..self.end).get_unchecked(slice)
919 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
920 (0..self.end).get_unchecked_mut(slice)
924 fn index(self, slice: &[T]) -> &[T] {
925 (0..self.end).index(slice)
929 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
930 (0..self.end).index_mut(slice)
934 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
935 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
939 fn get(self, slice: &[T]) -> Option<&[T]> {
940 (self.start..slice.len()).get(slice)
944 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
945 (self.start..slice.len()).get_mut(slice)
949 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
950 (self.start..slice.len()).get_unchecked(slice)
954 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
955 (self.start..slice.len()).get_unchecked_mut(slice)
959 fn index(self, slice: &[T]) -> &[T] {
960 (self.start..slice.len()).index(slice)
964 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
965 (self.start..slice.len()).index_mut(slice)
969 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
970 impl<T> SliceIndex<[T]> for ops::RangeFull {
974 fn get(self, slice: &[T]) -> Option<&[T]> {
979 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
984 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
989 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
994 fn index(self, slice: &[T]) -> &[T] {
999 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1005 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1006 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1010 fn get(self, slice: &[T]) -> Option<&[T]> {
1011 if self.end == usize::max_value() { None }
1012 else { (self.start..self.end + 1).get(slice) }
1016 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1017 if self.end == usize::max_value() { None }
1018 else { (self.start..self.end + 1).get_mut(slice) }
1022 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1023 (self.start..self.end + 1).get_unchecked(slice)
1027 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1028 (self.start..self.end + 1).get_unchecked_mut(slice)
1032 fn index(self, slice: &[T]) -> &[T] {
1033 assert!(self.end != usize::max_value(),
1034 "attempted to index slice up to maximum usize");
1035 (self.start..self.end + 1).index(slice)
1039 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1040 assert!(self.end != usize::max_value(),
1041 "attempted to index slice up to maximum usize");
1042 (self.start..self.end + 1).index_mut(slice)
1046 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1047 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1051 fn get(self, slice: &[T]) -> Option<&[T]> {
1052 (0...self.end).get(slice)
1056 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1057 (0...self.end).get_mut(slice)
1061 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1062 (0...self.end).get_unchecked(slice)
1066 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1067 (0...self.end).get_unchecked_mut(slice)
1071 fn index(self, slice: &[T]) -> &[T] {
1072 (0...self.end).index(slice)
1076 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1077 (0...self.end).index_mut(slice)
1081 ////////////////////////////////////////////////////////////////////////////////
1083 ////////////////////////////////////////////////////////////////////////////////
1085 #[stable(feature = "rust1", since = "1.0.0")]
1086 impl<'a, T> Default for &'a [T] {
1087 /// Creates an empty slice.
1088 fn default() -> &'a [T] { &[] }
1091 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1092 impl<'a, T> Default for &'a mut [T] {
1093 /// Creates a mutable empty slice.
1094 fn default() -> &'a mut [T] { &mut [] }
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<'a, T> IntoIterator for &'a [T] {
1104 type IntoIter = Iter<'a, T>;
1106 fn into_iter(self) -> Iter<'a, T> {
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<'a, T> IntoIterator for &'a mut [T] {
1113 type Item = &'a mut T;
1114 type IntoIter = IterMut<'a, T>;
1116 fn into_iter(self) -> IterMut<'a, T> {
1122 fn size_from_ptr<T>(_: *const T) -> usize {
1126 // The shared definition of the `Iter` and `IterMut` iterators
1127 macro_rules! iterator {
1128 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<'a, T> Iterator for $name<'a, T> {
1134 fn next(&mut self) -> Option<$elem> {
1135 // could be implemented with slices, but this avoids bounds checks
1137 if mem::size_of::<T>() != 0 {
1138 assume(!self.ptr.is_null());
1139 assume(!self.end.is_null());
1141 if self.ptr == self.end {
1144 Some($mkref!(self.ptr.post_inc()))
1150 fn size_hint(&self) -> (usize, Option<usize>) {
1151 let exact = ptrdistance(self.ptr, self.end);
1152 (exact, Some(exact))
1156 fn count(self) -> usize {
1161 fn nth(&mut self, n: usize) -> Option<$elem> {
1162 // Call helper method. Can't put the definition here because mut versus const.
1167 fn last(mut self) -> Option<$elem> {
1171 fn all<F>(&mut self, mut predicate: F) -> bool
1172 where F: FnMut(Self::Item) -> bool,
1174 self.search_while(true, move |elt| {
1176 SearchWhile::Continue
1178 SearchWhile::Done(false)
1183 fn any<F>(&mut self, mut predicate: F) -> bool
1184 where F: FnMut(Self::Item) -> bool,
1186 !self.all(move |elt| !predicate(elt))
1189 fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1190 where F: FnMut(&Self::Item) -> bool,
1192 self.search_while(None, move |elt| {
1193 if predicate(&elt) {
1194 SearchWhile::Done(Some(elt))
1196 SearchWhile::Continue
1201 fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1202 where F: FnMut(Self::Item) -> bool,
1205 self.search_while(None, move |elt| {
1207 SearchWhile::Done(Some(index))
1210 SearchWhile::Continue
1215 fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1216 where F: FnMut(Self::Item) -> bool,
1218 let mut index = self.len();
1219 self.rsearch_while(None, move |elt| {
1222 SearchWhile::Done(Some(index))
1224 SearchWhile::Continue
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1233 fn next_back(&mut self) -> Option<$elem> {
1234 // could be implemented with slices, but this avoids bounds checks
1236 if mem::size_of::<T>() != 0 {
1237 assume(!self.ptr.is_null());
1238 assume(!self.end.is_null());
1240 if self.end == self.ptr {
1243 Some($mkref!(self.end.pre_dec()))
1248 fn rfind<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1249 where F: FnMut(&Self::Item) -> bool,
1251 self.rsearch_while(None, move |elt| {
1252 if predicate(&elt) {
1253 SearchWhile::Done(Some(elt))
1255 SearchWhile::Continue
1262 // search_while is a generalization of the internal iteration methods.
1263 impl<'a, T> $name<'a, T> {
1264 // search through the iterator's element using the closure `g`.
1265 // if no element was found, return `default`.
1266 fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1268 G: FnMut($elem) -> SearchWhile<Acc>
1270 // manual unrolling is needed when there are conditional exits from the loop
1272 while ptrdistance(self.ptr, self.end) >= 4 {
1273 search_while!(g($mkref!(self.ptr.post_inc())));
1274 search_while!(g($mkref!(self.ptr.post_inc())));
1275 search_while!(g($mkref!(self.ptr.post_inc())));
1276 search_while!(g($mkref!(self.ptr.post_inc())));
1278 while self.ptr != self.end {
1279 search_while!(g($mkref!(self.ptr.post_inc())));
1285 fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1287 G: FnMut($elem) -> SearchWhile<Acc>
1290 while ptrdistance(self.ptr, self.end) >= 4 {
1291 search_while!(g($mkref!(self.end.pre_dec())));
1292 search_while!(g($mkref!(self.end.pre_dec())));
1293 search_while!(g($mkref!(self.end.pre_dec())));
1294 search_while!(g($mkref!(self.end.pre_dec())));
1296 while self.ptr != self.end {
1297 search_while!(g($mkref!(self.end.pre_dec())));
1306 macro_rules! make_slice {
1307 ($start: expr, $end: expr) => {{
1309 let diff = ($end as usize).wrapping_sub(start as usize);
1310 if size_from_ptr(start) == 0 {
1311 // use a non-null pointer value
1312 unsafe { from_raw_parts(1 as *const _, diff) }
1314 let len = diff / size_from_ptr(start);
1315 unsafe { from_raw_parts(start, len) }
1320 macro_rules! make_mut_slice {
1321 ($start: expr, $end: expr) => {{
1323 let diff = ($end as usize).wrapping_sub(start as usize);
1324 if size_from_ptr(start) == 0 {
1325 // use a non-null pointer value
1326 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1328 let len = diff / size_from_ptr(start);
1329 unsafe { from_raw_parts_mut(start, len) }
1334 // An enum used for controlling the execution of `.search_while()`.
1335 enum SearchWhile<T> {
1336 // Continue searching
1338 // Fold is complete and will return this value
1342 // helper macro for search while's control flow
1343 macro_rules! search_while {
1346 SearchWhile::Continue => { }
1347 SearchWhile::Done(done) => return done,
1352 /// Immutable slice iterator
1354 /// This struct is created by the [`iter`] method on [slices].
1361 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1362 /// let slice = &[1, 2, 3];
1364 /// // Then, we iterate over it:
1365 /// for element in slice.iter() {
1366 /// println!("{}", element);
1370 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1371 /// [slices]: ../../std/primitive.slice.html
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 pub struct Iter<'a, T: 'a> {
1376 _marker: marker::PhantomData<&'a T>,
1379 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1380 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1382 f.debug_tuple("Iter")
1383 .field(&self.as_slice())
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1393 impl<'a, T> Iter<'a, T> {
1394 /// View the underlying data as a subslice of the original data.
1396 /// This has the same lifetime as the original slice, and so the
1397 /// iterator can continue to be used while this exists.
1404 /// // First, we declare a type which has the `iter` method to get the `Iter`
1405 /// // struct (&[usize here]):
1406 /// let slice = &[1, 2, 3];
1408 /// // Then, we get the iterator:
1409 /// let mut iter = slice.iter();
1410 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1411 /// println!("{:?}", iter.as_slice());
1413 /// // Next, we move to the second element of the slice:
1415 /// // Now `as_slice` returns "[2, 3]":
1416 /// println!("{:?}", iter.as_slice());
1418 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1419 pub fn as_slice(&self) -> &'a [T] {
1420 make_slice!(self.ptr, self.end)
1423 // Helper function for Iter::nth
1424 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1425 match self.as_slice().get(n) {
1426 Some(elem_ref) => unsafe {
1427 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1431 self.ptr = self.end;
1438 iterator!{struct Iter -> *const T, &'a T, make_ref}
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1442 fn is_empty(&self) -> bool {
1443 self.ptr == self.end
1447 #[unstable(feature = "fused", issue = "35602")]
1448 impl<'a, T> FusedIterator for Iter<'a, T> {}
1450 #[unstable(feature = "trusted_len", issue = "37572")]
1451 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<'a, T> Clone for Iter<'a, T> {
1455 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1458 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1459 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1460 fn as_ref(&self) -> &[T] {
1465 /// Mutable slice iterator.
1467 /// This struct is created by the [`iter_mut`] method on [slices].
1474 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1475 /// // struct (&[usize here]):
1476 /// let mut slice = &mut [1, 2, 3];
1478 /// // Then, we iterate over it and increment each element value:
1479 /// for element in slice.iter_mut() {
1483 /// // We now have "[2, 3, 4]":
1484 /// println!("{:?}", slice);
1487 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1488 /// [slices]: ../../std/primitive.slice.html
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 pub struct IterMut<'a, T: 'a> {
1493 _marker: marker::PhantomData<&'a mut T>,
1496 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1497 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1499 f.debug_tuple("IterMut")
1500 .field(&make_slice!(self.ptr, self.end))
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1507 #[stable(feature = "rust1", since = "1.0.0")]
1508 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1510 impl<'a, T> IterMut<'a, T> {
1511 /// View the underlying data as a subslice of the original data.
1513 /// To avoid creating `&mut` references that alias, this is forced
1514 /// to consume the iterator. Consider using the `Slice` and
1515 /// `SliceMut` implementations for obtaining slices with more
1516 /// restricted lifetimes that do not consume the iterator.
1523 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1524 /// // struct (&[usize here]):
1525 /// let mut slice = &mut [1, 2, 3];
1528 /// // Then, we get the iterator:
1529 /// let mut iter = slice.iter_mut();
1530 /// // We move to next element:
1532 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1533 /// println!("{:?}", iter.into_slice());
1536 /// // Now let's modify a value of the slice:
1538 /// // First we get back the iterator:
1539 /// let mut iter = slice.iter_mut();
1540 /// // We change the value of the first element of the slice returned by the `next` method:
1541 /// *iter.next().unwrap() += 1;
1543 /// // Now slice is "[2, 2, 3]":
1544 /// println!("{:?}", slice);
1546 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1547 pub fn into_slice(self) -> &'a mut [T] {
1548 make_mut_slice!(self.ptr, self.end)
1551 // Helper function for IterMut::nth
1552 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1553 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1554 Some(elem_ref) => unsafe {
1555 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1559 self.ptr = self.end;
1566 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1570 fn is_empty(&self) -> bool {
1571 self.ptr == self.end
1575 #[unstable(feature = "fused", issue = "35602")]
1576 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1578 #[unstable(feature = "trusted_len", issue = "37572")]
1579 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1582 // Return the number of elements of `T` from `start` to `end`.
1583 // Return the arithmetic difference if `T` is zero size.
1585 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1586 match start.offset_to(end) {
1587 Some(x) => x as usize,
1588 None => (end as usize).wrapping_sub(start as usize),
1592 // Extension methods for raw pointers, used by the iterators
1593 trait PointerExt : Copy {
1594 unsafe fn slice_offset(self, i: isize) -> Self;
1596 /// Increments `self` by 1, but returns the old value.
1598 unsafe fn post_inc(&mut self) -> Self {
1599 let current = *self;
1600 *self = self.slice_offset(1);
1604 /// Decrements `self` by 1, and returns the new value.
1606 unsafe fn pre_dec(&mut self) -> Self {
1607 *self = self.slice_offset(-1);
1612 impl<T> PointerExt for *const T {
1614 unsafe fn slice_offset(self, i: isize) -> Self {
1615 slice_offset!(self, i)
1619 impl<T> PointerExt for *mut T {
1621 unsafe fn slice_offset(self, i: isize) -> Self {
1622 slice_offset!(self, i)
1626 /// An internal abstraction over the splitting iterators, so that
1627 /// splitn, splitn_mut etc can be implemented once.
1629 trait SplitIter: DoubleEndedIterator {
1630 /// Marks the underlying iterator as complete, extracting the remaining
1631 /// portion of the slice.
1632 fn finish(&mut self) -> Option<Self::Item>;
1635 /// An iterator over subslices separated by elements that match a predicate
1638 /// This struct is created by the [`split`] method on [slices].
1640 /// [`split`]: ../../std/primitive.slice.html#method.split
1641 /// [slices]: ../../std/primitive.slice.html
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1649 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1650 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1651 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1652 f.debug_struct("Split")
1653 .field("v", &self.v)
1654 .field("finished", &self.finished)
1659 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1662 fn clone(&self) -> Split<'a, T, P> {
1665 pred: self.pred.clone(),
1666 finished: self.finished,
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1673 type Item = &'a [T];
1676 fn next(&mut self) -> Option<&'a [T]> {
1677 if self.finished { return None; }
1679 match self.v.iter().position(|x| (self.pred)(x)) {
1680 None => self.finish(),
1682 let ret = Some(&self.v[..idx]);
1683 self.v = &self.v[idx + 1..];
1690 fn size_hint(&self) -> (usize, Option<usize>) {
1694 (1, Some(self.v.len() + 1))
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1702 fn next_back(&mut self) -> Option<&'a [T]> {
1703 if self.finished { return None; }
1705 match self.v.iter().rposition(|x| (self.pred)(x)) {
1706 None => self.finish(),
1708 let ret = Some(&self.v[idx + 1..]);
1709 self.v = &self.v[..idx];
1716 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1718 fn finish(&mut self) -> Option<&'a [T]> {
1719 if self.finished { None } else { self.finished = true; Some(self.v) }
1723 #[unstable(feature = "fused", issue = "35602")]
1724 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1726 /// An iterator over the subslices of the vector which are separated
1727 /// by elements that match `pred`.
1729 /// This struct is created by the [`split_mut`] method on [slices].
1731 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1732 /// [slices]: ../../std/primitive.slice.html
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1740 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1741 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1743 f.debug_struct("SplitMut")
1744 .field("v", &self.v)
1745 .field("finished", &self.finished)
1750 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1752 fn finish(&mut self) -> Option<&'a mut [T]> {
1756 self.finished = true;
1757 Some(mem::replace(&mut self.v, &mut []))
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1764 type Item = &'a mut [T];
1767 fn next(&mut self) -> Option<&'a mut [T]> {
1768 if self.finished { return None; }
1770 let idx_opt = { // work around borrowck limitations
1771 let pred = &mut self.pred;
1772 self.v.iter().position(|x| (*pred)(x))
1775 None => self.finish(),
1777 let tmp = mem::replace(&mut self.v, &mut []);
1778 let (head, tail) = tmp.split_at_mut(idx);
1779 self.v = &mut tail[1..];
1786 fn size_hint(&self) -> (usize, Option<usize>) {
1790 // if the predicate doesn't match anything, we yield one slice
1791 // if it matches every element, we yield len+1 empty slices.
1792 (1, Some(self.v.len() + 1))
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1799 P: FnMut(&T) -> bool,
1802 fn next_back(&mut self) -> Option<&'a mut [T]> {
1803 if self.finished { return None; }
1805 let idx_opt = { // work around borrowck limitations
1806 let pred = &mut self.pred;
1807 self.v.iter().rposition(|x| (*pred)(x))
1810 None => self.finish(),
1812 let tmp = mem::replace(&mut self.v, &mut []);
1813 let (head, tail) = tmp.split_at_mut(idx);
1815 Some(&mut tail[1..])
1821 #[unstable(feature = "fused", issue = "35602")]
1822 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1824 /// An iterator over subslices separated by elements that match a predicate
1825 /// function, starting from the end of the slice.
1827 /// This struct is created by the [`rsplit`] method on [slices].
1829 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1830 /// [slices]: ../../std/primitive.slice.html
1831 #[unstable(feature = "slice_rsplit", issue = "41020")]
1832 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1833 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1834 inner: Split<'a, T, P>
1837 #[unstable(feature = "slice_rsplit", issue = "41020")]
1838 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1840 f.debug_struct("RSplit")
1841 .field("v", &self.inner.v)
1842 .field("finished", &self.inner.finished)
1847 #[unstable(feature = "slice_rsplit", issue = "41020")]
1848 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1849 type Item = &'a [T];
1852 fn next(&mut self) -> Option<&'a [T]> {
1853 self.inner.next_back()
1857 fn size_hint(&self) -> (usize, Option<usize>) {
1858 self.inner.size_hint()
1862 #[unstable(feature = "slice_rsplit", issue = "41020")]
1863 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1865 fn next_back(&mut self) -> Option<&'a [T]> {
1870 #[unstable(feature = "slice_rsplit", issue = "41020")]
1871 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1873 fn finish(&mut self) -> Option<&'a [T]> {
1878 //#[unstable(feature = "fused", issue = "35602")]
1879 #[unstable(feature = "slice_rsplit", issue = "41020")]
1880 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1882 /// An iterator over the subslices of the vector which are separated
1883 /// by elements that match `pred`, starting from the end of the slice.
1885 /// This struct is created by the [`rsplit_mut`] method on [slices].
1887 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1888 /// [slices]: ../../std/primitive.slice.html
1889 #[unstable(feature = "slice_rsplit", issue = "41020")]
1890 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1891 inner: SplitMut<'a, T, P>
1894 #[unstable(feature = "slice_rsplit", issue = "41020")]
1895 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1896 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1897 f.debug_struct("RSplitMut")
1898 .field("v", &self.inner.v)
1899 .field("finished", &self.inner.finished)
1904 #[unstable(feature = "slice_rsplit", issue = "41020")]
1905 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1907 fn finish(&mut self) -> Option<&'a mut [T]> {
1912 #[unstable(feature = "slice_rsplit", issue = "41020")]
1913 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1914 type Item = &'a mut [T];
1917 fn next(&mut self) -> Option<&'a mut [T]> {
1918 self.inner.next_back()
1922 fn size_hint(&self) -> (usize, Option<usize>) {
1923 self.inner.size_hint()
1927 #[unstable(feature = "slice_rsplit", issue = "41020")]
1928 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1929 P: FnMut(&T) -> bool,
1932 fn next_back(&mut self) -> Option<&'a mut [T]> {
1937 //#[unstable(feature = "fused", issue = "35602")]
1938 #[unstable(feature = "slice_rsplit", issue = "41020")]
1939 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1941 /// An private iterator over subslices separated by elements that
1942 /// match a predicate function, splitting at most a fixed number of
1945 struct GenericSplitN<I> {
1950 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1954 fn next(&mut self) -> Option<T> {
1957 1 => { self.count -= 1; self.iter.finish() }
1958 _ => { self.count -= 1; self.iter.next() }
1963 fn size_hint(&self) -> (usize, Option<usize>) {
1964 let (lower, upper_opt) = self.iter.size_hint();
1965 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1969 /// An iterator over subslices separated by elements that match a predicate
1970 /// function, limited to a given number of splits.
1972 /// This struct is created by the [`splitn`] method on [slices].
1974 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1975 /// [slices]: ../../std/primitive.slice.html
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1978 inner: GenericSplitN<Split<'a, T, P>>
1981 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1982 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1983 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1984 f.debug_struct("SplitN")
1985 .field("inner", &self.inner)
1990 /// An iterator over subslices separated by elements that match a
1991 /// predicate function, limited to a given number of splits, starting
1992 /// from the end of the slice.
1994 /// This struct is created by the [`rsplitn`] method on [slices].
1996 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1997 /// [slices]: ../../std/primitive.slice.html
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2000 inner: GenericSplitN<RSplit<'a, T, P>>
2003 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2004 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
2005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2006 f.debug_struct("RSplitN")
2007 .field("inner", &self.inner)
2012 /// An iterator over subslices separated by elements that match a predicate
2013 /// function, limited to a given number of splits.
2015 /// This struct is created by the [`splitn_mut`] method on [slices].
2017 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
2018 /// [slices]: ../../std/primitive.slice.html
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2021 inner: GenericSplitN<SplitMut<'a, T, P>>
2024 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2025 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2026 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2027 f.debug_struct("SplitNMut")
2028 .field("inner", &self.inner)
2033 /// An iterator over subslices separated by elements that match a
2034 /// predicate function, limited to a given number of splits, starting
2035 /// from the end of the slice.
2037 /// This struct is created by the [`rsplitn_mut`] method on [slices].
2039 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
2040 /// [slices]: ../../std/primitive.slice.html
2041 #[stable(feature = "rust1", since = "1.0.0")]
2042 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2043 inner: GenericSplitN<RSplitMut<'a, T, P>>
2046 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2047 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2048 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2049 f.debug_struct("RSplitNMut")
2050 .field("inner", &self.inner)
2055 macro_rules! forward_iterator {
2056 ($name:ident: $elem:ident, $iter_of:ty) => {
2057 #[stable(feature = "rust1", since = "1.0.0")]
2058 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
2059 P: FnMut(&T) -> bool
2061 type Item = $iter_of;
2064 fn next(&mut self) -> Option<$iter_of> {
2069 fn size_hint(&self) -> (usize, Option<usize>) {
2070 self.inner.size_hint()
2074 #[unstable(feature = "fused", issue = "35602")]
2075 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2076 where P: FnMut(&T) -> bool {}
2080 forward_iterator! { SplitN: T, &'a [T] }
2081 forward_iterator! { RSplitN: T, &'a [T] }
2082 forward_iterator! { SplitNMut: T, &'a mut [T] }
2083 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2085 /// An iterator over overlapping subslices of length `size`.
2087 /// This struct is created by the [`windows`] method on [slices].
2089 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2090 /// [slices]: ../../std/primitive.slice.html
2092 #[stable(feature = "rust1", since = "1.0.0")]
2093 pub struct Windows<'a, T:'a> {
2098 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2099 #[stable(feature = "rust1", since = "1.0.0")]
2100 impl<'a, T> Clone for Windows<'a, T> {
2101 fn clone(&self) -> Windows<'a, T> {
2109 #[stable(feature = "rust1", since = "1.0.0")]
2110 impl<'a, T> Iterator for Windows<'a, T> {
2111 type Item = &'a [T];
2114 fn next(&mut self) -> Option<&'a [T]> {
2115 if self.size > self.v.len() {
2118 let ret = Some(&self.v[..self.size]);
2119 self.v = &self.v[1..];
2125 fn size_hint(&self) -> (usize, Option<usize>) {
2126 if self.size > self.v.len() {
2129 let size = self.v.len() - self.size + 1;
2135 fn count(self) -> usize {
2140 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2141 let (end, overflow) = self.size.overflowing_add(n);
2142 if end > self.v.len() || overflow {
2146 let nth = &self.v[n..end];
2147 self.v = &self.v[n+1..];
2153 fn last(self) -> Option<Self::Item> {
2154 if self.size > self.v.len() {
2157 let start = self.v.len() - self.size;
2158 Some(&self.v[start..])
2163 #[stable(feature = "rust1", since = "1.0.0")]
2164 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2166 fn next_back(&mut self) -> Option<&'a [T]> {
2167 if self.size > self.v.len() {
2170 let ret = Some(&self.v[self.v.len()-self.size..]);
2171 self.v = &self.v[..self.v.len()-1];
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2180 #[unstable(feature = "fused", issue = "35602")]
2181 impl<'a, T> FusedIterator for Windows<'a, T> {}
2183 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
2186 /// When the slice len is not evenly divided by the chunk size, the last slice
2187 /// of the iteration will be the remainder.
2189 /// This struct is created by the [`chunks`] method on [slices].
2191 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2192 /// [slices]: ../../std/primitive.slice.html
2194 #[stable(feature = "rust1", since = "1.0.0")]
2195 pub struct Chunks<'a, T:'a> {
2200 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 impl<'a, T> Clone for Chunks<'a, T> {
2203 fn clone(&self) -> Chunks<'a, T> {
2211 #[stable(feature = "rust1", since = "1.0.0")]
2212 impl<'a, T> Iterator for Chunks<'a, T> {
2213 type Item = &'a [T];
2216 fn next(&mut self) -> Option<&'a [T]> {
2217 if self.v.is_empty() {
2220 let chunksz = cmp::min(self.v.len(), self.size);
2221 let (fst, snd) = self.v.split_at(chunksz);
2228 fn size_hint(&self) -> (usize, Option<usize>) {
2229 if self.v.is_empty() {
2232 let n = self.v.len() / self.size;
2233 let rem = self.v.len() % self.size;
2234 let n = if rem > 0 { n+1 } else { n };
2240 fn count(self) -> usize {
2245 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2246 let (start, overflow) = n.overflowing_mul(self.size);
2247 if start >= self.v.len() || overflow {
2251 let end = match start.checked_add(self.size) {
2252 Some(sum) => cmp::min(self.v.len(), sum),
2253 None => self.v.len(),
2255 let nth = &self.v[start..end];
2256 self.v = &self.v[end..];
2262 fn last(self) -> Option<Self::Item> {
2263 if self.v.is_empty() {
2266 let start = (self.v.len() - 1) / self.size * self.size;
2267 Some(&self.v[start..])
2272 #[stable(feature = "rust1", since = "1.0.0")]
2273 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2275 fn next_back(&mut self) -> Option<&'a [T]> {
2276 if self.v.is_empty() {
2279 let remainder = self.v.len() % self.size;
2280 let chunksz = if remainder != 0 { remainder } else { self.size };
2281 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2288 #[stable(feature = "rust1", since = "1.0.0")]
2289 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2291 #[unstable(feature = "fused", issue = "35602")]
2292 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2294 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2295 /// elements at a time). When the slice len is not evenly divided by the chunk
2296 /// size, the last slice of the iteration will be the remainder.
2298 /// This struct is created by the [`chunks_mut`] method on [slices].
2300 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2301 /// [slices]: ../../std/primitive.slice.html
2303 #[stable(feature = "rust1", since = "1.0.0")]
2304 pub struct ChunksMut<'a, T:'a> {
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 impl<'a, T> Iterator for ChunksMut<'a, T> {
2311 type Item = &'a mut [T];
2314 fn next(&mut self) -> Option<&'a mut [T]> {
2315 if self.v.is_empty() {
2318 let sz = cmp::min(self.v.len(), self.chunk_size);
2319 let tmp = mem::replace(&mut self.v, &mut []);
2320 let (head, tail) = tmp.split_at_mut(sz);
2327 fn size_hint(&self) -> (usize, Option<usize>) {
2328 if self.v.is_empty() {
2331 let n = self.v.len() / self.chunk_size;
2332 let rem = self.v.len() % self.chunk_size;
2333 let n = if rem > 0 { n + 1 } else { n };
2339 fn count(self) -> usize {
2344 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2345 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2346 if start >= self.v.len() || overflow {
2350 let end = match start.checked_add(self.chunk_size) {
2351 Some(sum) => cmp::min(self.v.len(), sum),
2352 None => self.v.len(),
2354 let tmp = mem::replace(&mut self.v, &mut []);
2355 let (head, tail) = tmp.split_at_mut(end);
2356 let (_, nth) = head.split_at_mut(start);
2363 fn last(self) -> Option<Self::Item> {
2364 if self.v.is_empty() {
2367 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2368 Some(&mut self.v[start..])
2373 #[stable(feature = "rust1", since = "1.0.0")]
2374 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2376 fn next_back(&mut self) -> Option<&'a mut [T]> {
2377 if self.v.is_empty() {
2380 let remainder = self.v.len() % self.chunk_size;
2381 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2382 let tmp = mem::replace(&mut self.v, &mut []);
2383 let tmp_len = tmp.len();
2384 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2391 #[stable(feature = "rust1", since = "1.0.0")]
2392 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2394 #[unstable(feature = "fused", issue = "35602")]
2395 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2401 /// Forms a slice from a pointer and a length.
2403 /// The `len` argument is the number of **elements**, not the number of bytes.
2407 /// This function is unsafe as there is no guarantee that the given pointer is
2408 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2409 /// lifetime for the returned slice.
2411 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2412 /// are required to distinguish between a zero-length slice within `Some()`
2413 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2414 /// for zero-length slices, though.
2418 /// The lifetime for the returned slice is inferred from its usage. To
2419 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2420 /// source lifetime is safe in the context, such as by providing a helper
2421 /// function taking the lifetime of a host value for the slice, or by explicit
2429 /// // manifest a slice out of thin air!
2430 /// let ptr = 0x1234 as *const usize;
2433 /// let slice = slice::from_raw_parts(ptr, amt);
2437 #[stable(feature = "rust1", since = "1.0.0")]
2438 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2439 mem::transmute(Repr { data: p, len: len })
2442 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2443 /// slice is returned.
2445 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2446 /// as not being able to provide a non-aliasing guarantee of the returned
2447 /// mutable slice. `p` must be non-null even for zero-length slices as with
2448 /// `from_raw_parts`.
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2452 mem::transmute(Repr { data: p, len: len })
2455 // This function is public only because there is no other way to unit test heapsort.
2456 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2458 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2459 where F: FnMut(&T, &T) -> bool
2461 sort::heapsort(v, &mut is_less);
2465 // Comparison traits
2469 /// Calls implementation provided memcmp.
2471 /// Interprets the data as u8.
2473 /// Returns 0 for equal, < 0 for less than and > 0 for greater
2475 // FIXME(#32610): Return type should be c_int
2476 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2479 #[stable(feature = "rust1", since = "1.0.0")]
2480 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2481 fn eq(&self, other: &[B]) -> bool {
2482 SlicePartialEq::equal(self, other)
2485 fn ne(&self, other: &[B]) -> bool {
2486 SlicePartialEq::not_equal(self, other)
2490 #[stable(feature = "rust1", since = "1.0.0")]
2491 impl<T: Eq> Eq for [T] {}
2493 /// Implements comparison of vectors lexicographically.
2494 #[stable(feature = "rust1", since = "1.0.0")]
2495 impl<T: Ord> Ord for [T] {
2496 fn cmp(&self, other: &[T]) -> Ordering {
2497 SliceOrd::compare(self, other)
2501 /// Implements comparison of vectors lexicographically.
2502 #[stable(feature = "rust1", since = "1.0.0")]
2503 impl<T: PartialOrd> PartialOrd for [T] {
2504 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2505 SlicePartialOrd::partial_compare(self, other)
2510 // intermediate trait for specialization of slice's PartialEq
2511 trait SlicePartialEq<B> {
2512 fn equal(&self, other: &[B]) -> bool;
2514 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2517 // Generic slice equality
2518 impl<A, B> SlicePartialEq<B> for [A]
2519 where A: PartialEq<B>
2521 default fn equal(&self, other: &[B]) -> bool {
2522 if self.len() != other.len() {
2526 for i in 0..self.len() {
2527 if !self[i].eq(&other[i]) {
2536 // Use memcmp for bytewise equality when the types allow
2537 impl<A> SlicePartialEq<A> for [A]
2538 where A: PartialEq<A> + BytewiseEquality
2540 fn equal(&self, other: &[A]) -> bool {
2541 if self.len() != other.len() {
2544 if self.as_ptr() == other.as_ptr() {
2548 let size = mem::size_of_val(self);
2549 memcmp(self.as_ptr() as *const u8,
2550 other.as_ptr() as *const u8, size) == 0
2556 // intermediate trait for specialization of slice's PartialOrd
2557 trait SlicePartialOrd<B> {
2558 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2561 impl<A> SlicePartialOrd<A> for [A]
2564 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2565 let l = cmp::min(self.len(), other.len());
2567 // Slice to the loop iteration range to enable bound check
2568 // elimination in the compiler
2569 let lhs = &self[..l];
2570 let rhs = &other[..l];
2573 match lhs[i].partial_cmp(&rhs[i]) {
2574 Some(Ordering::Equal) => (),
2575 non_eq => return non_eq,
2579 self.len().partial_cmp(&other.len())
2583 impl<A> SlicePartialOrd<A> for [A]
2586 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2587 Some(SliceOrd::compare(self, other))
2592 // intermediate trait for specialization of slice's Ord
2594 fn compare(&self, other: &[B]) -> Ordering;
2597 impl<A> SliceOrd<A> for [A]
2600 default fn compare(&self, other: &[A]) -> Ordering {
2601 let l = cmp::min(self.len(), other.len());
2603 // Slice to the loop iteration range to enable bound check
2604 // elimination in the compiler
2605 let lhs = &self[..l];
2606 let rhs = &other[..l];
2609 match lhs[i].cmp(&rhs[i]) {
2610 Ordering::Equal => (),
2611 non_eq => return non_eq,
2615 self.len().cmp(&other.len())
2619 // memcmp compares a sequence of unsigned bytes lexicographically.
2620 // this matches the order we want for [u8], but no others (not even [i8]).
2621 impl SliceOrd<u8> for [u8] {
2623 fn compare(&self, other: &[u8]) -> Ordering {
2624 let order = unsafe {
2625 memcmp(self.as_ptr(), other.as_ptr(),
2626 cmp::min(self.len(), other.len()))
2629 self.len().cmp(&other.len())
2630 } else if order < 0 {
2639 /// Trait implemented for types that can be compared for equality using
2640 /// their bytewise representation
2641 trait BytewiseEquality { }
2643 macro_rules! impl_marker_for {
2644 ($traitname:ident, $($ty:ty)*) => {
2646 impl $traitname for $ty { }
2651 impl_marker_for!(BytewiseEquality,
2652 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2655 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2656 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2657 &*self.ptr.offset(i as isize)
2659 fn may_have_side_effect() -> bool { false }
2663 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2664 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2665 &mut *self.ptr.offset(i as isize)
2667 fn may_have_side_effect() -> bool { false }