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 // FIXME: after next stage0, change RangeInclusive { ... } back to ..=
20 use ops::RangeInclusive;
22 // How this module is organized.
24 // The library infrastructure for slices is fairly messy. There's
25 // a lot of stuff defined here. Let's keep it clean.
27 // Since slices don't support inherent methods; all operations
28 // on them are defined on traits, which are then reexported from
29 // the prelude for convenience. So there are a lot of traits here.
31 // The layout of this file is thus:
33 // * Slice-specific 'extension' traits and their implementations. This
34 // is where most of the slice API resides.
35 // * Implementations of a few common traits with important slice ops.
36 // * Definitions of a bunch of iterators.
38 // * The `raw` and `bytes` submodules.
39 // * Boilerplate trait implementations.
41 use cmp::Ordering::{self, Less, Equal, Greater};
44 use intrinsics::assume;
46 use ops::{FnMut, self};
48 use option::Option::{None, Some};
50 use result::Result::{Ok, Err};
53 use marker::{Copy, Send, Sync, Sized, self};
54 use iter_private::TrustedRandomAccess;
69 /// Extension methods for slices.
70 #[unstable(feature = "core_slice_ext",
71 reason = "stable interface provided by `impl [T]` in later crates",
73 #[allow(missing_docs)] // documented elsewhere
77 #[stable(feature = "core", since = "1.6.0")]
78 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
80 #[stable(feature = "core", since = "1.6.0")]
81 fn iter(&self) -> Iter<Self::Item>;
83 #[stable(feature = "core", since = "1.6.0")]
84 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
85 where P: FnMut(&Self::Item) -> bool;
87 #[unstable(feature = "slice_rsplit", issue = "41020")]
88 fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
89 where P: FnMut(&Self::Item) -> bool;
91 #[stable(feature = "core", since = "1.6.0")]
92 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
93 where P: FnMut(&Self::Item) -> bool;
95 #[stable(feature = "core", since = "1.6.0")]
96 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
97 where P: FnMut(&Self::Item) -> bool;
99 #[stable(feature = "core", since = "1.6.0")]
100 fn windows(&self, size: usize) -> Windows<Self::Item>;
102 #[stable(feature = "core", since = "1.6.0")]
103 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
105 #[stable(feature = "core", since = "1.6.0")]
106 fn get<I>(&self, index: I) -> Option<&I::Output>
107 where I: SliceIndex<Self>;
108 #[stable(feature = "core", since = "1.6.0")]
109 fn first(&self) -> Option<&Self::Item>;
111 #[stable(feature = "core", since = "1.6.0")]
112 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
114 #[stable(feature = "core", since = "1.6.0")]
115 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
117 #[stable(feature = "core", since = "1.6.0")]
118 fn last(&self) -> Option<&Self::Item>;
120 #[stable(feature = "core", since = "1.6.0")]
121 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
122 where I: SliceIndex<Self>;
123 #[stable(feature = "core", since = "1.6.0")]
124 fn as_ptr(&self) -> *const Self::Item;
126 #[stable(feature = "core", since = "1.6.0")]
127 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
128 where Self::Item: Ord;
130 #[stable(feature = "core", since = "1.6.0")]
131 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
132 where F: FnMut(&'a Self::Item) -> Ordering;
134 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
135 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
136 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(&self, x: &T) -> Result<usize, usize>
641 self.binary_search_by(|p| p.cmp(x))
644 fn rotate(&mut self, mid: usize) {
645 assert!(mid <= self.len());
646 let k = self.len() - mid;
649 let p = self.as_mut_ptr();
650 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
655 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
656 assert!(self.len() == src.len(),
657 "destination and source slices have different lengths");
658 // NOTE: We need to explicitly slice them to the same length
659 // for bounds checking to be elided, and the optimizer will
660 // generate memcpy for simple cases (for example T = u8).
661 let len = self.len();
662 let src = &src[..len];
664 self[i].clone_from(&src[i]);
669 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
670 assert!(self.len() == src.len(),
671 "destination and source slices have different lengths");
673 ptr::copy_nonoverlapping(
674 src.as_ptr(), self.as_mut_ptr(), self.len());
679 fn swap_with_slice(&mut self, src: &mut [T]) {
680 assert!(self.len() == src.len(),
681 "destination and source slices have different lengths");
683 ptr::swap_nonoverlapping(
684 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
689 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
690 where F: FnMut(&'a Self::Item) -> B,
693 self.binary_search_by(|k| f(k).cmp(b))
697 fn sort_unstable(&mut self)
698 where Self::Item: Ord
700 sort::quicksort(self, |a, b| a.lt(b));
704 fn sort_unstable_by<F>(&mut self, mut compare: F)
705 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
707 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
711 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
712 where F: FnMut(&Self::Item) -> B,
715 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
719 #[stable(feature = "rust1", since = "1.0.0")]
720 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
721 impl<T, I> ops::Index<I> for [T]
722 where I: SliceIndex<[T]>
724 type Output = I::Output;
727 fn index(&self, index: I) -> &I::Output {
732 #[stable(feature = "rust1", since = "1.0.0")]
733 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
734 impl<T, I> ops::IndexMut<I> for [T]
735 where I: SliceIndex<[T]>
738 fn index_mut(&mut self, index: I) -> &mut I::Output {
739 index.index_mut(self)
745 fn slice_index_len_fail(index: usize, len: usize) -> ! {
746 panic!("index {} out of range for slice of length {}", index, len);
751 fn slice_index_order_fail(index: usize, end: usize) -> ! {
752 panic!("slice index starts at {} but ends at {}", index, end);
755 /// A helper trait used for indexing operations.
756 #[unstable(feature = "slice_get_slice", issue = "35729")]
757 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
758 pub trait SliceIndex<T: ?Sized> {
759 /// The output type returned by methods.
762 /// Returns a shared reference to the output at this location, if in
764 fn get(self, slice: &T) -> Option<&Self::Output>;
766 /// Returns a mutable reference to the output at this location, if in
768 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
770 /// Returns a shared reference to the output at this location, without
771 /// performing any bounds checking.
772 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
774 /// Returns a mutable reference to the output at this location, without
775 /// performing any bounds checking.
776 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
778 /// Returns a shared reference to the output at this location, panicking
779 /// if out of bounds.
780 fn index(self, slice: &T) -> &Self::Output;
782 /// Returns a mutable reference to the output at this location, panicking
783 /// if out of bounds.
784 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
787 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
788 impl<T> SliceIndex<[T]> for usize {
792 fn get(self, slice: &[T]) -> Option<&T> {
793 if self < slice.len() {
795 Some(self.get_unchecked(slice))
803 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
804 if self < slice.len() {
806 Some(self.get_unchecked_mut(slice))
814 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
815 &*slice.as_ptr().offset(self as isize)
819 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
820 &mut *slice.as_mut_ptr().offset(self as isize)
824 fn index(self, slice: &[T]) -> &T {
825 // NB: use intrinsic indexing
830 fn index_mut(self, slice: &mut [T]) -> &mut T {
831 // NB: use intrinsic indexing
836 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
837 impl<T> SliceIndex<[T]> for ops::Range<usize> {
841 fn get(self, slice: &[T]) -> Option<&[T]> {
842 if self.start > self.end || self.end > slice.len() {
846 Some(self.get_unchecked(slice))
852 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
853 if self.start > self.end || self.end > slice.len() {
857 Some(self.get_unchecked_mut(slice))
863 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
864 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
868 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
869 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
873 fn index(self, slice: &[T]) -> &[T] {
874 if self.start > self.end {
875 slice_index_order_fail(self.start, self.end);
876 } else if self.end > slice.len() {
877 slice_index_len_fail(self.end, slice.len());
880 self.get_unchecked(slice)
885 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
886 if self.start > self.end {
887 slice_index_order_fail(self.start, self.end);
888 } else if self.end > slice.len() {
889 slice_index_len_fail(self.end, slice.len());
892 self.get_unchecked_mut(slice)
897 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
898 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
902 fn get(self, slice: &[T]) -> Option<&[T]> {
903 (0..self.end).get(slice)
907 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
908 (0..self.end).get_mut(slice)
912 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
913 (0..self.end).get_unchecked(slice)
917 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
918 (0..self.end).get_unchecked_mut(slice)
922 fn index(self, slice: &[T]) -> &[T] {
923 (0..self.end).index(slice)
927 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
928 (0..self.end).index_mut(slice)
932 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
933 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
937 fn get(self, slice: &[T]) -> Option<&[T]> {
938 (self.start..slice.len()).get(slice)
942 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
943 (self.start..slice.len()).get_mut(slice)
947 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
948 (self.start..slice.len()).get_unchecked(slice)
952 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
953 (self.start..slice.len()).get_unchecked_mut(slice)
957 fn index(self, slice: &[T]) -> &[T] {
958 (self.start..slice.len()).index(slice)
962 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
963 (self.start..slice.len()).index_mut(slice)
967 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
968 impl<T> SliceIndex<[T]> for ops::RangeFull {
972 fn get(self, slice: &[T]) -> Option<&[T]> {
977 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
982 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
987 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
992 fn index(self, slice: &[T]) -> &[T] {
997 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1003 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1004 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1008 fn get(self, slice: &[T]) -> Option<&[T]> {
1009 if self.end == usize::max_value() { None }
1010 else { (self.start..self.end + 1).get(slice) }
1014 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1015 if self.end == usize::max_value() { None }
1016 else { (self.start..self.end + 1).get_mut(slice) }
1020 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1021 (self.start..self.end + 1).get_unchecked(slice)
1025 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1026 (self.start..self.end + 1).get_unchecked_mut(slice)
1030 fn index(self, slice: &[T]) -> &[T] {
1031 assert!(self.end != usize::max_value(),
1032 "attempted to index slice up to maximum usize");
1033 (self.start..self.end + 1).index(slice)
1037 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1038 assert!(self.end != usize::max_value(),
1039 "attempted to index slice up to maximum usize");
1040 (self.start..self.end + 1).index_mut(slice)
1044 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1045 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1049 fn get(self, slice: &[T]) -> Option<&[T]> {
1050 (RangeInclusive { start: 0, end: self.end }).get(slice)
1054 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1055 (RangeInclusive { start: 0, end: self.end }).get_mut(slice)
1059 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1060 (RangeInclusive { start: 0, end: self.end }).get_unchecked(slice)
1064 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1065 (RangeInclusive { start: 0, end: self.end }).get_unchecked_mut(slice)
1069 fn index(self, slice: &[T]) -> &[T] {
1070 (RangeInclusive { start: 0, end: self.end }).index(slice)
1074 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1075 (RangeInclusive { start: 0, end: self.end }).index_mut(slice)
1079 ////////////////////////////////////////////////////////////////////////////////
1081 ////////////////////////////////////////////////////////////////////////////////
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<'a, T> Default for &'a [T] {
1085 /// Creates an empty slice.
1086 fn default() -> &'a [T] { &[] }
1089 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1090 impl<'a, T> Default for &'a mut [T] {
1091 /// Creates a mutable empty slice.
1092 fn default() -> &'a mut [T] { &mut [] }
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<'a, T> IntoIterator for &'a [T] {
1102 type IntoIter = Iter<'a, T>;
1104 fn into_iter(self) -> Iter<'a, T> {
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 impl<'a, T> IntoIterator for &'a mut [T] {
1111 type Item = &'a mut T;
1112 type IntoIter = IterMut<'a, T>;
1114 fn into_iter(self) -> IterMut<'a, T> {
1120 fn size_from_ptr<T>(_: *const T) -> usize {
1124 // The shared definition of the `Iter` and `IterMut` iterators
1125 macro_rules! iterator {
1126 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<'a, T> Iterator for $name<'a, T> {
1132 fn next(&mut self) -> Option<$elem> {
1133 // could be implemented with slices, but this avoids bounds checks
1135 if mem::size_of::<T>() != 0 {
1136 assume(!self.ptr.is_null());
1137 assume(!self.end.is_null());
1139 if self.ptr == self.end {
1142 Some($mkref!(self.ptr.post_inc()))
1148 fn size_hint(&self) -> (usize, Option<usize>) {
1149 let exact = ptrdistance(self.ptr, self.end);
1150 (exact, Some(exact))
1154 fn count(self) -> usize {
1159 fn nth(&mut self, n: usize) -> Option<$elem> {
1160 // Call helper method. Can't put the definition here because mut versus const.
1165 fn last(mut self) -> Option<$elem> {
1169 fn all<F>(&mut self, mut predicate: F) -> bool
1170 where F: FnMut(Self::Item) -> bool,
1172 self.search_while(true, move |elt| {
1174 SearchWhile::Continue
1176 SearchWhile::Done(false)
1181 fn any<F>(&mut self, mut predicate: F) -> bool
1182 where F: FnMut(Self::Item) -> bool,
1184 !self.all(move |elt| !predicate(elt))
1187 fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1188 where F: FnMut(&Self::Item) -> bool,
1190 self.search_while(None, move |elt| {
1191 if predicate(&elt) {
1192 SearchWhile::Done(Some(elt))
1194 SearchWhile::Continue
1199 fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1200 where F: FnMut(Self::Item) -> bool,
1203 self.search_while(None, move |elt| {
1205 SearchWhile::Done(Some(index))
1208 SearchWhile::Continue
1213 fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1214 where F: FnMut(Self::Item) -> bool,
1216 let mut index = self.len();
1217 self.rsearch_while(None, move |elt| {
1220 SearchWhile::Done(Some(index))
1222 SearchWhile::Continue
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1231 fn next_back(&mut self) -> Option<$elem> {
1232 // could be implemented with slices, but this avoids bounds checks
1234 if mem::size_of::<T>() != 0 {
1235 assume(!self.ptr.is_null());
1236 assume(!self.end.is_null());
1238 if self.end == self.ptr {
1241 Some($mkref!(self.end.pre_dec()))
1246 fn rfind<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1247 where F: FnMut(&Self::Item) -> bool,
1249 self.rsearch_while(None, move |elt| {
1250 if predicate(&elt) {
1251 SearchWhile::Done(Some(elt))
1253 SearchWhile::Continue
1260 // search_while is a generalization of the internal iteration methods.
1261 impl<'a, T> $name<'a, T> {
1262 // search through the iterator's element using the closure `g`.
1263 // if no element was found, return `default`.
1264 fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1266 G: FnMut($elem) -> SearchWhile<Acc>
1268 // manual unrolling is needed when there are conditional exits from the loop
1270 while ptrdistance(self.ptr, self.end) >= 4 {
1271 search_while!(g($mkref!(self.ptr.post_inc())));
1272 search_while!(g($mkref!(self.ptr.post_inc())));
1273 search_while!(g($mkref!(self.ptr.post_inc())));
1274 search_while!(g($mkref!(self.ptr.post_inc())));
1276 while self.ptr != self.end {
1277 search_while!(g($mkref!(self.ptr.post_inc())));
1283 fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1285 G: FnMut($elem) -> SearchWhile<Acc>
1288 while ptrdistance(self.ptr, self.end) >= 4 {
1289 search_while!(g($mkref!(self.end.pre_dec())));
1290 search_while!(g($mkref!(self.end.pre_dec())));
1291 search_while!(g($mkref!(self.end.pre_dec())));
1292 search_while!(g($mkref!(self.end.pre_dec())));
1294 while self.ptr != self.end {
1295 search_while!(g($mkref!(self.end.pre_dec())));
1304 macro_rules! make_slice {
1305 ($start: expr, $end: expr) => {{
1307 let diff = ($end as usize).wrapping_sub(start as usize);
1308 if size_from_ptr(start) == 0 {
1309 // use a non-null pointer value
1310 unsafe { from_raw_parts(1 as *const _, diff) }
1312 let len = diff / size_from_ptr(start);
1313 unsafe { from_raw_parts(start, len) }
1318 macro_rules! make_mut_slice {
1319 ($start: expr, $end: expr) => {{
1321 let diff = ($end as usize).wrapping_sub(start as usize);
1322 if size_from_ptr(start) == 0 {
1323 // use a non-null pointer value
1324 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1326 let len = diff / size_from_ptr(start);
1327 unsafe { from_raw_parts_mut(start, len) }
1332 // An enum used for controlling the execution of `.search_while()`.
1333 enum SearchWhile<T> {
1334 // Continue searching
1336 // Fold is complete and will return this value
1340 // helper macro for search while's control flow
1341 macro_rules! search_while {
1344 SearchWhile::Continue => { }
1345 SearchWhile::Done(done) => return done,
1350 /// Immutable slice iterator
1352 /// This struct is created by the [`iter`] method on [slices].
1359 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1360 /// let slice = &[1, 2, 3];
1362 /// // Then, we iterate over it:
1363 /// for element in slice.iter() {
1364 /// println!("{}", element);
1368 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1369 /// [slices]: ../../std/primitive.slice.html
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub struct Iter<'a, T: 'a> {
1374 _marker: marker::PhantomData<&'a T>,
1377 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1378 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1379 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380 f.debug_tuple("Iter")
1381 .field(&self.as_slice())
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1391 impl<'a, T> Iter<'a, T> {
1392 /// View the underlying data as a subslice of the original data.
1394 /// This has the same lifetime as the original slice, and so the
1395 /// iterator can continue to be used while this exists.
1402 /// // First, we declare a type which has the `iter` method to get the `Iter`
1403 /// // struct (&[usize here]):
1404 /// let slice = &[1, 2, 3];
1406 /// // Then, we get the iterator:
1407 /// let mut iter = slice.iter();
1408 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1409 /// println!("{:?}", iter.as_slice());
1411 /// // Next, we move to the second element of the slice:
1413 /// // Now `as_slice` returns "[2, 3]":
1414 /// println!("{:?}", iter.as_slice());
1416 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1417 pub fn as_slice(&self) -> &'a [T] {
1418 make_slice!(self.ptr, self.end)
1421 // Helper function for Iter::nth
1422 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1423 match self.as_slice().get(n) {
1424 Some(elem_ref) => unsafe {
1425 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1429 self.ptr = self.end;
1436 iterator!{struct Iter -> *const T, &'a T, make_ref}
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1440 fn is_empty(&self) -> bool {
1441 self.ptr == self.end
1445 #[unstable(feature = "fused", issue = "35602")]
1446 impl<'a, T> FusedIterator for Iter<'a, T> {}
1448 #[unstable(feature = "trusted_len", issue = "37572")]
1449 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<'a, T> Clone for Iter<'a, T> {
1453 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1456 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1457 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1458 fn as_ref(&self) -> &[T] {
1463 /// Mutable slice iterator.
1465 /// This struct is created by the [`iter_mut`] method on [slices].
1472 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1473 /// // struct (&[usize here]):
1474 /// let mut slice = &mut [1, 2, 3];
1476 /// // Then, we iterate over it and increment each element value:
1477 /// for element in slice.iter_mut() {
1481 /// // We now have "[2, 3, 4]":
1482 /// println!("{:?}", slice);
1485 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1486 /// [slices]: ../../std/primitive.slice.html
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 pub struct IterMut<'a, T: 'a> {
1491 _marker: marker::PhantomData<&'a mut T>,
1494 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1495 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1496 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1497 f.debug_tuple("IterMut")
1498 .field(&make_slice!(self.ptr, self.end))
1503 #[stable(feature = "rust1", since = "1.0.0")]
1504 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1508 impl<'a, T> IterMut<'a, T> {
1509 /// View the underlying data as a subslice of the original data.
1511 /// To avoid creating `&mut` references that alias, this is forced
1512 /// to consume the iterator. Consider using the `Slice` and
1513 /// `SliceMut` implementations for obtaining slices with more
1514 /// restricted lifetimes that do not consume the iterator.
1521 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1522 /// // struct (&[usize here]):
1523 /// let mut slice = &mut [1, 2, 3];
1526 /// // Then, we get the iterator:
1527 /// let mut iter = slice.iter_mut();
1528 /// // We move to next element:
1530 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1531 /// println!("{:?}", iter.into_slice());
1534 /// // Now let's modify a value of the slice:
1536 /// // First we get back the iterator:
1537 /// let mut iter = slice.iter_mut();
1538 /// // We change the value of the first element of the slice returned by the `next` method:
1539 /// *iter.next().unwrap() += 1;
1541 /// // Now slice is "[2, 2, 3]":
1542 /// println!("{:?}", slice);
1544 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1545 pub fn into_slice(self) -> &'a mut [T] {
1546 make_mut_slice!(self.ptr, self.end)
1549 // Helper function for IterMut::nth
1550 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1551 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1552 Some(elem_ref) => unsafe {
1553 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1557 self.ptr = self.end;
1564 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1568 fn is_empty(&self) -> bool {
1569 self.ptr == self.end
1573 #[unstable(feature = "fused", issue = "35602")]
1574 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1576 #[unstable(feature = "trusted_len", issue = "37572")]
1577 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1580 // Return the number of elements of `T` from `start` to `end`.
1581 // Return the arithmetic difference if `T` is zero size.
1583 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1584 match start.offset_to(end) {
1585 Some(x) => x as usize,
1586 None => (end as usize).wrapping_sub(start as usize),
1590 // Extension methods for raw pointers, used by the iterators
1591 trait PointerExt : Copy {
1592 unsafe fn slice_offset(self, i: isize) -> Self;
1594 /// Increments `self` by 1, but returns the old value.
1596 unsafe fn post_inc(&mut self) -> Self {
1597 let current = *self;
1598 *self = self.slice_offset(1);
1602 /// Decrements `self` by 1, and returns the new value.
1604 unsafe fn pre_dec(&mut self) -> Self {
1605 *self = self.slice_offset(-1);
1610 impl<T> PointerExt for *const T {
1612 unsafe fn slice_offset(self, i: isize) -> Self {
1613 slice_offset!(self, i)
1617 impl<T> PointerExt for *mut T {
1619 unsafe fn slice_offset(self, i: isize) -> Self {
1620 slice_offset!(self, i)
1624 /// An internal abstraction over the splitting iterators, so that
1625 /// splitn, splitn_mut etc can be implemented once.
1627 trait SplitIter: DoubleEndedIterator {
1628 /// Marks the underlying iterator as complete, extracting the remaining
1629 /// portion of the slice.
1630 fn finish(&mut self) -> Option<Self::Item>;
1633 /// An iterator over subslices separated by elements that match a predicate
1636 /// This struct is created by the [`split`] method on [slices].
1638 /// [`split`]: ../../std/primitive.slice.html#method.split
1639 /// [slices]: ../../std/primitive.slice.html
1640 #[stable(feature = "rust1", since = "1.0.0")]
1641 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1647 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1648 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1649 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1650 f.debug_struct("Split")
1651 .field("v", &self.v)
1652 .field("finished", &self.finished)
1657 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1660 fn clone(&self) -> Split<'a, T, P> {
1663 pred: self.pred.clone(),
1664 finished: self.finished,
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1671 type Item = &'a [T];
1674 fn next(&mut self) -> Option<&'a [T]> {
1675 if self.finished { return None; }
1677 match self.v.iter().position(|x| (self.pred)(x)) {
1678 None => self.finish(),
1680 let ret = Some(&self.v[..idx]);
1681 self.v = &self.v[idx + 1..];
1688 fn size_hint(&self) -> (usize, Option<usize>) {
1692 (1, Some(self.v.len() + 1))
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1700 fn next_back(&mut self) -> Option<&'a [T]> {
1701 if self.finished { return None; }
1703 match self.v.iter().rposition(|x| (self.pred)(x)) {
1704 None => self.finish(),
1706 let ret = Some(&self.v[idx + 1..]);
1707 self.v = &self.v[..idx];
1714 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1716 fn finish(&mut self) -> Option<&'a [T]> {
1717 if self.finished { None } else { self.finished = true; Some(self.v) }
1721 #[unstable(feature = "fused", issue = "35602")]
1722 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1724 /// An iterator over the subslices of the vector which are separated
1725 /// by elements that match `pred`.
1727 /// This struct is created by the [`split_mut`] method on [slices].
1729 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1730 /// [slices]: ../../std/primitive.slice.html
1731 #[stable(feature = "rust1", since = "1.0.0")]
1732 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1738 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1739 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1741 f.debug_struct("SplitMut")
1742 .field("v", &self.v)
1743 .field("finished", &self.finished)
1748 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1750 fn finish(&mut self) -> Option<&'a mut [T]> {
1754 self.finished = true;
1755 Some(mem::replace(&mut self.v, &mut []))
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1762 type Item = &'a mut [T];
1765 fn next(&mut self) -> Option<&'a mut [T]> {
1766 if self.finished { return None; }
1768 let idx_opt = { // work around borrowck limitations
1769 let pred = &mut self.pred;
1770 self.v.iter().position(|x| (*pred)(x))
1773 None => self.finish(),
1775 let tmp = mem::replace(&mut self.v, &mut []);
1776 let (head, tail) = tmp.split_at_mut(idx);
1777 self.v = &mut tail[1..];
1784 fn size_hint(&self) -> (usize, Option<usize>) {
1788 // if the predicate doesn't match anything, we yield one slice
1789 // if it matches every element, we yield len+1 empty slices.
1790 (1, Some(self.v.len() + 1))
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1797 P: FnMut(&T) -> bool,
1800 fn next_back(&mut self) -> Option<&'a mut [T]> {
1801 if self.finished { return None; }
1803 let idx_opt = { // work around borrowck limitations
1804 let pred = &mut self.pred;
1805 self.v.iter().rposition(|x| (*pred)(x))
1808 None => self.finish(),
1810 let tmp = mem::replace(&mut self.v, &mut []);
1811 let (head, tail) = tmp.split_at_mut(idx);
1813 Some(&mut tail[1..])
1819 #[unstable(feature = "fused", issue = "35602")]
1820 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1822 /// An iterator over subslices separated by elements that match a predicate
1823 /// function, starting from the end of the slice.
1825 /// This struct is created by the [`rsplit`] method on [slices].
1827 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1828 /// [slices]: ../../std/primitive.slice.html
1829 #[unstable(feature = "slice_rsplit", issue = "41020")]
1830 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1831 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1832 inner: Split<'a, T, P>
1835 #[unstable(feature = "slice_rsplit", issue = "41020")]
1836 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1838 f.debug_struct("RSplit")
1839 .field("v", &self.inner.v)
1840 .field("finished", &self.inner.finished)
1845 #[unstable(feature = "slice_rsplit", issue = "41020")]
1846 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1847 type Item = &'a [T];
1850 fn next(&mut self) -> Option<&'a [T]> {
1851 self.inner.next_back()
1855 fn size_hint(&self) -> (usize, Option<usize>) {
1856 self.inner.size_hint()
1860 #[unstable(feature = "slice_rsplit", issue = "41020")]
1861 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1863 fn next_back(&mut self) -> Option<&'a [T]> {
1868 #[unstable(feature = "slice_rsplit", issue = "41020")]
1869 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1871 fn finish(&mut self) -> Option<&'a [T]> {
1876 //#[unstable(feature = "fused", issue = "35602")]
1877 #[unstable(feature = "slice_rsplit", issue = "41020")]
1878 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1880 /// An iterator over the subslices of the vector which are separated
1881 /// by elements that match `pred`, starting from the end of the slice.
1883 /// This struct is created by the [`rsplit_mut`] method on [slices].
1885 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1886 /// [slices]: ../../std/primitive.slice.html
1887 #[unstable(feature = "slice_rsplit", issue = "41020")]
1888 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1889 inner: SplitMut<'a, T, P>
1892 #[unstable(feature = "slice_rsplit", issue = "41020")]
1893 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1894 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1895 f.debug_struct("RSplitMut")
1896 .field("v", &self.inner.v)
1897 .field("finished", &self.inner.finished)
1902 #[unstable(feature = "slice_rsplit", issue = "41020")]
1903 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1905 fn finish(&mut self) -> Option<&'a mut [T]> {
1910 #[unstable(feature = "slice_rsplit", issue = "41020")]
1911 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1912 type Item = &'a mut [T];
1915 fn next(&mut self) -> Option<&'a mut [T]> {
1916 self.inner.next_back()
1920 fn size_hint(&self) -> (usize, Option<usize>) {
1921 self.inner.size_hint()
1925 #[unstable(feature = "slice_rsplit", issue = "41020")]
1926 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1927 P: FnMut(&T) -> bool,
1930 fn next_back(&mut self) -> Option<&'a mut [T]> {
1935 //#[unstable(feature = "fused", issue = "35602")]
1936 #[unstable(feature = "slice_rsplit", issue = "41020")]
1937 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1939 /// An private iterator over subslices separated by elements that
1940 /// match a predicate function, splitting at most a fixed number of
1943 struct GenericSplitN<I> {
1948 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1952 fn next(&mut self) -> Option<T> {
1955 1 => { self.count -= 1; self.iter.finish() }
1956 _ => { self.count -= 1; self.iter.next() }
1961 fn size_hint(&self) -> (usize, Option<usize>) {
1962 let (lower, upper_opt) = self.iter.size_hint();
1963 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1967 /// An iterator over subslices separated by elements that match a predicate
1968 /// function, limited to a given number of splits.
1970 /// This struct is created by the [`splitn`] method on [slices].
1972 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1973 /// [slices]: ../../std/primitive.slice.html
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1976 inner: GenericSplitN<Split<'a, T, P>>
1979 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1980 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1982 f.debug_struct("SplitN")
1983 .field("inner", &self.inner)
1988 /// An iterator over subslices separated by elements that match a
1989 /// predicate function, limited to a given number of splits, starting
1990 /// from the end of the slice.
1992 /// This struct is created by the [`rsplitn`] method on [slices].
1994 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1995 /// [slices]: ../../std/primitive.slice.html
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1998 inner: GenericSplitN<RSplit<'a, T, P>>
2001 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2002 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
2003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2004 f.debug_struct("RSplitN")
2005 .field("inner", &self.inner)
2010 /// An iterator over subslices separated by elements that match a predicate
2011 /// function, limited to a given number of splits.
2013 /// This struct is created by the [`splitn_mut`] method on [slices].
2015 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
2016 /// [slices]: ../../std/primitive.slice.html
2017 #[stable(feature = "rust1", since = "1.0.0")]
2018 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2019 inner: GenericSplitN<SplitMut<'a, T, P>>
2022 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2023 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2024 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2025 f.debug_struct("SplitNMut")
2026 .field("inner", &self.inner)
2031 /// An iterator over subslices separated by elements that match a
2032 /// predicate function, limited to a given number of splits, starting
2033 /// from the end of the slice.
2035 /// This struct is created by the [`rsplitn_mut`] method on [slices].
2037 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
2038 /// [slices]: ../../std/primitive.slice.html
2039 #[stable(feature = "rust1", since = "1.0.0")]
2040 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2041 inner: GenericSplitN<RSplitMut<'a, T, P>>
2044 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2045 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2047 f.debug_struct("RSplitNMut")
2048 .field("inner", &self.inner)
2053 macro_rules! forward_iterator {
2054 ($name:ident: $elem:ident, $iter_of:ty) => {
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
2057 P: FnMut(&T) -> bool
2059 type Item = $iter_of;
2062 fn next(&mut self) -> Option<$iter_of> {
2067 fn size_hint(&self) -> (usize, Option<usize>) {
2068 self.inner.size_hint()
2072 #[unstable(feature = "fused", issue = "35602")]
2073 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2074 where P: FnMut(&T) -> bool {}
2078 forward_iterator! { SplitN: T, &'a [T] }
2079 forward_iterator! { RSplitN: T, &'a [T] }
2080 forward_iterator! { SplitNMut: T, &'a mut [T] }
2081 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2083 /// An iterator over overlapping subslices of length `size`.
2085 /// This struct is created by the [`windows`] method on [slices].
2087 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2088 /// [slices]: ../../std/primitive.slice.html
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub struct Windows<'a, T:'a> {
2096 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2097 #[stable(feature = "rust1", since = "1.0.0")]
2098 impl<'a, T> Clone for Windows<'a, T> {
2099 fn clone(&self) -> Windows<'a, T> {
2107 #[stable(feature = "rust1", since = "1.0.0")]
2108 impl<'a, T> Iterator for Windows<'a, T> {
2109 type Item = &'a [T];
2112 fn next(&mut self) -> Option<&'a [T]> {
2113 if self.size > self.v.len() {
2116 let ret = Some(&self.v[..self.size]);
2117 self.v = &self.v[1..];
2123 fn size_hint(&self) -> (usize, Option<usize>) {
2124 if self.size > self.v.len() {
2127 let size = self.v.len() - self.size + 1;
2133 fn count(self) -> usize {
2138 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2139 let (end, overflow) = self.size.overflowing_add(n);
2140 if end > self.v.len() || overflow {
2144 let nth = &self.v[n..end];
2145 self.v = &self.v[n+1..];
2151 fn last(self) -> Option<Self::Item> {
2152 if self.size > self.v.len() {
2155 let start = self.v.len() - self.size;
2156 Some(&self.v[start..])
2161 #[stable(feature = "rust1", since = "1.0.0")]
2162 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2164 fn next_back(&mut self) -> Option<&'a [T]> {
2165 if self.size > self.v.len() {
2168 let ret = Some(&self.v[self.v.len()-self.size..]);
2169 self.v = &self.v[..self.v.len()-1];
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2178 #[unstable(feature = "fused", issue = "35602")]
2179 impl<'a, T> FusedIterator for Windows<'a, T> {}
2181 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
2184 /// When the slice len is not evenly divided by the chunk size, the last slice
2185 /// of the iteration will be the remainder.
2187 /// This struct is created by the [`chunks`] method on [slices].
2189 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2190 /// [slices]: ../../std/primitive.slice.html
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 pub struct Chunks<'a, T:'a> {
2198 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<'a, T> Clone for Chunks<'a, T> {
2201 fn clone(&self) -> Chunks<'a, T> {
2209 #[stable(feature = "rust1", since = "1.0.0")]
2210 impl<'a, T> Iterator for Chunks<'a, T> {
2211 type Item = &'a [T];
2214 fn next(&mut self) -> Option<&'a [T]> {
2215 if self.v.is_empty() {
2218 let chunksz = cmp::min(self.v.len(), self.size);
2219 let (fst, snd) = self.v.split_at(chunksz);
2226 fn size_hint(&self) -> (usize, Option<usize>) {
2227 if self.v.is_empty() {
2230 let n = self.v.len() / self.size;
2231 let rem = self.v.len() % self.size;
2232 let n = if rem > 0 { n+1 } else { n };
2238 fn count(self) -> usize {
2243 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2244 let (start, overflow) = n.overflowing_mul(self.size);
2245 if start >= self.v.len() || overflow {
2249 let end = match start.checked_add(self.size) {
2250 Some(sum) => cmp::min(self.v.len(), sum),
2251 None => self.v.len(),
2253 let nth = &self.v[start..end];
2254 self.v = &self.v[end..];
2260 fn last(self) -> Option<Self::Item> {
2261 if self.v.is_empty() {
2264 let start = (self.v.len() - 1) / self.size * self.size;
2265 Some(&self.v[start..])
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2273 fn next_back(&mut self) -> Option<&'a [T]> {
2274 if self.v.is_empty() {
2277 let remainder = self.v.len() % self.size;
2278 let chunksz = if remainder != 0 { remainder } else { self.size };
2279 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2286 #[stable(feature = "rust1", since = "1.0.0")]
2287 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2289 #[unstable(feature = "fused", issue = "35602")]
2290 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2292 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2293 /// elements at a time). When the slice len is not evenly divided by the chunk
2294 /// size, the last slice of the iteration will be the remainder.
2296 /// This struct is created by the [`chunks_mut`] method on [slices].
2298 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2299 /// [slices]: ../../std/primitive.slice.html
2301 #[stable(feature = "rust1", since = "1.0.0")]
2302 pub struct ChunksMut<'a, T:'a> {
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl<'a, T> Iterator for ChunksMut<'a, T> {
2309 type Item = &'a mut [T];
2312 fn next(&mut self) -> Option<&'a mut [T]> {
2313 if self.v.is_empty() {
2316 let sz = cmp::min(self.v.len(), self.chunk_size);
2317 let tmp = mem::replace(&mut self.v, &mut []);
2318 let (head, tail) = tmp.split_at_mut(sz);
2325 fn size_hint(&self) -> (usize, Option<usize>) {
2326 if self.v.is_empty() {
2329 let n = self.v.len() / self.chunk_size;
2330 let rem = self.v.len() % self.chunk_size;
2331 let n = if rem > 0 { n + 1 } else { n };
2337 fn count(self) -> usize {
2342 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2343 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2344 if start >= self.v.len() || overflow {
2348 let end = match start.checked_add(self.chunk_size) {
2349 Some(sum) => cmp::min(self.v.len(), sum),
2350 None => self.v.len(),
2352 let tmp = mem::replace(&mut self.v, &mut []);
2353 let (head, tail) = tmp.split_at_mut(end);
2354 let (_, nth) = head.split_at_mut(start);
2361 fn last(self) -> Option<Self::Item> {
2362 if self.v.is_empty() {
2365 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2366 Some(&mut self.v[start..])
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2374 fn next_back(&mut self) -> Option<&'a mut [T]> {
2375 if self.v.is_empty() {
2378 let remainder = self.v.len() % self.chunk_size;
2379 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2380 let tmp = mem::replace(&mut self.v, &mut []);
2381 let tmp_len = tmp.len();
2382 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2392 #[unstable(feature = "fused", issue = "35602")]
2393 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2399 /// Forms a slice from a pointer and a length.
2401 /// The `len` argument is the number of **elements**, not the number of bytes.
2405 /// This function is unsafe as there is no guarantee that the given pointer is
2406 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2407 /// lifetime for the returned slice.
2409 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2410 /// are required to distinguish between a zero-length slice within `Some()`
2411 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2412 /// for zero-length slices, though.
2416 /// The lifetime for the returned slice is inferred from its usage. To
2417 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2418 /// source lifetime is safe in the context, such as by providing a helper
2419 /// function taking the lifetime of a host value for the slice, or by explicit
2427 /// // manifest a slice out of thin air!
2428 /// let ptr = 0x1234 as *const usize;
2431 /// let slice = slice::from_raw_parts(ptr, amt);
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2437 mem::transmute(Repr { data: p, len: len })
2440 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2441 /// slice is returned.
2443 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2444 /// as not being able to provide a non-aliasing guarantee of the returned
2445 /// mutable slice. `p` must be non-null even for zero-length slices as with
2446 /// `from_raw_parts`.
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2450 mem::transmute(Repr { data: p, len: len })
2453 // This function is public only because there is no other way to unit test heapsort.
2454 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2456 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2457 where F: FnMut(&T, &T) -> bool
2459 sort::heapsort(v, &mut is_less);
2463 // Comparison traits
2467 /// Calls implementation provided memcmp.
2469 /// Interprets the data as u8.
2471 /// Returns 0 for equal, < 0 for less than and > 0 for greater
2473 // FIXME(#32610): Return type should be c_int
2474 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2479 fn eq(&self, other: &[B]) -> bool {
2480 SlicePartialEq::equal(self, other)
2483 fn ne(&self, other: &[B]) -> bool {
2484 SlicePartialEq::not_equal(self, other)
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 impl<T: Eq> Eq for [T] {}
2491 /// Implements comparison of vectors lexicographically.
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl<T: Ord> Ord for [T] {
2494 fn cmp(&self, other: &[T]) -> Ordering {
2495 SliceOrd::compare(self, other)
2499 /// Implements comparison of vectors lexicographically.
2500 #[stable(feature = "rust1", since = "1.0.0")]
2501 impl<T: PartialOrd> PartialOrd for [T] {
2502 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2503 SlicePartialOrd::partial_compare(self, other)
2508 // intermediate trait for specialization of slice's PartialEq
2509 trait SlicePartialEq<B> {
2510 fn equal(&self, other: &[B]) -> bool;
2512 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2515 // Generic slice equality
2516 impl<A, B> SlicePartialEq<B> for [A]
2517 where A: PartialEq<B>
2519 default fn equal(&self, other: &[B]) -> bool {
2520 if self.len() != other.len() {
2524 for i in 0..self.len() {
2525 if !self[i].eq(&other[i]) {
2534 // Use memcmp for bytewise equality when the types allow
2535 impl<A> SlicePartialEq<A> for [A]
2536 where A: PartialEq<A> + BytewiseEquality
2538 fn equal(&self, other: &[A]) -> bool {
2539 if self.len() != other.len() {
2542 if self.as_ptr() == other.as_ptr() {
2546 let size = mem::size_of_val(self);
2547 memcmp(self.as_ptr() as *const u8,
2548 other.as_ptr() as *const u8, size) == 0
2554 // intermediate trait for specialization of slice's PartialOrd
2555 trait SlicePartialOrd<B> {
2556 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2559 impl<A> SlicePartialOrd<A> for [A]
2562 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2563 let l = cmp::min(self.len(), other.len());
2565 // Slice to the loop iteration range to enable bound check
2566 // elimination in the compiler
2567 let lhs = &self[..l];
2568 let rhs = &other[..l];
2571 match lhs[i].partial_cmp(&rhs[i]) {
2572 Some(Ordering::Equal) => (),
2573 non_eq => return non_eq,
2577 self.len().partial_cmp(&other.len())
2581 impl<A> SlicePartialOrd<A> for [A]
2584 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2585 Some(SliceOrd::compare(self, other))
2590 // intermediate trait for specialization of slice's Ord
2592 fn compare(&self, other: &[B]) -> Ordering;
2595 impl<A> SliceOrd<A> for [A]
2598 default fn compare(&self, other: &[A]) -> Ordering {
2599 let l = cmp::min(self.len(), other.len());
2601 // Slice to the loop iteration range to enable bound check
2602 // elimination in the compiler
2603 let lhs = &self[..l];
2604 let rhs = &other[..l];
2607 match lhs[i].cmp(&rhs[i]) {
2608 Ordering::Equal => (),
2609 non_eq => return non_eq,
2613 self.len().cmp(&other.len())
2617 // memcmp compares a sequence of unsigned bytes lexicographically.
2618 // this matches the order we want for [u8], but no others (not even [i8]).
2619 impl SliceOrd<u8> for [u8] {
2621 fn compare(&self, other: &[u8]) -> Ordering {
2622 let order = unsafe {
2623 memcmp(self.as_ptr(), other.as_ptr(),
2624 cmp::min(self.len(), other.len()))
2627 self.len().cmp(&other.len())
2628 } else if order < 0 {
2637 /// Trait implemented for types that can be compared for equality using
2638 /// their bytewise representation
2639 trait BytewiseEquality { }
2641 macro_rules! impl_marker_for {
2642 ($traitname:ident, $($ty:ty)*) => {
2644 impl $traitname for $ty { }
2649 impl_marker_for!(BytewiseEquality,
2650 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2653 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2654 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2655 &*self.ptr.offset(i as isize)
2657 fn may_have_side_effect() -> bool { false }
2661 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2662 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2663 &mut *self.ptr.offset(i as isize)
2665 fn may_have_side_effect() -> bool { false }