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 // The layout of this file is thus:
26 // * Inherent methods. This is where most of the slice API resides.
27 // * Implementations of a few common traits with important slice ops.
28 // * Definitions of a bunch of iterators.
30 // * The `raw` and `bytes` submodules.
31 // * Boilerplate trait implementations.
33 use cmp::Ordering::{self, Less, Equal, Greater};
36 use intrinsics::assume;
38 use ops::{FnMut, Try, self};
40 use option::Option::{None, Some};
42 use result::Result::{Ok, Err};
45 use marker::{Copy, Send, Sync, Sized, self};
46 use iter_private::TrustedRandomAccess;
48 #[unstable(feature = "slice_internals", issue = "0",
49 reason = "exposed from core to be reused in std; use the memchr crate")]
50 /// Pure rust memchr implementation, taken from rust-memchr
57 union Repr<'a, T: 'a> {
59 rust_mut: &'a mut [T],
76 /// Returns the number of elements in the slice.
81 /// let a = [1, 2, 3];
82 /// assert_eq!(a.len(), 3);
84 #[stable(feature = "rust1", since = "1.0.0")]
86 #[rustc_const_unstable(feature = "const_slice_len")]
87 pub const fn len(&self) -> usize {
89 Repr { rust: self }.raw.len
93 /// Returns `true` if the slice has a length of 0.
98 /// let a = [1, 2, 3];
99 /// assert!(!a.is_empty());
101 #[stable(feature = "rust1", since = "1.0.0")]
103 #[rustc_const_unstable(feature = "const_slice_len")]
104 pub const fn is_empty(&self) -> bool {
108 /// Returns the first element of the slice, or `None` if it is empty.
113 /// let v = [10, 40, 30];
114 /// assert_eq!(Some(&10), v.first());
116 /// let w: &[i32] = &[];
117 /// assert_eq!(None, w.first());
119 #[stable(feature = "rust1", since = "1.0.0")]
121 pub fn first(&self) -> Option<&T> {
125 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
130 /// let x = &mut [0, 1, 2];
132 /// if let Some(first) = x.first_mut() {
135 /// assert_eq!(x, &[5, 1, 2]);
137 #[stable(feature = "rust1", since = "1.0.0")]
139 pub fn first_mut(&mut self) -> Option<&mut T> {
143 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
148 /// let x = &[0, 1, 2];
150 /// if let Some((first, elements)) = x.split_first() {
151 /// assert_eq!(first, &0);
152 /// assert_eq!(elements, &[1, 2]);
155 #[stable(feature = "slice_splits", since = "1.5.0")]
157 pub fn split_first(&self) -> Option<(&T, &[T])> {
158 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
161 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
166 /// let x = &mut [0, 1, 2];
168 /// if let Some((first, elements)) = x.split_first_mut() {
173 /// assert_eq!(x, &[3, 4, 5]);
175 #[stable(feature = "slice_splits", since = "1.5.0")]
177 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
178 if self.is_empty() { None } else {
179 let split = self.split_at_mut(1);
180 Some((&mut split.0[0], split.1))
184 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
189 /// let x = &[0, 1, 2];
191 /// if let Some((last, elements)) = x.split_last() {
192 /// assert_eq!(last, &2);
193 /// assert_eq!(elements, &[0, 1]);
196 #[stable(feature = "slice_splits", since = "1.5.0")]
198 pub fn split_last(&self) -> Option<(&T, &[T])> {
199 let len = self.len();
200 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
203 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
208 /// let x = &mut [0, 1, 2];
210 /// if let Some((last, elements)) = x.split_last_mut() {
215 /// assert_eq!(x, &[4, 5, 3]);
217 #[stable(feature = "slice_splits", since = "1.5.0")]
219 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
220 let len = self.len();
221 if len == 0 { None } else {
222 let split = self.split_at_mut(len - 1);
223 Some((&mut split.1[0], split.0))
228 /// Returns the last element of the slice, or `None` if it is empty.
233 /// let v = [10, 40, 30];
234 /// assert_eq!(Some(&30), v.last());
236 /// let w: &[i32] = &[];
237 /// assert_eq!(None, w.last());
239 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn last(&self) -> Option<&T> {
242 let last_idx = self.len().checked_sub(1)?;
246 /// Returns a mutable pointer to the last item in the slice.
251 /// let x = &mut [0, 1, 2];
253 /// if let Some(last) = x.last_mut() {
256 /// assert_eq!(x, &[0, 1, 10]);
258 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn last_mut(&mut self) -> Option<&mut T> {
261 let last_idx = self.len().checked_sub(1)?;
262 self.get_mut(last_idx)
265 /// Returns a reference to an element or subslice depending on the type of
268 /// - If given a position, returns a reference to the element at that
269 /// position or `None` if out of bounds.
270 /// - If given a range, returns the subslice corresponding to that range,
271 /// or `None` if out of bounds.
276 /// let v = [10, 40, 30];
277 /// assert_eq!(Some(&40), v.get(1));
278 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
279 /// assert_eq!(None, v.get(3));
280 /// assert_eq!(None, v.get(0..4));
282 #[stable(feature = "rust1", since = "1.0.0")]
284 pub fn get<I>(&self, index: I) -> Option<&I::Output>
285 where I: SliceIndex<Self>
290 /// Returns a mutable reference to an element or subslice depending on the
291 /// type of index (see [`get`]) or `None` if the index is out of bounds.
293 /// [`get`]: #method.get
298 /// let x = &mut [0, 1, 2];
300 /// if let Some(elem) = x.get_mut(1) {
303 /// assert_eq!(x, &[0, 42, 2]);
305 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
308 where I: SliceIndex<Self>
313 /// Returns a reference to an element or subslice, without doing bounds
316 /// This is generally not recommended, use with caution! For a safe
317 /// alternative see [`get`].
319 /// [`get`]: #method.get
324 /// let x = &[1, 2, 4];
327 /// assert_eq!(x.get_unchecked(1), &2);
330 #[stable(feature = "rust1", since = "1.0.0")]
332 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
333 where I: SliceIndex<Self>
335 index.get_unchecked(self)
338 /// Returns a mutable reference to an element or subslice, without doing
341 /// This is generally not recommended, use with caution! For a safe
342 /// alternative see [`get_mut`].
344 /// [`get_mut`]: #method.get_mut
349 /// let x = &mut [1, 2, 4];
352 /// let elem = x.get_unchecked_mut(1);
355 /// assert_eq!(x, &[1, 13, 4]);
357 #[stable(feature = "rust1", since = "1.0.0")]
359 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
360 where I: SliceIndex<Self>
362 index.get_unchecked_mut(self)
365 /// Returns a raw pointer to the slice's buffer.
367 /// The caller must ensure that the slice outlives the pointer this
368 /// function returns, or else it will end up pointing to garbage.
370 /// Modifying the container referenced by this slice may cause its buffer
371 /// to be reallocated, which would also make any pointers to it invalid.
376 /// let x = &[1, 2, 4];
377 /// let x_ptr = x.as_ptr();
380 /// for i in 0..x.len() {
381 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
385 #[stable(feature = "rust1", since = "1.0.0")]
387 #[rustc_const_unstable(feature = "const_slice_as_ptr")]
388 pub const fn as_ptr(&self) -> *const T {
389 self as *const [T] as *const T
392 /// Returns an unsafe mutable pointer to the slice's buffer.
394 /// The caller must ensure that the slice outlives the pointer this
395 /// function returns, or else it will end up pointing to garbage.
397 /// Modifying the container referenced by this slice may cause its buffer
398 /// to be reallocated, which would also make any pointers to it invalid.
403 /// let x = &mut [1, 2, 4];
404 /// let x_ptr = x.as_mut_ptr();
407 /// for i in 0..x.len() {
408 /// *x_ptr.add(i) += 2;
411 /// assert_eq!(x, &[3, 4, 6]);
413 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn as_mut_ptr(&mut self) -> *mut T {
416 self as *mut [T] as *mut T
419 /// Swaps two elements in the slice.
423 /// * a - The index of the first element
424 /// * b - The index of the second element
428 /// Panics if `a` or `b` are out of bounds.
433 /// let mut v = ["a", "b", "c", "d"];
435 /// assert!(v == ["a", "d", "c", "b"]);
437 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn swap(&mut self, a: usize, b: usize) {
441 // Can't take two mutable loans from one vector, so instead just cast
442 // them to their raw pointers to do the swap
443 let pa: *mut T = &mut self[a];
444 let pb: *mut T = &mut self[b];
449 /// Reverses the order of elements in the slice, in place.
454 /// let mut v = [1, 2, 3];
456 /// assert!(v == [3, 2, 1]);
458 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn reverse(&mut self) {
461 let mut i: usize = 0;
464 // For very small types, all the individual reads in the normal
465 // path perform poorly. We can do better, given efficient unaligned
466 // load/store, by loading a larger chunk and reversing a register.
468 // Ideally LLVM would do this for us, as it knows better than we do
469 // whether unaligned reads are efficient (since that changes between
470 // different ARM versions, for example) and what the best chunk size
471 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
472 // the loop, so we need to do this ourselves. (Hypothesis: reverse
473 // is troublesome because the sides can be aligned differently --
474 // will be, when the length is odd -- so there's no way of emitting
475 // pre- and postludes to use fully-aligned SIMD in the middle.)
478 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
480 if fast_unaligned && mem::size_of::<T>() == 1 {
481 // Use the llvm.bswap intrinsic to reverse u8s in a usize
482 let chunk = mem::size_of::<usize>();
483 while i + chunk - 1 < ln / 2 {
485 let pa: *mut T = self.get_unchecked_mut(i);
486 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
487 let va = ptr::read_unaligned(pa as *mut usize);
488 let vb = ptr::read_unaligned(pb as *mut usize);
489 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
490 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
496 if fast_unaligned && mem::size_of::<T>() == 2 {
497 // Use rotate-by-16 to reverse u16s in a u32
498 let chunk = mem::size_of::<u32>() / 2;
499 while i + chunk - 1 < ln / 2 {
501 let pa: *mut T = self.get_unchecked_mut(i);
502 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
503 let va = ptr::read_unaligned(pa as *mut u32);
504 let vb = ptr::read_unaligned(pb as *mut u32);
505 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
506 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
513 // Unsafe swap to avoid the bounds check in safe swap.
515 let pa: *mut T = self.get_unchecked_mut(i);
516 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
523 /// Returns an iterator over the slice.
528 /// let x = &[1, 2, 4];
529 /// let mut iterator = x.iter();
531 /// assert_eq!(iterator.next(), Some(&1));
532 /// assert_eq!(iterator.next(), Some(&2));
533 /// assert_eq!(iterator.next(), Some(&4));
534 /// assert_eq!(iterator.next(), None);
536 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn iter(&self) -> Iter<T> {
540 let ptr = self.as_ptr();
541 assume(!ptr.is_null());
543 let end = if mem::size_of::<T>() == 0 {
544 (ptr as *const u8).wrapping_add(self.len()) as *const T
552 _marker: marker::PhantomData
557 /// Returns an iterator that allows modifying each value.
562 /// let x = &mut [1, 2, 4];
563 /// for elem in x.iter_mut() {
566 /// assert_eq!(x, &[3, 4, 6]);
568 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn iter_mut(&mut self) -> IterMut<T> {
572 let ptr = self.as_mut_ptr();
573 assume(!ptr.is_null());
575 let end = if mem::size_of::<T>() == 0 {
576 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
584 _marker: marker::PhantomData
589 /// Returns an iterator over all contiguous windows of length
590 /// `size`. The windows overlap. If the slice is shorter than
591 /// `size`, the iterator returns no values.
595 /// Panics if `size` is 0.
600 /// let slice = ['r', 'u', 's', 't'];
601 /// let mut iter = slice.windows(2);
602 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
603 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
604 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
605 /// assert!(iter.next().is_none());
608 /// If the slice is shorter than `size`:
611 /// let slice = ['f', 'o', 'o'];
612 /// let mut iter = slice.windows(4);
613 /// assert!(iter.next().is_none());
615 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn windows(&self, size: usize) -> Windows<T> {
619 Windows { v: self, size }
622 /// Returns an iterator over `chunk_size` elements of the slice at a
623 /// time. The chunks are slices and do not overlap. If `chunk_size` does
624 /// not divide the length of the slice, then the last chunk will
625 /// not have length `chunk_size`.
627 /// See [`exact_chunks`] for a variant of this iterator that returns chunks
628 /// of always exactly `chunk_size` elements.
632 /// Panics if `chunk_size` is 0.
637 /// let slice = ['l', 'o', 'r', 'e', 'm'];
638 /// let mut iter = slice.chunks(2);
639 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
640 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
641 /// assert_eq!(iter.next().unwrap(), &['m']);
642 /// assert!(iter.next().is_none());
645 /// [`exact_chunks`]: #method.exact_chunks
646 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
649 assert!(chunk_size != 0);
650 Chunks { v: self, chunk_size }
653 /// Returns an iterator over `chunk_size` elements of the slice at a time.
654 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
655 /// not divide the length of the slice, then the last chunk will not
656 /// have length `chunk_size`.
658 /// See [`exact_chunks_mut`] for a variant of this iterator that returns chunks
659 /// of always exactly `chunk_size` elements.
663 /// Panics if `chunk_size` is 0.
668 /// let v = &mut [0, 0, 0, 0, 0];
669 /// let mut count = 1;
671 /// for chunk in v.chunks_mut(2) {
672 /// for elem in chunk.iter_mut() {
677 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
680 /// [`exact_chunks_mut`]: #method.exact_chunks_mut
681 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
684 assert!(chunk_size != 0);
685 ChunksMut { v: self, chunk_size }
688 /// Returns an iterator over `chunk_size` elements of the slice at a
689 /// time. The chunks are slices and do not overlap. If `chunk_size` does
690 /// not divide the length of the slice, then the last up to `chunk_size-1`
691 /// elements will be omitted and can be retrieved from the `remainder`
692 /// function of the iterator.
694 /// Due to each chunk having exactly `chunk_size` elements, the compiler
695 /// can often optimize the resulting code better than in the case of
700 /// Panics if `chunk_size` is 0.
705 /// #![feature(exact_chunks)]
707 /// let slice = ['l', 'o', 'r', 'e', 'm'];
708 /// let mut iter = slice.exact_chunks(2);
709 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
710 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
711 /// assert!(iter.next().is_none());
714 /// [`chunks`]: #method.chunks
715 #[unstable(feature = "exact_chunks", issue = "47115")]
717 pub fn exact_chunks(&self, chunk_size: usize) -> ExactChunks<T> {
718 assert!(chunk_size != 0);
719 let rem = self.len() % chunk_size;
720 let len = self.len() - rem;
721 let (fst, snd) = self.split_at(len);
722 ExactChunks { v: fst, rem: snd, chunk_size }
725 /// Returns an iterator over `chunk_size` elements of the slice at a time.
726 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
727 /// not divide the length of the slice, then the last up to `chunk_size-1`
728 /// elements will be omitted and can be retrieved from the `into_remainder`
729 /// function of the iterator.
731 /// Due to each chunk having exactly `chunk_size` elements, the compiler
732 /// can often optimize the resulting code better than in the case of
737 /// Panics if `chunk_size` is 0.
742 /// #![feature(exact_chunks)]
744 /// let v = &mut [0, 0, 0, 0, 0];
745 /// let mut count = 1;
747 /// for chunk in v.exact_chunks_mut(2) {
748 /// for elem in chunk.iter_mut() {
753 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
756 /// [`chunks_mut`]: #method.chunks_mut
757 #[unstable(feature = "exact_chunks", issue = "47115")]
759 pub fn exact_chunks_mut(&mut self, chunk_size: usize) -> ExactChunksMut<T> {
760 assert!(chunk_size != 0);
761 let rem = self.len() % chunk_size;
762 let len = self.len() - rem;
763 let (fst, snd) = self.split_at_mut(len);
764 ExactChunksMut { v: fst, rem: snd, chunk_size }
767 /// Divides one slice into two at an index.
769 /// The first will contain all indices from `[0, mid)` (excluding
770 /// the index `mid` itself) and the second will contain all
771 /// indices from `[mid, len)` (excluding the index `len` itself).
775 /// Panics if `mid > len`.
780 /// let v = [1, 2, 3, 4, 5, 6];
783 /// let (left, right) = v.split_at(0);
784 /// assert!(left == []);
785 /// assert!(right == [1, 2, 3, 4, 5, 6]);
789 /// let (left, right) = v.split_at(2);
790 /// assert!(left == [1, 2]);
791 /// assert!(right == [3, 4, 5, 6]);
795 /// let (left, right) = v.split_at(6);
796 /// assert!(left == [1, 2, 3, 4, 5, 6]);
797 /// assert!(right == []);
800 #[stable(feature = "rust1", since = "1.0.0")]
802 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
803 (&self[..mid], &self[mid..])
806 /// Divides one mutable slice into two at an index.
808 /// The first will contain all indices from `[0, mid)` (excluding
809 /// the index `mid` itself) and the second will contain all
810 /// indices from `[mid, len)` (excluding the index `len` itself).
814 /// Panics if `mid > len`.
819 /// let mut v = [1, 0, 3, 0, 5, 6];
820 /// // scoped to restrict the lifetime of the borrows
822 /// let (left, right) = v.split_at_mut(2);
823 /// assert!(left == [1, 0]);
824 /// assert!(right == [3, 0, 5, 6]);
828 /// assert!(v == [1, 2, 3, 4, 5, 6]);
830 #[stable(feature = "rust1", since = "1.0.0")]
832 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
833 let len = self.len();
834 let ptr = self.as_mut_ptr();
839 (from_raw_parts_mut(ptr, mid),
840 from_raw_parts_mut(ptr.add(mid), len - mid))
844 /// Returns an iterator over subslices separated by elements that match
845 /// `pred`. The matched element is not contained in the subslices.
850 /// let slice = [10, 40, 33, 20];
851 /// let mut iter = slice.split(|num| num % 3 == 0);
853 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
854 /// assert_eq!(iter.next().unwrap(), &[20]);
855 /// assert!(iter.next().is_none());
858 /// If the first element is matched, an empty slice will be the first item
859 /// returned by the iterator. Similarly, if the last element in the slice
860 /// is matched, an empty slice will be the last item returned by the
864 /// let slice = [10, 40, 33];
865 /// let mut iter = slice.split(|num| num % 3 == 0);
867 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
868 /// assert_eq!(iter.next().unwrap(), &[]);
869 /// assert!(iter.next().is_none());
872 /// If two matched elements are directly adjacent, an empty slice will be
873 /// present between them:
876 /// let slice = [10, 6, 33, 20];
877 /// let mut iter = slice.split(|num| num % 3 == 0);
879 /// assert_eq!(iter.next().unwrap(), &[10]);
880 /// assert_eq!(iter.next().unwrap(), &[]);
881 /// assert_eq!(iter.next().unwrap(), &[20]);
882 /// assert!(iter.next().is_none());
884 #[stable(feature = "rust1", since = "1.0.0")]
886 pub fn split<F>(&self, pred: F) -> Split<T, F>
887 where F: FnMut(&T) -> bool
896 /// Returns an iterator over mutable subslices separated by elements that
897 /// match `pred`. The matched element is not contained in the subslices.
902 /// let mut v = [10, 40, 30, 20, 60, 50];
904 /// for group in v.split_mut(|num| *num % 3 == 0) {
907 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
909 #[stable(feature = "rust1", since = "1.0.0")]
911 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
912 where F: FnMut(&T) -> bool
914 SplitMut { v: self, pred, finished: false }
917 /// Returns an iterator over subslices separated by elements that match
918 /// `pred`, starting at the end of the slice and working backwards.
919 /// The matched element is not contained in the subslices.
924 /// let slice = [11, 22, 33, 0, 44, 55];
925 /// let mut iter = slice.rsplit(|num| *num == 0);
927 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
928 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
929 /// assert_eq!(iter.next(), None);
932 /// As with `split()`, if the first or last element is matched, an empty
933 /// slice will be the first (or last) item returned by the iterator.
936 /// let v = &[0, 1, 1, 2, 3, 5, 8];
937 /// let mut it = v.rsplit(|n| *n % 2 == 0);
938 /// assert_eq!(it.next().unwrap(), &[]);
939 /// assert_eq!(it.next().unwrap(), &[3, 5]);
940 /// assert_eq!(it.next().unwrap(), &[1, 1]);
941 /// assert_eq!(it.next().unwrap(), &[]);
942 /// assert_eq!(it.next(), None);
944 #[stable(feature = "slice_rsplit", since = "1.27.0")]
946 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
947 where F: FnMut(&T) -> bool
949 RSplit { inner: self.split(pred) }
952 /// Returns an iterator over mutable subslices separated by elements that
953 /// match `pred`, starting at the end of the slice and working
954 /// backwards. The matched element is not contained in the subslices.
959 /// let mut v = [100, 400, 300, 200, 600, 500];
961 /// let mut count = 0;
962 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
964 /// group[0] = count;
966 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
969 #[stable(feature = "slice_rsplit", since = "1.27.0")]
971 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
972 where F: FnMut(&T) -> bool
974 RSplitMut { inner: self.split_mut(pred) }
977 /// Returns an iterator over subslices separated by elements that match
978 /// `pred`, limited to returning at most `n` items. The matched element is
979 /// not contained in the subslices.
981 /// The last element returned, if any, will contain the remainder of the
986 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
990 /// let v = [10, 40, 30, 20, 60, 50];
992 /// for group in v.splitn(2, |num| *num % 3 == 0) {
993 /// println!("{:?}", group);
996 #[stable(feature = "rust1", since = "1.0.0")]
998 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
999 where F: FnMut(&T) -> bool
1002 inner: GenericSplitN {
1003 iter: self.split(pred),
1009 /// Returns an iterator over subslices separated by elements that match
1010 /// `pred`, limited to returning at most `n` items. The matched element is
1011 /// not contained in the subslices.
1013 /// The last element returned, if any, will contain the remainder of the
1019 /// let mut v = [10, 40, 30, 20, 60, 50];
1021 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1024 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1026 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1029 where F: FnMut(&T) -> bool
1032 inner: GenericSplitN {
1033 iter: self.split_mut(pred),
1039 /// Returns an iterator over subslices separated by elements that match
1040 /// `pred` limited to returning at most `n` items. This starts at the end of
1041 /// the slice and works backwards. The matched element is not contained in
1044 /// The last element returned, if any, will contain the remainder of the
1049 /// Print the slice split once, starting from the end, by numbers divisible
1050 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1053 /// let v = [10, 40, 30, 20, 60, 50];
1055 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1056 /// println!("{:?}", group);
1059 #[stable(feature = "rust1", since = "1.0.0")]
1061 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1062 where F: FnMut(&T) -> bool
1065 inner: GenericSplitN {
1066 iter: self.rsplit(pred),
1072 /// Returns an iterator over subslices separated by elements that match
1073 /// `pred` limited to returning at most `n` items. This starts at the end of
1074 /// the slice and works backwards. The matched element is not contained in
1077 /// The last element returned, if any, will contain the remainder of the
1083 /// let mut s = [10, 40, 30, 20, 60, 50];
1085 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1088 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1090 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1093 where F: FnMut(&T) -> bool
1096 inner: GenericSplitN {
1097 iter: self.rsplit_mut(pred),
1103 /// Returns `true` if the slice contains an element with the given value.
1108 /// let v = [10, 40, 30];
1109 /// assert!(v.contains(&30));
1110 /// assert!(!v.contains(&50));
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn contains(&self, x: &T) -> bool
1116 x.slice_contains(self)
1119 /// Returns `true` if `needle` is a prefix of the slice.
1124 /// let v = [10, 40, 30];
1125 /// assert!(v.starts_with(&[10]));
1126 /// assert!(v.starts_with(&[10, 40]));
1127 /// assert!(!v.starts_with(&[50]));
1128 /// assert!(!v.starts_with(&[10, 50]));
1131 /// Always returns `true` if `needle` is an empty slice:
1134 /// let v = &[10, 40, 30];
1135 /// assert!(v.starts_with(&[]));
1136 /// let v: &[u8] = &[];
1137 /// assert!(v.starts_with(&[]));
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub fn starts_with(&self, needle: &[T]) -> bool
1143 let n = needle.len();
1144 self.len() >= n && needle == &self[..n]
1147 /// Returns `true` if `needle` is a suffix of the slice.
1152 /// let v = [10, 40, 30];
1153 /// assert!(v.ends_with(&[30]));
1154 /// assert!(v.ends_with(&[40, 30]));
1155 /// assert!(!v.ends_with(&[50]));
1156 /// assert!(!v.ends_with(&[50, 30]));
1159 /// Always returns `true` if `needle` is an empty slice:
1162 /// let v = &[10, 40, 30];
1163 /// assert!(v.ends_with(&[]));
1164 /// let v: &[u8] = &[];
1165 /// assert!(v.ends_with(&[]));
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn ends_with(&self, needle: &[T]) -> bool
1171 let (m, n) = (self.len(), needle.len());
1172 m >= n && needle == &self[m-n..]
1175 /// Binary searches this sorted slice for a given element.
1177 /// If the value is found then `Ok` is returned, containing the
1178 /// index of the matching element; if the value is not found then
1179 /// `Err` is returned, containing the index where a matching
1180 /// element could be inserted while maintaining sorted order.
1184 /// Looks up a series of four elements. The first is found, with a
1185 /// uniquely determined position; the second and third are not
1186 /// found; the fourth could match any position in `[1, 4]`.
1189 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1191 /// assert_eq!(s.binary_search(&13), Ok(9));
1192 /// assert_eq!(s.binary_search(&4), Err(7));
1193 /// assert_eq!(s.binary_search(&100), Err(13));
1194 /// let r = s.binary_search(&1);
1195 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1201 self.binary_search_by(|p| p.cmp(x))
1204 /// Binary searches this sorted slice with a comparator function.
1206 /// The comparator function should implement an order consistent
1207 /// with the sort order of the underlying slice, returning an
1208 /// order code that indicates whether its argument is `Less`,
1209 /// `Equal` or `Greater` the desired target.
1211 /// If a matching value is found then returns `Ok`, containing
1212 /// the index for the matched element; if no match is found then
1213 /// `Err` is returned, containing the index where a matching
1214 /// element could be inserted while maintaining sorted order.
1218 /// Looks up a series of four elements. The first is found, with a
1219 /// uniquely determined position; the second and third are not
1220 /// found; the fourth could match any position in `[1, 4]`.
1223 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1226 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1228 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1230 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1232 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1233 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1235 #[stable(feature = "rust1", since = "1.0.0")]
1237 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1238 where F: FnMut(&'a T) -> Ordering
1241 let mut size = s.len();
1245 let mut base = 0usize;
1247 let half = size / 2;
1248 let mid = base + half;
1249 // mid is always in [0, size), that means mid is >= 0 and < size.
1250 // mid >= 0: by definition
1251 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1252 let cmp = f(unsafe { s.get_unchecked(mid) });
1253 base = if cmp == Greater { base } else { mid };
1256 // base is always in [0, size) because base <= mid.
1257 let cmp = f(unsafe { s.get_unchecked(base) });
1258 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1262 /// Binary searches this sorted slice with a key extraction function.
1264 /// Assumes that the slice is sorted by the key, for instance with
1265 /// [`sort_by_key`] using the same key extraction function.
1267 /// If a matching value is found then returns `Ok`, containing the
1268 /// index for the matched element; if no match is found then `Err`
1269 /// is returned, containing the index where a matching element could
1270 /// be inserted while maintaining sorted order.
1272 /// [`sort_by_key`]: #method.sort_by_key
1276 /// Looks up a series of four elements in a slice of pairs sorted by
1277 /// their second elements. The first is found, with a uniquely
1278 /// determined position; the second and third are not found; the
1279 /// fourth could match any position in `[1, 4]`.
1282 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1283 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1284 /// (1, 21), (2, 34), (4, 55)];
1286 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1287 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1288 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1289 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1290 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1292 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1294 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1295 where F: FnMut(&'a T) -> B,
1298 self.binary_search_by(|k| f(k).cmp(b))
1301 /// Sorts the slice, but may not preserve the order of equal elements.
1303 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1304 /// and `O(n log n)` worst-case.
1306 /// # Current implementation
1308 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1309 /// which combines the fast average case of randomized quicksort with the fast worst case of
1310 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1311 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1312 /// deterministic behavior.
1314 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1315 /// slice consists of several concatenated sorted sequences.
1320 /// let mut v = [-5, 4, 1, -3, 2];
1322 /// v.sort_unstable();
1323 /// assert!(v == [-5, -3, 1, 2, 4]);
1326 /// [pdqsort]: https://github.com/orlp/pdqsort
1327 #[stable(feature = "sort_unstable", since = "1.20.0")]
1329 pub fn sort_unstable(&mut self)
1332 sort::quicksort(self, |a, b| a.lt(b));
1335 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1338 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1339 /// and `O(n log n)` worst-case.
1341 /// # Current implementation
1343 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1344 /// which combines the fast average case of randomized quicksort with the fast worst case of
1345 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1346 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1347 /// deterministic behavior.
1349 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1350 /// slice consists of several concatenated sorted sequences.
1355 /// let mut v = [5, 4, 1, 3, 2];
1356 /// v.sort_unstable_by(|a, b| a.cmp(b));
1357 /// assert!(v == [1, 2, 3, 4, 5]);
1359 /// // reverse sorting
1360 /// v.sort_unstable_by(|a, b| b.cmp(a));
1361 /// assert!(v == [5, 4, 3, 2, 1]);
1364 /// [pdqsort]: https://github.com/orlp/pdqsort
1365 #[stable(feature = "sort_unstable", since = "1.20.0")]
1367 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1368 where F: FnMut(&T, &T) -> Ordering
1370 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1373 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1376 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1377 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1379 /// # Current implementation
1381 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1382 /// which combines the fast average case of randomized quicksort with the fast worst case of
1383 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1384 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1385 /// deterministic behavior.
1390 /// let mut v = [-5i32, 4, 1, -3, 2];
1392 /// v.sort_unstable_by_key(|k| k.abs());
1393 /// assert!(v == [1, 2, -3, 4, -5]);
1396 /// [pdqsort]: https://github.com/orlp/pdqsort
1397 #[stable(feature = "sort_unstable", since = "1.20.0")]
1399 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1400 where F: FnMut(&T) -> K, K: Ord
1402 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1405 /// Rotates the slice in-place such that the first `mid` elements of the
1406 /// slice move to the end while the last `self.len() - mid` elements move to
1407 /// the front. After calling `rotate_left`, the element previously at index
1408 /// `mid` will become the first element in the slice.
1412 /// This function will panic if `mid` is greater than the length of the
1413 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1418 /// Takes linear (in `self.len()`) time.
1423 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1424 /// a.rotate_left(2);
1425 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1428 /// Rotating a subslice:
1431 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1432 /// a[1..5].rotate_left(1);
1433 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1435 #[stable(feature = "slice_rotate", since = "1.26.0")]
1436 pub fn rotate_left(&mut self, mid: usize) {
1437 assert!(mid <= self.len());
1438 let k = self.len() - mid;
1441 let p = self.as_mut_ptr();
1442 rotate::ptr_rotate(mid, p.add(mid), k);
1446 /// Rotates the slice in-place such that the first `self.len() - k`
1447 /// elements of the slice move to the end while the last `k` elements move
1448 /// to the front. After calling `rotate_right`, the element previously at
1449 /// index `self.len() - k` will become the first element in the slice.
1453 /// This function will panic if `k` is greater than the length of the
1454 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1459 /// Takes linear (in `self.len()`) time.
1464 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1465 /// a.rotate_right(2);
1466 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1469 /// Rotate a subslice:
1472 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1473 /// a[1..5].rotate_right(1);
1474 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1476 #[stable(feature = "slice_rotate", since = "1.26.0")]
1477 pub fn rotate_right(&mut self, k: usize) {
1478 assert!(k <= self.len());
1479 let mid = self.len() - k;
1482 let p = self.as_mut_ptr();
1483 rotate::ptr_rotate(mid, p.add(mid), k);
1487 /// Copies the elements from `src` into `self`.
1489 /// The length of `src` must be the same as `self`.
1491 /// If `src` implements `Copy`, it can be more performant to use
1492 /// [`copy_from_slice`].
1496 /// This function will panic if the two slices have different lengths.
1500 /// Cloning two elements from a slice into another:
1503 /// let src = [1, 2, 3, 4];
1504 /// let mut dst = [0, 0];
1506 /// // Because the slices have to be the same length,
1507 /// // we slice the source slice from four elements
1508 /// // to two. It will panic if we don't do this.
1509 /// dst.clone_from_slice(&src[2..]);
1511 /// assert_eq!(src, [1, 2, 3, 4]);
1512 /// assert_eq!(dst, [3, 4]);
1515 /// Rust enforces that there can only be one mutable reference with no
1516 /// immutable references to a particular piece of data in a particular
1517 /// scope. Because of this, attempting to use `clone_from_slice` on a
1518 /// single slice will result in a compile failure:
1521 /// let mut slice = [1, 2, 3, 4, 5];
1523 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1526 /// To work around this, we can use [`split_at_mut`] to create two distinct
1527 /// sub-slices from a slice:
1530 /// let mut slice = [1, 2, 3, 4, 5];
1533 /// let (left, right) = slice.split_at_mut(2);
1534 /// left.clone_from_slice(&right[1..]);
1537 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1540 /// [`copy_from_slice`]: #method.copy_from_slice
1541 /// [`split_at_mut`]: #method.split_at_mut
1542 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1543 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1544 assert!(self.len() == src.len(),
1545 "destination and source slices have different lengths");
1546 // NOTE: We need to explicitly slice them to the same length
1547 // for bounds checking to be elided, and the optimizer will
1548 // generate memcpy for simple cases (for example T = u8).
1549 let len = self.len();
1550 let src = &src[..len];
1552 self[i].clone_from(&src[i]);
1557 /// Copies all elements from `src` into `self`, using a memcpy.
1559 /// The length of `src` must be the same as `self`.
1561 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1565 /// This function will panic if the two slices have different lengths.
1569 /// Copying two elements from a slice into another:
1572 /// let src = [1, 2, 3, 4];
1573 /// let mut dst = [0, 0];
1575 /// // Because the slices have to be the same length,
1576 /// // we slice the source slice from four elements
1577 /// // to two. It will panic if we don't do this.
1578 /// dst.copy_from_slice(&src[2..]);
1580 /// assert_eq!(src, [1, 2, 3, 4]);
1581 /// assert_eq!(dst, [3, 4]);
1584 /// Rust enforces that there can only be one mutable reference with no
1585 /// immutable references to a particular piece of data in a particular
1586 /// scope. Because of this, attempting to use `copy_from_slice` on a
1587 /// single slice will result in a compile failure:
1590 /// let mut slice = [1, 2, 3, 4, 5];
1592 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1595 /// To work around this, we can use [`split_at_mut`] to create two distinct
1596 /// sub-slices from a slice:
1599 /// let mut slice = [1, 2, 3, 4, 5];
1602 /// let (left, right) = slice.split_at_mut(2);
1603 /// left.copy_from_slice(&right[1..]);
1606 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1609 /// [`clone_from_slice`]: #method.clone_from_slice
1610 /// [`split_at_mut`]: #method.split_at_mut
1611 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1612 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1613 assert_eq!(self.len(), src.len(),
1614 "destination and source slices have different lengths");
1616 ptr::copy_nonoverlapping(
1617 src.as_ptr(), self.as_mut_ptr(), self.len());
1621 /// Copies elements from one part of the slice to another part of itself,
1622 /// using a memmove.
1624 /// `src` is the range within `self` to copy from. `dest` is the starting
1625 /// index of the range within `self` to copy to, which will have the same
1626 /// length as `src`. The two ranges may overlap. The ends of the two ranges
1627 /// must be less than or equal to `self.len()`.
1631 /// This function will panic if either range exceeds the end of the slice,
1632 /// or if the end of `src` is before the start.
1636 /// Copying four bytes within a slice:
1639 /// # #![feature(copy_within)]
1640 /// let mut bytes = *b"Hello, World!";
1642 /// bytes.copy_within(1..5, 8);
1644 /// assert_eq!(&bytes, b"Hello, Wello!");
1646 #[unstable(feature = "copy_within", issue = "54236")]
1647 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
1651 let src_start = match src.start_bound() {
1652 ops::Bound::Included(&n) => n,
1653 ops::Bound::Excluded(&n) => n
1655 .unwrap_or_else(|| slice_index_overflow_fail()),
1656 ops::Bound::Unbounded => 0,
1658 let src_end = match src.end_bound() {
1659 ops::Bound::Included(&n) => n
1661 .unwrap_or_else(|| slice_index_overflow_fail()),
1662 ops::Bound::Excluded(&n) => n,
1663 ops::Bound::Unbounded => self.len(),
1665 assert!(src_start <= src_end, "src end is before src start");
1666 assert!(src_end <= self.len(), "src is out of bounds");
1667 let count = src_end - src_start;
1668 assert!(dest <= self.len() - count, "dest is out of bounds");
1671 self.get_unchecked(src_start),
1672 self.get_unchecked_mut(dest),
1678 /// Swaps all elements in `self` with those in `other`.
1680 /// The length of `other` must be the same as `self`.
1684 /// This function will panic if the two slices have different lengths.
1688 /// Swapping two elements across slices:
1691 /// let mut slice1 = [0, 0];
1692 /// let mut slice2 = [1, 2, 3, 4];
1694 /// slice1.swap_with_slice(&mut slice2[2..]);
1696 /// assert_eq!(slice1, [3, 4]);
1697 /// assert_eq!(slice2, [1, 2, 0, 0]);
1700 /// Rust enforces that there can only be one mutable reference to a
1701 /// particular piece of data in a particular scope. Because of this,
1702 /// attempting to use `swap_with_slice` on a single slice will result in
1703 /// a compile failure:
1706 /// let mut slice = [1, 2, 3, 4, 5];
1707 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
1710 /// To work around this, we can use [`split_at_mut`] to create two distinct
1711 /// mutable sub-slices from a slice:
1714 /// let mut slice = [1, 2, 3, 4, 5];
1717 /// let (left, right) = slice.split_at_mut(2);
1718 /// left.swap_with_slice(&mut right[1..]);
1721 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
1724 /// [`split_at_mut`]: #method.split_at_mut
1725 #[stable(feature = "swap_with_slice", since = "1.27.0")]
1726 pub fn swap_with_slice(&mut self, other: &mut [T]) {
1727 assert!(self.len() == other.len(),
1728 "destination and source slices have different lengths");
1730 ptr::swap_nonoverlapping(
1731 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
1735 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
1736 fn align_to_offsets<U>(&self) -> (usize, usize) {
1737 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
1738 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
1740 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
1741 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
1742 // place of every 3 Ts in the `rest` slice. A bit more complicated.
1744 // Formula to calculate this is:
1746 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
1747 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
1749 // Expanded and simplified:
1751 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
1752 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
1754 // Luckily since all this is constant-evaluated... performance here matters not!
1756 fn gcd(a: usize, b: usize) -> usize {
1757 // iterative stein’s algorithm
1758 // We should still make this `const fn` (and revert to recursive algorithm if we do)
1759 // because relying on llvm to consteval all this is… well, it makes me
1760 let (ctz_a, mut ctz_b) = unsafe {
1761 if a == 0 { return b; }
1762 if b == 0 { return a; }
1763 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
1765 let k = ctz_a.min(ctz_b);
1766 let mut a = a >> ctz_a;
1769 // remove all factors of 2 from b
1772 ::mem::swap(&mut a, &mut b);
1779 ctz_b = ::intrinsics::cttz_nonzero(b);
1784 let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
1785 let ts: usize = ::mem::size_of::<U>() / gcd;
1786 let us: usize = ::mem::size_of::<T>() / gcd;
1788 // Armed with this knowledge, we can find how many `U`s we can fit!
1789 let us_len = self.len() / ts * us;
1790 // And how many `T`s will be in the trailing slice!
1791 let ts_len = self.len() % ts;
1795 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
1798 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1799 /// slice of a new type, and the suffix slice. The method does a best effort to make the
1800 /// middle slice the greatest length possible for a given type and input slice, but only
1801 /// your algorithm's performance should depend on that, not its correctness.
1803 /// This method has no purpose when either input element `T` or output element `U` are
1804 /// zero-sized and will return the original slice without splitting anything.
1808 /// This method is essentially a `transmute` with respect to the elements in the returned
1809 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1817 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1818 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
1819 /// // less_efficient_algorithm_for_bytes(prefix);
1820 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1821 /// // less_efficient_algorithm_for_bytes(suffix);
1824 #[stable(feature = "slice_align_to", since = "1.30.0")]
1825 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
1826 // Note that most of this function will be constant-evaluated,
1827 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1828 // handle ZSTs specially, which is – don't handle them at all.
1829 return (self, &[], &[]);
1832 // First, find at what point do we split between the first and 2nd slice. Easy with
1833 // ptr.align_offset.
1834 let ptr = self.as_ptr();
1835 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1836 if offset > self.len() {
1839 let (left, rest) = self.split_at(offset);
1840 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
1841 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1843 from_raw_parts(rest.as_ptr() as *const U, us_len),
1844 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
1848 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
1851 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1852 /// slice of a new type, and the suffix slice. The method does a best effort to make the
1853 /// middle slice the greatest length possible for a given type and input slice, but only
1854 /// your algorithm's performance should depend on that, not its correctness.
1856 /// This method has no purpose when either input element `T` or output element `U` are
1857 /// zero-sized and will return the original slice without splitting anything.
1861 /// This method is essentially a `transmute` with respect to the elements in the returned
1862 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1870 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1871 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
1872 /// // less_efficient_algorithm_for_bytes(prefix);
1873 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1874 /// // less_efficient_algorithm_for_bytes(suffix);
1877 #[stable(feature = "slice_align_to", since = "1.30.0")]
1878 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
1879 // Note that most of this function will be constant-evaluated,
1880 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1881 // handle ZSTs specially, which is – don't handle them at all.
1882 return (self, &mut [], &mut []);
1885 // First, find at what point do we split between the first and 2nd slice. Easy with
1886 // ptr.align_offset.
1887 let ptr = self.as_ptr();
1888 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1889 if offset > self.len() {
1890 (self, &mut [], &mut [])
1892 let (left, rest) = self.split_at_mut(offset);
1893 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
1894 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1895 let mut_ptr = rest.as_mut_ptr();
1897 from_raw_parts_mut(mut_ptr as *mut U, us_len),
1898 from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
1903 #[lang = "slice_u8"]
1906 /// Checks if all bytes in this slice are within the ASCII range.
1907 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1909 pub fn is_ascii(&self) -> bool {
1910 self.iter().all(|b| b.is_ascii())
1913 /// Checks that two slices are an ASCII case-insensitive match.
1915 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1916 /// but without allocating and copying temporaries.
1917 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1919 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
1920 self.len() == other.len() &&
1921 self.iter().zip(other).all(|(a, b)| {
1922 a.eq_ignore_ascii_case(b)
1926 /// Converts this slice to its ASCII upper case equivalent in-place.
1928 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1929 /// but non-ASCII letters are unchanged.
1931 /// To return a new uppercased value without modifying the existing one, use
1932 /// [`to_ascii_uppercase`].
1934 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1935 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1937 pub fn make_ascii_uppercase(&mut self) {
1939 byte.make_ascii_uppercase();
1943 /// Converts this slice to its ASCII lower case equivalent in-place.
1945 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1946 /// but non-ASCII letters are unchanged.
1948 /// To return a new lowercased value without modifying the existing one, use
1949 /// [`to_ascii_lowercase`].
1951 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1952 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1954 pub fn make_ascii_lowercase(&mut self) {
1956 byte.make_ascii_lowercase();
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1964 impl<T, I> ops::Index<I> for [T]
1965 where I: SliceIndex<[T]>
1967 type Output = I::Output;
1970 fn index(&self, index: I) -> &I::Output {
1975 #[stable(feature = "rust1", since = "1.0.0")]
1976 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1977 impl<T, I> ops::IndexMut<I> for [T]
1978 where I: SliceIndex<[T]>
1981 fn index_mut(&mut self, index: I) -> &mut I::Output {
1982 index.index_mut(self)
1988 fn slice_index_len_fail(index: usize, len: usize) -> ! {
1989 panic!("index {} out of range for slice of length {}", index, len);
1994 fn slice_index_order_fail(index: usize, end: usize) -> ! {
1995 panic!("slice index starts at {} but ends at {}", index, end);
2000 fn slice_index_overflow_fail() -> ! {
2001 panic!("attempted to index slice up to maximum usize");
2004 mod private_slice_index {
2006 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2009 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2010 impl Sealed for usize {}
2011 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2012 impl Sealed for ops::Range<usize> {}
2013 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2014 impl Sealed for ops::RangeTo<usize> {}
2015 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2016 impl Sealed for ops::RangeFrom<usize> {}
2017 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2018 impl Sealed for ops::RangeFull {}
2019 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2020 impl Sealed for ops::RangeInclusive<usize> {}
2021 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2022 impl Sealed for ops::RangeToInclusive<usize> {}
2025 /// A helper trait used for indexing operations.
2026 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2027 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2028 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2029 /// The output type returned by methods.
2030 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2031 type Output: ?Sized;
2033 /// Returns a shared reference to the output at this location, if in
2035 #[unstable(feature = "slice_index_methods", issue = "0")]
2036 fn get(self, slice: &T) -> Option<&Self::Output>;
2038 /// Returns a mutable reference to the output at this location, if in
2040 #[unstable(feature = "slice_index_methods", issue = "0")]
2041 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2043 /// Returns a shared reference to the output at this location, without
2044 /// performing any bounds checking.
2045 #[unstable(feature = "slice_index_methods", issue = "0")]
2046 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2048 /// Returns a mutable reference to the output at this location, without
2049 /// performing any bounds checking.
2050 #[unstable(feature = "slice_index_methods", issue = "0")]
2051 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2053 /// Returns a shared reference to the output at this location, panicking
2054 /// if out of bounds.
2055 #[unstable(feature = "slice_index_methods", issue = "0")]
2056 fn index(self, slice: &T) -> &Self::Output;
2058 /// Returns a mutable reference to the output at this location, panicking
2059 /// if out of bounds.
2060 #[unstable(feature = "slice_index_methods", issue = "0")]
2061 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2064 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2065 impl<T> SliceIndex<[T]> for usize {
2069 fn get(self, slice: &[T]) -> Option<&T> {
2070 if self < slice.len() {
2072 Some(self.get_unchecked(slice))
2080 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2081 if self < slice.len() {
2083 Some(self.get_unchecked_mut(slice))
2091 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2092 &*slice.as_ptr().add(self)
2096 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2097 &mut *slice.as_mut_ptr().add(self)
2101 fn index(self, slice: &[T]) -> &T {
2102 // NB: use intrinsic indexing
2107 fn index_mut(self, slice: &mut [T]) -> &mut T {
2108 // NB: use intrinsic indexing
2113 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2114 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2118 fn get(self, slice: &[T]) -> Option<&[T]> {
2119 if self.start > self.end || self.end > slice.len() {
2123 Some(self.get_unchecked(slice))
2129 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2130 if self.start > self.end || self.end > slice.len() {
2134 Some(self.get_unchecked_mut(slice))
2140 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2141 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2145 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2146 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2150 fn index(self, slice: &[T]) -> &[T] {
2151 if self.start > self.end {
2152 slice_index_order_fail(self.start, self.end);
2153 } else if self.end > slice.len() {
2154 slice_index_len_fail(self.end, slice.len());
2157 self.get_unchecked(slice)
2162 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2163 if self.start > self.end {
2164 slice_index_order_fail(self.start, self.end);
2165 } else if self.end > slice.len() {
2166 slice_index_len_fail(self.end, slice.len());
2169 self.get_unchecked_mut(slice)
2174 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2175 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2179 fn get(self, slice: &[T]) -> Option<&[T]> {
2180 (0..self.end).get(slice)
2184 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2185 (0..self.end).get_mut(slice)
2189 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2190 (0..self.end).get_unchecked(slice)
2194 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2195 (0..self.end).get_unchecked_mut(slice)
2199 fn index(self, slice: &[T]) -> &[T] {
2200 (0..self.end).index(slice)
2204 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2205 (0..self.end).index_mut(slice)
2209 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2210 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2214 fn get(self, slice: &[T]) -> Option<&[T]> {
2215 (self.start..slice.len()).get(slice)
2219 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2220 (self.start..slice.len()).get_mut(slice)
2224 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2225 (self.start..slice.len()).get_unchecked(slice)
2229 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2230 (self.start..slice.len()).get_unchecked_mut(slice)
2234 fn index(self, slice: &[T]) -> &[T] {
2235 (self.start..slice.len()).index(slice)
2239 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2240 (self.start..slice.len()).index_mut(slice)
2244 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2245 impl<T> SliceIndex<[T]> for ops::RangeFull {
2249 fn get(self, slice: &[T]) -> Option<&[T]> {
2254 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2259 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2264 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2269 fn index(self, slice: &[T]) -> &[T] {
2274 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2280 #[stable(feature = "inclusive_range", since = "1.26.0")]
2281 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2285 fn get(self, slice: &[T]) -> Option<&[T]> {
2286 if *self.end() == usize::max_value() { None }
2287 else { (*self.start()..self.end() + 1).get(slice) }
2291 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2292 if *self.end() == usize::max_value() { None }
2293 else { (*self.start()..self.end() + 1).get_mut(slice) }
2297 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2298 (*self.start()..self.end() + 1).get_unchecked(slice)
2302 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2303 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2307 fn index(self, slice: &[T]) -> &[T] {
2308 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2309 (*self.start()..self.end() + 1).index(slice)
2313 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2314 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2315 (*self.start()..self.end() + 1).index_mut(slice)
2319 #[stable(feature = "inclusive_range", since = "1.26.0")]
2320 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2324 fn get(self, slice: &[T]) -> Option<&[T]> {
2325 (0..=self.end).get(slice)
2329 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2330 (0..=self.end).get_mut(slice)
2334 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2335 (0..=self.end).get_unchecked(slice)
2339 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2340 (0..=self.end).get_unchecked_mut(slice)
2344 fn index(self, slice: &[T]) -> &[T] {
2345 (0..=self.end).index(slice)
2349 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2350 (0..=self.end).index_mut(slice)
2354 ////////////////////////////////////////////////////////////////////////////////
2356 ////////////////////////////////////////////////////////////////////////////////
2358 #[stable(feature = "rust1", since = "1.0.0")]
2359 impl<'a, T> Default for &'a [T] {
2360 /// Creates an empty slice.
2361 fn default() -> &'a [T] { &[] }
2364 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2365 impl<'a, T> Default for &'a mut [T] {
2366 /// Creates a mutable empty slice.
2367 fn default() -> &'a mut [T] { &mut [] }
2374 #[stable(feature = "rust1", since = "1.0.0")]
2375 impl<'a, T> IntoIterator for &'a [T] {
2377 type IntoIter = Iter<'a, T>;
2379 fn into_iter(self) -> Iter<'a, T> {
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<'a, T> IntoIterator for &'a mut [T] {
2386 type Item = &'a mut T;
2387 type IntoIter = IterMut<'a, T>;
2389 fn into_iter(self) -> IterMut<'a, T> {
2394 // Macro helper functions
2396 fn size_from_ptr<T>(_: *const T) -> usize {
2400 // Inlining is_empty and len makes a huge performance difference
2401 macro_rules! is_empty {
2402 // The way we encode the length of a ZST iterator, this works both for ZST
2404 ($self: ident) => {$self.ptr == $self.end}
2406 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2407 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2409 ($self: ident) => {{
2410 let start = $self.ptr;
2411 let diff = ($self.end as usize).wrapping_sub(start as usize);
2412 let size = size_from_ptr(start);
2416 // Using division instead of `offset_from` helps LLVM remove bounds checks
2422 // The shared definition of the `Iter` and `IterMut` iterators
2423 macro_rules! iterator {
2424 (struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
2425 impl<'a, T> $name<'a, T> {
2426 // Helper function for creating a slice from the iterator.
2428 fn make_slice(&self) -> &'a [T] {
2429 unsafe { from_raw_parts(self.ptr, len!(self)) }
2432 // Helper function for moving the start of the iterator forwards by `offset` elements,
2433 // returning the old start.
2434 // Unsafe because the offset must be in-bounds or one-past-the-end.
2436 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2437 if mem::size_of::<T>() == 0 {
2438 // This is *reducing* the length. `ptr` never changes with ZST.
2439 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2443 self.ptr = self.ptr.offset(offset);
2448 // Helper function for moving the end of the iterator backwards by `offset` elements,
2449 // returning the new end.
2450 // Unsafe because the offset must be in-bounds or one-past-the-end.
2452 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2453 if mem::size_of::<T>() == 0 {
2454 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2457 self.end = self.end.offset(-offset);
2463 #[stable(feature = "rust1", since = "1.0.0")]
2464 impl<'a, T> ExactSizeIterator for $name<'a, T> {
2466 fn len(&self) -> usize {
2471 fn is_empty(&self) -> bool {
2476 #[stable(feature = "rust1", since = "1.0.0")]
2477 impl<'a, T> Iterator for $name<'a, T> {
2481 fn next(&mut self) -> Option<$elem> {
2482 // could be implemented with slices, but this avoids bounds checks
2484 assume(!self.ptr.is_null());
2485 if mem::size_of::<T>() != 0 {
2486 assume(!self.end.is_null());
2488 if is_empty!(self) {
2491 Some(& $( $mut_ )* *self.post_inc_start(1))
2497 fn size_hint(&self) -> (usize, Option<usize>) {
2498 let exact = len!(self);
2499 (exact, Some(exact))
2503 fn count(self) -> usize {
2508 fn nth(&mut self, n: usize) -> Option<$elem> {
2509 if n >= len!(self) {
2510 // This iterator is now empty.
2511 if mem::size_of::<T>() == 0 {
2512 // We have to do it this way as `ptr` may never be 0, but `end`
2513 // could be (due to wrapping).
2514 self.end = self.ptr;
2516 self.ptr = self.end;
2520 // We are in bounds. `offset` does the right thing even for ZSTs.
2522 let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2523 self.post_inc_start((n as isize).wrapping_add(1));
2529 fn last(mut self) -> Option<$elem> {
2534 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2535 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2537 // manual unrolling is needed when there are conditional exits from the loop
2538 let mut accum = init;
2540 while len!(self) >= 4 {
2541 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2542 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2543 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2544 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2546 while !is_empty!(self) {
2547 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2554 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2555 where Fold: FnMut(Acc, Self::Item) -> Acc,
2557 // Let LLVM unroll this, rather than using the default
2558 // impl that would force the manual unrolling above
2559 let mut accum = init;
2560 while let Some(x) = self.next() {
2561 accum = f(accum, x);
2567 #[rustc_inherit_overflow_checks]
2568 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2570 P: FnMut(Self::Item) -> bool,
2572 // The addition might panic on overflow.
2574 self.try_fold(0, move |i, x| {
2575 if predicate(x) { Err(i) }
2579 unsafe { assume(i < n) };
2585 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2586 P: FnMut(Self::Item) -> bool,
2587 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2589 // No need for an overflow check here, because `ExactSizeIterator`
2591 self.try_rfold(n, move |i, x| {
2593 if predicate(x) { Err(i) }
2597 unsafe { assume(i < n) };
2603 #[stable(feature = "rust1", since = "1.0.0")]
2604 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2606 fn next_back(&mut self) -> Option<$elem> {
2607 // could be implemented with slices, but this avoids bounds checks
2609 assume(!self.ptr.is_null());
2610 if mem::size_of::<T>() != 0 {
2611 assume(!self.end.is_null());
2613 if is_empty!(self) {
2616 Some(& $( $mut_ )* *self.pre_dec_end(1))
2622 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2623 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2625 // manual unrolling is needed when there are conditional exits from the loop
2626 let mut accum = init;
2628 while len!(self) >= 4 {
2629 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2630 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2631 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2632 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2634 // inlining is_empty everywhere makes a huge performance difference
2635 while !is_empty!(self) {
2636 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2643 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2644 where Fold: FnMut(Acc, Self::Item) -> Acc,
2646 // Let LLVM unroll this, rather than using the default
2647 // impl that would force the manual unrolling above
2648 let mut accum = init;
2649 while let Some(x) = self.next_back() {
2650 accum = f(accum, x);
2656 #[stable(feature = "fused", since = "1.26.0")]
2657 impl<'a, T> FusedIterator for $name<'a, T> {}
2659 #[unstable(feature = "trusted_len", issue = "37572")]
2660 unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
2664 /// Immutable slice iterator
2666 /// This struct is created by the [`iter`] method on [slices].
2673 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2674 /// let slice = &[1, 2, 3];
2676 /// // Then, we iterate over it:
2677 /// for element in slice.iter() {
2678 /// println!("{}", element);
2682 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2683 /// [slices]: ../../std/primitive.slice.html
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 pub struct Iter<'a, T: 'a> {
2687 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
2688 // ptr == end is a quick test for the Iterator being empty, that works
2689 // for both ZST and non-ZST.
2690 _marker: marker::PhantomData<&'a T>,
2693 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2694 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2695 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2696 f.debug_tuple("Iter")
2697 .field(&self.as_slice())
2702 #[stable(feature = "rust1", since = "1.0.0")]
2703 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2704 #[stable(feature = "rust1", since = "1.0.0")]
2705 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2707 impl<'a, T> Iter<'a, T> {
2708 /// View the underlying data as a subslice of the original data.
2710 /// This has the same lifetime as the original slice, and so the
2711 /// iterator can continue to be used while this exists.
2718 /// // First, we declare a type which has the `iter` method to get the `Iter`
2719 /// // struct (&[usize here]):
2720 /// let slice = &[1, 2, 3];
2722 /// // Then, we get the iterator:
2723 /// let mut iter = slice.iter();
2724 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2725 /// println!("{:?}", iter.as_slice());
2727 /// // Next, we move to the second element of the slice:
2729 /// // Now `as_slice` returns "[2, 3]":
2730 /// println!("{:?}", iter.as_slice());
2732 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2733 pub fn as_slice(&self) -> &'a [T] {
2738 iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 impl<'a, T> Clone for Iter<'a, T> {
2742 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2745 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2746 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2747 fn as_ref(&self) -> &[T] {
2752 /// Mutable slice iterator.
2754 /// This struct is created by the [`iter_mut`] method on [slices].
2761 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2762 /// // struct (&[usize here]):
2763 /// let mut slice = &mut [1, 2, 3];
2765 /// // Then, we iterate over it and increment each element value:
2766 /// for element in slice.iter_mut() {
2770 /// // We now have "[2, 3, 4]":
2771 /// println!("{:?}", slice);
2774 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2775 /// [slices]: ../../std/primitive.slice.html
2776 #[stable(feature = "rust1", since = "1.0.0")]
2777 pub struct IterMut<'a, T: 'a> {
2779 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
2780 // ptr == end is a quick test for the Iterator being empty, that works
2781 // for both ZST and non-ZST.
2782 _marker: marker::PhantomData<&'a mut T>,
2785 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2786 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2788 f.debug_tuple("IterMut")
2789 .field(&self.make_slice())
2794 #[stable(feature = "rust1", since = "1.0.0")]
2795 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2796 #[stable(feature = "rust1", since = "1.0.0")]
2797 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2799 impl<'a, T> IterMut<'a, T> {
2800 /// View the underlying data as a subslice of the original data.
2802 /// To avoid creating `&mut` references that alias, this is forced
2803 /// to consume the iterator.
2810 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2811 /// // struct (&[usize here]):
2812 /// let mut slice = &mut [1, 2, 3];
2815 /// // Then, we get the iterator:
2816 /// let mut iter = slice.iter_mut();
2817 /// // We move to next element:
2819 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
2820 /// println!("{:?}", iter.into_slice());
2823 /// // Now let's modify a value of the slice:
2825 /// // First we get back the iterator:
2826 /// let mut iter = slice.iter_mut();
2827 /// // We change the value of the first element of the slice returned by the `next` method:
2828 /// *iter.next().unwrap() += 1;
2830 /// // Now slice is "[2, 2, 3]":
2831 /// println!("{:?}", slice);
2833 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2834 pub fn into_slice(self) -> &'a mut [T] {
2835 unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
2839 iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
2841 /// An internal abstraction over the splitting iterators, so that
2842 /// splitn, splitn_mut etc can be implemented once.
2844 trait SplitIter: DoubleEndedIterator {
2845 /// Marks the underlying iterator as complete, extracting the remaining
2846 /// portion of the slice.
2847 fn finish(&mut self) -> Option<Self::Item>;
2850 /// An iterator over subslices separated by elements that match a predicate
2853 /// This struct is created by the [`split`] method on [slices].
2855 /// [`split`]: ../../std/primitive.slice.html#method.split
2856 /// [slices]: ../../std/primitive.slice.html
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
2864 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2865 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
2866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2867 f.debug_struct("Split")
2868 .field("v", &self.v)
2869 .field("finished", &self.finished)
2874 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2875 #[stable(feature = "rust1", since = "1.0.0")]
2876 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
2877 fn clone(&self) -> Split<'a, T, P> {
2880 pred: self.pred.clone(),
2881 finished: self.finished,
2886 #[stable(feature = "rust1", since = "1.0.0")]
2887 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2888 type Item = &'a [T];
2891 fn next(&mut self) -> Option<&'a [T]> {
2892 if self.finished { return None; }
2894 match self.v.iter().position(|x| (self.pred)(x)) {
2895 None => self.finish(),
2897 let ret = Some(&self.v[..idx]);
2898 self.v = &self.v[idx + 1..];
2905 fn size_hint(&self) -> (usize, Option<usize>) {
2909 (1, Some(self.v.len() + 1))
2914 #[stable(feature = "rust1", since = "1.0.0")]
2915 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2917 fn next_back(&mut self) -> Option<&'a [T]> {
2918 if self.finished { return None; }
2920 match self.v.iter().rposition(|x| (self.pred)(x)) {
2921 None => self.finish(),
2923 let ret = Some(&self.v[idx + 1..]);
2924 self.v = &self.v[..idx];
2931 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
2933 fn finish(&mut self) -> Option<&'a [T]> {
2934 if self.finished { None } else { self.finished = true; Some(self.v) }
2938 #[stable(feature = "fused", since = "1.26.0")]
2939 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
2941 /// An iterator over the subslices of the vector which are separated
2942 /// by elements that match `pred`.
2944 /// This struct is created by the [`split_mut`] method on [slices].
2946 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
2947 /// [slices]: ../../std/primitive.slice.html
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
2955 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2956 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2957 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2958 f.debug_struct("SplitMut")
2959 .field("v", &self.v)
2960 .field("finished", &self.finished)
2965 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2967 fn finish(&mut self) -> Option<&'a mut [T]> {
2971 self.finished = true;
2972 Some(mem::replace(&mut self.v, &mut []))
2977 #[stable(feature = "rust1", since = "1.0.0")]
2978 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2979 type Item = &'a mut [T];
2982 fn next(&mut self) -> Option<&'a mut [T]> {
2983 if self.finished { return None; }
2985 let idx_opt = { // work around borrowck limitations
2986 let pred = &mut self.pred;
2987 self.v.iter().position(|x| (*pred)(x))
2990 None => self.finish(),
2992 let tmp = mem::replace(&mut self.v, &mut []);
2993 let (head, tail) = tmp.split_at_mut(idx);
2994 self.v = &mut tail[1..];
3001 fn size_hint(&self) -> (usize, Option<usize>) {
3005 // if the predicate doesn't match anything, we yield one slice
3006 // if it matches every element, we yield len+1 empty slices.
3007 (1, Some(self.v.len() + 1))
3012 #[stable(feature = "rust1", since = "1.0.0")]
3013 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3014 P: FnMut(&T) -> bool,
3017 fn next_back(&mut self) -> Option<&'a mut [T]> {
3018 if self.finished { return None; }
3020 let idx_opt = { // work around borrowck limitations
3021 let pred = &mut self.pred;
3022 self.v.iter().rposition(|x| (*pred)(x))
3025 None => self.finish(),
3027 let tmp = mem::replace(&mut self.v, &mut []);
3028 let (head, tail) = tmp.split_at_mut(idx);
3030 Some(&mut tail[1..])
3036 #[stable(feature = "fused", since = "1.26.0")]
3037 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3039 /// An iterator over subslices separated by elements that match a predicate
3040 /// function, starting from the end of the slice.
3042 /// This struct is created by the [`rsplit`] method on [slices].
3044 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3045 /// [slices]: ../../std/primitive.slice.html
3046 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3047 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3048 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3049 inner: Split<'a, T, P>
3052 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3053 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3055 f.debug_struct("RSplit")
3056 .field("v", &self.inner.v)
3057 .field("finished", &self.inner.finished)
3062 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3063 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3064 type Item = &'a [T];
3067 fn next(&mut self) -> Option<&'a [T]> {
3068 self.inner.next_back()
3072 fn size_hint(&self) -> (usize, Option<usize>) {
3073 self.inner.size_hint()
3077 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3078 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3080 fn next_back(&mut self) -> Option<&'a [T]> {
3085 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3086 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3088 fn finish(&mut self) -> Option<&'a [T]> {
3093 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3094 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
3096 /// An iterator over the subslices of the vector which are separated
3097 /// by elements that match `pred`, starting from the end of the slice.
3099 /// This struct is created by the [`rsplit_mut`] method on [slices].
3101 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3102 /// [slices]: ../../std/primitive.slice.html
3103 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3104 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3105 inner: SplitMut<'a, T, P>
3108 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3109 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3111 f.debug_struct("RSplitMut")
3112 .field("v", &self.inner.v)
3113 .field("finished", &self.inner.finished)
3118 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3119 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3121 fn finish(&mut self) -> Option<&'a mut [T]> {
3126 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3127 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3128 type Item = &'a mut [T];
3131 fn next(&mut self) -> Option<&'a mut [T]> {
3132 self.inner.next_back()
3136 fn size_hint(&self) -> (usize, Option<usize>) {
3137 self.inner.size_hint()
3141 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3142 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3143 P: FnMut(&T) -> bool,
3146 fn next_back(&mut self) -> Option<&'a mut [T]> {
3151 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3152 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3154 /// An private iterator over subslices separated by elements that
3155 /// match a predicate function, splitting at most a fixed number of
3158 struct GenericSplitN<I> {
3163 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3167 fn next(&mut self) -> Option<T> {
3170 1 => { self.count -= 1; self.iter.finish() }
3171 _ => { self.count -= 1; self.iter.next() }
3176 fn size_hint(&self) -> (usize, Option<usize>) {
3177 let (lower, upper_opt) = self.iter.size_hint();
3178 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3182 /// An iterator over subslices separated by elements that match a predicate
3183 /// function, limited to a given number of splits.
3185 /// This struct is created by the [`splitn`] method on [slices].
3187 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3188 /// [slices]: ../../std/primitive.slice.html
3189 #[stable(feature = "rust1", since = "1.0.0")]
3190 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3191 inner: GenericSplitN<Split<'a, T, P>>
3194 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3195 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
3196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3197 f.debug_struct("SplitN")
3198 .field("inner", &self.inner)
3203 /// An iterator over subslices separated by elements that match a
3204 /// predicate function, limited to a given number of splits, starting
3205 /// from the end of the slice.
3207 /// This struct is created by the [`rsplitn`] method on [slices].
3209 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3210 /// [slices]: ../../std/primitive.slice.html
3211 #[stable(feature = "rust1", since = "1.0.0")]
3212 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3213 inner: GenericSplitN<RSplit<'a, T, P>>
3216 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3217 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3219 f.debug_struct("RSplitN")
3220 .field("inner", &self.inner)
3225 /// An iterator over subslices separated by elements that match a predicate
3226 /// function, limited to a given number of splits.
3228 /// This struct is created by the [`splitn_mut`] method on [slices].
3230 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3231 /// [slices]: ../../std/primitive.slice.html
3232 #[stable(feature = "rust1", since = "1.0.0")]
3233 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3234 inner: GenericSplitN<SplitMut<'a, T, P>>
3237 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3238 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3240 f.debug_struct("SplitNMut")
3241 .field("inner", &self.inner)
3246 /// An iterator over subslices separated by elements that match a
3247 /// predicate function, limited to a given number of splits, starting
3248 /// from the end of the slice.
3250 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3252 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3253 /// [slices]: ../../std/primitive.slice.html
3254 #[stable(feature = "rust1", since = "1.0.0")]
3255 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3256 inner: GenericSplitN<RSplitMut<'a, T, P>>
3259 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3260 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3261 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3262 f.debug_struct("RSplitNMut")
3263 .field("inner", &self.inner)
3268 macro_rules! forward_iterator {
3269 ($name:ident: $elem:ident, $iter_of:ty) => {
3270 #[stable(feature = "rust1", since = "1.0.0")]
3271 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3272 P: FnMut(&T) -> bool
3274 type Item = $iter_of;
3277 fn next(&mut self) -> Option<$iter_of> {
3282 fn size_hint(&self) -> (usize, Option<usize>) {
3283 self.inner.size_hint()
3287 #[stable(feature = "fused", since = "1.26.0")]
3288 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3289 where P: FnMut(&T) -> bool {}
3293 forward_iterator! { SplitN: T, &'a [T] }
3294 forward_iterator! { RSplitN: T, &'a [T] }
3295 forward_iterator! { SplitNMut: T, &'a mut [T] }
3296 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3298 /// An iterator over overlapping subslices of length `size`.
3300 /// This struct is created by the [`windows`] method on [slices].
3302 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3303 /// [slices]: ../../std/primitive.slice.html
3305 #[stable(feature = "rust1", since = "1.0.0")]
3306 pub struct Windows<'a, T:'a> {
3311 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3312 #[stable(feature = "rust1", since = "1.0.0")]
3313 impl<'a, T> Clone for Windows<'a, T> {
3314 fn clone(&self) -> Windows<'a, T> {
3322 #[stable(feature = "rust1", since = "1.0.0")]
3323 impl<'a, T> Iterator for Windows<'a, T> {
3324 type Item = &'a [T];
3327 fn next(&mut self) -> Option<&'a [T]> {
3328 if self.size > self.v.len() {
3331 let ret = Some(&self.v[..self.size]);
3332 self.v = &self.v[1..];
3338 fn size_hint(&self) -> (usize, Option<usize>) {
3339 if self.size > self.v.len() {
3342 let size = self.v.len() - self.size + 1;
3348 fn count(self) -> usize {
3353 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3354 let (end, overflow) = self.size.overflowing_add(n);
3355 if end > self.v.len() || overflow {
3359 let nth = &self.v[n..end];
3360 self.v = &self.v[n+1..];
3366 fn last(self) -> Option<Self::Item> {
3367 if self.size > self.v.len() {
3370 let start = self.v.len() - self.size;
3371 Some(&self.v[start..])
3376 #[stable(feature = "rust1", since = "1.0.0")]
3377 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3379 fn next_back(&mut self) -> Option<&'a [T]> {
3380 if self.size > self.v.len() {
3383 let ret = Some(&self.v[self.v.len()-self.size..]);
3384 self.v = &self.v[..self.v.len()-1];
3390 #[stable(feature = "rust1", since = "1.0.0")]
3391 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3393 #[unstable(feature = "trusted_len", issue = "37572")]
3394 unsafe impl<'a, T> TrustedLen for Windows<'a, T> {}
3396 #[stable(feature = "fused", since = "1.26.0")]
3397 impl<'a, T> FusedIterator for Windows<'a, T> {}
3400 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3401 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3402 from_raw_parts(self.v.as_ptr().add(i), self.size)
3404 fn may_have_side_effect() -> bool { false }
3407 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3410 /// When the slice len is not evenly divided by the chunk size, the last slice
3411 /// of the iteration will be the remainder.
3413 /// This struct is created by the [`chunks`] method on [slices].
3415 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3416 /// [slices]: ../../std/primitive.slice.html
3418 #[stable(feature = "rust1", since = "1.0.0")]
3419 pub struct Chunks<'a, T:'a> {
3424 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3425 #[stable(feature = "rust1", since = "1.0.0")]
3426 impl<'a, T> Clone for Chunks<'a, T> {
3427 fn clone(&self) -> Chunks<'a, T> {
3430 chunk_size: self.chunk_size,
3435 #[stable(feature = "rust1", since = "1.0.0")]
3436 impl<'a, T> Iterator for Chunks<'a, T> {
3437 type Item = &'a [T];
3440 fn next(&mut self) -> Option<&'a [T]> {
3441 if self.v.is_empty() {
3444 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3445 let (fst, snd) = self.v.split_at(chunksz);
3452 fn size_hint(&self) -> (usize, Option<usize>) {
3453 if self.v.is_empty() {
3456 let n = self.v.len() / self.chunk_size;
3457 let rem = self.v.len() % self.chunk_size;
3458 let n = if rem > 0 { n+1 } else { n };
3464 fn count(self) -> usize {
3469 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3470 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3471 if start >= self.v.len() || overflow {
3475 let end = match start.checked_add(self.chunk_size) {
3476 Some(sum) => cmp::min(self.v.len(), sum),
3477 None => self.v.len(),
3479 let nth = &self.v[start..end];
3480 self.v = &self.v[end..];
3486 fn last(self) -> Option<Self::Item> {
3487 if self.v.is_empty() {
3490 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3491 Some(&self.v[start..])
3496 #[stable(feature = "rust1", since = "1.0.0")]
3497 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3499 fn next_back(&mut self) -> Option<&'a [T]> {
3500 if self.v.is_empty() {
3503 let remainder = self.v.len() % self.chunk_size;
3504 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3505 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3512 #[stable(feature = "rust1", since = "1.0.0")]
3513 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3515 #[unstable(feature = "trusted_len", issue = "37572")]
3516 unsafe impl<'a, T> TrustedLen for Chunks<'a, T> {}
3518 #[stable(feature = "fused", since = "1.26.0")]
3519 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3522 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3523 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3524 let start = i * self.chunk_size;
3525 let end = match start.checked_add(self.chunk_size) {
3526 None => self.v.len(),
3527 Some(end) => cmp::min(end, self.v.len()),
3529 from_raw_parts(self.v.as_ptr().add(start), end - start)
3531 fn may_have_side_effect() -> bool { false }
3534 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3535 /// elements at a time). When the slice len is not evenly divided by the chunk
3536 /// size, the last slice of the iteration will be the remainder.
3538 /// This struct is created by the [`chunks_mut`] method on [slices].
3540 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3541 /// [slices]: ../../std/primitive.slice.html
3543 #[stable(feature = "rust1", since = "1.0.0")]
3544 pub struct ChunksMut<'a, T:'a> {
3549 #[stable(feature = "rust1", since = "1.0.0")]
3550 impl<'a, T> Iterator for ChunksMut<'a, T> {
3551 type Item = &'a mut [T];
3554 fn next(&mut self) -> Option<&'a mut [T]> {
3555 if self.v.is_empty() {
3558 let sz = cmp::min(self.v.len(), self.chunk_size);
3559 let tmp = mem::replace(&mut self.v, &mut []);
3560 let (head, tail) = tmp.split_at_mut(sz);
3567 fn size_hint(&self) -> (usize, Option<usize>) {
3568 if self.v.is_empty() {
3571 let n = self.v.len() / self.chunk_size;
3572 let rem = self.v.len() % self.chunk_size;
3573 let n = if rem > 0 { n + 1 } else { n };
3579 fn count(self) -> usize {
3584 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3585 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3586 if start >= self.v.len() || overflow {
3590 let end = match start.checked_add(self.chunk_size) {
3591 Some(sum) => cmp::min(self.v.len(), sum),
3592 None => self.v.len(),
3594 let tmp = mem::replace(&mut self.v, &mut []);
3595 let (head, tail) = tmp.split_at_mut(end);
3596 let (_, nth) = head.split_at_mut(start);
3603 fn last(self) -> Option<Self::Item> {
3604 if self.v.is_empty() {
3607 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3608 Some(&mut self.v[start..])
3613 #[stable(feature = "rust1", since = "1.0.0")]
3614 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3616 fn next_back(&mut self) -> Option<&'a mut [T]> {
3617 if self.v.is_empty() {
3620 let remainder = self.v.len() % self.chunk_size;
3621 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3622 let tmp = mem::replace(&mut self.v, &mut []);
3623 let tmp_len = tmp.len();
3624 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3631 #[stable(feature = "rust1", since = "1.0.0")]
3632 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3634 #[unstable(feature = "trusted_len", issue = "37572")]
3635 unsafe impl<'a, T> TrustedLen for ChunksMut<'a, T> {}
3637 #[stable(feature = "fused", since = "1.26.0")]
3638 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3641 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3642 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3643 let start = i * self.chunk_size;
3644 let end = match start.checked_add(self.chunk_size) {
3645 None => self.v.len(),
3646 Some(end) => cmp::min(end, self.v.len()),
3648 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
3650 fn may_have_side_effect() -> bool { false }
3653 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3656 /// When the slice len is not evenly divided by the chunk size, the last
3657 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
3658 /// the [`remainder`] function from the iterator.
3660 /// This struct is created by the [`exact_chunks`] method on [slices].
3662 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3663 /// [`remainder`]: ../../std/slice/struct.ExactChunks.html#method.remainder
3664 /// [slices]: ../../std/primitive.slice.html
3666 #[unstable(feature = "exact_chunks", issue = "47115")]
3667 pub struct ExactChunks<'a, T:'a> {
3673 #[unstable(feature = "exact_chunks", issue = "47115")]
3674 impl<'a, T> ExactChunks<'a, T> {
3675 /// Return the remainder of the original slice that is not going to be
3676 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3678 pub fn remainder(&self) -> &'a [T] {
3683 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3684 #[unstable(feature = "exact_chunks", issue = "47115")]
3685 impl<'a, T> Clone for ExactChunks<'a, T> {
3686 fn clone(&self) -> ExactChunks<'a, T> {
3690 chunk_size: self.chunk_size,
3695 #[unstable(feature = "exact_chunks", issue = "47115")]
3696 impl<'a, T> Iterator for ExactChunks<'a, T> {
3697 type Item = &'a [T];
3700 fn next(&mut self) -> Option<&'a [T]> {
3701 if self.v.len() < self.chunk_size {
3704 let (fst, snd) = self.v.split_at(self.chunk_size);
3711 fn size_hint(&self) -> (usize, Option<usize>) {
3712 let n = self.v.len() / self.chunk_size;
3717 fn count(self) -> usize {
3722 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3723 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3724 if start >= self.v.len() || overflow {
3728 let (_, snd) = self.v.split_at(start);
3735 fn last(mut self) -> Option<Self::Item> {
3740 #[unstable(feature = "exact_chunks", issue = "47115")]
3741 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3743 fn next_back(&mut self) -> Option<&'a [T]> {
3744 if self.v.len() < self.chunk_size {
3747 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3754 #[unstable(feature = "exact_chunks", issue = "47115")]
3755 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
3756 fn is_empty(&self) -> bool {
3761 #[unstable(feature = "trusted_len", issue = "37572")]
3762 unsafe impl<'a, T> TrustedLen for ExactChunks<'a, T> {}
3764 #[unstable(feature = "exact_chunks", issue = "47115")]
3765 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
3768 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
3769 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3770 let start = i * self.chunk_size;
3771 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
3773 fn may_have_side_effect() -> bool { false }
3776 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3777 /// elements at a time).
3779 /// When the slice len is not evenly divided by the chunk size, the last up to
3780 /// `chunk_size-1` elements will be omitted but can be retrieved from the
3781 /// [`into_remainder`] function from the iterator.
3783 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
3785 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
3786 /// [`into_remainder`]: ../../std/slice/struct.ExactChunksMut.html#method.into_remainder
3787 /// [slices]: ../../std/primitive.slice.html
3789 #[unstable(feature = "exact_chunks", issue = "47115")]
3790 pub struct ExactChunksMut<'a, T:'a> {
3796 #[unstable(feature = "exact_chunks", issue = "47115")]
3797 impl<'a, T> ExactChunksMut<'a, T> {
3798 /// Return the remainder of the original slice that is not going to be
3799 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3801 pub fn into_remainder(self) -> &'a mut [T] {
3806 #[unstable(feature = "exact_chunks", issue = "47115")]
3807 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
3808 type Item = &'a mut [T];
3811 fn next(&mut self) -> Option<&'a mut [T]> {
3812 if self.v.len() < self.chunk_size {
3815 let tmp = mem::replace(&mut self.v, &mut []);
3816 let (head, tail) = tmp.split_at_mut(self.chunk_size);
3823 fn size_hint(&self) -> (usize, Option<usize>) {
3824 let n = self.v.len() / self.chunk_size;
3829 fn count(self) -> usize {
3834 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3835 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3836 if start >= self.v.len() || overflow {
3840 let tmp = mem::replace(&mut self.v, &mut []);
3841 let (_, snd) = tmp.split_at_mut(start);
3848 fn last(mut self) -> Option<Self::Item> {
3853 #[unstable(feature = "exact_chunks", issue = "47115")]
3854 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
3856 fn next_back(&mut self) -> Option<&'a mut [T]> {
3857 if self.v.len() < self.chunk_size {
3860 let tmp = mem::replace(&mut self.v, &mut []);
3861 let tmp_len = tmp.len();
3862 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
3869 #[unstable(feature = "exact_chunks", issue = "47115")]
3870 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
3871 fn is_empty(&self) -> bool {
3876 #[unstable(feature = "trusted_len", issue = "37572")]
3877 unsafe impl<'a, T> TrustedLen for ExactChunksMut<'a, T> {}
3879 #[unstable(feature = "exact_chunks", issue = "47115")]
3880 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
3883 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
3884 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3885 let start = i * self.chunk_size;
3886 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
3888 fn may_have_side_effect() -> bool { false }
3895 /// Forms a slice from a pointer and a length.
3897 /// The `len` argument is the number of **elements**, not the number of bytes.
3901 /// This function is unsafe as there is no guarantee that the given pointer is
3902 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
3903 /// lifetime for the returned slice.
3905 /// `data` must be non-null and aligned, even for zero-length slices. One
3906 /// reason for this is that enum layout optimizations may rely on references
3907 /// (including slices of any length) being aligned and non-null to distinguish
3908 /// them from other data. You can obtain a pointer that is usable as `data`
3909 /// for zero-length slices using [`NonNull::dangling()`].
3913 /// The lifetime for the returned slice is inferred from its usage. To
3914 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
3915 /// source lifetime is safe in the context, such as by providing a helper
3916 /// function taking the lifetime of a host value for the slice, or by explicit
3924 /// // manifest a slice for a single element
3926 /// let ptr = &x as *const _;
3927 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
3928 /// assert_eq!(slice[0], 42);
3931 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
3933 #[stable(feature = "rust1", since = "1.0.0")]
3934 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
3935 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
3936 Repr { raw: FatPtr { data, len } }.rust
3939 /// Performs the same functionality as [`from_raw_parts`], except that a
3940 /// mutable slice is returned.
3942 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
3943 /// as not being able to provide a non-aliasing guarantee of the returned
3944 /// mutable slice. `data` must be non-null and aligned even for zero-length
3945 /// slices as with [`from_raw_parts`]. See the documentation of
3946 /// [`from_raw_parts`] for more details.
3948 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
3950 #[stable(feature = "rust1", since = "1.0.0")]
3951 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
3952 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
3953 Repr { raw: FatPtr { data, len} }.rust_mut
3956 /// Converts a reference to T into a slice of length 1 (without copying).
3957 #[stable(feature = "from_ref", since = "1.28.0")]
3958 pub fn from_ref<T>(s: &T) -> &[T] {
3960 from_raw_parts(s, 1)
3964 /// Converts a reference to T into a slice of length 1 (without copying).
3965 #[stable(feature = "from_ref", since = "1.28.0")]
3966 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
3968 from_raw_parts_mut(s, 1)
3972 // This function is public only because there is no other way to unit test heapsort.
3973 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
3975 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
3976 where F: FnMut(&T, &T) -> bool
3978 sort::heapsort(v, &mut is_less);
3982 // Comparison traits
3986 /// Calls implementation provided memcmp.
3988 /// Interprets the data as u8.
3990 /// Returns 0 for equal, < 0 for less than and > 0 for greater
3992 // FIXME(#32610): Return type should be c_int
3993 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
3996 #[stable(feature = "rust1", since = "1.0.0")]
3997 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
3998 fn eq(&self, other: &[B]) -> bool {
3999 SlicePartialEq::equal(self, other)
4002 fn ne(&self, other: &[B]) -> bool {
4003 SlicePartialEq::not_equal(self, other)
4007 #[stable(feature = "rust1", since = "1.0.0")]
4008 impl<T: Eq> Eq for [T] {}
4010 /// Implements comparison of vectors lexicographically.
4011 #[stable(feature = "rust1", since = "1.0.0")]
4012 impl<T: Ord> Ord for [T] {
4013 fn cmp(&self, other: &[T]) -> Ordering {
4014 SliceOrd::compare(self, other)
4018 /// Implements comparison of vectors lexicographically.
4019 #[stable(feature = "rust1", since = "1.0.0")]
4020 impl<T: PartialOrd> PartialOrd for [T] {
4021 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4022 SlicePartialOrd::partial_compare(self, other)
4027 // intermediate trait for specialization of slice's PartialEq
4028 trait SlicePartialEq<B> {
4029 fn equal(&self, other: &[B]) -> bool;
4031 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4034 // Generic slice equality
4035 impl<A, B> SlicePartialEq<B> for [A]
4036 where A: PartialEq<B>
4038 default fn equal(&self, other: &[B]) -> bool {
4039 if self.len() != other.len() {
4043 for i in 0..self.len() {
4044 if !self[i].eq(&other[i]) {
4053 // Use memcmp for bytewise equality when the types allow
4054 impl<A> SlicePartialEq<A> for [A]
4055 where A: PartialEq<A> + BytewiseEquality
4057 fn equal(&self, other: &[A]) -> bool {
4058 if self.len() != other.len() {
4061 if self.as_ptr() == other.as_ptr() {
4065 let size = mem::size_of_val(self);
4066 memcmp(self.as_ptr() as *const u8,
4067 other.as_ptr() as *const u8, size) == 0
4073 // intermediate trait for specialization of slice's PartialOrd
4074 trait SlicePartialOrd<B> {
4075 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4078 impl<A> SlicePartialOrd<A> for [A]
4081 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4082 let l = cmp::min(self.len(), other.len());
4084 // Slice to the loop iteration range to enable bound check
4085 // elimination in the compiler
4086 let lhs = &self[..l];
4087 let rhs = &other[..l];
4090 match lhs[i].partial_cmp(&rhs[i]) {
4091 Some(Ordering::Equal) => (),
4092 non_eq => return non_eq,
4096 self.len().partial_cmp(&other.len())
4100 impl<A> SlicePartialOrd<A> for [A]
4103 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4104 Some(SliceOrd::compare(self, other))
4109 // intermediate trait for specialization of slice's Ord
4111 fn compare(&self, other: &[B]) -> Ordering;
4114 impl<A> SliceOrd<A> for [A]
4117 default fn compare(&self, other: &[A]) -> Ordering {
4118 let l = cmp::min(self.len(), other.len());
4120 // Slice to the loop iteration range to enable bound check
4121 // elimination in the compiler
4122 let lhs = &self[..l];
4123 let rhs = &other[..l];
4126 match lhs[i].cmp(&rhs[i]) {
4127 Ordering::Equal => (),
4128 non_eq => return non_eq,
4132 self.len().cmp(&other.len())
4136 // memcmp compares a sequence of unsigned bytes lexicographically.
4137 // this matches the order we want for [u8], but no others (not even [i8]).
4138 impl SliceOrd<u8> for [u8] {
4140 fn compare(&self, other: &[u8]) -> Ordering {
4141 let order = unsafe {
4142 memcmp(self.as_ptr(), other.as_ptr(),
4143 cmp::min(self.len(), other.len()))
4146 self.len().cmp(&other.len())
4147 } else if order < 0 {
4156 /// Trait implemented for types that can be compared for equality using
4157 /// their bytewise representation
4158 trait BytewiseEquality { }
4160 macro_rules! impl_marker_for {
4161 ($traitname:ident, $($ty:ty)*) => {
4163 impl $traitname for $ty { }
4168 impl_marker_for!(BytewiseEquality,
4169 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4172 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4173 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4176 fn may_have_side_effect() -> bool { false }
4180 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4181 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4182 &mut *self.ptr.add(i)
4184 fn may_have_side_effect() -> bool { false }
4187 trait SliceContains: Sized {
4188 fn slice_contains(&self, x: &[Self]) -> bool;
4191 impl<T> SliceContains for T where T: PartialEq {
4192 default fn slice_contains(&self, x: &[Self]) -> bool {
4193 x.iter().any(|y| *y == *self)
4197 impl SliceContains for u8 {
4198 fn slice_contains(&self, x: &[Self]) -> bool {
4199 memchr::memchr(*self, x).is_some()
4203 impl SliceContains for i8 {
4204 fn slice_contains(&self, x: &[Self]) -> bool {
4205 let byte = *self as u8;
4206 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4207 memchr::memchr(byte, bytes).is_some()