1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Slice management and manipulation
13 //! For more details see [`std::slice`].
15 //! [`std::slice`]: ../../std/slice/index.html
17 #![stable(feature = "rust1", since = "1.0.0")]
19 // How this module is organized.
21 // The library infrastructure for slices is fairly messy. There's
22 // a lot of stuff defined here. Let's keep it clean.
24 // Since slices don't support inherent methods; all operations
25 // on them are defined on traits, which are then reexported from
26 // the prelude for convenience. So there are a lot of traits here.
28 // The layout of this file is thus:
30 // * Slice-specific 'extension' traits and their implementations. This
31 // is where most of the slice API resides.
32 // * Implementations of a few common traits with important slice ops.
33 // * Definitions of a bunch of iterators.
35 // * The `raw` and `bytes` submodules.
36 // * Boilerplate trait implementations.
38 use cmp::Ordering::{self, Less, Equal, Greater};
41 use intrinsics::assume;
43 use ops::{FnMut, self};
45 use option::Option::{None, Some};
47 use result::Result::{Ok, Err};
50 use marker::{Copy, Send, Sync, Sized, self};
51 use iter_private::TrustedRandomAccess;
66 /// Extension methods for slices.
67 #[unstable(feature = "core_slice_ext",
68 reason = "stable interface provided by `impl [T]` in later crates",
70 #[allow(missing_docs)] // documented elsewhere
74 #[stable(feature = "core", since = "1.6.0")]
75 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
77 #[stable(feature = "core", since = "1.6.0")]
78 fn iter(&self) -> Iter<Self::Item>;
80 #[stable(feature = "core", since = "1.6.0")]
81 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
82 where P: FnMut(&Self::Item) -> bool;
84 #[unstable(feature = "slice_rsplit", issue = "41020")]
85 fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
86 where P: FnMut(&Self::Item) -> bool;
88 #[stable(feature = "core", since = "1.6.0")]
89 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
90 where P: FnMut(&Self::Item) -> bool;
92 #[stable(feature = "core", since = "1.6.0")]
93 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
94 where P: FnMut(&Self::Item) -> bool;
96 #[stable(feature = "core", since = "1.6.0")]
97 fn windows(&self, size: usize) -> Windows<Self::Item>;
99 #[stable(feature = "core", since = "1.6.0")]
100 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
102 #[stable(feature = "core", since = "1.6.0")]
103 fn get<I>(&self, index: I) -> Option<&I::Output>
104 where I: SliceIndex<Self>;
105 #[stable(feature = "core", since = "1.6.0")]
106 fn first(&self) -> Option<&Self::Item>;
108 #[stable(feature = "core", since = "1.6.0")]
109 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
111 #[stable(feature = "core", since = "1.6.0")]
112 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
114 #[stable(feature = "core", since = "1.6.0")]
115 fn last(&self) -> Option<&Self::Item>;
117 #[stable(feature = "core", since = "1.6.0")]
118 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
119 where I: SliceIndex<Self>;
120 #[stable(feature = "core", since = "1.6.0")]
121 fn as_ptr(&self) -> *const Self::Item;
123 #[stable(feature = "core", since = "1.6.0")]
124 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
125 where Self::Item: Ord;
127 #[stable(feature = "core", since = "1.6.0")]
128 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
129 where F: FnMut(&'a Self::Item) -> Ordering;
131 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
132 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
133 where F: FnMut(&'a Self::Item) -> B,
136 #[stable(feature = "core", since = "1.6.0")]
137 fn len(&self) -> usize;
139 #[stable(feature = "core", since = "1.6.0")]
140 fn is_empty(&self) -> bool { self.len() == 0 }
142 #[stable(feature = "core", since = "1.6.0")]
143 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
144 where I: SliceIndex<Self>;
145 #[stable(feature = "core", since = "1.6.0")]
146 fn iter_mut(&mut self) -> IterMut<Self::Item>;
148 #[stable(feature = "core", since = "1.6.0")]
149 fn first_mut(&mut self) -> Option<&mut Self::Item>;
151 #[stable(feature = "core", since = "1.6.0")]
152 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
154 #[stable(feature = "core", since = "1.6.0")]
155 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
157 #[stable(feature = "core", since = "1.6.0")]
158 fn last_mut(&mut self) -> Option<&mut Self::Item>;
160 #[stable(feature = "core", since = "1.6.0")]
161 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
162 where P: FnMut(&Self::Item) -> bool;
164 #[unstable(feature = "slice_rsplit", issue = "41020")]
165 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
166 where P: FnMut(&Self::Item) -> bool;
168 #[stable(feature = "core", since = "1.6.0")]
169 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
170 where P: FnMut(&Self::Item) -> bool;
172 #[stable(feature = "core", since = "1.6.0")]
173 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
174 where P: FnMut(&Self::Item) -> bool;
176 #[stable(feature = "core", since = "1.6.0")]
177 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
179 #[stable(feature = "core", since = "1.6.0")]
180 fn swap(&mut self, a: usize, b: usize);
182 #[stable(feature = "core", since = "1.6.0")]
183 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
185 #[stable(feature = "core", since = "1.6.0")]
186 fn reverse(&mut self);
188 #[stable(feature = "core", since = "1.6.0")]
189 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
190 where I: SliceIndex<Self>;
191 #[stable(feature = "core", since = "1.6.0")]
192 fn as_mut_ptr(&mut self) -> *mut Self::Item;
194 #[stable(feature = "core", since = "1.6.0")]
195 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
197 #[stable(feature = "core", since = "1.6.0")]
198 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
200 #[stable(feature = "core", since = "1.6.0")]
201 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
203 #[unstable(feature = "slice_rotate", issue = "41891")]
204 fn rotate(&mut self, mid: usize);
206 #[stable(feature = "clone_from_slice", since = "1.7.0")]
207 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
209 #[stable(feature = "copy_from_slice", since = "1.9.0")]
210 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
212 #[unstable(feature = "swap_with_slice", issue = "44030")]
213 fn swap_with_slice(&mut self, src: &mut [Self::Item]);
215 #[stable(feature = "sort_unstable", since = "1.20.0")]
216 fn sort_unstable(&mut self)
217 where Self::Item: Ord;
219 #[stable(feature = "sort_unstable", since = "1.20.0")]
220 fn sort_unstable_by<F>(&mut self, compare: F)
221 where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
223 #[stable(feature = "sort_unstable", since = "1.20.0")]
224 fn sort_unstable_by_key<B, F>(&mut self, f: F)
225 where F: FnMut(&Self::Item) -> B,
229 // Use macros to be generic over const/mut
230 macro_rules! slice_offset {
231 ($ptr:expr, $by:expr) => {{
233 if size_from_ptr(ptr) == 0 {
234 (ptr as *mut i8).wrapping_offset($by) as _
241 // make a &T from a *const T
242 macro_rules! make_ref {
245 if size_from_ptr(ptr) == 0 {
246 // Use a non-null pointer value
254 // make a &mut T from a *mut T
255 macro_rules! make_ref_mut {
258 if size_from_ptr(ptr) == 0 {
259 // Use a non-null pointer value
267 #[unstable(feature = "core_slice_ext",
268 reason = "stable interface provided by `impl [T]` in later crates",
270 impl<T> SliceExt for [T] {
274 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
275 (&self[..mid], &self[mid..])
279 fn iter(&self) -> Iter<T> {
281 let p = if mem::size_of::<T>() == 0 {
284 let p = self.as_ptr();
285 assume(!p.is_null());
291 end: slice_offset!(p, self.len() as isize),
292 _marker: marker::PhantomData
298 fn split<P>(&self, pred: P) -> Split<T, P>
299 where P: FnMut(&T) -> bool
309 fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
310 where P: FnMut(&T) -> bool
312 RSplit { inner: self.split(pred) }
316 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
317 where P: FnMut(&T) -> bool
320 inner: GenericSplitN {
321 iter: self.split(pred),
328 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
329 where P: FnMut(&T) -> bool
332 inner: GenericSplitN {
333 iter: self.rsplit(pred),
340 fn windows(&self, size: usize) -> Windows<T> {
342 Windows { v: self, size: size }
346 fn chunks(&self, size: usize) -> Chunks<T> {
348 Chunks { v: self, size: size }
352 fn get<I>(&self, index: I) -> Option<&I::Output>
353 where I: SliceIndex<[T]>
359 fn first(&self) -> Option<&T> {
360 if self.is_empty() { None } else { Some(&self[0]) }
364 fn split_first(&self) -> Option<(&T, &[T])> {
365 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
369 fn split_last(&self) -> Option<(&T, &[T])> {
370 let len = self.len();
371 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
375 fn last(&self) -> Option<&T> {
376 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
380 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
381 where I: SliceIndex<[T]>
383 index.get_unchecked(self)
387 fn as_ptr(&self) -> *const T {
388 self as *const [T] as *const T
391 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
392 where F: FnMut(&'a T) -> Ordering
394 let mut base = 0usize;
398 let (head, tail) = s.split_at(s.len() >> 1);
404 base += head.len() + 1;
408 Equal => return Ok(base + head.len()),
414 fn len(&self) -> usize {
416 mem::transmute::<&[T], Repr<T>>(self).len
421 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
422 where I: SliceIndex<[T]>
428 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
429 let len = self.len();
430 let ptr = self.as_mut_ptr();
435 (from_raw_parts_mut(ptr, mid),
436 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
441 fn iter_mut(&mut self) -> IterMut<T> {
443 let p = if mem::size_of::<T>() == 0 {
446 let p = self.as_mut_ptr();
447 assume(!p.is_null());
453 end: slice_offset!(p, self.len() as isize),
454 _marker: marker::PhantomData
460 fn last_mut(&mut self) -> Option<&mut T> {
461 let len = self.len();
462 if len == 0 { return None; }
463 Some(&mut self[len - 1])
467 fn first_mut(&mut self) -> Option<&mut T> {
468 if self.is_empty() { None } else { Some(&mut self[0]) }
472 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
473 if self.is_empty() { None } else {
474 let split = self.split_at_mut(1);
475 Some((&mut split.0[0], split.1))
480 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
481 let len = self.len();
482 if len == 0 { None } else {
483 let split = self.split_at_mut(len - 1);
484 Some((&mut split.1[0], split.0))
489 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
490 where P: FnMut(&T) -> bool
492 SplitMut { v: self, pred: pred, finished: false }
496 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
497 where P: FnMut(&T) -> bool
499 RSplitMut { inner: self.split_mut(pred) }
503 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
504 where P: FnMut(&T) -> bool
507 inner: GenericSplitN {
508 iter: self.split_mut(pred),
515 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
516 P: FnMut(&T) -> bool,
519 inner: GenericSplitN {
520 iter: self.rsplit_mut(pred),
527 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
528 assert!(chunk_size > 0);
529 ChunksMut { v: self, chunk_size: chunk_size }
533 fn swap(&mut self, a: usize, b: usize) {
535 // Can't take two mutable loans from one vector, so instead just cast
536 // them to their raw pointers to do the swap
537 let pa: *mut T = &mut self[a];
538 let pb: *mut T = &mut self[b];
543 fn reverse(&mut self) {
544 let mut i: usize = 0;
547 // For very small types, all the individual reads in the normal
548 // path perform poorly. We can do better, given efficient unaligned
549 // load/store, by loading a larger chunk and reversing a register.
551 // Ideally LLVM would do this for us, as it knows better than we do
552 // whether unaligned reads are efficient (since that changes between
553 // different ARM versions, for example) and what the best chunk size
554 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
555 // the loop, so we need to do this ourselves. (Hypothesis: reverse
556 // is troublesome because the sides can be aligned differently --
557 // will be, when the length is odd -- so there's no way of emitting
558 // pre- and postludes to use fully-aligned SIMD in the middle.)
561 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
563 if fast_unaligned && mem::size_of::<T>() == 1 {
564 // Use the llvm.bswap intrinsic to reverse u8s in a usize
565 let chunk = mem::size_of::<usize>();
566 while i + chunk - 1 < ln / 2 {
568 let pa: *mut T = self.get_unchecked_mut(i);
569 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
570 let va = ptr::read_unaligned(pa as *mut usize);
571 let vb = ptr::read_unaligned(pb as *mut usize);
572 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
573 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
579 if fast_unaligned && mem::size_of::<T>() == 2 {
580 // Use rotate-by-16 to reverse u16s in a u32
581 let chunk = mem::size_of::<u32>() / 2;
582 while i + chunk - 1 < ln / 2 {
584 let pa: *mut T = self.get_unchecked_mut(i);
585 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
586 let va = ptr::read_unaligned(pa as *mut u32);
587 let vb = ptr::read_unaligned(pb as *mut u32);
588 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
589 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
596 // Unsafe swap to avoid the bounds check in safe swap.
598 let pa: *mut T = self.get_unchecked_mut(i);
599 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
607 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
608 where I: SliceIndex<[T]>
610 index.get_unchecked_mut(self)
614 fn as_mut_ptr(&mut self) -> *mut T {
615 self as *mut [T] as *mut T
619 fn contains(&self, x: &T) -> bool where T: PartialEq {
620 self.iter().any(|elt| *x == *elt)
624 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
625 let n = needle.len();
626 self.len() >= n && needle == &self[..n]
630 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
631 let (m, n) = (self.len(), needle.len());
632 m >= n && needle == &self[m-n..]
635 fn binary_search(&self, x: &T) -> Result<usize, usize>
638 self.binary_search_by(|p| p.cmp(x))
641 fn rotate(&mut self, mid: usize) {
642 assert!(mid <= self.len());
643 let k = self.len() - mid;
646 let p = self.as_mut_ptr();
647 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
652 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
653 assert!(self.len() == src.len(),
654 "destination and source slices have different lengths");
655 // NOTE: We need to explicitly slice them to the same length
656 // for bounds checking to be elided, and the optimizer will
657 // generate memcpy for simple cases (for example T = u8).
658 let len = self.len();
659 let src = &src[..len];
661 self[i].clone_from(&src[i]);
666 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
667 assert!(self.len() == src.len(),
668 "destination and source slices have different lengths");
670 ptr::copy_nonoverlapping(
671 src.as_ptr(), self.as_mut_ptr(), self.len());
676 fn swap_with_slice(&mut self, src: &mut [T]) {
677 assert!(self.len() == src.len(),
678 "destination and source slices have different lengths");
680 ptr::swap_nonoverlapping(
681 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
686 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
687 where F: FnMut(&'a Self::Item) -> B,
690 self.binary_search_by(|k| f(k).cmp(b))
694 fn sort_unstable(&mut self)
695 where Self::Item: Ord
697 sort::quicksort(self, |a, b| a.lt(b));
701 fn sort_unstable_by<F>(&mut self, mut compare: F)
702 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
704 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
708 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
709 where F: FnMut(&Self::Item) -> B,
712 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
716 #[stable(feature = "rust1", since = "1.0.0")]
717 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
718 impl<T, I> ops::Index<I> for [T]
719 where I: SliceIndex<[T]>
721 type Output = I::Output;
724 fn index(&self, index: I) -> &I::Output {
729 #[stable(feature = "rust1", since = "1.0.0")]
730 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
731 impl<T, I> ops::IndexMut<I> for [T]
732 where I: SliceIndex<[T]>
735 fn index_mut(&mut self, index: I) -> &mut I::Output {
736 index.index_mut(self)
742 fn slice_index_len_fail(index: usize, len: usize) -> ! {
743 panic!("index {} out of range for slice of length {}", index, len);
748 fn slice_index_order_fail(index: usize, end: usize) -> ! {
749 panic!("slice index starts at {} but ends at {}", index, end);
752 /// A helper trait used for indexing operations.
753 #[unstable(feature = "slice_get_slice", issue = "35729")]
754 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
755 pub trait SliceIndex<T: ?Sized> {
756 /// The output type returned by methods.
759 /// Returns a shared reference to the output at this location, if in
761 fn get(self, slice: &T) -> Option<&Self::Output>;
763 /// Returns a mutable reference to the output at this location, if in
765 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
767 /// Returns a shared reference to the output at this location, without
768 /// performing any bounds checking.
769 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
771 /// Returns a mutable reference to the output at this location, without
772 /// performing any bounds checking.
773 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
775 /// Returns a shared reference to the output at this location, panicking
776 /// if out of bounds.
777 fn index(self, slice: &T) -> &Self::Output;
779 /// Returns a mutable reference to the output at this location, panicking
780 /// if out of bounds.
781 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
784 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
785 impl<T> SliceIndex<[T]> for usize {
789 fn get(self, slice: &[T]) -> Option<&T> {
790 if self < slice.len() {
792 Some(self.get_unchecked(slice))
800 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
801 if self < slice.len() {
803 Some(self.get_unchecked_mut(slice))
811 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
812 &*slice.as_ptr().offset(self as isize)
816 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
817 &mut *slice.as_mut_ptr().offset(self as isize)
821 fn index(self, slice: &[T]) -> &T {
822 // NB: use intrinsic indexing
827 fn index_mut(self, slice: &mut [T]) -> &mut T {
828 // NB: use intrinsic indexing
833 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
834 impl<T> SliceIndex<[T]> for ops::Range<usize> {
838 fn get(self, slice: &[T]) -> Option<&[T]> {
839 if self.start > self.end || self.end > slice.len() {
843 Some(self.get_unchecked(slice))
849 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
850 if self.start > self.end || self.end > slice.len() {
854 Some(self.get_unchecked_mut(slice))
860 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
861 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
865 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
866 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
870 fn index(self, slice: &[T]) -> &[T] {
871 if self.start > self.end {
872 slice_index_order_fail(self.start, self.end);
873 } else if self.end > slice.len() {
874 slice_index_len_fail(self.end, slice.len());
877 self.get_unchecked(slice)
882 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
883 if self.start > self.end {
884 slice_index_order_fail(self.start, self.end);
885 } else if self.end > slice.len() {
886 slice_index_len_fail(self.end, slice.len());
889 self.get_unchecked_mut(slice)
894 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
895 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
899 fn get(self, slice: &[T]) -> Option<&[T]> {
900 (0..self.end).get(slice)
904 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
905 (0..self.end).get_mut(slice)
909 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
910 (0..self.end).get_unchecked(slice)
914 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
915 (0..self.end).get_unchecked_mut(slice)
919 fn index(self, slice: &[T]) -> &[T] {
920 (0..self.end).index(slice)
924 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
925 (0..self.end).index_mut(slice)
929 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
930 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
934 fn get(self, slice: &[T]) -> Option<&[T]> {
935 (self.start..slice.len()).get(slice)
939 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
940 (self.start..slice.len()).get_mut(slice)
944 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
945 (self.start..slice.len()).get_unchecked(slice)
949 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
950 (self.start..slice.len()).get_unchecked_mut(slice)
954 fn index(self, slice: &[T]) -> &[T] {
955 (self.start..slice.len()).index(slice)
959 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
960 (self.start..slice.len()).index_mut(slice)
964 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
965 impl<T> SliceIndex<[T]> for ops::RangeFull {
969 fn get(self, slice: &[T]) -> Option<&[T]> {
974 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
979 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
984 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
989 fn index(self, slice: &[T]) -> &[T] {
994 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1000 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1001 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
1005 fn get(self, slice: &[T]) -> Option<&[T]> {
1006 if self.end == usize::max_value() { None }
1007 else { (self.start..self.end + 1).get(slice) }
1011 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1012 if self.end == usize::max_value() { None }
1013 else { (self.start..self.end + 1).get_mut(slice) }
1017 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1018 (self.start..self.end + 1).get_unchecked(slice)
1022 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1023 (self.start..self.end + 1).get_unchecked_mut(slice)
1027 fn index(self, slice: &[T]) -> &[T] {
1028 assert!(self.end != usize::max_value(),
1029 "attempted to index slice up to maximum usize");
1030 (self.start..self.end + 1).index(slice)
1034 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1035 assert!(self.end != usize::max_value(),
1036 "attempted to index slice up to maximum usize");
1037 (self.start..self.end + 1).index_mut(slice)
1041 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1042 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
1046 fn get(self, slice: &[T]) -> Option<&[T]> {
1047 (0...self.end).get(slice)
1051 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1052 (0...self.end).get_mut(slice)
1056 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1057 (0...self.end).get_unchecked(slice)
1061 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1062 (0...self.end).get_unchecked_mut(slice)
1066 fn index(self, slice: &[T]) -> &[T] {
1067 (0...self.end).index(slice)
1071 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1072 (0...self.end).index_mut(slice)
1076 ////////////////////////////////////////////////////////////////////////////////
1078 ////////////////////////////////////////////////////////////////////////////////
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<'a, T> Default for &'a [T] {
1082 /// Creates an empty slice.
1083 fn default() -> &'a [T] { &[] }
1086 #[stable(feature = "mut_slice_default", since = "1.5.0")]
1087 impl<'a, T> Default for &'a mut [T] {
1088 /// Creates a mutable empty slice.
1089 fn default() -> &'a mut [T] { &mut [] }
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<'a, T> IntoIterator for &'a [T] {
1099 type IntoIter = Iter<'a, T>;
1101 fn into_iter(self) -> Iter<'a, T> {
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 impl<'a, T> IntoIterator for &'a mut [T] {
1108 type Item = &'a mut T;
1109 type IntoIter = IterMut<'a, T>;
1111 fn into_iter(self) -> IterMut<'a, T> {
1117 fn size_from_ptr<T>(_: *const T) -> usize {
1121 // The shared definition of the `Iter` and `IterMut` iterators
1122 macro_rules! iterator {
1123 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 impl<'a, T> Iterator for $name<'a, T> {
1129 fn next(&mut self) -> Option<$elem> {
1130 // could be implemented with slices, but this avoids bounds checks
1132 if mem::size_of::<T>() != 0 {
1133 assume(!self.ptr.is_null());
1134 assume(!self.end.is_null());
1136 if self.ptr == self.end {
1139 Some($mkref!(self.ptr.post_inc()))
1145 fn size_hint(&self) -> (usize, Option<usize>) {
1146 let exact = ptrdistance(self.ptr, self.end);
1147 (exact, Some(exact))
1151 fn count(self) -> usize {
1156 fn nth(&mut self, n: usize) -> Option<$elem> {
1157 // Call helper method. Can't put the definition here because mut versus const.
1162 fn last(mut self) -> Option<$elem> {
1166 fn all<F>(&mut self, mut predicate: F) -> bool
1167 where F: FnMut(Self::Item) -> bool,
1169 self.search_while(true, move |elt| {
1171 SearchWhile::Continue
1173 SearchWhile::Done(false)
1178 fn any<F>(&mut self, mut predicate: F) -> bool
1179 where F: FnMut(Self::Item) -> bool,
1181 !self.all(move |elt| !predicate(elt))
1184 fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1185 where F: FnMut(&Self::Item) -> bool,
1187 self.search_while(None, move |elt| {
1188 if predicate(&elt) {
1189 SearchWhile::Done(Some(elt))
1191 SearchWhile::Continue
1196 fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1197 where F: FnMut(Self::Item) -> bool,
1200 self.search_while(None, move |elt| {
1202 SearchWhile::Done(Some(index))
1205 SearchWhile::Continue
1210 fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1211 where F: FnMut(Self::Item) -> bool,
1213 let mut index = self.len();
1214 self.rsearch_while(None, move |elt| {
1217 SearchWhile::Done(Some(index))
1219 SearchWhile::Continue
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1228 fn next_back(&mut self) -> Option<$elem> {
1229 // could be implemented with slices, but this avoids bounds checks
1231 if mem::size_of::<T>() != 0 {
1232 assume(!self.ptr.is_null());
1233 assume(!self.end.is_null());
1235 if self.end == self.ptr {
1238 Some($mkref!(self.end.pre_dec()))
1243 fn rfind<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1244 where F: FnMut(&Self::Item) -> bool,
1246 self.rsearch_while(None, move |elt| {
1247 if predicate(&elt) {
1248 SearchWhile::Done(Some(elt))
1250 SearchWhile::Continue
1257 // search_while is a generalization of the internal iteration methods.
1258 impl<'a, T> $name<'a, T> {
1259 // search through the iterator's element using the closure `g`.
1260 // if no element was found, return `default`.
1261 fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1263 G: FnMut($elem) -> SearchWhile<Acc>
1265 // manual unrolling is needed when there are conditional exits from the loop
1267 while ptrdistance(self.ptr, self.end) >= 4 {
1268 search_while!(g($mkref!(self.ptr.post_inc())));
1269 search_while!(g($mkref!(self.ptr.post_inc())));
1270 search_while!(g($mkref!(self.ptr.post_inc())));
1271 search_while!(g($mkref!(self.ptr.post_inc())));
1273 while self.ptr != self.end {
1274 search_while!(g($mkref!(self.ptr.post_inc())));
1280 fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1282 G: FnMut($elem) -> SearchWhile<Acc>
1285 while ptrdistance(self.ptr, self.end) >= 4 {
1286 search_while!(g($mkref!(self.end.pre_dec())));
1287 search_while!(g($mkref!(self.end.pre_dec())));
1288 search_while!(g($mkref!(self.end.pre_dec())));
1289 search_while!(g($mkref!(self.end.pre_dec())));
1291 while self.ptr != self.end {
1292 search_while!(g($mkref!(self.end.pre_dec())));
1301 macro_rules! make_slice {
1302 ($start: expr, $end: expr) => {{
1304 let diff = ($end as usize).wrapping_sub(start as usize);
1305 if size_from_ptr(start) == 0 {
1306 // use a non-null pointer value
1307 unsafe { from_raw_parts(1 as *const _, diff) }
1309 let len = diff / size_from_ptr(start);
1310 unsafe { from_raw_parts(start, len) }
1315 macro_rules! make_mut_slice {
1316 ($start: expr, $end: expr) => {{
1318 let diff = ($end as usize).wrapping_sub(start as usize);
1319 if size_from_ptr(start) == 0 {
1320 // use a non-null pointer value
1321 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1323 let len = diff / size_from_ptr(start);
1324 unsafe { from_raw_parts_mut(start, len) }
1329 // An enum used for controlling the execution of `.search_while()`.
1330 enum SearchWhile<T> {
1331 // Continue searching
1333 // Fold is complete and will return this value
1337 // helper macro for search while's control flow
1338 macro_rules! search_while {
1341 SearchWhile::Continue => { }
1342 SearchWhile::Done(done) => return done,
1347 /// Immutable slice iterator
1349 /// This struct is created by the [`iter`] method on [slices].
1356 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1357 /// let slice = &[1, 2, 3];
1359 /// // Then, we iterate over it:
1360 /// for element in slice.iter() {
1361 /// println!("{}", element);
1365 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1366 /// [slices]: ../../std/primitive.slice.html
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 pub struct Iter<'a, T: 'a> {
1371 _marker: marker::PhantomData<&'a T>,
1374 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1375 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1376 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1377 f.debug_tuple("Iter")
1378 .field(&self.as_slice())
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1388 impl<'a, T> Iter<'a, T> {
1389 /// View the underlying data as a subslice of the original data.
1391 /// This has the same lifetime as the original slice, and so the
1392 /// iterator can continue to be used while this exists.
1399 /// // First, we declare a type which has the `iter` method to get the `Iter`
1400 /// // struct (&[usize here]):
1401 /// let slice = &[1, 2, 3];
1403 /// // Then, we get the iterator:
1404 /// let mut iter = slice.iter();
1405 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1406 /// println!("{:?}", iter.as_slice());
1408 /// // Next, we move to the second element of the slice:
1410 /// // Now `as_slice` returns "[2, 3]":
1411 /// println!("{:?}", iter.as_slice());
1413 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1414 pub fn as_slice(&self) -> &'a [T] {
1415 make_slice!(self.ptr, self.end)
1418 // Helper function for Iter::nth
1419 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1420 match self.as_slice().get(n) {
1421 Some(elem_ref) => unsafe {
1422 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1426 self.ptr = self.end;
1433 iterator!{struct Iter -> *const T, &'a T, make_ref}
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1437 fn is_empty(&self) -> bool {
1438 self.ptr == self.end
1442 #[unstable(feature = "fused", issue = "35602")]
1443 impl<'a, T> FusedIterator for Iter<'a, T> {}
1445 #[unstable(feature = "trusted_len", issue = "37572")]
1446 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl<'a, T> Clone for Iter<'a, T> {
1450 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1453 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
1454 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1455 fn as_ref(&self) -> &[T] {
1460 /// Mutable slice iterator.
1462 /// This struct is created by the [`iter_mut`] method on [slices].
1469 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1470 /// // struct (&[usize here]):
1471 /// let mut slice = &mut [1, 2, 3];
1473 /// // Then, we iterate over it and increment each element value:
1474 /// for element in slice.iter_mut() {
1478 /// // We now have "[2, 3, 4]":
1479 /// println!("{:?}", slice);
1482 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1483 /// [slices]: ../../std/primitive.slice.html
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 pub struct IterMut<'a, T: 'a> {
1488 _marker: marker::PhantomData<&'a mut T>,
1491 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1492 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1494 f.debug_tuple("IterMut")
1495 .field(&make_slice!(self.ptr, self.end))
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1502 #[stable(feature = "rust1", since = "1.0.0")]
1503 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1505 impl<'a, T> IterMut<'a, T> {
1506 /// View the underlying data as a subslice of the original data.
1508 /// To avoid creating `&mut` references that alias, this is forced
1509 /// to consume the iterator. Consider using the `Slice` and
1510 /// `SliceMut` implementations for obtaining slices with more
1511 /// restricted lifetimes that do not consume the iterator.
1518 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1519 /// // struct (&[usize here]):
1520 /// let mut slice = &mut [1, 2, 3];
1523 /// // Then, we get the iterator:
1524 /// let mut iter = slice.iter_mut();
1525 /// // We move to next element:
1527 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1528 /// println!("{:?}", iter.into_slice());
1531 /// // Now let's modify a value of the slice:
1533 /// // First we get back the iterator:
1534 /// let mut iter = slice.iter_mut();
1535 /// // We change the value of the first element of the slice returned by the `next` method:
1536 /// *iter.next().unwrap() += 1;
1538 /// // Now slice is "[2, 2, 3]":
1539 /// println!("{:?}", slice);
1541 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1542 pub fn into_slice(self) -> &'a mut [T] {
1543 make_mut_slice!(self.ptr, self.end)
1546 // Helper function for IterMut::nth
1547 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1548 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1549 Some(elem_ref) => unsafe {
1550 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1554 self.ptr = self.end;
1561 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1565 fn is_empty(&self) -> bool {
1566 self.ptr == self.end
1570 #[unstable(feature = "fused", issue = "35602")]
1571 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1573 #[unstable(feature = "trusted_len", issue = "37572")]
1574 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1577 // Return the number of elements of `T` from `start` to `end`.
1578 // Return the arithmetic difference if `T` is zero size.
1580 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1581 match start.offset_to(end) {
1582 Some(x) => x as usize,
1583 None => (end as usize).wrapping_sub(start as usize),
1587 // Extension methods for raw pointers, used by the iterators
1588 trait PointerExt : Copy {
1589 unsafe fn slice_offset(self, i: isize) -> Self;
1591 /// Increments `self` by 1, but returns the old value.
1593 unsafe fn post_inc(&mut self) -> Self {
1594 let current = *self;
1595 *self = self.slice_offset(1);
1599 /// Decrements `self` by 1, and returns the new value.
1601 unsafe fn pre_dec(&mut self) -> Self {
1602 *self = self.slice_offset(-1);
1607 impl<T> PointerExt for *const T {
1609 unsafe fn slice_offset(self, i: isize) -> Self {
1610 slice_offset!(self, i)
1614 impl<T> PointerExt for *mut T {
1616 unsafe fn slice_offset(self, i: isize) -> Self {
1617 slice_offset!(self, i)
1621 /// An internal abstraction over the splitting iterators, so that
1622 /// splitn, splitn_mut etc can be implemented once.
1624 trait SplitIter: DoubleEndedIterator {
1625 /// Marks the underlying iterator as complete, extracting the remaining
1626 /// portion of the slice.
1627 fn finish(&mut self) -> Option<Self::Item>;
1630 /// An iterator over subslices separated by elements that match a predicate
1633 /// This struct is created by the [`split`] method on [slices].
1635 /// [`split`]: ../../std/primitive.slice.html#method.split
1636 /// [slices]: ../../std/primitive.slice.html
1637 #[stable(feature = "rust1", since = "1.0.0")]
1638 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1644 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1645 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1647 f.debug_struct("Split")
1648 .field("v", &self.v)
1649 .field("finished", &self.finished)
1654 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1657 fn clone(&self) -> Split<'a, T, P> {
1660 pred: self.pred.clone(),
1661 finished: self.finished,
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1668 type Item = &'a [T];
1671 fn next(&mut self) -> Option<&'a [T]> {
1672 if self.finished { return None; }
1674 match self.v.iter().position(|x| (self.pred)(x)) {
1675 None => self.finish(),
1677 let ret = Some(&self.v[..idx]);
1678 self.v = &self.v[idx + 1..];
1685 fn size_hint(&self) -> (usize, Option<usize>) {
1689 (1, Some(self.v.len() + 1))
1694 #[stable(feature = "rust1", since = "1.0.0")]
1695 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1697 fn next_back(&mut self) -> Option<&'a [T]> {
1698 if self.finished { return None; }
1700 match self.v.iter().rposition(|x| (self.pred)(x)) {
1701 None => self.finish(),
1703 let ret = Some(&self.v[idx + 1..]);
1704 self.v = &self.v[..idx];
1711 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1713 fn finish(&mut self) -> Option<&'a [T]> {
1714 if self.finished { None } else { self.finished = true; Some(self.v) }
1718 #[unstable(feature = "fused", issue = "35602")]
1719 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1721 /// An iterator over the subslices of the vector which are separated
1722 /// by elements that match `pred`.
1724 /// This struct is created by the [`split_mut`] method on [slices].
1726 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1727 /// [slices]: ../../std/primitive.slice.html
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1735 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1736 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1738 f.debug_struct("SplitMut")
1739 .field("v", &self.v)
1740 .field("finished", &self.finished)
1745 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1747 fn finish(&mut self) -> Option<&'a mut [T]> {
1751 self.finished = true;
1752 Some(mem::replace(&mut self.v, &mut []))
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1759 type Item = &'a mut [T];
1762 fn next(&mut self) -> Option<&'a mut [T]> {
1763 if self.finished { return None; }
1765 let idx_opt = { // work around borrowck limitations
1766 let pred = &mut self.pred;
1767 self.v.iter().position(|x| (*pred)(x))
1770 None => self.finish(),
1772 let tmp = mem::replace(&mut self.v, &mut []);
1773 let (head, tail) = tmp.split_at_mut(idx);
1774 self.v = &mut tail[1..];
1781 fn size_hint(&self) -> (usize, Option<usize>) {
1785 // if the predicate doesn't match anything, we yield one slice
1786 // if it matches every element, we yield len+1 empty slices.
1787 (1, Some(self.v.len() + 1))
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1794 P: FnMut(&T) -> bool,
1797 fn next_back(&mut self) -> Option<&'a mut [T]> {
1798 if self.finished { return None; }
1800 let idx_opt = { // work around borrowck limitations
1801 let pred = &mut self.pred;
1802 self.v.iter().rposition(|x| (*pred)(x))
1805 None => self.finish(),
1807 let tmp = mem::replace(&mut self.v, &mut []);
1808 let (head, tail) = tmp.split_at_mut(idx);
1810 Some(&mut tail[1..])
1816 #[unstable(feature = "fused", issue = "35602")]
1817 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1819 /// An iterator over subslices separated by elements that match a predicate
1820 /// function, starting from the end of the slice.
1822 /// This struct is created by the [`rsplit`] method on [slices].
1824 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
1825 /// [slices]: ../../std/primitive.slice.html
1826 #[unstable(feature = "slice_rsplit", issue = "41020")]
1827 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
1828 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
1829 inner: Split<'a, T, P>
1832 #[unstable(feature = "slice_rsplit", issue = "41020")]
1833 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1834 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1835 f.debug_struct("RSplit")
1836 .field("v", &self.inner.v)
1837 .field("finished", &self.inner.finished)
1842 #[unstable(feature = "slice_rsplit", issue = "41020")]
1843 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1844 type Item = &'a [T];
1847 fn next(&mut self) -> Option<&'a [T]> {
1848 self.inner.next_back()
1852 fn size_hint(&self) -> (usize, Option<usize>) {
1853 self.inner.size_hint()
1857 #[unstable(feature = "slice_rsplit", issue = "41020")]
1858 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1860 fn next_back(&mut self) -> Option<&'a [T]> {
1865 #[unstable(feature = "slice_rsplit", issue = "41020")]
1866 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
1868 fn finish(&mut self) -> Option<&'a [T]> {
1873 //#[unstable(feature = "fused", issue = "35602")]
1874 #[unstable(feature = "slice_rsplit", issue = "41020")]
1875 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
1877 /// An iterator over the subslices of the vector which are separated
1878 /// by elements that match `pred`, starting from the end of the slice.
1880 /// This struct is created by the [`rsplit_mut`] method on [slices].
1882 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
1883 /// [slices]: ../../std/primitive.slice.html
1884 #[unstable(feature = "slice_rsplit", issue = "41020")]
1885 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1886 inner: SplitMut<'a, T, P>
1889 #[unstable(feature = "slice_rsplit", issue = "41020")]
1890 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1891 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1892 f.debug_struct("RSplitMut")
1893 .field("v", &self.inner.v)
1894 .field("finished", &self.inner.finished)
1899 #[unstable(feature = "slice_rsplit", issue = "41020")]
1900 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1902 fn finish(&mut self) -> Option<&'a mut [T]> {
1907 #[unstable(feature = "slice_rsplit", issue = "41020")]
1908 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1909 type Item = &'a mut [T];
1912 fn next(&mut self) -> Option<&'a mut [T]> {
1913 self.inner.next_back()
1917 fn size_hint(&self) -> (usize, Option<usize>) {
1918 self.inner.size_hint()
1922 #[unstable(feature = "slice_rsplit", issue = "41020")]
1923 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
1924 P: FnMut(&T) -> bool,
1927 fn next_back(&mut self) -> Option<&'a mut [T]> {
1932 //#[unstable(feature = "fused", issue = "35602")]
1933 #[unstable(feature = "slice_rsplit", issue = "41020")]
1934 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1936 /// An private iterator over subslices separated by elements that
1937 /// match a predicate function, splitting at most a fixed number of
1940 struct GenericSplitN<I> {
1945 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1949 fn next(&mut self) -> Option<T> {
1952 1 => { self.count -= 1; self.iter.finish() }
1953 _ => { self.count -= 1; self.iter.next() }
1958 fn size_hint(&self) -> (usize, Option<usize>) {
1959 let (lower, upper_opt) = self.iter.size_hint();
1960 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1964 /// An iterator over subslices separated by elements that match a predicate
1965 /// function, limited to a given number of splits.
1967 /// This struct is created by the [`splitn`] method on [slices].
1969 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1970 /// [slices]: ../../std/primitive.slice.html
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1973 inner: GenericSplitN<Split<'a, T, P>>
1976 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1977 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1978 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1979 f.debug_struct("SplitN")
1980 .field("inner", &self.inner)
1985 /// An iterator over subslices separated by elements that match a
1986 /// predicate function, limited to a given number of splits, starting
1987 /// from the end of the slice.
1989 /// This struct is created by the [`rsplitn`] method on [slices].
1991 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1992 /// [slices]: ../../std/primitive.slice.html
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1995 inner: GenericSplitN<RSplit<'a, T, P>>
1998 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1999 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
2000 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2001 f.debug_struct("RSplitN")
2002 .field("inner", &self.inner)
2007 /// An iterator over subslices separated by elements that match a predicate
2008 /// function, limited to a given number of splits.
2010 /// This struct is created by the [`splitn_mut`] method on [slices].
2012 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
2013 /// [slices]: ../../std/primitive.slice.html
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2016 inner: GenericSplitN<SplitMut<'a, T, P>>
2019 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2020 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2021 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2022 f.debug_struct("SplitNMut")
2023 .field("inner", &self.inner)
2028 /// An iterator over subslices separated by elements that match a
2029 /// predicate function, limited to a given number of splits, starting
2030 /// from the end of the slice.
2032 /// This struct is created by the [`rsplitn_mut`] method on [slices].
2034 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
2035 /// [slices]: ../../std/primitive.slice.html
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2038 inner: GenericSplitN<RSplitMut<'a, T, P>>
2041 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2042 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
2043 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2044 f.debug_struct("RSplitNMut")
2045 .field("inner", &self.inner)
2050 macro_rules! forward_iterator {
2051 ($name:ident: $elem:ident, $iter_of:ty) => {
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
2054 P: FnMut(&T) -> bool
2056 type Item = $iter_of;
2059 fn next(&mut self) -> Option<$iter_of> {
2064 fn size_hint(&self) -> (usize, Option<usize>) {
2065 self.inner.size_hint()
2069 #[unstable(feature = "fused", issue = "35602")]
2070 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
2071 where P: FnMut(&T) -> bool {}
2075 forward_iterator! { SplitN: T, &'a [T] }
2076 forward_iterator! { RSplitN: T, &'a [T] }
2077 forward_iterator! { SplitNMut: T, &'a mut [T] }
2078 forward_iterator! { RSplitNMut: T, &'a mut [T] }
2080 /// An iterator over overlapping subslices of length `size`.
2082 /// This struct is created by the [`windows`] method on [slices].
2084 /// [`windows`]: ../../std/primitive.slice.html#method.windows
2085 /// [slices]: ../../std/primitive.slice.html
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 pub struct Windows<'a, T:'a> {
2093 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl<'a, T> Clone for Windows<'a, T> {
2096 fn clone(&self) -> Windows<'a, T> {
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<'a, T> Iterator for Windows<'a, T> {
2106 type Item = &'a [T];
2109 fn next(&mut self) -> Option<&'a [T]> {
2110 if self.size > self.v.len() {
2113 let ret = Some(&self.v[..self.size]);
2114 self.v = &self.v[1..];
2120 fn size_hint(&self) -> (usize, Option<usize>) {
2121 if self.size > self.v.len() {
2124 let size = self.v.len() - self.size + 1;
2130 fn count(self) -> usize {
2135 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2136 let (end, overflow) = self.size.overflowing_add(n);
2137 if end > self.v.len() || overflow {
2141 let nth = &self.v[n..end];
2142 self.v = &self.v[n+1..];
2148 fn last(self) -> Option<Self::Item> {
2149 if self.size > self.v.len() {
2152 let start = self.v.len() - self.size;
2153 Some(&self.v[start..])
2158 #[stable(feature = "rust1", since = "1.0.0")]
2159 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
2161 fn next_back(&mut self) -> Option<&'a [T]> {
2162 if self.size > self.v.len() {
2165 let ret = Some(&self.v[self.v.len()-self.size..]);
2166 self.v = &self.v[..self.v.len()-1];
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
2175 #[unstable(feature = "fused", issue = "35602")]
2176 impl<'a, T> FusedIterator for Windows<'a, T> {}
2178 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
2181 /// When the slice len is not evenly divided by the chunk size, the last slice
2182 /// of the iteration will be the remainder.
2184 /// This struct is created by the [`chunks`] method on [slices].
2186 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
2187 /// [slices]: ../../std/primitive.slice.html
2189 #[stable(feature = "rust1", since = "1.0.0")]
2190 pub struct Chunks<'a, T:'a> {
2195 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 impl<'a, T> Clone for Chunks<'a, T> {
2198 fn clone(&self) -> Chunks<'a, T> {
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 impl<'a, T> Iterator for Chunks<'a, T> {
2208 type Item = &'a [T];
2211 fn next(&mut self) -> Option<&'a [T]> {
2212 if self.v.is_empty() {
2215 let chunksz = cmp::min(self.v.len(), self.size);
2216 let (fst, snd) = self.v.split_at(chunksz);
2223 fn size_hint(&self) -> (usize, Option<usize>) {
2224 if self.v.is_empty() {
2227 let n = self.v.len() / self.size;
2228 let rem = self.v.len() % self.size;
2229 let n = if rem > 0 { n+1 } else { n };
2235 fn count(self) -> usize {
2240 fn nth(&mut self, n: usize) -> Option<Self::Item> {
2241 let (start, overflow) = n.overflowing_mul(self.size);
2242 if start >= self.v.len() || overflow {
2246 let end = match start.checked_add(self.size) {
2247 Some(sum) => cmp::min(self.v.len(), sum),
2248 None => self.v.len(),
2250 let nth = &self.v[start..end];
2251 self.v = &self.v[end..];
2257 fn last(self) -> Option<Self::Item> {
2258 if self.v.is_empty() {
2261 let start = (self.v.len() - 1) / self.size * self.size;
2262 Some(&self.v[start..])
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2270 fn next_back(&mut self) -> Option<&'a [T]> {
2271 if self.v.is_empty() {
2274 let remainder = self.v.len() % self.size;
2275 let chunksz = if remainder != 0 { remainder } else { self.size };
2276 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2286 #[unstable(feature = "fused", issue = "35602")]
2287 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2289 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2290 /// elements at a time). When the slice len is not evenly divided by the chunk
2291 /// size, the last slice of the iteration will be the remainder.
2293 /// This struct is created by the [`chunks_mut`] method on [slices].
2295 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2296 /// [slices]: ../../std/primitive.slice.html
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 pub struct ChunksMut<'a, T:'a> {
2304 #[stable(feature = "rust1", since = "1.0.0")]
2305 impl<'a, T> Iterator for ChunksMut<'a, T> {
2306 type Item = &'a mut [T];
2309 fn next(&mut self) -> Option<&'a mut [T]> {
2310 if self.v.is_empty() {
2313 let sz = cmp::min(self.v.len(), self.chunk_size);
2314 let tmp = mem::replace(&mut self.v, &mut []);
2315 let (head, tail) = tmp.split_at_mut(sz);
2322 fn size_hint(&self) -> (usize, Option<usize>) {
2323 if self.v.is_empty() {
2326 let n = self.v.len() / self.chunk_size;
2327 let rem = self.v.len() % self.chunk_size;
2328 let n = if rem > 0 { n + 1 } else { n };
2334 fn count(self) -> usize {
2339 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2340 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2341 if start >= self.v.len() || overflow {
2345 let end = match start.checked_add(self.chunk_size) {
2346 Some(sum) => cmp::min(self.v.len(), sum),
2347 None => self.v.len(),
2349 let tmp = mem::replace(&mut self.v, &mut []);
2350 let (head, tail) = tmp.split_at_mut(end);
2351 let (_, nth) = head.split_at_mut(start);
2358 fn last(self) -> Option<Self::Item> {
2359 if self.v.is_empty() {
2362 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2363 Some(&mut self.v[start..])
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2371 fn next_back(&mut self) -> Option<&'a mut [T]> {
2372 if self.v.is_empty() {
2375 let remainder = self.v.len() % self.chunk_size;
2376 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2377 let tmp = mem::replace(&mut self.v, &mut []);
2378 let tmp_len = tmp.len();
2379 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2386 #[stable(feature = "rust1", since = "1.0.0")]
2387 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2389 #[unstable(feature = "fused", issue = "35602")]
2390 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2396 /// Forms a slice from a pointer and a length.
2398 /// The `len` argument is the number of **elements**, not the number of bytes.
2402 /// This function is unsafe as there is no guarantee that the given pointer is
2403 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2404 /// lifetime for the returned slice.
2406 /// `p` must be non-null, even for zero-length slices, because non-zero bits
2407 /// are required to distinguish between a zero-length slice within `Some()`
2408 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
2409 /// for zero-length slices, though.
2413 /// The lifetime for the returned slice is inferred from its usage. To
2414 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2415 /// source lifetime is safe in the context, such as by providing a helper
2416 /// function taking the lifetime of a host value for the slice, or by explicit
2424 /// // manifest a slice out of thin air!
2425 /// let ptr = 0x1234 as *const usize;
2428 /// let slice = slice::from_raw_parts(ptr, amt);
2432 #[stable(feature = "rust1", since = "1.0.0")]
2433 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2434 mem::transmute(Repr { data: p, len: len })
2437 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2438 /// slice is returned.
2440 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2441 /// as not being able to provide a non-aliasing guarantee of the returned
2442 /// mutable slice. `p` must be non-null even for zero-length slices as with
2443 /// `from_raw_parts`.
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2447 mem::transmute(Repr { data: p, len: len })
2450 // This function is public only because there is no other way to unit test heapsort.
2451 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
2453 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
2454 where F: FnMut(&T, &T) -> bool
2456 sort::heapsort(v, &mut is_less);
2460 // Comparison traits
2464 /// Calls implementation provided memcmp.
2466 /// Interprets the data as u8.
2468 /// Returns 0 for equal, < 0 for less than and > 0 for greater
2470 // FIXME(#32610): Return type should be c_int
2471 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2476 fn eq(&self, other: &[B]) -> bool {
2477 SlicePartialEq::equal(self, other)
2480 fn ne(&self, other: &[B]) -> bool {
2481 SlicePartialEq::not_equal(self, other)
2485 #[stable(feature = "rust1", since = "1.0.0")]
2486 impl<T: Eq> Eq for [T] {}
2488 /// Implements comparison of vectors lexicographically.
2489 #[stable(feature = "rust1", since = "1.0.0")]
2490 impl<T: Ord> Ord for [T] {
2491 fn cmp(&self, other: &[T]) -> Ordering {
2492 SliceOrd::compare(self, other)
2496 /// Implements comparison of vectors lexicographically.
2497 #[stable(feature = "rust1", since = "1.0.0")]
2498 impl<T: PartialOrd> PartialOrd for [T] {
2499 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2500 SlicePartialOrd::partial_compare(self, other)
2505 // intermediate trait for specialization of slice's PartialEq
2506 trait SlicePartialEq<B> {
2507 fn equal(&self, other: &[B]) -> bool;
2509 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2512 // Generic slice equality
2513 impl<A, B> SlicePartialEq<B> for [A]
2514 where A: PartialEq<B>
2516 default fn equal(&self, other: &[B]) -> bool {
2517 if self.len() != other.len() {
2521 for i in 0..self.len() {
2522 if !self[i].eq(&other[i]) {
2531 // Use memcmp for bytewise equality when the types allow
2532 impl<A> SlicePartialEq<A> for [A]
2533 where A: PartialEq<A> + BytewiseEquality
2535 fn equal(&self, other: &[A]) -> bool {
2536 if self.len() != other.len() {
2539 if self.as_ptr() == other.as_ptr() {
2543 let size = mem::size_of_val(self);
2544 memcmp(self.as_ptr() as *const u8,
2545 other.as_ptr() as *const u8, size) == 0
2551 // intermediate trait for specialization of slice's PartialOrd
2552 trait SlicePartialOrd<B> {
2553 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2556 impl<A> SlicePartialOrd<A> for [A]
2559 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2560 let l = cmp::min(self.len(), other.len());
2562 // Slice to the loop iteration range to enable bound check
2563 // elimination in the compiler
2564 let lhs = &self[..l];
2565 let rhs = &other[..l];
2568 match lhs[i].partial_cmp(&rhs[i]) {
2569 Some(Ordering::Equal) => (),
2570 non_eq => return non_eq,
2574 self.len().partial_cmp(&other.len())
2578 impl<A> SlicePartialOrd<A> for [A]
2581 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2582 Some(SliceOrd::compare(self, other))
2587 // intermediate trait for specialization of slice's Ord
2589 fn compare(&self, other: &[B]) -> Ordering;
2592 impl<A> SliceOrd<A> for [A]
2595 default fn compare(&self, other: &[A]) -> Ordering {
2596 let l = cmp::min(self.len(), other.len());
2598 // Slice to the loop iteration range to enable bound check
2599 // elimination in the compiler
2600 let lhs = &self[..l];
2601 let rhs = &other[..l];
2604 match lhs[i].cmp(&rhs[i]) {
2605 Ordering::Equal => (),
2606 non_eq => return non_eq,
2610 self.len().cmp(&other.len())
2614 // memcmp compares a sequence of unsigned bytes lexicographically.
2615 // this matches the order we want for [u8], but no others (not even [i8]).
2616 impl SliceOrd<u8> for [u8] {
2618 fn compare(&self, other: &[u8]) -> Ordering {
2619 let order = unsafe {
2620 memcmp(self.as_ptr(), other.as_ptr(),
2621 cmp::min(self.len(), other.len()))
2624 self.len().cmp(&other.len())
2625 } else if order < 0 {
2634 /// Trait implemented for types that can be compared for equality using
2635 /// their bytewise representation
2636 trait BytewiseEquality { }
2638 macro_rules! impl_marker_for {
2639 ($traitname:ident, $($ty:ty)*) => {
2641 impl $traitname for $ty { }
2646 impl_marker_for!(BytewiseEquality,
2647 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2650 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2651 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2652 &*self.ptr.offset(i as isize)
2654 fn may_have_side_effect() -> bool { false }
2658 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2659 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2660 &mut *self.ptr.offset(i as isize)
2662 fn may_have_side_effect() -> bool { false }