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;
39 use ops::{FnMut, Try, self};
41 use option::Option::{None, Some};
43 use result::Result::{Ok, Err};
46 use marker::{Copy, Send, Sync, Sized, self};
47 use iter_private::TrustedRandomAccess;
49 #[unstable(feature = "slice_internals", issue = "0",
50 reason = "exposed from core to be reused in std; use the memchr crate")]
51 /// Pure rust memchr implementation, taken from rust-memchr
58 union Repr<'a, T: 'a> {
60 rust_mut: &'a mut [T],
77 /// Returns the number of elements in the slice.
82 /// let a = [1, 2, 3];
83 /// assert_eq!(a.len(), 3);
85 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_const_unstable(feature = "const_slice_len")]
88 pub const fn len(&self) -> usize {
90 Repr { rust: self }.raw.len
94 /// Returns `true` if the slice has a length of 0.
99 /// let a = [1, 2, 3];
100 /// assert!(!a.is_empty());
102 #[stable(feature = "rust1", since = "1.0.0")]
104 #[rustc_const_unstable(feature = "const_slice_len")]
105 pub const fn is_empty(&self) -> bool {
109 /// Returns the first element of the slice, or `None` if it is empty.
114 /// let v = [10, 40, 30];
115 /// assert_eq!(Some(&10), v.first());
117 /// let w: &[i32] = &[];
118 /// assert_eq!(None, w.first());
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn first(&self) -> Option<&T> {
123 if self.is_empty() { None } else { Some(&self[0]) }
126 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
131 /// let x = &mut [0, 1, 2];
133 /// if let Some(first) = x.first_mut() {
136 /// assert_eq!(x, &[5, 1, 2]);
138 #[stable(feature = "rust1", since = "1.0.0")]
140 pub fn first_mut(&mut self) -> Option<&mut T> {
141 if self.is_empty() { None } else { Some(&mut self[0]) }
144 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
149 /// let x = &[0, 1, 2];
151 /// if let Some((first, elements)) = x.split_first() {
152 /// assert_eq!(first, &0);
153 /// assert_eq!(elements, &[1, 2]);
156 #[stable(feature = "slice_splits", since = "1.5.0")]
158 pub fn split_first(&self) -> Option<(&T, &[T])> {
159 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
162 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
167 /// let x = &mut [0, 1, 2];
169 /// if let Some((first, elements)) = x.split_first_mut() {
174 /// assert_eq!(x, &[3, 4, 5]);
176 #[stable(feature = "slice_splits", since = "1.5.0")]
178 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
179 if self.is_empty() { None } else {
180 let split = self.split_at_mut(1);
181 Some((&mut split.0[0], split.1))
185 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
190 /// let x = &[0, 1, 2];
192 /// if let Some((last, elements)) = x.split_last() {
193 /// assert_eq!(last, &2);
194 /// assert_eq!(elements, &[0, 1]);
197 #[stable(feature = "slice_splits", since = "1.5.0")]
199 pub fn split_last(&self) -> Option<(&T, &[T])> {
200 let len = self.len();
201 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
204 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
209 /// let x = &mut [0, 1, 2];
211 /// if let Some((last, elements)) = x.split_last_mut() {
216 /// assert_eq!(x, &[4, 5, 3]);
218 #[stable(feature = "slice_splits", since = "1.5.0")]
220 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
221 let len = self.len();
222 if len == 0 { None } else {
223 let split = self.split_at_mut(len - 1);
224 Some((&mut split.1[0], split.0))
229 /// Returns the last element of the slice, or `None` if it is empty.
234 /// let v = [10, 40, 30];
235 /// assert_eq!(Some(&30), v.last());
237 /// let w: &[i32] = &[];
238 /// assert_eq!(None, w.last());
240 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn last(&self) -> Option<&T> {
243 if self.is_empty() { None } else { Some(&self[self.len() - 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 len = self.len();
262 if len == 0 { return None; }
263 Some(&mut self[len - 1])
266 /// Returns a reference to an element or subslice depending on the type of
269 /// - If given a position, returns a reference to the element at that
270 /// position or `None` if out of bounds.
271 /// - If given a range, returns the subslice corresponding to that range,
272 /// or `None` if out of bounds.
277 /// let v = [10, 40, 30];
278 /// assert_eq!(Some(&40), v.get(1));
279 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
280 /// assert_eq!(None, v.get(3));
281 /// assert_eq!(None, v.get(0..4));
283 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn get<I>(&self, index: I) -> Option<&I::Output>
286 where I: SliceIndex<Self>
291 /// Returns a mutable reference to an element or subslice depending on the
292 /// type of index (see [`get`]) or `None` if the index is out of bounds.
294 /// [`get`]: #method.get
299 /// let x = &mut [0, 1, 2];
301 /// if let Some(elem) = x.get_mut(1) {
304 /// assert_eq!(x, &[0, 42, 2]);
306 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
309 where I: SliceIndex<Self>
314 /// Returns a reference to an element or subslice, without doing bounds
317 /// This is generally not recommended, use with caution! For a safe
318 /// alternative see [`get`].
320 /// [`get`]: #method.get
325 /// let x = &[1, 2, 4];
328 /// assert_eq!(x.get_unchecked(1), &2);
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
334 where I: SliceIndex<Self>
336 index.get_unchecked(self)
339 /// Returns a mutable reference to an element or subslice, without doing
342 /// This is generally not recommended, use with caution! For a safe
343 /// alternative see [`get_mut`].
345 /// [`get_mut`]: #method.get_mut
350 /// let x = &mut [1, 2, 4];
353 /// let elem = x.get_unchecked_mut(1);
356 /// assert_eq!(x, &[1, 13, 4]);
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
361 where I: SliceIndex<Self>
363 index.get_unchecked_mut(self)
366 /// Returns a raw pointer to the slice's buffer.
368 /// The caller must ensure that the slice outlives the pointer this
369 /// function returns, or else it will end up pointing to garbage.
371 /// Modifying the container referenced by this slice may cause its buffer
372 /// to be reallocated, which would also make any pointers to it invalid.
377 /// let x = &[1, 2, 4];
378 /// let x_ptr = x.as_ptr();
381 /// for i in 0..x.len() {
382 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
386 #[stable(feature = "rust1", since = "1.0.0")]
388 #[rustc_const_unstable(feature = "const_slice_as_ptr")]
389 pub const fn as_ptr(&self) -> *const T {
390 self as *const [T] as *const T
393 /// Returns an unsafe mutable pointer to the slice's buffer.
395 /// The caller must ensure that the slice outlives the pointer this
396 /// function returns, or else it will end up pointing to garbage.
398 /// Modifying the container referenced by this slice may cause its buffer
399 /// to be reallocated, which would also make any pointers to it invalid.
404 /// let x = &mut [1, 2, 4];
405 /// let x_ptr = x.as_mut_ptr();
408 /// for i in 0..x.len() {
409 /// *x_ptr.add(i) += 2;
412 /// assert_eq!(x, &[3, 4, 6]);
414 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn as_mut_ptr(&mut self) -> *mut T {
417 self as *mut [T] as *mut T
420 /// Swaps two elements in the slice.
424 /// * a - The index of the first element
425 /// * b - The index of the second element
429 /// Panics if `a` or `b` are out of bounds.
434 /// let mut v = ["a", "b", "c", "d"];
436 /// assert!(v == ["a", "d", "c", "b"]);
438 #[stable(feature = "rust1", since = "1.0.0")]
440 pub fn swap(&mut self, a: usize, b: usize) {
442 // Can't take two mutable loans from one vector, so instead just cast
443 // them to their raw pointers to do the swap
444 let pa: *mut T = &mut self[a];
445 let pb: *mut T = &mut self[b];
450 /// Reverses the order of elements in the slice, in place.
455 /// let mut v = [1, 2, 3];
457 /// assert!(v == [3, 2, 1]);
459 #[stable(feature = "rust1", since = "1.0.0")]
461 pub fn reverse(&mut self) {
462 let mut i: usize = 0;
465 // For very small types, all the individual reads in the normal
466 // path perform poorly. We can do better, given efficient unaligned
467 // load/store, by loading a larger chunk and reversing a register.
469 // Ideally LLVM would do this for us, as it knows better than we do
470 // whether unaligned reads are efficient (since that changes between
471 // different ARM versions, for example) and what the best chunk size
472 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
473 // the loop, so we need to do this ourselves. (Hypothesis: reverse
474 // is troublesome because the sides can be aligned differently --
475 // will be, when the length is odd -- so there's no way of emitting
476 // pre- and postludes to use fully-aligned SIMD in the middle.)
479 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
481 if fast_unaligned && mem::size_of::<T>() == 1 {
482 // Use the llvm.bswap intrinsic to reverse u8s in a usize
483 let chunk = mem::size_of::<usize>();
484 while i + chunk - 1 < ln / 2 {
486 let pa: *mut T = self.get_unchecked_mut(i);
487 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
488 let va = ptr::read_unaligned(pa as *mut usize);
489 let vb = ptr::read_unaligned(pb as *mut usize);
490 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
491 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
497 if fast_unaligned && mem::size_of::<T>() == 2 {
498 // Use rotate-by-16 to reverse u16s in a u32
499 let chunk = mem::size_of::<u32>() / 2;
500 while i + chunk - 1 < ln / 2 {
502 let pa: *mut T = self.get_unchecked_mut(i);
503 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
504 let va = ptr::read_unaligned(pa as *mut u32);
505 let vb = ptr::read_unaligned(pb as *mut u32);
506 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
507 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
514 // Unsafe swap to avoid the bounds check in safe swap.
516 let pa: *mut T = self.get_unchecked_mut(i);
517 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
524 /// Returns an iterator over the slice.
529 /// let x = &[1, 2, 4];
530 /// let mut iterator = x.iter();
532 /// assert_eq!(iterator.next(), Some(&1));
533 /// assert_eq!(iterator.next(), Some(&2));
534 /// assert_eq!(iterator.next(), Some(&4));
535 /// assert_eq!(iterator.next(), None);
537 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn iter(&self) -> Iter<T> {
541 let ptr = self.as_ptr();
542 assume(!ptr.is_null());
544 let end = if mem::size_of::<T>() == 0 {
545 (ptr as *const u8).wrapping_add(self.len()) as *const T
553 _marker: marker::PhantomData
558 /// Returns an iterator that allows modifying each value.
563 /// let x = &mut [1, 2, 4];
564 /// for elem in x.iter_mut() {
567 /// assert_eq!(x, &[3, 4, 6]);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn iter_mut(&mut self) -> IterMut<T> {
573 let ptr = self.as_mut_ptr();
574 assume(!ptr.is_null());
576 let end = if mem::size_of::<T>() == 0 {
577 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
585 _marker: marker::PhantomData
590 /// Returns an iterator over all contiguous windows of length
591 /// `size`. The windows overlap. If the slice is shorter than
592 /// `size`, the iterator returns no values.
596 /// Panics if `size` is 0.
601 /// let slice = ['r', 'u', 's', 't'];
602 /// let mut iter = slice.windows(2);
603 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
604 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
605 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
606 /// assert!(iter.next().is_none());
609 /// If the slice is shorter than `size`:
612 /// let slice = ['f', 'o', 'o'];
613 /// let mut iter = slice.windows(4);
614 /// assert!(iter.next().is_none());
616 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn windows(&self, size: usize) -> Windows<T> {
620 Windows { v: self, size }
623 /// Returns an iterator over `chunk_size` elements of the slice at a
624 /// time. The chunks are slices and do not overlap. If `chunk_size` does
625 /// not divide the length of the slice, then the last chunk will
626 /// not have length `chunk_size`.
628 /// See [`exact_chunks`] for a variant of this iterator that returns chunks
629 /// of always exactly `chunk_size` elements.
633 /// Panics if `chunk_size` is 0.
638 /// let slice = ['l', 'o', 'r', 'e', 'm'];
639 /// let mut iter = slice.chunks(2);
640 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
641 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
642 /// assert_eq!(iter.next().unwrap(), &['m']);
643 /// assert!(iter.next().is_none());
646 /// [`exact_chunks`]: #method.exact_chunks
647 #[stable(feature = "rust1", since = "1.0.0")]
649 pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
650 assert!(chunk_size != 0);
651 Chunks { v: self, chunk_size }
654 /// Returns an iterator over `chunk_size` elements of the slice at a time.
655 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
656 /// not divide the length of the slice, then the last chunk will not
657 /// have length `chunk_size`.
659 /// See [`exact_chunks_mut`] for a variant of this iterator that returns chunks
660 /// of always exactly `chunk_size` elements.
664 /// Panics if `chunk_size` is 0.
669 /// let v = &mut [0, 0, 0, 0, 0];
670 /// let mut count = 1;
672 /// for chunk in v.chunks_mut(2) {
673 /// for elem in chunk.iter_mut() {
678 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
681 /// [`exact_chunks_mut`]: #method.exact_chunks_mut
682 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
685 assert!(chunk_size != 0);
686 ChunksMut { v: self, chunk_size }
689 /// Returns an iterator over `chunk_size` elements of the slice at a
690 /// time. The chunks are slices and do not overlap. If `chunk_size` does
691 /// not divide the length of the slice, then the last up to `chunk_size-1`
692 /// elements will be omitted and can be retrieved from the `remainder`
693 /// function of the iterator.
695 /// Due to each chunk having exactly `chunk_size` elements, the compiler
696 /// can often optimize the resulting code better than in the case of
701 /// Panics if `chunk_size` is 0.
706 /// #![feature(exact_chunks)]
708 /// let slice = ['l', 'o', 'r', 'e', 'm'];
709 /// let mut iter = slice.exact_chunks(2);
710 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
711 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
712 /// assert!(iter.next().is_none());
715 /// [`chunks`]: #method.chunks
716 #[unstable(feature = "exact_chunks", issue = "47115")]
718 pub fn exact_chunks(&self, chunk_size: usize) -> ExactChunks<T> {
719 assert!(chunk_size != 0);
720 let rem = self.len() % chunk_size;
721 let len = self.len() - rem;
722 let (fst, snd) = self.split_at(len);
723 ExactChunks { v: fst, rem: snd, chunk_size }
726 /// Returns an iterator over `chunk_size` elements of the slice at a time.
727 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
728 /// not divide the length of the slice, then the last up to `chunk_size-1`
729 /// elements will be omitted and can be retrieved from the `into_remainder`
730 /// function of the iterator.
732 /// Due to each chunk having exactly `chunk_size` elements, the compiler
733 /// can often optimize the resulting code better than in the case of
738 /// Panics if `chunk_size` is 0.
743 /// #![feature(exact_chunks)]
745 /// let v = &mut [0, 0, 0, 0, 0];
746 /// let mut count = 1;
748 /// for chunk in v.exact_chunks_mut(2) {
749 /// for elem in chunk.iter_mut() {
754 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
757 /// [`chunks_mut`]: #method.chunks_mut
758 #[unstable(feature = "exact_chunks", issue = "47115")]
760 pub fn exact_chunks_mut(&mut self, chunk_size: usize) -> ExactChunksMut<T> {
761 assert!(chunk_size != 0);
762 let rem = self.len() % chunk_size;
763 let len = self.len() - rem;
764 let (fst, snd) = self.split_at_mut(len);
765 ExactChunksMut { v: fst, rem: snd, chunk_size }
768 /// Divides one slice into two at an index.
770 /// The first will contain all indices from `[0, mid)` (excluding
771 /// the index `mid` itself) and the second will contain all
772 /// indices from `[mid, len)` (excluding the index `len` itself).
776 /// Panics if `mid > len`.
781 /// let v = [1, 2, 3, 4, 5, 6];
784 /// let (left, right) = v.split_at(0);
785 /// assert!(left == []);
786 /// assert!(right == [1, 2, 3, 4, 5, 6]);
790 /// let (left, right) = v.split_at(2);
791 /// assert!(left == [1, 2]);
792 /// assert!(right == [3, 4, 5, 6]);
796 /// let (left, right) = v.split_at(6);
797 /// assert!(left == [1, 2, 3, 4, 5, 6]);
798 /// assert!(right == []);
801 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
804 (&self[..mid], &self[mid..])
807 /// Divides one mutable slice into two at an index.
809 /// The first will contain all indices from `[0, mid)` (excluding
810 /// the index `mid` itself) and the second will contain all
811 /// indices from `[mid, len)` (excluding the index `len` itself).
815 /// Panics if `mid > len`.
820 /// let mut v = [1, 0, 3, 0, 5, 6];
821 /// // scoped to restrict the lifetime of the borrows
823 /// let (left, right) = v.split_at_mut(2);
824 /// assert!(left == [1, 0]);
825 /// assert!(right == [3, 0, 5, 6]);
829 /// assert!(v == [1, 2, 3, 4, 5, 6]);
831 #[stable(feature = "rust1", since = "1.0.0")]
833 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
834 let len = self.len();
835 let ptr = self.as_mut_ptr();
840 (from_raw_parts_mut(ptr, mid),
841 from_raw_parts_mut(ptr.add(mid), len - mid))
845 /// Returns an iterator over subslices separated by elements that match
846 /// `pred`. The matched element is not contained in the subslices.
851 /// let slice = [10, 40, 33, 20];
852 /// let mut iter = slice.split(|num| num % 3 == 0);
854 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
855 /// assert_eq!(iter.next().unwrap(), &[20]);
856 /// assert!(iter.next().is_none());
859 /// If the first element is matched, an empty slice will be the first item
860 /// returned by the iterator. Similarly, if the last element in the slice
861 /// is matched, an empty slice will be the last item returned by the
865 /// let slice = [10, 40, 33];
866 /// let mut iter = slice.split(|num| num % 3 == 0);
868 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
869 /// assert_eq!(iter.next().unwrap(), &[]);
870 /// assert!(iter.next().is_none());
873 /// If two matched elements are directly adjacent, an empty slice will be
874 /// present between them:
877 /// let slice = [10, 6, 33, 20];
878 /// let mut iter = slice.split(|num| num % 3 == 0);
880 /// assert_eq!(iter.next().unwrap(), &[10]);
881 /// assert_eq!(iter.next().unwrap(), &[]);
882 /// assert_eq!(iter.next().unwrap(), &[20]);
883 /// assert!(iter.next().is_none());
885 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn split<F>(&self, pred: F) -> Split<T, F>
888 where F: FnMut(&T) -> bool
897 /// Returns an iterator over mutable subslices separated by elements that
898 /// match `pred`. The matched element is not contained in the subslices.
903 /// let mut v = [10, 40, 30, 20, 60, 50];
905 /// for group in v.split_mut(|num| *num % 3 == 0) {
908 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
910 #[stable(feature = "rust1", since = "1.0.0")]
912 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
913 where F: FnMut(&T) -> bool
915 SplitMut { v: self, pred, finished: false }
918 /// Returns an iterator over subslices separated by elements that match
919 /// `pred`, starting at the end of the slice and working backwards.
920 /// The matched element is not contained in the subslices.
925 /// let slice = [11, 22, 33, 0, 44, 55];
926 /// let mut iter = slice.rsplit(|num| *num == 0);
928 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
929 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
930 /// assert_eq!(iter.next(), None);
933 /// As with `split()`, if the first or last element is matched, an empty
934 /// slice will be the first (or last) item returned by the iterator.
937 /// let v = &[0, 1, 1, 2, 3, 5, 8];
938 /// let mut it = v.rsplit(|n| *n % 2 == 0);
939 /// assert_eq!(it.next().unwrap(), &[]);
940 /// assert_eq!(it.next().unwrap(), &[3, 5]);
941 /// assert_eq!(it.next().unwrap(), &[1, 1]);
942 /// assert_eq!(it.next().unwrap(), &[]);
943 /// assert_eq!(it.next(), None);
945 #[stable(feature = "slice_rsplit", since = "1.27.0")]
947 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
948 where F: FnMut(&T) -> bool
950 RSplit { inner: self.split(pred) }
953 /// Returns an iterator over mutable subslices separated by elements that
954 /// match `pred`, starting at the end of the slice and working
955 /// backwards. The matched element is not contained in the subslices.
960 /// let mut v = [100, 400, 300, 200, 600, 500];
962 /// let mut count = 0;
963 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
965 /// group[0] = count;
967 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
970 #[stable(feature = "slice_rsplit", since = "1.27.0")]
972 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
973 where F: FnMut(&T) -> bool
975 RSplitMut { inner: self.split_mut(pred) }
978 /// Returns an iterator over subslices separated by elements that match
979 /// `pred`, limited to returning at most `n` items. The matched element is
980 /// not contained in the subslices.
982 /// The last element returned, if any, will contain the remainder of the
987 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
991 /// let v = [10, 40, 30, 20, 60, 50];
993 /// for group in v.splitn(2, |num| *num % 3 == 0) {
994 /// println!("{:?}", group);
997 #[stable(feature = "rust1", since = "1.0.0")]
999 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
1000 where F: FnMut(&T) -> bool
1003 inner: GenericSplitN {
1004 iter: self.split(pred),
1010 /// Returns an iterator over subslices separated by elements that match
1011 /// `pred`, limited to returning at most `n` items. The matched element is
1012 /// not contained in the subslices.
1014 /// The last element returned, if any, will contain the remainder of the
1020 /// let mut v = [10, 40, 30, 20, 60, 50];
1022 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1025 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1027 #[stable(feature = "rust1", since = "1.0.0")]
1029 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1030 where F: FnMut(&T) -> bool
1033 inner: GenericSplitN {
1034 iter: self.split_mut(pred),
1040 /// Returns an iterator over subslices separated by elements that match
1041 /// `pred` limited to returning at most `n` items. This starts at the end of
1042 /// the slice and works backwards. The matched element is not contained in
1045 /// The last element returned, if any, will contain the remainder of the
1050 /// Print the slice split once, starting from the end, by numbers divisible
1051 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1054 /// let v = [10, 40, 30, 20, 60, 50];
1056 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1057 /// println!("{:?}", group);
1060 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1063 where F: FnMut(&T) -> bool
1066 inner: GenericSplitN {
1067 iter: self.rsplit(pred),
1073 /// Returns an iterator over subslices separated by elements that match
1074 /// `pred` limited to returning at most `n` items. This starts at the end of
1075 /// the slice and works backwards. The matched element is not contained in
1078 /// The last element returned, if any, will contain the remainder of the
1084 /// let mut s = [10, 40, 30, 20, 60, 50];
1086 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1089 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1091 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1094 where F: FnMut(&T) -> bool
1097 inner: GenericSplitN {
1098 iter: self.rsplit_mut(pred),
1104 /// Returns `true` if the slice contains an element with the given value.
1109 /// let v = [10, 40, 30];
1110 /// assert!(v.contains(&30));
1111 /// assert!(!v.contains(&50));
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn contains(&self, x: &T) -> bool
1117 x.slice_contains(self)
1120 /// Returns `true` if `needle` is a prefix of the slice.
1125 /// let v = [10, 40, 30];
1126 /// assert!(v.starts_with(&[10]));
1127 /// assert!(v.starts_with(&[10, 40]));
1128 /// assert!(!v.starts_with(&[50]));
1129 /// assert!(!v.starts_with(&[10, 50]));
1132 /// Always returns `true` if `needle` is an empty slice:
1135 /// let v = &[10, 40, 30];
1136 /// assert!(v.starts_with(&[]));
1137 /// let v: &[u8] = &[];
1138 /// assert!(v.starts_with(&[]));
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 pub fn starts_with(&self, needle: &[T]) -> bool
1144 let n = needle.len();
1145 self.len() >= n && needle == &self[..n]
1148 /// Returns `true` if `needle` is a suffix of the slice.
1153 /// let v = [10, 40, 30];
1154 /// assert!(v.ends_with(&[30]));
1155 /// assert!(v.ends_with(&[40, 30]));
1156 /// assert!(!v.ends_with(&[50]));
1157 /// assert!(!v.ends_with(&[50, 30]));
1160 /// Always returns `true` if `needle` is an empty slice:
1163 /// let v = &[10, 40, 30];
1164 /// assert!(v.ends_with(&[]));
1165 /// let v: &[u8] = &[];
1166 /// assert!(v.ends_with(&[]));
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 pub fn ends_with(&self, needle: &[T]) -> bool
1172 let (m, n) = (self.len(), needle.len());
1173 m >= n && needle == &self[m-n..]
1176 /// Binary searches this sorted slice for a given element.
1178 /// If the value is found then `Ok` is returned, containing the
1179 /// index of the matching element; if the value is not found then
1180 /// `Err` is returned, containing the index where a matching
1181 /// element could be inserted while maintaining sorted order.
1185 /// Looks up a series of four elements. The first is found, with a
1186 /// uniquely determined position; the second and third are not
1187 /// found; the fourth could match any position in `[1, 4]`.
1190 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1192 /// assert_eq!(s.binary_search(&13), Ok(9));
1193 /// assert_eq!(s.binary_search(&4), Err(7));
1194 /// assert_eq!(s.binary_search(&100), Err(13));
1195 /// let r = s.binary_search(&1);
1196 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1202 self.binary_search_by(|p| p.cmp(x))
1205 /// Binary searches this sorted slice with a comparator function.
1207 /// The comparator function should implement an order consistent
1208 /// with the sort order of the underlying slice, returning an
1209 /// order code that indicates whether its argument is `Less`,
1210 /// `Equal` or `Greater` the desired target.
1212 /// If a matching value is found then returns `Ok`, containing
1213 /// the index for the matched element; if no match is found then
1214 /// `Err` is returned, containing the index where a matching
1215 /// element could be inserted while maintaining sorted order.
1219 /// Looks up a series of four elements. The first is found, with a
1220 /// uniquely determined position; the second and third are not
1221 /// found; the fourth could match any position in `[1, 4]`.
1224 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1227 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1229 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1231 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1233 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1234 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1236 #[stable(feature = "rust1", since = "1.0.0")]
1238 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1239 where F: FnMut(&'a T) -> Ordering
1242 let mut size = s.len();
1246 let mut base = 0usize;
1248 let half = size / 2;
1249 let mid = base + half;
1250 // mid is always in [0, size), that means mid is >= 0 and < size.
1251 // mid >= 0: by definition
1252 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1253 let cmp = f(unsafe { s.get_unchecked(mid) });
1254 base = if cmp == Greater { base } else { mid };
1257 // base is always in [0, size) because base <= mid.
1258 let cmp = f(unsafe { s.get_unchecked(base) });
1259 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1263 /// Binary searches this sorted slice with a key extraction function.
1265 /// Assumes that the slice is sorted by the key, for instance with
1266 /// [`sort_by_key`] using the same key extraction function.
1268 /// If a matching value is found then returns `Ok`, containing the
1269 /// index for the matched element; if no match is found then `Err`
1270 /// is returned, containing the index where a matching element could
1271 /// be inserted while maintaining sorted order.
1273 /// [`sort_by_key`]: #method.sort_by_key
1277 /// Looks up a series of four elements in a slice of pairs sorted by
1278 /// their second elements. The first is found, with a uniquely
1279 /// determined position; the second and third are not found; the
1280 /// fourth could match any position in `[1, 4]`.
1283 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1284 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1285 /// (1, 21), (2, 34), (4, 55)];
1287 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1288 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1289 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1290 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1291 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1293 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1295 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1296 where F: FnMut(&'a T) -> B,
1299 self.binary_search_by(|k| f(k).cmp(b))
1302 /// Sorts the slice, but may not preserve the order of equal elements.
1304 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1305 /// and `O(n log n)` worst-case.
1307 /// # Current implementation
1309 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1310 /// which combines the fast average case of randomized quicksort with the fast worst case of
1311 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1312 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1313 /// deterministic behavior.
1315 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1316 /// slice consists of several concatenated sorted sequences.
1321 /// let mut v = [-5, 4, 1, -3, 2];
1323 /// v.sort_unstable();
1324 /// assert!(v == [-5, -3, 1, 2, 4]);
1327 /// [pdqsort]: https://github.com/orlp/pdqsort
1328 #[stable(feature = "sort_unstable", since = "1.20.0")]
1330 pub fn sort_unstable(&mut self)
1333 sort::quicksort(self, |a, b| a.lt(b));
1336 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1339 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1340 /// and `O(n log n)` worst-case.
1342 /// # Current implementation
1344 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1345 /// which combines the fast average case of randomized quicksort with the fast worst case of
1346 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1347 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1348 /// deterministic behavior.
1350 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1351 /// slice consists of several concatenated sorted sequences.
1356 /// let mut v = [5, 4, 1, 3, 2];
1357 /// v.sort_unstable_by(|a, b| a.cmp(b));
1358 /// assert!(v == [1, 2, 3, 4, 5]);
1360 /// // reverse sorting
1361 /// v.sort_unstable_by(|a, b| b.cmp(a));
1362 /// assert!(v == [5, 4, 3, 2, 1]);
1365 /// [pdqsort]: https://github.com/orlp/pdqsort
1366 #[stable(feature = "sort_unstable", since = "1.20.0")]
1368 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1369 where F: FnMut(&T, &T) -> Ordering
1371 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1374 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1377 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1378 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1380 /// # Current implementation
1382 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1383 /// which combines the fast average case of randomized quicksort with the fast worst case of
1384 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1385 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1386 /// deterministic behavior.
1391 /// let mut v = [-5i32, 4, 1, -3, 2];
1393 /// v.sort_unstable_by_key(|k| k.abs());
1394 /// assert!(v == [1, 2, -3, 4, -5]);
1397 /// [pdqsort]: https://github.com/orlp/pdqsort
1398 #[stable(feature = "sort_unstable", since = "1.20.0")]
1400 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1401 where F: FnMut(&T) -> K, K: Ord
1403 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1406 /// Rotates the slice in-place such that the first `mid` elements of the
1407 /// slice move to the end while the last `self.len() - mid` elements move to
1408 /// the front. After calling `rotate_left`, the element previously at index
1409 /// `mid` will become the first element in the slice.
1413 /// This function will panic if `mid` is greater than the length of the
1414 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1419 /// Takes linear (in `self.len()`) time.
1424 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1425 /// a.rotate_left(2);
1426 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1429 /// Rotating a subslice:
1432 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1433 /// a[1..5].rotate_left(1);
1434 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1436 #[stable(feature = "slice_rotate", since = "1.26.0")]
1437 pub fn rotate_left(&mut self, mid: usize) {
1438 assert!(mid <= self.len());
1439 let k = self.len() - mid;
1442 let p = self.as_mut_ptr();
1443 rotate::ptr_rotate(mid, p.add(mid), k);
1447 /// Rotates the slice in-place such that the first `self.len() - k`
1448 /// elements of the slice move to the end while the last `k` elements move
1449 /// to the front. After calling `rotate_right`, the element previously at
1450 /// index `self.len() - k` will become the first element in the slice.
1454 /// This function will panic if `k` is greater than the length of the
1455 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1460 /// Takes linear (in `self.len()`) time.
1465 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1466 /// a.rotate_right(2);
1467 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1470 /// Rotate a subslice:
1473 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1474 /// a[1..5].rotate_right(1);
1475 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1477 #[stable(feature = "slice_rotate", since = "1.26.0")]
1478 pub fn rotate_right(&mut self, k: usize) {
1479 assert!(k <= self.len());
1480 let mid = self.len() - k;
1483 let p = self.as_mut_ptr();
1484 rotate::ptr_rotate(mid, p.add(mid), k);
1488 /// Copies the elements from `src` into `self`.
1490 /// The length of `src` must be the same as `self`.
1492 /// If `src` implements `Copy`, it can be more performant to use
1493 /// [`copy_from_slice`].
1497 /// This function will panic if the two slices have different lengths.
1501 /// Cloning two elements from a slice into another:
1504 /// let src = [1, 2, 3, 4];
1505 /// let mut dst = [0, 0];
1507 /// // Because the slices have to be the same length,
1508 /// // we slice the source slice from four elements
1509 /// // to two. It will panic if we don't do this.
1510 /// dst.clone_from_slice(&src[2..]);
1512 /// assert_eq!(src, [1, 2, 3, 4]);
1513 /// assert_eq!(dst, [3, 4]);
1516 /// Rust enforces that there can only be one mutable reference with no
1517 /// immutable references to a particular piece of data in a particular
1518 /// scope. Because of this, attempting to use `clone_from_slice` on a
1519 /// single slice will result in a compile failure:
1522 /// let mut slice = [1, 2, 3, 4, 5];
1524 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1527 /// To work around this, we can use [`split_at_mut`] to create two distinct
1528 /// sub-slices from a slice:
1531 /// let mut slice = [1, 2, 3, 4, 5];
1534 /// let (left, right) = slice.split_at_mut(2);
1535 /// left.clone_from_slice(&right[1..]);
1538 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1541 /// [`copy_from_slice`]: #method.copy_from_slice
1542 /// [`split_at_mut`]: #method.split_at_mut
1543 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1544 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1545 assert!(self.len() == src.len(),
1546 "destination and source slices have different lengths");
1547 // NOTE: We need to explicitly slice them to the same length
1548 // for bounds checking to be elided, and the optimizer will
1549 // generate memcpy for simple cases (for example T = u8).
1550 let len = self.len();
1551 let src = &src[..len];
1553 self[i].clone_from(&src[i]);
1558 /// Copies all elements from `src` into `self`, using a memcpy.
1560 /// The length of `src` must be the same as `self`.
1562 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1566 /// This function will panic if the two slices have different lengths.
1570 /// Copying two elements from a slice into another:
1573 /// let src = [1, 2, 3, 4];
1574 /// let mut dst = [0, 0];
1576 /// // Because the slices have to be the same length,
1577 /// // we slice the source slice from four elements
1578 /// // to two. It will panic if we don't do this.
1579 /// dst.copy_from_slice(&src[2..]);
1581 /// assert_eq!(src, [1, 2, 3, 4]);
1582 /// assert_eq!(dst, [3, 4]);
1585 /// Rust enforces that there can only be one mutable reference with no
1586 /// immutable references to a particular piece of data in a particular
1587 /// scope. Because of this, attempting to use `copy_from_slice` on a
1588 /// single slice will result in a compile failure:
1591 /// let mut slice = [1, 2, 3, 4, 5];
1593 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1596 /// To work around this, we can use [`split_at_mut`] to create two distinct
1597 /// sub-slices from a slice:
1600 /// let mut slice = [1, 2, 3, 4, 5];
1603 /// let (left, right) = slice.split_at_mut(2);
1604 /// left.copy_from_slice(&right[1..]);
1607 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1610 /// [`clone_from_slice`]: #method.clone_from_slice
1611 /// [`split_at_mut`]: #method.split_at_mut
1612 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1613 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1614 assert_eq!(self.len(), src.len(),
1615 "destination and source slices have different lengths");
1617 ptr::copy_nonoverlapping(
1618 src.as_ptr(), self.as_mut_ptr(), self.len());
1622 /// Swaps all elements in `self` with those in `other`.
1624 /// The length of `other` must be the same as `self`.
1628 /// This function will panic if the two slices have different lengths.
1632 /// Swapping two elements across slices:
1635 /// let mut slice1 = [0, 0];
1636 /// let mut slice2 = [1, 2, 3, 4];
1638 /// slice1.swap_with_slice(&mut slice2[2..]);
1640 /// assert_eq!(slice1, [3, 4]);
1641 /// assert_eq!(slice2, [1, 2, 0, 0]);
1644 /// Rust enforces that there can only be one mutable reference to a
1645 /// particular piece of data in a particular scope. Because of this,
1646 /// attempting to use `swap_with_slice` on a single slice will result in
1647 /// a compile failure:
1650 /// let mut slice = [1, 2, 3, 4, 5];
1651 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
1654 /// To work around this, we can use [`split_at_mut`] to create two distinct
1655 /// mutable sub-slices from a slice:
1658 /// let mut slice = [1, 2, 3, 4, 5];
1661 /// let (left, right) = slice.split_at_mut(2);
1662 /// left.swap_with_slice(&mut right[1..]);
1665 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
1668 /// [`split_at_mut`]: #method.split_at_mut
1669 #[stable(feature = "swap_with_slice", since = "1.27.0")]
1670 pub fn swap_with_slice(&mut self, other: &mut [T]) {
1671 assert!(self.len() == other.len(),
1672 "destination and source slices have different lengths");
1674 ptr::swap_nonoverlapping(
1675 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
1679 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
1680 fn align_to_offsets<U>(&self) -> (usize, usize) {
1681 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
1682 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
1684 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
1685 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
1686 // place of every 3 Ts in the `rest` slice. A bit more complicated.
1688 // Formula to calculate this is:
1690 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
1691 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
1693 // Expanded and simplified:
1695 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
1696 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
1698 // Luckily since all this is constant-evaluated... performance here matters not!
1700 fn gcd(a: usize, b: usize) -> usize {
1701 // iterative stein’s algorithm
1702 // We should still make this `const fn` (and revert to recursive algorithm if we do)
1703 // because relying on llvm to consteval all this is… well, it makes me
1704 let (ctz_a, mut ctz_b) = unsafe {
1705 if a == 0 { return b; }
1706 if b == 0 { return a; }
1707 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
1709 let k = ctz_a.min(ctz_b);
1710 let mut a = a >> ctz_a;
1713 // remove all factors of 2 from b
1716 ::mem::swap(&mut a, &mut b);
1723 ctz_b = ::intrinsics::cttz_nonzero(b);
1728 let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
1729 let ts: usize = ::mem::size_of::<U>() / gcd;
1730 let us: usize = ::mem::size_of::<T>() / gcd;
1732 // Armed with this knowledge, we can find how many `U`s we can fit!
1733 let us_len = self.len() / ts * us;
1734 // And how many `T`s will be in the trailing slice!
1735 let ts_len = self.len() % ts;
1739 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
1742 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1743 /// slice of a new type, and the suffix slice. The middle slice will have the greatest length
1744 /// possible for a given type and input slice.
1746 /// This method has no purpose when either input element `T` or output element `U` are
1747 /// zero-sized and will return the original slice without splitting anything.
1751 /// This method is essentially a `transmute` with respect to the elements in the returned
1752 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1759 /// # #![feature(slice_align_to)]
1761 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1762 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
1763 /// // less_efficient_algorithm_for_bytes(prefix);
1764 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1765 /// // less_efficient_algorithm_for_bytes(suffix);
1768 #[unstable(feature = "slice_align_to", issue = "44488")]
1769 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
1770 // Note that most of this function will be constant-evaluated,
1771 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1772 // handle ZSTs specially, which is – don't handle them at all.
1773 return (self, &[], &[]);
1776 // First, find at what point do we split between the first and 2nd slice. Easy with
1777 // ptr.align_offset.
1778 let ptr = self.as_ptr();
1779 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1780 if offset > self.len() {
1783 let (left, rest) = self.split_at(offset);
1784 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
1785 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1787 from_raw_parts(rest.as_ptr() as *const U, us_len),
1788 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
1792 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
1795 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1796 /// slice of a new type, and the suffix slice. The middle slice will have the greatest length
1797 /// possible for a given type and input slice.
1799 /// This method has no purpose when either input element `T` or output element `U` are
1800 /// zero-sized and will return the original slice without splitting anything.
1804 /// This method is essentially a `transmute` with respect to the elements in the returned
1805 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1812 /// # #![feature(slice_align_to)]
1814 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1815 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
1816 /// // less_efficient_algorithm_for_bytes(prefix);
1817 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1818 /// // less_efficient_algorithm_for_bytes(suffix);
1821 #[unstable(feature = "slice_align_to", issue = "44488")]
1822 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
1823 // Note that most of this function will be constant-evaluated,
1824 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1825 // handle ZSTs specially, which is – don't handle them at all.
1826 return (self, &mut [], &mut []);
1829 // First, find at what point do we split between the first and 2nd slice. Easy with
1830 // ptr.align_offset.
1831 let ptr = self.as_ptr();
1832 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1833 if offset > self.len() {
1834 (self, &mut [], &mut [])
1836 let (left, rest) = self.split_at_mut(offset);
1837 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
1838 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1839 let mut_ptr = rest.as_mut_ptr();
1841 from_raw_parts_mut(mut_ptr as *mut U, us_len),
1842 from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
1847 #[lang = "slice_u8"]
1850 /// Checks if all bytes in this slice are within the ASCII range.
1851 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1853 pub fn is_ascii(&self) -> bool {
1854 self.iter().all(|b| b.is_ascii())
1857 /// Checks that two slices are an ASCII case-insensitive match.
1859 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1860 /// but without allocating and copying temporaries.
1861 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1863 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
1864 self.len() == other.len() &&
1865 self.iter().zip(other).all(|(a, b)| {
1866 a.eq_ignore_ascii_case(b)
1870 /// Converts this slice to its ASCII upper case equivalent in-place.
1872 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1873 /// but non-ASCII letters are unchanged.
1875 /// To return a new uppercased value without modifying the existing one, use
1876 /// [`to_ascii_uppercase`].
1878 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1879 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1881 pub fn make_ascii_uppercase(&mut self) {
1883 byte.make_ascii_uppercase();
1887 /// Converts this slice to its ASCII lower case equivalent in-place.
1889 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1890 /// but non-ASCII letters are unchanged.
1892 /// To return a new lowercased value without modifying the existing one, use
1893 /// [`to_ascii_lowercase`].
1895 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1896 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1898 pub fn make_ascii_lowercase(&mut self) {
1900 byte.make_ascii_lowercase();
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1908 impl<T, I> ops::Index<I> for [T]
1909 where I: SliceIndex<[T]>
1911 type Output = I::Output;
1914 fn index(&self, index: I) -> &I::Output {
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1921 impl<T, I> ops::IndexMut<I> for [T]
1922 where I: SliceIndex<[T]>
1925 fn index_mut(&mut self, index: I) -> &mut I::Output {
1926 index.index_mut(self)
1932 fn slice_index_len_fail(index: usize, len: usize) -> ! {
1933 panic!("index {} out of range for slice of length {}", index, len);
1938 fn slice_index_order_fail(index: usize, end: usize) -> ! {
1939 panic!("slice index starts at {} but ends at {}", index, end);
1944 fn slice_index_overflow_fail() -> ! {
1945 panic!("attempted to index slice up to maximum usize");
1948 mod private_slice_index {
1950 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1953 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1954 impl Sealed for usize {}
1955 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1956 impl Sealed for ops::Range<usize> {}
1957 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1958 impl Sealed for ops::RangeTo<usize> {}
1959 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1960 impl Sealed for ops::RangeFrom<usize> {}
1961 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1962 impl Sealed for ops::RangeFull {}
1963 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1964 impl Sealed for ops::RangeInclusive<usize> {}
1965 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1966 impl Sealed for ops::RangeToInclusive<usize> {}
1969 /// A helper trait used for indexing operations.
1970 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1971 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1972 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
1973 /// The output type returned by methods.
1974 #[stable(feature = "slice_get_slice", since = "1.28.0")]
1975 type Output: ?Sized;
1977 /// Returns a shared reference to the output at this location, if in
1979 #[unstable(feature = "slice_index_methods", issue = "0")]
1980 fn get(self, slice: &T) -> Option<&Self::Output>;
1982 /// Returns a mutable reference to the output at this location, if in
1984 #[unstable(feature = "slice_index_methods", issue = "0")]
1985 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
1987 /// Returns a shared reference to the output at this location, without
1988 /// performing any bounds checking.
1989 #[unstable(feature = "slice_index_methods", issue = "0")]
1990 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
1992 /// Returns a mutable reference to the output at this location, without
1993 /// performing any bounds checking.
1994 #[unstable(feature = "slice_index_methods", issue = "0")]
1995 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
1997 /// Returns a shared reference to the output at this location, panicking
1998 /// if out of bounds.
1999 #[unstable(feature = "slice_index_methods", issue = "0")]
2000 fn index(self, slice: &T) -> &Self::Output;
2002 /// Returns a mutable reference to the output at this location, panicking
2003 /// if out of bounds.
2004 #[unstable(feature = "slice_index_methods", issue = "0")]
2005 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2008 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2009 impl<T> SliceIndex<[T]> for usize {
2013 fn get(self, slice: &[T]) -> Option<&T> {
2014 if self < slice.len() {
2016 Some(self.get_unchecked(slice))
2024 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2025 if self < slice.len() {
2027 Some(self.get_unchecked_mut(slice))
2035 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2036 &*slice.as_ptr().add(self)
2040 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2041 &mut *slice.as_mut_ptr().add(self)
2045 fn index(self, slice: &[T]) -> &T {
2046 // NB: use intrinsic indexing
2051 fn index_mut(self, slice: &mut [T]) -> &mut T {
2052 // NB: use intrinsic indexing
2057 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2058 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2062 fn get(self, slice: &[T]) -> Option<&[T]> {
2063 if self.start > self.end || self.end > slice.len() {
2067 Some(self.get_unchecked(slice))
2073 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2074 if self.start > self.end || self.end > slice.len() {
2078 Some(self.get_unchecked_mut(slice))
2084 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2085 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2089 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2090 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2094 fn index(self, slice: &[T]) -> &[T] {
2095 if self.start > self.end {
2096 slice_index_order_fail(self.start, self.end);
2097 } else if self.end > slice.len() {
2098 slice_index_len_fail(self.end, slice.len());
2101 self.get_unchecked(slice)
2106 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2107 if self.start > self.end {
2108 slice_index_order_fail(self.start, self.end);
2109 } else if self.end > slice.len() {
2110 slice_index_len_fail(self.end, slice.len());
2113 self.get_unchecked_mut(slice)
2118 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2119 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2123 fn get(self, slice: &[T]) -> Option<&[T]> {
2124 (0..self.end).get(slice)
2128 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2129 (0..self.end).get_mut(slice)
2133 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2134 (0..self.end).get_unchecked(slice)
2138 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2139 (0..self.end).get_unchecked_mut(slice)
2143 fn index(self, slice: &[T]) -> &[T] {
2144 (0..self.end).index(slice)
2148 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2149 (0..self.end).index_mut(slice)
2153 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2154 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2158 fn get(self, slice: &[T]) -> Option<&[T]> {
2159 (self.start..slice.len()).get(slice)
2163 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2164 (self.start..slice.len()).get_mut(slice)
2168 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2169 (self.start..slice.len()).get_unchecked(slice)
2173 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2174 (self.start..slice.len()).get_unchecked_mut(slice)
2178 fn index(self, slice: &[T]) -> &[T] {
2179 (self.start..slice.len()).index(slice)
2183 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2184 (self.start..slice.len()).index_mut(slice)
2188 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2189 impl<T> SliceIndex<[T]> for ops::RangeFull {
2193 fn get(self, slice: &[T]) -> Option<&[T]> {
2198 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2203 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2208 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2213 fn index(self, slice: &[T]) -> &[T] {
2218 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2224 #[stable(feature = "inclusive_range", since = "1.26.0")]
2225 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2229 fn get(self, slice: &[T]) -> Option<&[T]> {
2230 if *self.end() == usize::max_value() { None }
2231 else { (*self.start()..self.end() + 1).get(slice) }
2235 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2236 if *self.end() == usize::max_value() { None }
2237 else { (*self.start()..self.end() + 1).get_mut(slice) }
2241 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2242 (*self.start()..self.end() + 1).get_unchecked(slice)
2246 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2247 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2251 fn index(self, slice: &[T]) -> &[T] {
2252 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2253 (*self.start()..self.end() + 1).index(slice)
2257 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2258 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2259 (*self.start()..self.end() + 1).index_mut(slice)
2263 #[stable(feature = "inclusive_range", since = "1.26.0")]
2264 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2268 fn get(self, slice: &[T]) -> Option<&[T]> {
2269 (0..=self.end).get(slice)
2273 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2274 (0..=self.end).get_mut(slice)
2278 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2279 (0..=self.end).get_unchecked(slice)
2283 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2284 (0..=self.end).get_unchecked_mut(slice)
2288 fn index(self, slice: &[T]) -> &[T] {
2289 (0..=self.end).index(slice)
2293 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2294 (0..=self.end).index_mut(slice)
2298 ////////////////////////////////////////////////////////////////////////////////
2300 ////////////////////////////////////////////////////////////////////////////////
2302 #[stable(feature = "rust1", since = "1.0.0")]
2303 impl<'a, T> Default for &'a [T] {
2304 /// Creates an empty slice.
2305 fn default() -> &'a [T] { &[] }
2308 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2309 impl<'a, T> Default for &'a mut [T] {
2310 /// Creates a mutable empty slice.
2311 fn default() -> &'a mut [T] { &mut [] }
2318 #[stable(feature = "rust1", since = "1.0.0")]
2319 impl<'a, T> IntoIterator for &'a [T] {
2321 type IntoIter = Iter<'a, T>;
2323 fn into_iter(self) -> Iter<'a, T> {
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<'a, T> IntoIterator for &'a mut [T] {
2330 type Item = &'a mut T;
2331 type IntoIter = IterMut<'a, T>;
2333 fn into_iter(self) -> IterMut<'a, T> {
2338 // Macro helper functions
2340 fn size_from_ptr<T>(_: *const T) -> usize {
2344 // Inlining is_empty and len makes a huge performance difference
2345 macro_rules! is_empty {
2346 // The way we encode the length of a ZST iterator, this works both for ZST
2348 ($self: ident) => {$self.ptr == $self.end}
2350 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2351 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2353 ($self: ident) => {{
2354 let start = $self.ptr;
2355 let diff = ($self.end as usize).wrapping_sub(start as usize);
2356 let size = size_from_ptr(start);
2360 // Using division instead of `offset_from` helps LLVM remove bounds checks
2366 // The shared definition of the `Iter` and `IterMut` iterators
2367 macro_rules! iterator {
2368 (struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
2369 impl<'a, T> $name<'a, T> {
2370 // Helper function for creating a slice from the iterator.
2372 fn make_slice(&self) -> &'a [T] {
2373 unsafe { from_raw_parts(self.ptr, len!(self)) }
2376 // Helper function for moving the start of the iterator forwards by `offset` elements,
2377 // returning the old start.
2378 // Unsafe because the offset must be in-bounds or one-past-the-end.
2380 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2381 if mem::size_of::<T>() == 0 {
2382 // This is *reducing* the length. `ptr` never changes with ZST.
2383 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2387 self.ptr = self.ptr.offset(offset);
2392 // Helper function for moving the end of the iterator backwards by `offset` elements,
2393 // returning the new end.
2394 // Unsafe because the offset must be in-bounds or one-past-the-end.
2396 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2397 if mem::size_of::<T>() == 0 {
2398 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2401 self.end = self.end.offset(-offset);
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 impl<'a, T> ExactSizeIterator for $name<'a, T> {
2410 fn len(&self) -> usize {
2415 fn is_empty(&self) -> bool {
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl<'a, T> Iterator for $name<'a, T> {
2425 fn next(&mut self) -> Option<$elem> {
2426 // could be implemented with slices, but this avoids bounds checks
2428 assume(!self.ptr.is_null());
2429 if mem::size_of::<T>() != 0 {
2430 assume(!self.end.is_null());
2432 if is_empty!(self) {
2435 Some(& $( $mut_ )* *self.post_inc_start(1))
2441 fn size_hint(&self) -> (usize, Option<usize>) {
2442 let exact = len!(self);
2443 (exact, Some(exact))
2447 fn count(self) -> usize {
2452 fn nth(&mut self, n: usize) -> Option<$elem> {
2453 if n >= len!(self) {
2454 // This iterator is now empty.
2455 if mem::size_of::<T>() == 0 {
2456 // We have to do it this way as `ptr` may never be 0, but `end`
2457 // could be (due to wrapping).
2458 self.end = self.ptr;
2460 self.ptr = self.end;
2464 // We are in bounds. `offset` does the right thing even for ZSTs.
2466 let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2467 self.post_inc_start((n as isize).wrapping_add(1));
2473 fn last(mut self) -> Option<$elem> {
2478 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2479 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2481 // manual unrolling is needed when there are conditional exits from the loop
2482 let mut accum = init;
2484 while len!(self) >= 4 {
2485 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2486 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2487 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2488 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2490 while !is_empty!(self) {
2491 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2498 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2499 where Fold: FnMut(Acc, Self::Item) -> Acc,
2501 // Let LLVM unroll this, rather than using the default
2502 // impl that would force the manual unrolling above
2503 let mut accum = init;
2504 while let Some(x) = self.next() {
2505 accum = f(accum, x);
2511 #[rustc_inherit_overflow_checks]
2512 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2514 P: FnMut(Self::Item) -> bool,
2516 // The addition might panic on overflow.
2518 self.try_fold(0, move |i, x| {
2519 if predicate(x) { Err(i) }
2523 unsafe { assume(i < n) };
2529 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2530 P: FnMut(Self::Item) -> bool,
2531 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2533 // No need for an overflow check here, because `ExactSizeIterator`
2535 self.try_rfold(n, move |i, x| {
2537 if predicate(x) { Err(i) }
2541 unsafe { assume(i < n) };
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2550 fn next_back(&mut self) -> Option<$elem> {
2551 // could be implemented with slices, but this avoids bounds checks
2553 assume(!self.ptr.is_null());
2554 if mem::size_of::<T>() != 0 {
2555 assume(!self.end.is_null());
2557 if is_empty!(self) {
2560 Some(& $( $mut_ )* *self.pre_dec_end(1))
2566 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2567 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2569 // manual unrolling is needed when there are conditional exits from the loop
2570 let mut accum = init;
2572 while len!(self) >= 4 {
2573 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2574 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2575 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2576 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2578 // inlining is_empty everywhere makes a huge performance difference
2579 while !is_empty!(self) {
2580 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2587 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2588 where Fold: FnMut(Acc, Self::Item) -> Acc,
2590 // Let LLVM unroll this, rather than using the default
2591 // impl that would force the manual unrolling above
2592 let mut accum = init;
2593 while let Some(x) = self.next_back() {
2594 accum = f(accum, x);
2600 #[stable(feature = "fused", since = "1.26.0")]
2601 impl<'a, T> FusedIterator for $name<'a, T> {}
2603 #[unstable(feature = "trusted_len", issue = "37572")]
2604 unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
2608 /// Immutable slice iterator
2610 /// This struct is created by the [`iter`] method on [slices].
2617 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2618 /// let slice = &[1, 2, 3];
2620 /// // Then, we iterate over it:
2621 /// for element in slice.iter() {
2622 /// println!("{}", element);
2626 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2627 /// [slices]: ../../std/primitive.slice.html
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 pub struct Iter<'a, T: 'a> {
2631 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
2632 // ptr == end is a quick test for the Iterator being empty, that works
2633 // for both ZST and non-ZST.
2634 _marker: marker::PhantomData<&'a T>,
2637 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2638 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2640 f.debug_tuple("Iter")
2641 .field(&self.as_slice())
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2651 impl<'a, T> Iter<'a, T> {
2652 /// View the underlying data as a subslice of the original data.
2654 /// This has the same lifetime as the original slice, and so the
2655 /// iterator can continue to be used while this exists.
2662 /// // First, we declare a type which has the `iter` method to get the `Iter`
2663 /// // struct (&[usize here]):
2664 /// let slice = &[1, 2, 3];
2666 /// // Then, we get the iterator:
2667 /// let mut iter = slice.iter();
2668 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2669 /// println!("{:?}", iter.as_slice());
2671 /// // Next, we move to the second element of the slice:
2673 /// // Now `as_slice` returns "[2, 3]":
2674 /// println!("{:?}", iter.as_slice());
2676 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2677 pub fn as_slice(&self) -> &'a [T] {
2682 iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
2684 #[stable(feature = "rust1", since = "1.0.0")]
2685 impl<'a, T> Clone for Iter<'a, T> {
2686 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2689 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2690 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2691 fn as_ref(&self) -> &[T] {
2696 /// Mutable slice iterator.
2698 /// This struct is created by the [`iter_mut`] method on [slices].
2705 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2706 /// // struct (&[usize here]):
2707 /// let mut slice = &mut [1, 2, 3];
2709 /// // Then, we iterate over it and increment each element value:
2710 /// for element in slice.iter_mut() {
2714 /// // We now have "[2, 3, 4]":
2715 /// println!("{:?}", slice);
2718 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2719 /// [slices]: ../../std/primitive.slice.html
2720 #[stable(feature = "rust1", since = "1.0.0")]
2721 pub struct IterMut<'a, T: 'a> {
2723 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
2724 // ptr == end is a quick test for the Iterator being empty, that works
2725 // for both ZST and non-ZST.
2726 _marker: marker::PhantomData<&'a mut T>,
2729 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2730 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2731 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2732 f.debug_tuple("IterMut")
2733 .field(&self.make_slice())
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2740 #[stable(feature = "rust1", since = "1.0.0")]
2741 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2743 impl<'a, T> IterMut<'a, T> {
2744 /// View the underlying data as a subslice of the original data.
2746 /// To avoid creating `&mut` references that alias, this is forced
2747 /// to consume the iterator.
2754 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2755 /// // struct (&[usize here]):
2756 /// let mut slice = &mut [1, 2, 3];
2759 /// // Then, we get the iterator:
2760 /// let mut iter = slice.iter_mut();
2761 /// // We move to next element:
2763 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
2764 /// println!("{:?}", iter.into_slice());
2767 /// // Now let's modify a value of the slice:
2769 /// // First we get back the iterator:
2770 /// let mut iter = slice.iter_mut();
2771 /// // We change the value of the first element of the slice returned by the `next` method:
2772 /// *iter.next().unwrap() += 1;
2774 /// // Now slice is "[2, 2, 3]":
2775 /// println!("{:?}", slice);
2777 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2778 pub fn into_slice(self) -> &'a mut [T] {
2779 unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
2783 iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
2785 /// An internal abstraction over the splitting iterators, so that
2786 /// splitn, splitn_mut etc can be implemented once.
2788 trait SplitIter: DoubleEndedIterator {
2789 /// Marks the underlying iterator as complete, extracting the remaining
2790 /// portion of the slice.
2791 fn finish(&mut self) -> Option<Self::Item>;
2794 /// An iterator over subslices separated by elements that match a predicate
2797 /// This struct is created by the [`split`] method on [slices].
2799 /// [`split`]: ../../std/primitive.slice.html#method.split
2800 /// [slices]: ../../std/primitive.slice.html
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
2808 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2809 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
2810 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2811 f.debug_struct("Split")
2812 .field("v", &self.v)
2813 .field("finished", &self.finished)
2818 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2819 #[stable(feature = "rust1", since = "1.0.0")]
2820 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
2821 fn clone(&self) -> Split<'a, T, P> {
2824 pred: self.pred.clone(),
2825 finished: self.finished,
2830 #[stable(feature = "rust1", since = "1.0.0")]
2831 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2832 type Item = &'a [T];
2835 fn next(&mut self) -> Option<&'a [T]> {
2836 if self.finished { return None; }
2838 match self.v.iter().position(|x| (self.pred)(x)) {
2839 None => self.finish(),
2841 let ret = Some(&self.v[..idx]);
2842 self.v = &self.v[idx + 1..];
2849 fn size_hint(&self) -> (usize, Option<usize>) {
2853 (1, Some(self.v.len() + 1))
2858 #[stable(feature = "rust1", since = "1.0.0")]
2859 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2861 fn next_back(&mut self) -> Option<&'a [T]> {
2862 if self.finished { return None; }
2864 match self.v.iter().rposition(|x| (self.pred)(x)) {
2865 None => self.finish(),
2867 let ret = Some(&self.v[idx + 1..]);
2868 self.v = &self.v[..idx];
2875 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
2877 fn finish(&mut self) -> Option<&'a [T]> {
2878 if self.finished { None } else { self.finished = true; Some(self.v) }
2882 #[stable(feature = "fused", since = "1.26.0")]
2883 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
2885 /// An iterator over the subslices of the vector which are separated
2886 /// by elements that match `pred`.
2888 /// This struct is created by the [`split_mut`] method on [slices].
2890 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
2891 /// [slices]: ../../std/primitive.slice.html
2892 #[stable(feature = "rust1", since = "1.0.0")]
2893 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
2899 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2900 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2901 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2902 f.debug_struct("SplitMut")
2903 .field("v", &self.v)
2904 .field("finished", &self.finished)
2909 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2911 fn finish(&mut self) -> Option<&'a mut [T]> {
2915 self.finished = true;
2916 Some(mem::replace(&mut self.v, &mut []))
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2923 type Item = &'a mut [T];
2926 fn next(&mut self) -> Option<&'a mut [T]> {
2927 if self.finished { return None; }
2929 let idx_opt = { // work around borrowck limitations
2930 let pred = &mut self.pred;
2931 self.v.iter().position(|x| (*pred)(x))
2934 None => self.finish(),
2936 let tmp = mem::replace(&mut self.v, &mut []);
2937 let (head, tail) = tmp.split_at_mut(idx);
2938 self.v = &mut tail[1..];
2945 fn size_hint(&self) -> (usize, Option<usize>) {
2949 // if the predicate doesn't match anything, we yield one slice
2950 // if it matches every element, we yield len+1 empty slices.
2951 (1, Some(self.v.len() + 1))
2956 #[stable(feature = "rust1", since = "1.0.0")]
2957 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
2958 P: FnMut(&T) -> bool,
2961 fn next_back(&mut self) -> Option<&'a mut [T]> {
2962 if self.finished { return None; }
2964 let idx_opt = { // work around borrowck limitations
2965 let pred = &mut self.pred;
2966 self.v.iter().rposition(|x| (*pred)(x))
2969 None => self.finish(),
2971 let tmp = mem::replace(&mut self.v, &mut []);
2972 let (head, tail) = tmp.split_at_mut(idx);
2974 Some(&mut tail[1..])
2980 #[stable(feature = "fused", since = "1.26.0")]
2981 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
2983 /// An iterator over subslices separated by elements that match a predicate
2984 /// function, starting from the end of the slice.
2986 /// This struct is created by the [`rsplit`] method on [slices].
2988 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
2989 /// [slices]: ../../std/primitive.slice.html
2990 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2991 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
2992 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
2993 inner: Split<'a, T, P>
2996 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2997 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
2998 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2999 f.debug_struct("RSplit")
3000 .field("v", &self.inner.v)
3001 .field("finished", &self.inner.finished)
3006 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3007 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3008 type Item = &'a [T];
3011 fn next(&mut self) -> Option<&'a [T]> {
3012 self.inner.next_back()
3016 fn size_hint(&self) -> (usize, Option<usize>) {
3017 self.inner.size_hint()
3021 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3022 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3024 fn next_back(&mut self) -> Option<&'a [T]> {
3029 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3030 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3032 fn finish(&mut self) -> Option<&'a [T]> {
3037 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3038 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
3040 /// An iterator over the subslices of the vector which are separated
3041 /// by elements that match `pred`, starting from the end of the slice.
3043 /// This struct is created by the [`rsplit_mut`] method on [slices].
3045 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3046 /// [slices]: ../../std/primitive.slice.html
3047 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3048 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3049 inner: SplitMut<'a, T, P>
3052 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3053 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3055 f.debug_struct("RSplitMut")
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> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3065 fn finish(&mut self) -> Option<&'a mut [T]> {
3070 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3071 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3072 type Item = &'a mut [T];
3075 fn next(&mut self) -> Option<&'a mut [T]> {
3076 self.inner.next_back()
3080 fn size_hint(&self) -> (usize, Option<usize>) {
3081 self.inner.size_hint()
3085 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3086 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3087 P: FnMut(&T) -> bool,
3090 fn next_back(&mut self) -> Option<&'a mut [T]> {
3095 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3096 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3098 /// An private iterator over subslices separated by elements that
3099 /// match a predicate function, splitting at most a fixed number of
3102 struct GenericSplitN<I> {
3107 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3111 fn next(&mut self) -> Option<T> {
3114 1 => { self.count -= 1; self.iter.finish() }
3115 _ => { self.count -= 1; self.iter.next() }
3120 fn size_hint(&self) -> (usize, Option<usize>) {
3121 let (lower, upper_opt) = self.iter.size_hint();
3122 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3126 /// An iterator over subslices separated by elements that match a predicate
3127 /// function, limited to a given number of splits.
3129 /// This struct is created by the [`splitn`] method on [slices].
3131 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3132 /// [slices]: ../../std/primitive.slice.html
3133 #[stable(feature = "rust1", since = "1.0.0")]
3134 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3135 inner: GenericSplitN<Split<'a, T, P>>
3138 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3139 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
3140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3141 f.debug_struct("SplitN")
3142 .field("inner", &self.inner)
3147 /// An iterator over subslices separated by elements that match a
3148 /// predicate function, limited to a given number of splits, starting
3149 /// from the end of the slice.
3151 /// This struct is created by the [`rsplitn`] method on [slices].
3153 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3154 /// [slices]: ../../std/primitive.slice.html
3155 #[stable(feature = "rust1", since = "1.0.0")]
3156 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3157 inner: GenericSplitN<RSplit<'a, T, P>>
3160 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3161 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3162 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3163 f.debug_struct("RSplitN")
3164 .field("inner", &self.inner)
3169 /// An iterator over subslices separated by elements that match a predicate
3170 /// function, limited to a given number of splits.
3172 /// This struct is created by the [`splitn_mut`] method on [slices].
3174 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3175 /// [slices]: ../../std/primitive.slice.html
3176 #[stable(feature = "rust1", since = "1.0.0")]
3177 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3178 inner: GenericSplitN<SplitMut<'a, T, P>>
3181 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3182 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3184 f.debug_struct("SplitNMut")
3185 .field("inner", &self.inner)
3190 /// An iterator over subslices separated by elements that match a
3191 /// predicate function, limited to a given number of splits, starting
3192 /// from the end of the slice.
3194 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3196 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3197 /// [slices]: ../../std/primitive.slice.html
3198 #[stable(feature = "rust1", since = "1.0.0")]
3199 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3200 inner: GenericSplitN<RSplitMut<'a, T, P>>
3203 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3204 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3206 f.debug_struct("RSplitNMut")
3207 .field("inner", &self.inner)
3212 macro_rules! forward_iterator {
3213 ($name:ident: $elem:ident, $iter_of:ty) => {
3214 #[stable(feature = "rust1", since = "1.0.0")]
3215 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3216 P: FnMut(&T) -> bool
3218 type Item = $iter_of;
3221 fn next(&mut self) -> Option<$iter_of> {
3226 fn size_hint(&self) -> (usize, Option<usize>) {
3227 self.inner.size_hint()
3231 #[stable(feature = "fused", since = "1.26.0")]
3232 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3233 where P: FnMut(&T) -> bool {}
3237 forward_iterator! { SplitN: T, &'a [T] }
3238 forward_iterator! { RSplitN: T, &'a [T] }
3239 forward_iterator! { SplitNMut: T, &'a mut [T] }
3240 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3242 /// An iterator over overlapping subslices of length `size`.
3244 /// This struct is created by the [`windows`] method on [slices].
3246 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3247 /// [slices]: ../../std/primitive.slice.html
3249 #[stable(feature = "rust1", since = "1.0.0")]
3250 pub struct Windows<'a, T:'a> {
3255 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3256 #[stable(feature = "rust1", since = "1.0.0")]
3257 impl<'a, T> Clone for Windows<'a, T> {
3258 fn clone(&self) -> Windows<'a, T> {
3266 #[stable(feature = "rust1", since = "1.0.0")]
3267 impl<'a, T> Iterator for Windows<'a, T> {
3268 type Item = &'a [T];
3271 fn next(&mut self) -> Option<&'a [T]> {
3272 if self.size > self.v.len() {
3275 let ret = Some(&self.v[..self.size]);
3276 self.v = &self.v[1..];
3282 fn size_hint(&self) -> (usize, Option<usize>) {
3283 if self.size > self.v.len() {
3286 let size = self.v.len() - self.size + 1;
3292 fn count(self) -> usize {
3297 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3298 let (end, overflow) = self.size.overflowing_add(n);
3299 if end > self.v.len() || overflow {
3303 let nth = &self.v[n..end];
3304 self.v = &self.v[n+1..];
3310 fn last(self) -> Option<Self::Item> {
3311 if self.size > self.v.len() {
3314 let start = self.v.len() - self.size;
3315 Some(&self.v[start..])
3320 #[stable(feature = "rust1", since = "1.0.0")]
3321 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3323 fn next_back(&mut self) -> Option<&'a [T]> {
3324 if self.size > self.v.len() {
3327 let ret = Some(&self.v[self.v.len()-self.size..]);
3328 self.v = &self.v[..self.v.len()-1];
3334 #[stable(feature = "rust1", since = "1.0.0")]
3335 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3337 #[unstable(feature = "trusted_len", issue = "37572")]
3338 unsafe impl<'a, T> TrustedLen for Windows<'a, T> {}
3340 #[stable(feature = "fused", since = "1.26.0")]
3341 impl<'a, T> FusedIterator for Windows<'a, T> {}
3344 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3345 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3346 from_raw_parts(self.v.as_ptr().add(i), self.size)
3348 fn may_have_side_effect() -> bool { false }
3351 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3354 /// When the slice len is not evenly divided by the chunk size, the last slice
3355 /// of the iteration will be the remainder.
3357 /// This struct is created by the [`chunks`] method on [slices].
3359 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3360 /// [slices]: ../../std/primitive.slice.html
3362 #[stable(feature = "rust1", since = "1.0.0")]
3363 pub struct Chunks<'a, T:'a> {
3368 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3369 #[stable(feature = "rust1", since = "1.0.0")]
3370 impl<'a, T> Clone for Chunks<'a, T> {
3371 fn clone(&self) -> Chunks<'a, T> {
3374 chunk_size: self.chunk_size,
3379 #[stable(feature = "rust1", since = "1.0.0")]
3380 impl<'a, T> Iterator for Chunks<'a, T> {
3381 type Item = &'a [T];
3384 fn next(&mut self) -> Option<&'a [T]> {
3385 if self.v.is_empty() {
3388 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3389 let (fst, snd) = self.v.split_at(chunksz);
3396 fn size_hint(&self) -> (usize, Option<usize>) {
3397 if self.v.is_empty() {
3400 let n = self.v.len() / self.chunk_size;
3401 let rem = self.v.len() % self.chunk_size;
3402 let n = if rem > 0 { n+1 } else { n };
3408 fn count(self) -> usize {
3413 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3414 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3415 if start >= self.v.len() || overflow {
3419 let end = match start.checked_add(self.chunk_size) {
3420 Some(sum) => cmp::min(self.v.len(), sum),
3421 None => self.v.len(),
3423 let nth = &self.v[start..end];
3424 self.v = &self.v[end..];
3430 fn last(self) -> Option<Self::Item> {
3431 if self.v.is_empty() {
3434 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3435 Some(&self.v[start..])
3440 #[stable(feature = "rust1", since = "1.0.0")]
3441 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3443 fn next_back(&mut self) -> Option<&'a [T]> {
3444 if self.v.is_empty() {
3447 let remainder = self.v.len() % self.chunk_size;
3448 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3449 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3456 #[stable(feature = "rust1", since = "1.0.0")]
3457 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3459 #[unstable(feature = "trusted_len", issue = "37572")]
3460 unsafe impl<'a, T> TrustedLen for Chunks<'a, T> {}
3462 #[stable(feature = "fused", since = "1.26.0")]
3463 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3466 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3467 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3468 let start = i * self.chunk_size;
3469 let end = match start.checked_add(self.chunk_size) {
3470 None => self.v.len(),
3471 Some(end) => cmp::min(end, self.v.len()),
3473 from_raw_parts(self.v.as_ptr().add(start), end - start)
3475 fn may_have_side_effect() -> bool { false }
3478 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3479 /// elements at a time). When the slice len is not evenly divided by the chunk
3480 /// size, the last slice of the iteration will be the remainder.
3482 /// This struct is created by the [`chunks_mut`] method on [slices].
3484 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3485 /// [slices]: ../../std/primitive.slice.html
3487 #[stable(feature = "rust1", since = "1.0.0")]
3488 pub struct ChunksMut<'a, T:'a> {
3493 #[stable(feature = "rust1", since = "1.0.0")]
3494 impl<'a, T> Iterator for ChunksMut<'a, T> {
3495 type Item = &'a mut [T];
3498 fn next(&mut self) -> Option<&'a mut [T]> {
3499 if self.v.is_empty() {
3502 let sz = cmp::min(self.v.len(), self.chunk_size);
3503 let tmp = mem::replace(&mut self.v, &mut []);
3504 let (head, tail) = tmp.split_at_mut(sz);
3511 fn size_hint(&self) -> (usize, Option<usize>) {
3512 if self.v.is_empty() {
3515 let n = self.v.len() / self.chunk_size;
3516 let rem = self.v.len() % self.chunk_size;
3517 let n = if rem > 0 { n + 1 } else { n };
3523 fn count(self) -> usize {
3528 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3529 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3530 if start >= self.v.len() || overflow {
3534 let end = match start.checked_add(self.chunk_size) {
3535 Some(sum) => cmp::min(self.v.len(), sum),
3536 None => self.v.len(),
3538 let tmp = mem::replace(&mut self.v, &mut []);
3539 let (head, tail) = tmp.split_at_mut(end);
3540 let (_, nth) = head.split_at_mut(start);
3547 fn last(self) -> Option<Self::Item> {
3548 if self.v.is_empty() {
3551 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3552 Some(&mut self.v[start..])
3557 #[stable(feature = "rust1", since = "1.0.0")]
3558 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3560 fn next_back(&mut self) -> Option<&'a mut [T]> {
3561 if self.v.is_empty() {
3564 let remainder = self.v.len() % self.chunk_size;
3565 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3566 let tmp = mem::replace(&mut self.v, &mut []);
3567 let tmp_len = tmp.len();
3568 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3575 #[stable(feature = "rust1", since = "1.0.0")]
3576 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3578 #[unstable(feature = "trusted_len", issue = "37572")]
3579 unsafe impl<'a, T> TrustedLen for ChunksMut<'a, T> {}
3581 #[stable(feature = "fused", since = "1.26.0")]
3582 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3585 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3586 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3587 let start = i * self.chunk_size;
3588 let end = match start.checked_add(self.chunk_size) {
3589 None => self.v.len(),
3590 Some(end) => cmp::min(end, self.v.len()),
3592 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
3594 fn may_have_side_effect() -> bool { false }
3597 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3600 /// When the slice len is not evenly divided by the chunk size, the last
3601 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
3602 /// the [`remainder`] function from the iterator.
3604 /// This struct is created by the [`exact_chunks`] method on [slices].
3606 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3607 /// [`remainder`]: ../../std/slice/struct.ExactChunks.html#method.remainder
3608 /// [slices]: ../../std/primitive.slice.html
3610 #[unstable(feature = "exact_chunks", issue = "47115")]
3611 pub struct ExactChunks<'a, T:'a> {
3617 #[unstable(feature = "exact_chunks", issue = "47115")]
3618 impl<'a, T> ExactChunks<'a, T> {
3619 /// Return the remainder of the original slice that is not going to be
3620 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3622 pub fn remainder(&self) -> &'a [T] {
3627 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3628 #[unstable(feature = "exact_chunks", issue = "47115")]
3629 impl<'a, T> Clone for ExactChunks<'a, T> {
3630 fn clone(&self) -> ExactChunks<'a, T> {
3634 chunk_size: self.chunk_size,
3639 #[unstable(feature = "exact_chunks", issue = "47115")]
3640 impl<'a, T> Iterator for ExactChunks<'a, T> {
3641 type Item = &'a [T];
3644 fn next(&mut self) -> Option<&'a [T]> {
3645 if self.v.len() < self.chunk_size {
3648 let (fst, snd) = self.v.split_at(self.chunk_size);
3655 fn size_hint(&self) -> (usize, Option<usize>) {
3656 let n = self.v.len() / self.chunk_size;
3661 fn count(self) -> usize {
3666 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3667 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3668 if start >= self.v.len() || overflow {
3672 let (_, snd) = self.v.split_at(start);
3679 fn last(mut self) -> Option<Self::Item> {
3684 #[unstable(feature = "exact_chunks", issue = "47115")]
3685 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3687 fn next_back(&mut self) -> Option<&'a [T]> {
3688 if self.v.len() < self.chunk_size {
3691 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3698 #[unstable(feature = "exact_chunks", issue = "47115")]
3699 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
3700 fn is_empty(&self) -> bool {
3705 #[unstable(feature = "trusted_len", issue = "37572")]
3706 unsafe impl<'a, T> TrustedLen for ExactChunks<'a, T> {}
3708 #[unstable(feature = "exact_chunks", issue = "47115")]
3709 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
3712 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
3713 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3714 let start = i * self.chunk_size;
3715 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
3717 fn may_have_side_effect() -> bool { false }
3720 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3721 /// elements at a time).
3723 /// When the slice len is not evenly divided by the chunk size, the last up to
3724 /// `chunk_size-1` elements will be omitted but can be retrieved from the
3725 /// [`into_remainder`] function from the iterator.
3727 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
3729 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
3730 /// [`into_remainder`]: ../../std/slice/struct.ExactChunksMut.html#method.into_remainder
3731 /// [slices]: ../../std/primitive.slice.html
3733 #[unstable(feature = "exact_chunks", issue = "47115")]
3734 pub struct ExactChunksMut<'a, T:'a> {
3740 #[unstable(feature = "exact_chunks", issue = "47115")]
3741 impl<'a, T> ExactChunksMut<'a, T> {
3742 /// Return the remainder of the original slice that is not going to be
3743 /// returned by the iterator. The returned slice has at most `chunk_size-1`
3745 pub fn into_remainder(self) -> &'a mut [T] {
3750 #[unstable(feature = "exact_chunks", issue = "47115")]
3751 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
3752 type Item = &'a mut [T];
3755 fn next(&mut self) -> Option<&'a mut [T]> {
3756 if self.v.len() < self.chunk_size {
3759 let tmp = mem::replace(&mut self.v, &mut []);
3760 let (head, tail) = tmp.split_at_mut(self.chunk_size);
3767 fn size_hint(&self) -> (usize, Option<usize>) {
3768 let n = self.v.len() / self.chunk_size;
3773 fn count(self) -> usize {
3778 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3779 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3780 if start >= self.v.len() || overflow {
3784 let tmp = mem::replace(&mut self.v, &mut []);
3785 let (_, snd) = tmp.split_at_mut(start);
3792 fn last(mut self) -> Option<Self::Item> {
3797 #[unstable(feature = "exact_chunks", issue = "47115")]
3798 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
3800 fn next_back(&mut self) -> Option<&'a mut [T]> {
3801 if self.v.len() < self.chunk_size {
3804 let tmp = mem::replace(&mut self.v, &mut []);
3805 let tmp_len = tmp.len();
3806 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
3813 #[unstable(feature = "exact_chunks", issue = "47115")]
3814 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
3815 fn is_empty(&self) -> bool {
3820 #[unstable(feature = "trusted_len", issue = "37572")]
3821 unsafe impl<'a, T> TrustedLen for ExactChunksMut<'a, T> {}
3823 #[unstable(feature = "exact_chunks", issue = "47115")]
3824 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
3827 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
3828 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3829 let start = i * self.chunk_size;
3830 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
3832 fn may_have_side_effect() -> bool { false }
3839 /// Forms a slice from a pointer and a length.
3841 /// The `len` argument is the number of **elements**, not the number of bytes.
3845 /// This function is unsafe as there is no guarantee that the given pointer is
3846 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
3847 /// lifetime for the returned slice.
3849 /// `data` must be non-null and aligned, even for zero-length slices. One
3850 /// reason for this is that enum layout optimizations may rely on references
3851 /// (including slices of any length) being aligned and non-null to distinguish
3852 /// them from other data. You can obtain a pointer that is usable as `data`
3853 /// for zero-length slices using [`NonNull::dangling()`].
3855 /// The total size of the slice must lower than `isize::MAX` **bytes** in
3856 /// memory. See the safety documentation of [`pointer::offset`].
3860 /// The lifetime for the returned slice is inferred from its usage. To
3861 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
3862 /// source lifetime is safe in the context, such as by providing a helper
3863 /// function taking the lifetime of a host value for the slice, or by explicit
3871 /// // manifest a slice for a single element
3873 /// let ptr = &x as *const _;
3874 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
3875 /// assert_eq!(slice[0], 42);
3878 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
3879 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
3881 #[stable(feature = "rust1", since = "1.0.0")]
3882 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
3883 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
3884 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
3885 "attempt to create slice covering half the address space");
3886 Repr { raw: FatPtr { data, len } }.rust
3889 /// Performs the same functionality as [`from_raw_parts`], except that a
3890 /// mutable slice is returned.
3892 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
3893 /// as not being able to provide a non-aliasing guarantee of the returned
3894 /// mutable slice. `data` must be non-null and aligned even for zero-length
3895 /// slices as with [`from_raw_parts`]. The total size of the slice must be
3896 /// lower than `isize::MAX` **bytes** in memory. See the safety documentation
3897 /// of [`pointer::offset`].
3899 /// See the documentation of [`from_raw_parts`] for more details.
3901 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
3902 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
3904 #[stable(feature = "rust1", since = "1.0.0")]
3905 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
3906 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
3907 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
3908 "attempt to create slice covering half the address space");
3909 Repr { raw: FatPtr { data, len } }.rust_mut
3912 /// Converts a reference to T into a slice of length 1 (without copying).
3913 #[stable(feature = "from_ref", since = "1.28.0")]
3914 pub fn from_ref<T>(s: &T) -> &[T] {
3916 from_raw_parts(s, 1)
3920 /// Converts a reference to T into a slice of length 1 (without copying).
3921 #[stable(feature = "from_ref", since = "1.28.0")]
3922 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
3924 from_raw_parts_mut(s, 1)
3928 // This function is public only because there is no other way to unit test heapsort.
3929 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
3931 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
3932 where F: FnMut(&T, &T) -> bool
3934 sort::heapsort(v, &mut is_less);
3938 // Comparison traits
3942 /// Calls implementation provided memcmp.
3944 /// Interprets the data as u8.
3946 /// Returns 0 for equal, < 0 for less than and > 0 for greater
3948 // FIXME(#32610): Return type should be c_int
3949 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
3952 #[stable(feature = "rust1", since = "1.0.0")]
3953 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
3954 fn eq(&self, other: &[B]) -> bool {
3955 SlicePartialEq::equal(self, other)
3958 fn ne(&self, other: &[B]) -> bool {
3959 SlicePartialEq::not_equal(self, other)
3963 #[stable(feature = "rust1", since = "1.0.0")]
3964 impl<T: Eq> Eq for [T] {}
3966 /// Implements comparison of vectors lexicographically.
3967 #[stable(feature = "rust1", since = "1.0.0")]
3968 impl<T: Ord> Ord for [T] {
3969 fn cmp(&self, other: &[T]) -> Ordering {
3970 SliceOrd::compare(self, other)
3974 /// Implements comparison of vectors lexicographically.
3975 #[stable(feature = "rust1", since = "1.0.0")]
3976 impl<T: PartialOrd> PartialOrd for [T] {
3977 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
3978 SlicePartialOrd::partial_compare(self, other)
3983 // intermediate trait for specialization of slice's PartialEq
3984 trait SlicePartialEq<B> {
3985 fn equal(&self, other: &[B]) -> bool;
3987 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
3990 // Generic slice equality
3991 impl<A, B> SlicePartialEq<B> for [A]
3992 where A: PartialEq<B>
3994 default fn equal(&self, other: &[B]) -> bool {
3995 if self.len() != other.len() {
3999 for i in 0..self.len() {
4000 if !self[i].eq(&other[i]) {
4009 // Use memcmp for bytewise equality when the types allow
4010 impl<A> SlicePartialEq<A> for [A]
4011 where A: PartialEq<A> + BytewiseEquality
4013 fn equal(&self, other: &[A]) -> bool {
4014 if self.len() != other.len() {
4017 if self.as_ptr() == other.as_ptr() {
4021 let size = mem::size_of_val(self);
4022 memcmp(self.as_ptr() as *const u8,
4023 other.as_ptr() as *const u8, size) == 0
4029 // intermediate trait for specialization of slice's PartialOrd
4030 trait SlicePartialOrd<B> {
4031 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4034 impl<A> SlicePartialOrd<A> for [A]
4037 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4038 let l = cmp::min(self.len(), other.len());
4040 // Slice to the loop iteration range to enable bound check
4041 // elimination in the compiler
4042 let lhs = &self[..l];
4043 let rhs = &other[..l];
4046 match lhs[i].partial_cmp(&rhs[i]) {
4047 Some(Ordering::Equal) => (),
4048 non_eq => return non_eq,
4052 self.len().partial_cmp(&other.len())
4056 impl<A> SlicePartialOrd<A> for [A]
4059 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4060 Some(SliceOrd::compare(self, other))
4065 // intermediate trait for specialization of slice's Ord
4067 fn compare(&self, other: &[B]) -> Ordering;
4070 impl<A> SliceOrd<A> for [A]
4073 default fn compare(&self, other: &[A]) -> Ordering {
4074 let l = cmp::min(self.len(), other.len());
4076 // Slice to the loop iteration range to enable bound check
4077 // elimination in the compiler
4078 let lhs = &self[..l];
4079 let rhs = &other[..l];
4082 match lhs[i].cmp(&rhs[i]) {
4083 Ordering::Equal => (),
4084 non_eq => return non_eq,
4088 self.len().cmp(&other.len())
4092 // memcmp compares a sequence of unsigned bytes lexicographically.
4093 // this matches the order we want for [u8], but no others (not even [i8]).
4094 impl SliceOrd<u8> for [u8] {
4096 fn compare(&self, other: &[u8]) -> Ordering {
4097 let order = unsafe {
4098 memcmp(self.as_ptr(), other.as_ptr(),
4099 cmp::min(self.len(), other.len()))
4102 self.len().cmp(&other.len())
4103 } else if order < 0 {
4112 /// Trait implemented for types that can be compared for equality using
4113 /// their bytewise representation
4114 trait BytewiseEquality { }
4116 macro_rules! impl_marker_for {
4117 ($traitname:ident, $($ty:ty)*) => {
4119 impl $traitname for $ty { }
4124 impl_marker_for!(BytewiseEquality,
4125 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4128 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4129 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4132 fn may_have_side_effect() -> bool { false }
4136 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4137 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4138 &mut *self.ptr.add(i)
4140 fn may_have_side_effect() -> bool { false }
4143 trait SliceContains: Sized {
4144 fn slice_contains(&self, x: &[Self]) -> bool;
4147 impl<T> SliceContains for T where T: PartialEq {
4148 default fn slice_contains(&self, x: &[Self]) -> bool {
4149 x.iter().any(|y| *y == *self)
4153 impl SliceContains for u8 {
4154 fn slice_contains(&self, x: &[Self]) -> bool {
4155 memchr::memchr(*self, x).is_some()
4159 impl SliceContains for i8 {
4160 fn slice_contains(&self, x: &[Self]) -> bool {
4161 let byte = *self as u8;
4162 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4163 memchr::memchr(byte, bytes).is_some()