1 // ignore-tidy-filelength
2 // ignore-tidy-undocumented-unsafe
4 //! Slice management and manipulation.
6 //! For more details see [`std::slice`].
8 //! [`std::slice`]: ../../std/slice/index.html
10 #![stable(feature = "rust1", since = "1.0.0")]
12 // How this module is organized.
14 // The library infrastructure for slices is fairly messy. There's
15 // a lot of stuff defined here. Let's keep it clean.
17 // The layout of this file is thus:
19 // * Inherent methods. This is where most of the slice API resides.
20 // * Implementations of a few common traits with important slice ops.
21 // * Definitions of a bunch of iterators.
23 // * The `raw` and `bytes` submodules.
24 // * Boilerplate trait implementations.
26 use crate::cmp::Ordering::{self, Less, Equal, Greater};
29 use crate::intrinsics::{assume, exact_div, unchecked_sub, is_aligned_and_not_null};
32 use crate::ops::{FnMut, Range, self};
33 use crate::option::Option;
34 use crate::option::Option::{None, Some};
35 use crate::result::Result;
36 use crate::result::Result::{Ok, Err};
39 use crate::marker::{Copy, Send, Sync, Sized, self};
41 #[unstable(feature = "slice_internals", issue = "none",
42 reason = "exposed from core to be reused in std; use the memchr crate")]
43 /// Pure rust memchr implementation, taken from rust-memchr
56 /// Returns the number of elements in the slice.
61 /// let a = [1, 2, 3];
62 /// assert_eq!(a.len(), 3);
64 #[stable(feature = "rust1", since = "1.0.0")]
65 #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
67 // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
68 #[allow(unused_attributes)]
69 #[allow_internal_unstable(const_fn_union)]
70 pub const fn len(&self) -> usize {
72 crate::ptr::Repr { rust: self }.raw.len
76 /// Returns `true` if the slice has a length of 0.
81 /// let a = [1, 2, 3];
82 /// assert!(!a.is_empty());
84 #[stable(feature = "rust1", since = "1.0.0")]
85 #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.32.0")]
87 pub const fn is_empty(&self) -> bool {
91 /// Returns the first element of the slice, or `None` if it is empty.
96 /// let v = [10, 40, 30];
97 /// assert_eq!(Some(&10), v.first());
99 /// let w: &[i32] = &[];
100 /// assert_eq!(None, w.first());
102 #[stable(feature = "rust1", since = "1.0.0")]
104 pub fn first(&self) -> Option<&T> {
108 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
113 /// let x = &mut [0, 1, 2];
115 /// if let Some(first) = x.first_mut() {
118 /// assert_eq!(x, &[5, 1, 2]);
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn first_mut(&mut self) -> Option<&mut T> {
126 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
131 /// let x = &[0, 1, 2];
133 /// if let Some((first, elements)) = x.split_first() {
134 /// assert_eq!(first, &0);
135 /// assert_eq!(elements, &[1, 2]);
138 #[stable(feature = "slice_splits", since = "1.5.0")]
140 pub fn split_first(&self) -> Option<(&T, &[T])> {
141 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
144 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
149 /// let x = &mut [0, 1, 2];
151 /// if let Some((first, elements)) = x.split_first_mut() {
156 /// assert_eq!(x, &[3, 4, 5]);
158 #[stable(feature = "slice_splits", since = "1.5.0")]
160 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
161 if self.is_empty() { None } else {
162 let split = self.split_at_mut(1);
163 Some((&mut split.0[0], split.1))
167 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
172 /// let x = &[0, 1, 2];
174 /// if let Some((last, elements)) = x.split_last() {
175 /// assert_eq!(last, &2);
176 /// assert_eq!(elements, &[0, 1]);
179 #[stable(feature = "slice_splits", since = "1.5.0")]
181 pub fn split_last(&self) -> Option<(&T, &[T])> {
182 let len = self.len();
183 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
186 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
191 /// let x = &mut [0, 1, 2];
193 /// if let Some((last, elements)) = x.split_last_mut() {
198 /// assert_eq!(x, &[4, 5, 3]);
200 #[stable(feature = "slice_splits", since = "1.5.0")]
202 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
203 let len = self.len();
204 if len == 0 { None } else {
205 let split = self.split_at_mut(len - 1);
206 Some((&mut split.1[0], split.0))
211 /// Returns the last element of the slice, or `None` if it is empty.
216 /// let v = [10, 40, 30];
217 /// assert_eq!(Some(&30), v.last());
219 /// let w: &[i32] = &[];
220 /// assert_eq!(None, w.last());
222 #[stable(feature = "rust1", since = "1.0.0")]
224 pub fn last(&self) -> Option<&T> {
225 let last_idx = self.len().checked_sub(1)?;
229 /// Returns a mutable pointer to the last item in the slice.
234 /// let x = &mut [0, 1, 2];
236 /// if let Some(last) = x.last_mut() {
239 /// assert_eq!(x, &[0, 1, 10]);
241 #[stable(feature = "rust1", since = "1.0.0")]
243 pub fn last_mut(&mut self) -> Option<&mut T> {
244 let last_idx = self.len().checked_sub(1)?;
245 self.get_mut(last_idx)
248 /// Returns a reference to an element or subslice depending on the type of
251 /// - If given a position, returns a reference to the element at that
252 /// position or `None` if out of bounds.
253 /// - If given a range, returns the subslice corresponding to that range,
254 /// or `None` if out of bounds.
259 /// let v = [10, 40, 30];
260 /// assert_eq!(Some(&40), v.get(1));
261 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
262 /// assert_eq!(None, v.get(3));
263 /// assert_eq!(None, v.get(0..4));
265 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn get<I>(&self, index: I) -> Option<&I::Output>
268 where I: SliceIndex<Self>
273 /// Returns a mutable reference to an element or subslice depending on the
274 /// type of index (see [`get`]) or `None` if the index is out of bounds.
276 /// [`get`]: #method.get
281 /// let x = &mut [0, 1, 2];
283 /// if let Some(elem) = x.get_mut(1) {
286 /// assert_eq!(x, &[0, 42, 2]);
288 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
291 where I: SliceIndex<Self>
296 /// Returns a reference to an element or subslice, without doing bounds
299 /// This is generally not recommended, use with caution!
300 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
301 /// even if the resulting reference is not used.
302 /// For a safe alternative see [`get`].
304 /// [`get`]: #method.get
305 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
310 /// let x = &[1, 2, 4];
313 /// assert_eq!(x.get_unchecked(1), &2);
316 #[stable(feature = "rust1", since = "1.0.0")]
318 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
319 where I: SliceIndex<Self>
321 index.get_unchecked(self)
324 /// Returns a mutable reference to an element or subslice, without doing
327 /// This is generally not recommended, use with caution!
328 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
329 /// even if the resulting reference is not used.
330 /// For a safe alternative see [`get_mut`].
332 /// [`get_mut`]: #method.get_mut
333 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
338 /// let x = &mut [1, 2, 4];
341 /// let elem = x.get_unchecked_mut(1);
344 /// assert_eq!(x, &[1, 13, 4]);
346 #[stable(feature = "rust1", since = "1.0.0")]
348 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
349 where I: SliceIndex<Self>
351 index.get_unchecked_mut(self)
354 /// Returns a raw pointer to the slice's buffer.
356 /// The caller must ensure that the slice outlives the pointer this
357 /// function returns, or else it will end up pointing to garbage.
359 /// The caller must also ensure that the memory the pointer (non-transitively) points to
360 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
361 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
363 /// Modifying the container referenced by this slice may cause its buffer
364 /// to be reallocated, which would also make any pointers to it invalid.
369 /// let x = &[1, 2, 4];
370 /// let x_ptr = x.as_ptr();
373 /// for i in 0..x.len() {
374 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
379 /// [`as_mut_ptr`]: #method.as_mut_ptr
380 #[stable(feature = "rust1", since = "1.0.0")]
381 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
383 pub const fn as_ptr(&self) -> *const T {
384 self as *const [T] as *const T
387 /// Returns an unsafe mutable pointer to the slice's buffer.
389 /// The caller must ensure that the slice outlives the pointer this
390 /// function returns, or else it will end up pointing to garbage.
392 /// Modifying the container referenced by this slice may cause its buffer
393 /// to be reallocated, which would also make any pointers to it invalid.
398 /// let x = &mut [1, 2, 4];
399 /// let x_ptr = x.as_mut_ptr();
402 /// for i in 0..x.len() {
403 /// *x_ptr.add(i) += 2;
406 /// assert_eq!(x, &[3, 4, 6]);
408 #[stable(feature = "rust1", since = "1.0.0")]
410 pub fn as_mut_ptr(&mut self) -> *mut T {
411 self as *mut [T] as *mut T
414 /// Returns the two raw pointers spanning the slice.
416 /// The returned range is half-open, which means that the end pointer
417 /// points *one past* the last element of the slice. This way, an empty
418 /// slice is represented by two equal pointers, and the difference between
419 /// the two pointers represents the size of the size.
421 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
422 /// requires extra caution, as it does not point to a valid element in the
425 /// This function is useful for interacting with foreign interfaces which
426 /// use two pointers to refer to a range of elements in memory, as is
429 /// It can also be useful to check if a pointer to an element refers to an
430 /// element of this slice:
433 /// #![feature(slice_ptr_range)]
435 /// let a = [1, 2, 3];
436 /// let x = &a[1] as *const _;
437 /// let y = &5 as *const _;
439 /// assert!(a.as_ptr_range().contains(&x));
440 /// assert!(!a.as_ptr_range().contains(&y));
443 /// [`as_ptr`]: #method.as_ptr
444 #[unstable(feature = "slice_ptr_range", issue = "65807")]
446 pub fn as_ptr_range(&self) -> Range<*const T> {
447 // The `add` here is safe, because:
449 // - Both pointers are part of the same object, as pointing directly
450 // past the object also counts.
452 // - The size of the slice is never larger than isize::MAX bytes, as
454 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
455 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
456 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
457 // (This doesn't seem normative yet, but the very same assumption is
458 // made in many places, including the Index implementation of slices.)
460 // - There is no wrapping around involved, as slices do not wrap past
461 // the end of the address space.
463 // See the documentation of pointer::add.
464 let start = self.as_ptr();
465 let end = unsafe { start.add(self.len()) };
469 /// Returns the two unsafe mutable pointers spanning the slice.
471 /// The returned range is half-open, which means that the end pointer
472 /// points *one past* the last element of the slice. This way, an empty
473 /// slice is represented by two equal pointers, and the difference between
474 /// the two pointers represents the size of the size.
476 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
477 /// pointer requires extra caution, as it does not point to a valid element
480 /// This function is useful for interacting with foreign interfaces which
481 /// use two pointers to refer to a range of elements in memory, as is
484 /// [`as_mut_ptr`]: #method.as_mut_ptr
485 #[unstable(feature = "slice_ptr_range", issue = "65807")]
487 pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
488 // See as_ptr_range() above for why `add` here is safe.
489 let start = self.as_mut_ptr();
490 let end = unsafe { start.add(self.len()) };
494 /// Swaps two elements in the slice.
498 /// * a - The index of the first element
499 /// * b - The index of the second element
503 /// Panics if `a` or `b` are out of bounds.
508 /// let mut v = ["a", "b", "c", "d"];
510 /// assert!(v == ["a", "d", "c", "b"]);
512 #[stable(feature = "rust1", since = "1.0.0")]
514 pub fn swap(&mut self, a: usize, b: usize) {
516 // Can't take two mutable loans from one vector, so instead just cast
517 // them to their raw pointers to do the swap
518 let pa: *mut T = &mut self[a];
519 let pb: *mut T = &mut self[b];
524 /// Reverses the order of elements in the slice, in place.
529 /// let mut v = [1, 2, 3];
531 /// assert!(v == [3, 2, 1]);
533 #[stable(feature = "rust1", since = "1.0.0")]
535 pub fn reverse(&mut self) {
536 let mut i: usize = 0;
539 // For very small types, all the individual reads in the normal
540 // path perform poorly. We can do better, given efficient unaligned
541 // load/store, by loading a larger chunk and reversing a register.
543 // Ideally LLVM would do this for us, as it knows better than we do
544 // whether unaligned reads are efficient (since that changes between
545 // different ARM versions, for example) and what the best chunk size
546 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
547 // the loop, so we need to do this ourselves. (Hypothesis: reverse
548 // is troublesome because the sides can be aligned differently --
549 // will be, when the length is odd -- so there's no way of emitting
550 // pre- and postludes to use fully-aligned SIMD in the middle.)
553 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
555 if fast_unaligned && mem::size_of::<T>() == 1 {
556 // Use the llvm.bswap intrinsic to reverse u8s in a usize
557 let chunk = mem::size_of::<usize>();
558 while i + chunk - 1 < ln / 2 {
560 let pa: *mut T = self.get_unchecked_mut(i);
561 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
562 let va = ptr::read_unaligned(pa as *mut usize);
563 let vb = ptr::read_unaligned(pb as *mut usize);
564 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
565 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
571 if fast_unaligned && mem::size_of::<T>() == 2 {
572 // Use rotate-by-16 to reverse u16s in a u32
573 let chunk = mem::size_of::<u32>() / 2;
574 while i + chunk - 1 < ln / 2 {
576 let pa: *mut T = self.get_unchecked_mut(i);
577 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
578 let va = ptr::read_unaligned(pa as *mut u32);
579 let vb = ptr::read_unaligned(pb as *mut u32);
580 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
581 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
588 // Unsafe swap to avoid the bounds check in safe swap.
590 let pa: *mut T = self.get_unchecked_mut(i);
591 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
598 /// Returns an iterator over the slice.
603 /// let x = &[1, 2, 4];
604 /// let mut iterator = x.iter();
606 /// assert_eq!(iterator.next(), Some(&1));
607 /// assert_eq!(iterator.next(), Some(&2));
608 /// assert_eq!(iterator.next(), Some(&4));
609 /// assert_eq!(iterator.next(), None);
611 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn iter(&self) -> Iter<'_, T> {
615 let ptr = self.as_ptr();
616 assume(!ptr.is_null());
618 let end = if mem::size_of::<T>() == 0 {
619 (ptr as *const u8).wrapping_add(self.len()) as *const T
627 _marker: marker::PhantomData
632 /// Returns an iterator that allows modifying each value.
637 /// let x = &mut [1, 2, 4];
638 /// for elem in x.iter_mut() {
641 /// assert_eq!(x, &[3, 4, 6]);
643 #[stable(feature = "rust1", since = "1.0.0")]
645 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
647 let ptr = self.as_mut_ptr();
648 assume(!ptr.is_null());
650 let end = if mem::size_of::<T>() == 0 {
651 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
659 _marker: marker::PhantomData
664 /// Returns an iterator over all contiguous windows of length
665 /// `size`. The windows overlap. If the slice is shorter than
666 /// `size`, the iterator returns no values.
670 /// Panics if `size` is 0.
675 /// let slice = ['r', 'u', 's', 't'];
676 /// let mut iter = slice.windows(2);
677 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
678 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
679 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
680 /// assert!(iter.next().is_none());
683 /// If the slice is shorter than `size`:
686 /// let slice = ['f', 'o', 'o'];
687 /// let mut iter = slice.windows(4);
688 /// assert!(iter.next().is_none());
690 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn windows(&self, size: usize) -> Windows<'_, T> {
694 Windows { v: self, size }
697 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
698 /// beginning of the slice.
700 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
701 /// slice, then the last chunk will not have length `chunk_size`.
703 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
704 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
709 /// Panics if `chunk_size` is 0.
714 /// let slice = ['l', 'o', 'r', 'e', 'm'];
715 /// let mut iter = slice.chunks(2);
716 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
717 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
718 /// assert_eq!(iter.next().unwrap(), &['m']);
719 /// assert!(iter.next().is_none());
722 /// [`chunks_exact`]: #method.chunks_exact
723 /// [`rchunks`]: #method.rchunks
724 #[stable(feature = "rust1", since = "1.0.0")]
726 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
727 assert!(chunk_size != 0);
728 Chunks { v: self, chunk_size }
731 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
732 /// beginning of the slice.
734 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
735 /// length of the slice, then the last chunk will not have length `chunk_size`.
737 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
738 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
739 /// the end of the slice.
743 /// Panics if `chunk_size` is 0.
748 /// let v = &mut [0, 0, 0, 0, 0];
749 /// let mut count = 1;
751 /// for chunk in v.chunks_mut(2) {
752 /// for elem in chunk.iter_mut() {
757 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
760 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
761 /// [`rchunks_mut`]: #method.rchunks_mut
762 #[stable(feature = "rust1", since = "1.0.0")]
764 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
765 assert!(chunk_size != 0);
766 ChunksMut { v: self, chunk_size }
769 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
770 /// beginning of the slice.
772 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
773 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
774 /// from the `remainder` function of the iterator.
776 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
777 /// resulting code better than in the case of [`chunks`].
779 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
780 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
784 /// Panics if `chunk_size` is 0.
789 /// let slice = ['l', 'o', 'r', 'e', 'm'];
790 /// let mut iter = slice.chunks_exact(2);
791 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
792 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
793 /// assert!(iter.next().is_none());
794 /// assert_eq!(iter.remainder(), &['m']);
797 /// [`chunks`]: #method.chunks
798 /// [`rchunks_exact`]: #method.rchunks_exact
799 #[stable(feature = "chunks_exact", since = "1.31.0")]
801 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
802 assert!(chunk_size != 0);
803 let rem = self.len() % chunk_size;
804 let len = self.len() - rem;
805 let (fst, snd) = self.split_at(len);
806 ChunksExact { v: fst, rem: snd, chunk_size }
809 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
810 /// beginning of the slice.
812 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
813 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
814 /// retrieved from the `into_remainder` function of the iterator.
816 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
817 /// resulting code better than in the case of [`chunks_mut`].
819 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
820 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
825 /// Panics if `chunk_size` is 0.
830 /// let v = &mut [0, 0, 0, 0, 0];
831 /// let mut count = 1;
833 /// for chunk in v.chunks_exact_mut(2) {
834 /// for elem in chunk.iter_mut() {
839 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
842 /// [`chunks_mut`]: #method.chunks_mut
843 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
844 #[stable(feature = "chunks_exact", since = "1.31.0")]
846 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
847 assert!(chunk_size != 0);
848 let rem = self.len() % chunk_size;
849 let len = self.len() - rem;
850 let (fst, snd) = self.split_at_mut(len);
851 ChunksExactMut { v: fst, rem: snd, chunk_size }
854 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
857 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
858 /// slice, then the last chunk will not have length `chunk_size`.
860 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
861 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
866 /// Panics if `chunk_size` is 0.
871 /// let slice = ['l', 'o', 'r', 'e', 'm'];
872 /// let mut iter = slice.rchunks(2);
873 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
874 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
875 /// assert_eq!(iter.next().unwrap(), &['l']);
876 /// assert!(iter.next().is_none());
879 /// [`rchunks_exact`]: #method.rchunks_exact
880 /// [`chunks`]: #method.chunks
881 #[stable(feature = "rchunks", since = "1.31.0")]
883 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
884 assert!(chunk_size != 0);
885 RChunks { v: self, chunk_size }
888 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
891 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
892 /// length of the slice, then the last chunk will not have length `chunk_size`.
894 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
895 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
896 /// beginning of the slice.
900 /// Panics if `chunk_size` is 0.
905 /// let v = &mut [0, 0, 0, 0, 0];
906 /// let mut count = 1;
908 /// for chunk in v.rchunks_mut(2) {
909 /// for elem in chunk.iter_mut() {
914 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
917 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
918 /// [`chunks_mut`]: #method.chunks_mut
919 #[stable(feature = "rchunks", since = "1.31.0")]
921 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
922 assert!(chunk_size != 0);
923 RChunksMut { v: self, chunk_size }
926 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
927 /// end of the slice.
929 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
930 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
931 /// from the `remainder` function of the iterator.
933 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
934 /// resulting code better than in the case of [`chunks`].
936 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
937 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
942 /// Panics if `chunk_size` is 0.
947 /// let slice = ['l', 'o', 'r', 'e', 'm'];
948 /// let mut iter = slice.rchunks_exact(2);
949 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
950 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
951 /// assert!(iter.next().is_none());
952 /// assert_eq!(iter.remainder(), &['l']);
955 /// [`chunks`]: #method.chunks
956 /// [`rchunks`]: #method.rchunks
957 /// [`chunks_exact`]: #method.chunks_exact
958 #[stable(feature = "rchunks", since = "1.31.0")]
960 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
961 assert!(chunk_size != 0);
962 let rem = self.len() % chunk_size;
963 let (fst, snd) = self.split_at(rem);
964 RChunksExact { v: snd, rem: fst, chunk_size }
967 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
970 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
971 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
972 /// retrieved from the `into_remainder` function of the iterator.
974 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
975 /// resulting code better than in the case of [`chunks_mut`].
977 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
978 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
983 /// Panics if `chunk_size` is 0.
988 /// let v = &mut [0, 0, 0, 0, 0];
989 /// let mut count = 1;
991 /// for chunk in v.rchunks_exact_mut(2) {
992 /// for elem in chunk.iter_mut() {
997 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
1000 /// [`chunks_mut`]: #method.chunks_mut
1001 /// [`rchunks_mut`]: #method.rchunks_mut
1002 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
1003 #[stable(feature = "rchunks", since = "1.31.0")]
1005 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
1006 assert!(chunk_size != 0);
1007 let rem = self.len() % chunk_size;
1008 let (fst, snd) = self.split_at_mut(rem);
1009 RChunksExactMut { v: snd, rem: fst, chunk_size }
1012 /// Divides one slice into two at an index.
1014 /// The first will contain all indices from `[0, mid)` (excluding
1015 /// the index `mid` itself) and the second will contain all
1016 /// indices from `[mid, len)` (excluding the index `len` itself).
1020 /// Panics if `mid > len`.
1025 /// let v = [1, 2, 3, 4, 5, 6];
1028 /// let (left, right) = v.split_at(0);
1029 /// assert!(left == []);
1030 /// assert!(right == [1, 2, 3, 4, 5, 6]);
1034 /// let (left, right) = v.split_at(2);
1035 /// assert!(left == [1, 2]);
1036 /// assert!(right == [3, 4, 5, 6]);
1040 /// let (left, right) = v.split_at(6);
1041 /// assert!(left == [1, 2, 3, 4, 5, 6]);
1042 /// assert!(right == []);
1045 #[stable(feature = "rust1", since = "1.0.0")]
1047 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1048 (&self[..mid], &self[mid..])
1051 /// Divides one mutable slice into two at an index.
1053 /// The first will contain all indices from `[0, mid)` (excluding
1054 /// the index `mid` itself) and the second will contain all
1055 /// indices from `[mid, len)` (excluding the index `len` itself).
1059 /// Panics if `mid > len`.
1064 /// let mut v = [1, 0, 3, 0, 5, 6];
1065 /// // scoped to restrict the lifetime of the borrows
1067 /// let (left, right) = v.split_at_mut(2);
1068 /// assert!(left == [1, 0]);
1069 /// assert!(right == [3, 0, 5, 6]);
1073 /// assert!(v == [1, 2, 3, 4, 5, 6]);
1075 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1078 let len = self.len();
1079 let ptr = self.as_mut_ptr();
1082 assert!(mid <= len);
1084 (from_raw_parts_mut(ptr, mid),
1085 from_raw_parts_mut(ptr.add(mid), len - mid))
1089 /// Returns an iterator over subslices separated by elements that match
1090 /// `pred`. The matched element is not contained in the subslices.
1095 /// let slice = [10, 40, 33, 20];
1096 /// let mut iter = slice.split(|num| num % 3 == 0);
1098 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1099 /// assert_eq!(iter.next().unwrap(), &[20]);
1100 /// assert!(iter.next().is_none());
1103 /// If the first element is matched, an empty slice will be the first item
1104 /// returned by the iterator. Similarly, if the last element in the slice
1105 /// is matched, an empty slice will be the last item returned by the
1109 /// let slice = [10, 40, 33];
1110 /// let mut iter = slice.split(|num| num % 3 == 0);
1112 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1113 /// assert_eq!(iter.next().unwrap(), &[]);
1114 /// assert!(iter.next().is_none());
1117 /// If two matched elements are directly adjacent, an empty slice will be
1118 /// present between them:
1121 /// let slice = [10, 6, 33, 20];
1122 /// let mut iter = slice.split(|num| num % 3 == 0);
1124 /// assert_eq!(iter.next().unwrap(), &[10]);
1125 /// assert_eq!(iter.next().unwrap(), &[]);
1126 /// assert_eq!(iter.next().unwrap(), &[20]);
1127 /// assert!(iter.next().is_none());
1129 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1132 where F: FnMut(&T) -> bool
1141 /// Returns an iterator over mutable subslices separated by elements that
1142 /// match `pred`. The matched element is not contained in the subslices.
1147 /// let mut v = [10, 40, 30, 20, 60, 50];
1149 /// for group in v.split_mut(|num| *num % 3 == 0) {
1152 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1154 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1157 where F: FnMut(&T) -> bool
1159 SplitMut { v: self, pred, finished: false }
1162 /// Returns an iterator over subslices separated by elements that match
1163 /// `pred`, starting at the end of the slice and working backwards.
1164 /// The matched element is not contained in the subslices.
1169 /// let slice = [11, 22, 33, 0, 44, 55];
1170 /// let mut iter = slice.rsplit(|num| *num == 0);
1172 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1173 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1174 /// assert_eq!(iter.next(), None);
1177 /// As with `split()`, if the first or last element is matched, an empty
1178 /// slice will be the first (or last) item returned by the iterator.
1181 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1182 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1183 /// assert_eq!(it.next().unwrap(), &[]);
1184 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1185 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1186 /// assert_eq!(it.next().unwrap(), &[]);
1187 /// assert_eq!(it.next(), None);
1189 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1191 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1192 where F: FnMut(&T) -> bool
1194 RSplit { inner: self.split(pred) }
1197 /// Returns an iterator over mutable subslices separated by elements that
1198 /// match `pred`, starting at the end of the slice and working
1199 /// backwards. The matched element is not contained in the subslices.
1204 /// let mut v = [100, 400, 300, 200, 600, 500];
1206 /// let mut count = 0;
1207 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1209 /// group[0] = count;
1211 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1214 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1216 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1217 where F: FnMut(&T) -> bool
1219 RSplitMut { inner: self.split_mut(pred) }
1222 /// Returns an iterator over subslices separated by elements that match
1223 /// `pred`, limited to returning at most `n` items. The matched element is
1224 /// not contained in the subslices.
1226 /// The last element returned, if any, will contain the remainder of the
1231 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1232 /// `[20, 60, 50]`):
1235 /// let v = [10, 40, 30, 20, 60, 50];
1237 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1238 /// println!("{:?}", group);
1241 #[stable(feature = "rust1", since = "1.0.0")]
1243 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1244 where F: FnMut(&T) -> bool
1247 inner: GenericSplitN {
1248 iter: self.split(pred),
1254 /// Returns an iterator over subslices separated by elements that match
1255 /// `pred`, limited to returning at most `n` items. The matched element is
1256 /// not contained in the subslices.
1258 /// The last element returned, if any, will contain the remainder of the
1264 /// let mut v = [10, 40, 30, 20, 60, 50];
1266 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1269 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1271 #[stable(feature = "rust1", since = "1.0.0")]
1273 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1274 where F: FnMut(&T) -> bool
1277 inner: GenericSplitN {
1278 iter: self.split_mut(pred),
1284 /// Returns an iterator over subslices separated by elements that match
1285 /// `pred` limited to returning at most `n` items. This starts at the end of
1286 /// the slice and works backwards. The matched element is not contained in
1289 /// The last element returned, if any, will contain the remainder of the
1294 /// Print the slice split once, starting from the end, by numbers divisible
1295 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1298 /// let v = [10, 40, 30, 20, 60, 50];
1300 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1301 /// println!("{:?}", group);
1304 #[stable(feature = "rust1", since = "1.0.0")]
1306 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1307 where F: FnMut(&T) -> bool
1310 inner: GenericSplitN {
1311 iter: self.rsplit(pred),
1317 /// Returns an iterator over subslices separated by elements that match
1318 /// `pred` limited to returning at most `n` items. This starts at the end of
1319 /// the slice and works backwards. The matched element is not contained in
1322 /// The last element returned, if any, will contain the remainder of the
1328 /// let mut s = [10, 40, 30, 20, 60, 50];
1330 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1333 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1335 #[stable(feature = "rust1", since = "1.0.0")]
1337 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1338 where F: FnMut(&T) -> bool
1341 inner: GenericSplitN {
1342 iter: self.rsplit_mut(pred),
1348 /// Returns `true` if the slice contains an element with the given value.
1353 /// let v = [10, 40, 30];
1354 /// assert!(v.contains(&30));
1355 /// assert!(!v.contains(&50));
1358 /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1359 /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1362 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1363 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1364 /// assert!(!v.iter().any(|e| e == "hi"));
1366 #[stable(feature = "rust1", since = "1.0.0")]
1367 pub fn contains(&self, x: &T) -> bool
1370 x.slice_contains(self)
1373 /// Returns `true` if `needle` is a prefix of the slice.
1378 /// let v = [10, 40, 30];
1379 /// assert!(v.starts_with(&[10]));
1380 /// assert!(v.starts_with(&[10, 40]));
1381 /// assert!(!v.starts_with(&[50]));
1382 /// assert!(!v.starts_with(&[10, 50]));
1385 /// Always returns `true` if `needle` is an empty slice:
1388 /// let v = &[10, 40, 30];
1389 /// assert!(v.starts_with(&[]));
1390 /// let v: &[u8] = &[];
1391 /// assert!(v.starts_with(&[]));
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub fn starts_with(&self, needle: &[T]) -> bool
1397 let n = needle.len();
1398 self.len() >= n && needle == &self[..n]
1401 /// Returns `true` if `needle` is a suffix of the slice.
1406 /// let v = [10, 40, 30];
1407 /// assert!(v.ends_with(&[30]));
1408 /// assert!(v.ends_with(&[40, 30]));
1409 /// assert!(!v.ends_with(&[50]));
1410 /// assert!(!v.ends_with(&[50, 30]));
1413 /// Always returns `true` if `needle` is an empty slice:
1416 /// let v = &[10, 40, 30];
1417 /// assert!(v.ends_with(&[]));
1418 /// let v: &[u8] = &[];
1419 /// assert!(v.ends_with(&[]));
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 pub fn ends_with(&self, needle: &[T]) -> bool
1425 let (m, n) = (self.len(), needle.len());
1426 m >= n && needle == &self[m-n..]
1429 /// Binary searches this sorted slice for a given element.
1431 /// If the value is found then [`Result::Ok`] is returned, containing the
1432 /// index of the matching element. If there are multiple matches, then any
1433 /// one of the matches could be returned. If the value is not found then
1434 /// [`Result::Err`] is returned, containing the index where a matching
1435 /// element could be inserted while maintaining sorted order.
1439 /// Looks up a series of four elements. The first is found, with a
1440 /// uniquely determined position; the second and third are not
1441 /// found; the fourth could match any position in `[1, 4]`.
1444 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1446 /// assert_eq!(s.binary_search(&13), Ok(9));
1447 /// assert_eq!(s.binary_search(&4), Err(7));
1448 /// assert_eq!(s.binary_search(&100), Err(13));
1449 /// let r = s.binary_search(&1);
1450 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1453 /// If you want to insert an item to a sorted vector, while maintaining
1457 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1459 /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1460 /// s.insert(idx, num);
1461 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1467 self.binary_search_by(|p| p.cmp(x))
1470 /// Binary searches this sorted slice with a comparator function.
1472 /// The comparator function should implement an order consistent
1473 /// with the sort order of the underlying slice, returning an
1474 /// order code that indicates whether its argument is `Less`,
1475 /// `Equal` or `Greater` the desired target.
1477 /// If the value is found then [`Result::Ok`] is returned, containing the
1478 /// index of the matching element. If there are multiple matches, then any
1479 /// one of the matches could be returned. If the value is not found then
1480 /// [`Result::Err`] is returned, containing the index where a matching
1481 /// element could be inserted while maintaining sorted order.
1485 /// Looks up a series of four elements. The first is found, with a
1486 /// uniquely determined position; the second and third are not
1487 /// found; the fourth could match any position in `[1, 4]`.
1490 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1493 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1495 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1497 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1499 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1500 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1502 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1505 where F: FnMut(&'a T) -> Ordering
1508 let mut size = s.len();
1512 let mut base = 0usize;
1514 let half = size / 2;
1515 let mid = base + half;
1516 // mid is always in [0, size), that means mid is >= 0 and < size.
1517 // mid >= 0: by definition
1518 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1519 let cmp = f(unsafe { s.get_unchecked(mid) });
1520 base = if cmp == Greater { base } else { mid };
1523 // base is always in [0, size) because base <= mid.
1524 let cmp = f(unsafe { s.get_unchecked(base) });
1525 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1529 /// Binary searches this sorted slice with a key extraction function.
1531 /// Assumes that the slice is sorted by the key, for instance with
1532 /// [`sort_by_key`] using the same key extraction function.
1534 /// If the value is found then [`Result::Ok`] is returned, containing the
1535 /// index of the matching element. If there are multiple matches, then any
1536 /// one of the matches could be returned. If the value is not found then
1537 /// [`Result::Err`] is returned, containing the index where a matching
1538 /// element could be inserted while maintaining sorted order.
1540 /// [`sort_by_key`]: #method.sort_by_key
1544 /// Looks up a series of four elements in a slice of pairs sorted by
1545 /// their second elements. The first is found, with a uniquely
1546 /// determined position; the second and third are not found; the
1547 /// fourth could match any position in `[1, 4]`.
1550 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1551 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1552 /// (1, 21), (2, 34), (4, 55)];
1554 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1555 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1556 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1557 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1558 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1560 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1562 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1563 where F: FnMut(&'a T) -> B,
1566 self.binary_search_by(|k| f(k).cmp(b))
1569 /// Sorts the slice, but may not preserve the order of equal elements.
1571 /// This sort is unstable (i.e., may reorder equal elements), in-place
1572 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1574 /// # Current implementation
1576 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1577 /// which combines the fast average case of randomized quicksort with the fast worst case of
1578 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1579 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1580 /// deterministic behavior.
1582 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1583 /// slice consists of several concatenated sorted sequences.
1588 /// let mut v = [-5, 4, 1, -3, 2];
1590 /// v.sort_unstable();
1591 /// assert!(v == [-5, -3, 1, 2, 4]);
1594 /// [pdqsort]: https://github.com/orlp/pdqsort
1595 #[stable(feature = "sort_unstable", since = "1.20.0")]
1597 pub fn sort_unstable(&mut self)
1600 sort::quicksort(self, |a, b| a.lt(b));
1603 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1606 /// This sort is unstable (i.e., may reorder equal elements), in-place
1607 /// (i.e., does not allocate), and `O(n log n)` worst-case.
1609 /// The comparator function must define a total ordering for the elements in the slice. If
1610 /// the ordering is not total, the order of the elements is unspecified. An order is a
1611 /// total order if it is (for all a, b and c):
1613 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1614 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1616 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1617 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1620 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1621 /// floats.sort_by(|a, b| a.partial_cmp(b).unwrap());
1622 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1625 /// # Current implementation
1627 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1628 /// which combines the fast average case of randomized quicksort with the fast worst case of
1629 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1630 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1631 /// deterministic behavior.
1633 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1634 /// slice consists of several concatenated sorted sequences.
1639 /// let mut v = [5, 4, 1, 3, 2];
1640 /// v.sort_unstable_by(|a, b| a.cmp(b));
1641 /// assert!(v == [1, 2, 3, 4, 5]);
1643 /// // reverse sorting
1644 /// v.sort_unstable_by(|a, b| b.cmp(a));
1645 /// assert!(v == [5, 4, 3, 2, 1]);
1648 /// [pdqsort]: https://github.com/orlp/pdqsort
1649 #[stable(feature = "sort_unstable", since = "1.20.0")]
1651 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1652 where F: FnMut(&T, &T) -> Ordering
1654 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1657 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1660 /// This sort is unstable (i.e., may reorder equal elements), in-place
1661 /// (i.e., does not allocate), and `O(m n log(m n))` worst-case, where the key function is
1664 /// # Current implementation
1666 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1667 /// which combines the fast average case of randomized quicksort with the fast worst case of
1668 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1669 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1670 /// deterministic behavior.
1672 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
1673 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
1674 /// cases where the key function is expensive.
1679 /// let mut v = [-5i32, 4, 1, -3, 2];
1681 /// v.sort_unstable_by_key(|k| k.abs());
1682 /// assert!(v == [1, 2, -3, 4, -5]);
1685 /// [pdqsort]: https://github.com/orlp/pdqsort
1686 #[stable(feature = "sort_unstable", since = "1.20.0")]
1688 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1689 where F: FnMut(&T) -> K, K: Ord
1691 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1694 /// Reorder the slice such that the element at `index` is at its final sorted position.
1696 /// This reordering has the additional property that any value at position `i < index` will be
1697 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
1698 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
1699 /// (i.e. does not allocate), and `O(n)` worst-case. This function is also/ known as "kth
1700 /// element" in other libraries. It returns a triplet of the following values: all elements less
1701 /// than the one at the given index, the value at the given index, and all elements greater than
1702 /// the one at the given index.
1704 /// # Current implementation
1706 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1707 /// used for [`sort_unstable`].
1709 /// [`sort_unstable`]: #method.sort_unstable
1713 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1718 /// #![feature(slice_partition_at_index)]
1720 /// let mut v = [-5i32, 4, 1, -3, 2];
1722 /// // Find the median
1723 /// v.partition_at_index(2);
1725 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1726 /// // about the specified index.
1727 /// assert!(v == [-3, -5, 1, 2, 4] ||
1728 /// v == [-5, -3, 1, 2, 4] ||
1729 /// v == [-3, -5, 1, 4, 2] ||
1730 /// v == [-5, -3, 1, 4, 2]);
1732 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1734 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
1737 let mut f = |a: &T, b: &T| a.lt(b);
1738 sort::partition_at_index(self, index, &mut f)
1741 /// Reorder the slice with a comparator function such that the element at `index` is at its
1742 /// final sorted position.
1744 /// This reordering has the additional property that any value at position `i < index` will be
1745 /// less than or equal to any value at a position `j > index` using the comparator function.
1746 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1747 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1748 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1749 /// values: all elements less than the one at the given index, the value at the given index,
1750 /// and all elements greater than the one at the given index, using the provided comparator
1753 /// # Current implementation
1755 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1756 /// used for [`sort_unstable`].
1758 /// [`sort_unstable`]: #method.sort_unstable
1762 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1767 /// #![feature(slice_partition_at_index)]
1769 /// let mut v = [-5i32, 4, 1, -3, 2];
1771 /// // Find the median as if the slice were sorted in descending order.
1772 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
1774 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1775 /// // about the specified index.
1776 /// assert!(v == [2, 4, 1, -5, -3] ||
1777 /// v == [2, 4, 1, -3, -5] ||
1778 /// v == [4, 2, 1, -5, -3] ||
1779 /// v == [4, 2, 1, -3, -5]);
1781 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1783 pub fn partition_at_index_by<F>(&mut self, index: usize, mut compare: F)
1784 -> (&mut [T], &mut T, &mut [T])
1785 where F: FnMut(&T, &T) -> Ordering
1787 let mut f = |a: &T, b: &T| compare(a, b) == Less;
1788 sort::partition_at_index(self, index, &mut f)
1791 /// Reorder the slice with a key extraction function such that the element at `index` is at its
1792 /// final sorted position.
1794 /// This reordering has the additional property that any value at position `i < index` will be
1795 /// less than or equal to any value at a position `j > index` using the key extraction function.
1796 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1797 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1798 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1799 /// values: all elements less than the one at the given index, the value at the given index, and
1800 /// all elements greater than the one at the given index, using the provided key extraction
1803 /// # Current implementation
1805 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1806 /// used for [`sort_unstable`].
1808 /// [`sort_unstable`]: #method.sort_unstable
1812 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1817 /// #![feature(slice_partition_at_index)]
1819 /// let mut v = [-5i32, 4, 1, -3, 2];
1821 /// // Return the median as if the array were sorted according to absolute value.
1822 /// v.partition_at_index_by_key(2, |a| a.abs());
1824 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1825 /// // about the specified index.
1826 /// assert!(v == [1, 2, -3, 4, -5] ||
1827 /// v == [1, 2, -3, -5, 4] ||
1828 /// v == [2, 1, -3, 4, -5] ||
1829 /// v == [2, 1, -3, -5, 4]);
1831 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1833 pub fn partition_at_index_by_key<K, F>(&mut self, index: usize, mut f: F)
1834 -> (&mut [T], &mut T, &mut [T])
1835 where F: FnMut(&T) -> K, K: Ord
1837 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
1838 sort::partition_at_index(self, index, &mut g)
1841 /// Moves all consecutive repeated elements to the end of the slice according to the
1842 /// [`PartialEq`] trait implementation.
1844 /// Returns two slices. The first contains no consecutive repeated elements.
1845 /// The second contains all the duplicates in no specified order.
1847 /// If the slice is sorted, the first returned slice contains no duplicates.
1852 /// #![feature(slice_partition_dedup)]
1854 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1856 /// let (dedup, duplicates) = slice.partition_dedup();
1858 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1859 /// assert_eq!(duplicates, [2, 3, 1]);
1861 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1863 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1866 self.partition_dedup_by(|a, b| a == b)
1869 /// Moves all but the first of consecutive elements to the end of the slice satisfying
1870 /// a given equality relation.
1872 /// Returns two slices. The first contains no consecutive repeated elements.
1873 /// The second contains all the duplicates in no specified order.
1875 /// The `same_bucket` function is passed references to two elements from the slice and
1876 /// must determine if the elements compare equal. The elements are passed in opposite order
1877 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1878 /// at the end of the slice.
1880 /// If the slice is sorted, the first returned slice contains no duplicates.
1885 /// #![feature(slice_partition_dedup)]
1887 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1889 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1891 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1892 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1894 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1896 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1897 where F: FnMut(&mut T, &mut T) -> bool
1899 // Although we have a mutable reference to `self`, we cannot make
1900 // *arbitrary* changes. The `same_bucket` calls could panic, so we
1901 // must ensure that the slice is in a valid state at all times.
1903 // The way that we handle this is by using swaps; we iterate
1904 // over all the elements, swapping as we go so that at the end
1905 // the elements we wish to keep are in the front, and those we
1906 // wish to reject are at the back. We can then split the slice.
1907 // This operation is still O(n).
1909 // Example: We start in this state, where `r` represents "next
1910 // read" and `w` represents "next_write`.
1913 // +---+---+---+---+---+---+
1914 // | 0 | 1 | 1 | 2 | 3 | 3 |
1915 // +---+---+---+---+---+---+
1918 // Comparing self[r] against self[w-1], this is not a duplicate, so
1919 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1920 // r and w, leaving us with:
1923 // +---+---+---+---+---+---+
1924 // | 0 | 1 | 1 | 2 | 3 | 3 |
1925 // +---+---+---+---+---+---+
1928 // Comparing self[r] against self[w-1], this value is a duplicate,
1929 // so we increment `r` but leave everything else unchanged:
1932 // +---+---+---+---+---+---+
1933 // | 0 | 1 | 1 | 2 | 3 | 3 |
1934 // +---+---+---+---+---+---+
1937 // Comparing self[r] against self[w-1], this is not a duplicate,
1938 // so swap self[r] and self[w] and advance r and w:
1941 // +---+---+---+---+---+---+
1942 // | 0 | 1 | 2 | 1 | 3 | 3 |
1943 // +---+---+---+---+---+---+
1946 // Not a duplicate, repeat:
1949 // +---+---+---+---+---+---+
1950 // | 0 | 1 | 2 | 3 | 1 | 3 |
1951 // +---+---+---+---+---+---+
1954 // Duplicate, advance r. End of slice. Split at w.
1956 let len = self.len();
1958 return (self, &mut [])
1961 let ptr = self.as_mut_ptr();
1962 let mut next_read: usize = 1;
1963 let mut next_write: usize = 1;
1966 // Avoid bounds checks by using raw pointers.
1967 while next_read < len {
1968 let ptr_read = ptr.add(next_read);
1969 let prev_ptr_write = ptr.add(next_write - 1);
1970 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1971 if next_read != next_write {
1972 let ptr_write = prev_ptr_write.offset(1);
1973 mem::swap(&mut *ptr_read, &mut *ptr_write);
1981 self.split_at_mut(next_write)
1984 /// Moves all but the first of consecutive elements to the end of the slice that resolve
1985 /// to the same key.
1987 /// Returns two slices. The first contains no consecutive repeated elements.
1988 /// The second contains all the duplicates in no specified order.
1990 /// If the slice is sorted, the first returned slice contains no duplicates.
1995 /// #![feature(slice_partition_dedup)]
1997 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1999 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2001 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2002 /// assert_eq!(duplicates, [21, 30, 13]);
2004 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2006 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2007 where F: FnMut(&mut T) -> K,
2010 self.partition_dedup_by(|a, b| key(a) == key(b))
2013 /// Rotates the slice in-place such that the first `mid` elements of the
2014 /// slice move to the end while the last `self.len() - mid` elements move to
2015 /// the front. After calling `rotate_left`, the element previously at index
2016 /// `mid` will become the first element in the slice.
2020 /// This function will panic if `mid` is greater than the length of the
2021 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2026 /// Takes linear (in `self.len()`) time.
2031 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2032 /// a.rotate_left(2);
2033 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2036 /// Rotating a subslice:
2039 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2040 /// a[1..5].rotate_left(1);
2041 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2043 #[stable(feature = "slice_rotate", since = "1.26.0")]
2044 pub fn rotate_left(&mut self, mid: usize) {
2045 assert!(mid <= self.len());
2046 let k = self.len() - mid;
2049 let p = self.as_mut_ptr();
2050 rotate::ptr_rotate(mid, p.add(mid), k);
2054 /// Rotates the slice in-place such that the first `self.len() - k`
2055 /// elements of the slice move to the end while the last `k` elements move
2056 /// to the front. After calling `rotate_right`, the element previously at
2057 /// index `self.len() - k` will become the first element in the slice.
2061 /// This function will panic if `k` is greater than the length of the
2062 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2067 /// Takes linear (in `self.len()`) time.
2072 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2073 /// a.rotate_right(2);
2074 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2077 /// Rotate a subslice:
2080 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2081 /// a[1..5].rotate_right(1);
2082 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2084 #[stable(feature = "slice_rotate", since = "1.26.0")]
2085 pub fn rotate_right(&mut self, k: usize) {
2086 assert!(k <= self.len());
2087 let mid = self.len() - k;
2090 let p = self.as_mut_ptr();
2091 rotate::ptr_rotate(mid, p.add(mid), k);
2095 /// Copies the elements from `src` into `self`.
2097 /// The length of `src` must be the same as `self`.
2099 /// If `src` implements `Copy`, it can be more performant to use
2100 /// [`copy_from_slice`].
2104 /// This function will panic if the two slices have different lengths.
2108 /// Cloning two elements from a slice into another:
2111 /// let src = [1, 2, 3, 4];
2112 /// let mut dst = [0, 0];
2114 /// // Because the slices have to be the same length,
2115 /// // we slice the source slice from four elements
2116 /// // to two. It will panic if we don't do this.
2117 /// dst.clone_from_slice(&src[2..]);
2119 /// assert_eq!(src, [1, 2, 3, 4]);
2120 /// assert_eq!(dst, [3, 4]);
2123 /// Rust enforces that there can only be one mutable reference with no
2124 /// immutable references to a particular piece of data in a particular
2125 /// scope. Because of this, attempting to use `clone_from_slice` on a
2126 /// single slice will result in a compile failure:
2129 /// let mut slice = [1, 2, 3, 4, 5];
2131 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2134 /// To work around this, we can use [`split_at_mut`] to create two distinct
2135 /// sub-slices from a slice:
2138 /// let mut slice = [1, 2, 3, 4, 5];
2141 /// let (left, right) = slice.split_at_mut(2);
2142 /// left.clone_from_slice(&right[1..]);
2145 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2148 /// [`copy_from_slice`]: #method.copy_from_slice
2149 /// [`split_at_mut`]: #method.split_at_mut
2150 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2151 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
2152 assert!(self.len() == src.len(),
2153 "destination and source slices have different lengths");
2154 // NOTE: We need to explicitly slice them to the same length
2155 // for bounds checking to be elided, and the optimizer will
2156 // generate memcpy for simple cases (for example T = u8).
2157 let len = self.len();
2158 let src = &src[..len];
2160 self[i].clone_from(&src[i]);
2165 /// Copies all elements from `src` into `self`, using a memcpy.
2167 /// The length of `src` must be the same as `self`.
2169 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
2173 /// This function will panic if the two slices have different lengths.
2177 /// Copying two elements from a slice into another:
2180 /// let src = [1, 2, 3, 4];
2181 /// let mut dst = [0, 0];
2183 /// // Because the slices have to be the same length,
2184 /// // we slice the source slice from four elements
2185 /// // to two. It will panic if we don't do this.
2186 /// dst.copy_from_slice(&src[2..]);
2188 /// assert_eq!(src, [1, 2, 3, 4]);
2189 /// assert_eq!(dst, [3, 4]);
2192 /// Rust enforces that there can only be one mutable reference with no
2193 /// immutable references to a particular piece of data in a particular
2194 /// scope. Because of this, attempting to use `copy_from_slice` on a
2195 /// single slice will result in a compile failure:
2198 /// let mut slice = [1, 2, 3, 4, 5];
2200 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2203 /// To work around this, we can use [`split_at_mut`] to create two distinct
2204 /// sub-slices from a slice:
2207 /// let mut slice = [1, 2, 3, 4, 5];
2210 /// let (left, right) = slice.split_at_mut(2);
2211 /// left.copy_from_slice(&right[1..]);
2214 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2217 /// [`clone_from_slice`]: #method.clone_from_slice
2218 /// [`split_at_mut`]: #method.split_at_mut
2219 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2220 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
2221 assert_eq!(self.len(), src.len(),
2222 "destination and source slices have different lengths");
2224 ptr::copy_nonoverlapping(
2225 src.as_ptr(), self.as_mut_ptr(), self.len());
2229 /// Copies elements from one part of the slice to another part of itself,
2230 /// using a memmove.
2232 /// `src` is the range within `self` to copy from. `dest` is the starting
2233 /// index of the range within `self` to copy to, which will have the same
2234 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2235 /// must be less than or equal to `self.len()`.
2239 /// This function will panic if either range exceeds the end of the slice,
2240 /// or if the end of `src` is before the start.
2244 /// Copying four bytes within a slice:
2247 /// let mut bytes = *b"Hello, World!";
2249 /// bytes.copy_within(1..5, 8);
2251 /// assert_eq!(&bytes, b"Hello, Wello!");
2253 #[stable(feature = "copy_within", since = "1.37.0")]
2254 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2258 let src_start = match src.start_bound() {
2259 ops::Bound::Included(&n) => n,
2260 ops::Bound::Excluded(&n) => n
2262 .unwrap_or_else(|| slice_index_overflow_fail()),
2263 ops::Bound::Unbounded => 0,
2265 let src_end = match src.end_bound() {
2266 ops::Bound::Included(&n) => n
2268 .unwrap_or_else(|| slice_index_overflow_fail()),
2269 ops::Bound::Excluded(&n) => n,
2270 ops::Bound::Unbounded => self.len(),
2272 assert!(src_start <= src_end, "src end is before src start");
2273 assert!(src_end <= self.len(), "src is out of bounds");
2274 let count = src_end - src_start;
2275 assert!(dest <= self.len() - count, "dest is out of bounds");
2278 self.as_ptr().add(src_start),
2279 self.as_mut_ptr().add(dest),
2285 /// Swaps all elements in `self` with those in `other`.
2287 /// The length of `other` must be the same as `self`.
2291 /// This function will panic if the two slices have different lengths.
2295 /// Swapping two elements across slices:
2298 /// let mut slice1 = [0, 0];
2299 /// let mut slice2 = [1, 2, 3, 4];
2301 /// slice1.swap_with_slice(&mut slice2[2..]);
2303 /// assert_eq!(slice1, [3, 4]);
2304 /// assert_eq!(slice2, [1, 2, 0, 0]);
2307 /// Rust enforces that there can only be one mutable reference to a
2308 /// particular piece of data in a particular scope. Because of this,
2309 /// attempting to use `swap_with_slice` on a single slice will result in
2310 /// a compile failure:
2313 /// let mut slice = [1, 2, 3, 4, 5];
2314 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2317 /// To work around this, we can use [`split_at_mut`] to create two distinct
2318 /// mutable sub-slices from a slice:
2321 /// let mut slice = [1, 2, 3, 4, 5];
2324 /// let (left, right) = slice.split_at_mut(2);
2325 /// left.swap_with_slice(&mut right[1..]);
2328 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2331 /// [`split_at_mut`]: #method.split_at_mut
2332 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2333 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2334 assert!(self.len() == other.len(),
2335 "destination and source slices have different lengths");
2337 ptr::swap_nonoverlapping(
2338 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2342 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2343 fn align_to_offsets<U>(&self) -> (usize, usize) {
2344 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2345 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2347 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2348 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2349 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2351 // Formula to calculate this is:
2353 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2354 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2356 // Expanded and simplified:
2358 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2359 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2361 // Luckily since all this is constant-evaluated... performance here matters not!
2363 fn gcd(a: usize, b: usize) -> usize {
2364 use crate::intrinsics;
2365 // iterative stein’s algorithm
2366 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2367 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2368 let (ctz_a, mut ctz_b) = unsafe {
2369 if a == 0 { return b; }
2370 if b == 0 { return a; }
2371 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2373 let k = ctz_a.min(ctz_b);
2374 let mut a = a >> ctz_a;
2377 // remove all factors of 2 from b
2380 mem::swap(&mut a, &mut b);
2387 ctz_b = intrinsics::cttz_nonzero(b);
2392 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2393 let ts: usize = mem::size_of::<U>() / gcd;
2394 let us: usize = mem::size_of::<T>() / gcd;
2396 // Armed with this knowledge, we can find how many `U`s we can fit!
2397 let us_len = self.len() / ts * us;
2398 // And how many `T`s will be in the trailing slice!
2399 let ts_len = self.len() % ts;
2403 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2406 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2407 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2408 /// length possible for a given type and input slice, but only your algorithm's performance
2409 /// should depend on that, not its correctness. It is permissible for all of the input data to
2410 /// be returned as the prefix or suffix slice.
2412 /// This method has no purpose when either input element `T` or output element `U` are
2413 /// zero-sized and will return the original slice without splitting anything.
2417 /// This method is essentially a `transmute` with respect to the elements in the returned
2418 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2426 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2427 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2428 /// // less_efficient_algorithm_for_bytes(prefix);
2429 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2430 /// // less_efficient_algorithm_for_bytes(suffix);
2433 #[stable(feature = "slice_align_to", since = "1.30.0")]
2434 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2435 // Note that most of this function will be constant-evaluated,
2436 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2437 // handle ZSTs specially, which is – don't handle them at all.
2438 return (self, &[], &[]);
2441 // First, find at what point do we split between the first and 2nd slice. Easy with
2442 // ptr.align_offset.
2443 let ptr = self.as_ptr();
2444 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2445 if offset > self.len() {
2448 let (left, rest) = self.split_at(offset);
2449 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2450 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2452 from_raw_parts(rest.as_ptr() as *const U, us_len),
2453 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2457 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2460 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2461 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2462 /// length possible for a given type and input slice, but only your algorithm's performance
2463 /// should depend on that, not its correctness. It is permissible for all of the input data to
2464 /// be returned as the prefix or suffix slice.
2466 /// This method has no purpose when either input element `T` or output element `U` are
2467 /// zero-sized and will return the original slice without splitting anything.
2471 /// This method is essentially a `transmute` with respect to the elements in the returned
2472 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2480 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2481 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2482 /// // less_efficient_algorithm_for_bytes(prefix);
2483 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2484 /// // less_efficient_algorithm_for_bytes(suffix);
2487 #[stable(feature = "slice_align_to", since = "1.30.0")]
2488 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2489 // Note that most of this function will be constant-evaluated,
2490 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2491 // handle ZSTs specially, which is – don't handle them at all.
2492 return (self, &mut [], &mut []);
2495 // First, find at what point do we split between the first and 2nd slice. Easy with
2496 // ptr.align_offset.
2497 let ptr = self.as_ptr();
2498 let offset = crate::ptr::align_offset(ptr, mem::align_of::<U>());
2499 if offset > self.len() {
2500 (self, &mut [], &mut [])
2502 let (left, rest) = self.split_at_mut(offset);
2503 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2504 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2505 let mut_ptr = rest.as_mut_ptr();
2507 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2508 from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2512 /// Checks if the elements of this slice are sorted.
2514 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2515 /// slice yields exactly zero or one element, `true` is returned.
2517 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2518 /// implies that this function returns `false` if any two consecutive items are not
2524 /// #![feature(is_sorted)]
2525 /// let empty: [i32; 0] = [];
2527 /// assert!([1, 2, 2, 9].is_sorted());
2528 /// assert!(![1, 3, 2, 4].is_sorted());
2529 /// assert!([0].is_sorted());
2530 /// assert!(empty.is_sorted());
2531 /// assert!(![0.0, 1.0, std::f32::NAN].is_sorted());
2534 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2535 pub fn is_sorted(&self) -> bool
2539 self.is_sorted_by(|a, b| a.partial_cmp(b))
2542 /// Checks if the elements of this slice are sorted using the given comparator function.
2544 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2545 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2546 /// [`is_sorted`]; see its documentation for more information.
2548 /// [`is_sorted`]: #method.is_sorted
2549 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2550 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2552 F: FnMut(&T, &T) -> Option<Ordering>
2554 self.iter().is_sorted_by(|a, b| compare(*a, *b))
2557 /// Checks if the elements of this slice are sorted using the given key extraction function.
2559 /// Instead of comparing the slice's elements directly, this function compares the keys of the
2560 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2561 /// documentation for more information.
2563 /// [`is_sorted`]: #method.is_sorted
2568 /// #![feature(is_sorted)]
2570 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2571 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2574 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2575 pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
2580 self.iter().is_sorted_by_key(f)
2584 #[lang = "slice_u8"]
2587 /// Checks if all bytes in this slice are within the ASCII range.
2588 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2590 pub fn is_ascii(&self) -> bool {
2591 self.iter().all(|b| b.is_ascii())
2594 /// Checks that two slices are an ASCII case-insensitive match.
2596 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2597 /// but without allocating and copying temporaries.
2598 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2600 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2601 self.len() == other.len() &&
2602 self.iter().zip(other).all(|(a, b)| {
2603 a.eq_ignore_ascii_case(b)
2607 /// Converts this slice to its ASCII upper case equivalent in-place.
2609 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2610 /// but non-ASCII letters are unchanged.
2612 /// To return a new uppercased value without modifying the existing one, use
2613 /// [`to_ascii_uppercase`].
2615 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2616 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2618 pub fn make_ascii_uppercase(&mut self) {
2620 byte.make_ascii_uppercase();
2624 /// Converts this slice to its ASCII lower case equivalent in-place.
2626 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2627 /// but non-ASCII letters are unchanged.
2629 /// To return a new lowercased value without modifying the existing one, use
2630 /// [`to_ascii_lowercase`].
2632 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2633 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2635 pub fn make_ascii_lowercase(&mut self) {
2637 byte.make_ascii_lowercase();
2643 #[stable(feature = "rust1", since = "1.0.0")]
2644 impl<T, I> ops::Index<I> for [T]
2645 where I: SliceIndex<[T]>
2647 type Output = I::Output;
2650 fn index(&self, index: I) -> &I::Output {
2655 #[stable(feature = "rust1", since = "1.0.0")]
2656 impl<T, I> ops::IndexMut<I> for [T]
2657 where I: SliceIndex<[T]>
2660 fn index_mut(&mut self, index: I) -> &mut I::Output {
2661 index.index_mut(self)
2667 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2668 panic!("index {} out of range for slice of length {}", index, len);
2673 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2674 panic!("slice index starts at {} but ends at {}", index, end);
2679 fn slice_index_overflow_fail() -> ! {
2680 panic!("attempted to index slice up to maximum usize");
2683 mod private_slice_index {
2685 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2688 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2689 impl Sealed for usize {}
2690 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2691 impl Sealed for ops::Range<usize> {}
2692 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2693 impl Sealed for ops::RangeTo<usize> {}
2694 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2695 impl Sealed for ops::RangeFrom<usize> {}
2696 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2697 impl Sealed for ops::RangeFull {}
2698 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2699 impl Sealed for ops::RangeInclusive<usize> {}
2700 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2701 impl Sealed for ops::RangeToInclusive<usize> {}
2704 /// A helper trait used for indexing operations.
2705 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2706 #[rustc_on_unimplemented(
2709 label = "string indices are ranges of `usize`",
2712 all(any(T = "str", T = "&str", T = "std::string::String"), _Self="{integer}"),
2713 note="you can use `.chars().nth()` or `.bytes().nth()`
2714 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
2716 message = "the type `{T}` cannot be indexed by `{Self}`",
2717 label = "slice indices are of type `usize` or ranges of `usize`",
2719 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2720 /// The output type returned by methods.
2721 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2722 type Output: ?Sized;
2724 /// Returns a shared reference to the output at this location, if in
2726 #[unstable(feature = "slice_index_methods", issue = "none")]
2727 fn get(self, slice: &T) -> Option<&Self::Output>;
2729 /// Returns a mutable reference to the output at this location, if in
2731 #[unstable(feature = "slice_index_methods", issue = "none")]
2732 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2734 /// Returns a shared reference to the output at this location, without
2735 /// performing any bounds checking.
2736 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2737 /// even if the resulting reference is not used.
2738 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
2739 #[unstable(feature = "slice_index_methods", issue = "none")]
2740 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2742 /// Returns a mutable reference to the output at this location, without
2743 /// performing any bounds checking.
2744 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
2745 /// even if the resulting reference is not used.
2746 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
2747 #[unstable(feature = "slice_index_methods", issue = "none")]
2748 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2750 /// Returns a shared reference to the output at this location, panicking
2751 /// if out of bounds.
2752 #[unstable(feature = "slice_index_methods", issue = "none")]
2753 fn index(self, slice: &T) -> &Self::Output;
2755 /// Returns a mutable reference to the output at this location, panicking
2756 /// if out of bounds.
2757 #[unstable(feature = "slice_index_methods", issue = "none")]
2758 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2761 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2762 impl<T> SliceIndex<[T]> for usize {
2766 fn get(self, slice: &[T]) -> Option<&T> {
2767 if self < slice.len() {
2769 Some(self.get_unchecked(slice))
2777 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2778 if self < slice.len() {
2780 Some(self.get_unchecked_mut(slice))
2788 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2789 &*slice.as_ptr().add(self)
2793 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2794 &mut *slice.as_mut_ptr().add(self)
2798 fn index(self, slice: &[T]) -> &T {
2799 // N.B., use intrinsic indexing
2804 fn index_mut(self, slice: &mut [T]) -> &mut T {
2805 // N.B., use intrinsic indexing
2810 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2811 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2815 fn get(self, slice: &[T]) -> Option<&[T]> {
2816 if self.start > self.end || self.end > slice.len() {
2820 Some(self.get_unchecked(slice))
2826 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2827 if self.start > self.end || self.end > slice.len() {
2831 Some(self.get_unchecked_mut(slice))
2837 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2838 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2842 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2843 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2847 fn index(self, slice: &[T]) -> &[T] {
2848 if self.start > self.end {
2849 slice_index_order_fail(self.start, self.end);
2850 } else if self.end > slice.len() {
2851 slice_index_len_fail(self.end, slice.len());
2854 self.get_unchecked(slice)
2859 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2860 if self.start > self.end {
2861 slice_index_order_fail(self.start, self.end);
2862 } else if self.end > slice.len() {
2863 slice_index_len_fail(self.end, slice.len());
2866 self.get_unchecked_mut(slice)
2871 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2872 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2876 fn get(self, slice: &[T]) -> Option<&[T]> {
2877 (0..self.end).get(slice)
2881 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2882 (0..self.end).get_mut(slice)
2886 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2887 (0..self.end).get_unchecked(slice)
2891 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2892 (0..self.end).get_unchecked_mut(slice)
2896 fn index(self, slice: &[T]) -> &[T] {
2897 (0..self.end).index(slice)
2901 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2902 (0..self.end).index_mut(slice)
2906 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2907 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2911 fn get(self, slice: &[T]) -> Option<&[T]> {
2912 (self.start..slice.len()).get(slice)
2916 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2917 (self.start..slice.len()).get_mut(slice)
2921 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2922 (self.start..slice.len()).get_unchecked(slice)
2926 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2927 (self.start..slice.len()).get_unchecked_mut(slice)
2931 fn index(self, slice: &[T]) -> &[T] {
2932 (self.start..slice.len()).index(slice)
2936 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2937 (self.start..slice.len()).index_mut(slice)
2941 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2942 impl<T> SliceIndex<[T]> for ops::RangeFull {
2946 fn get(self, slice: &[T]) -> Option<&[T]> {
2951 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2956 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2961 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2966 fn index(self, slice: &[T]) -> &[T] {
2971 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2977 #[stable(feature = "inclusive_range", since = "1.26.0")]
2978 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2982 fn get(self, slice: &[T]) -> Option<&[T]> {
2983 if *self.end() == usize::max_value() { None }
2984 else { (*self.start()..self.end() + 1).get(slice) }
2988 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2989 if *self.end() == usize::max_value() { None }
2990 else { (*self.start()..self.end() + 1).get_mut(slice) }
2994 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2995 (*self.start()..self.end() + 1).get_unchecked(slice)
2999 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
3000 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
3004 fn index(self, slice: &[T]) -> &[T] {
3005 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
3006 (*self.start()..self.end() + 1).index(slice)
3010 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3011 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
3012 (*self.start()..self.end() + 1).index_mut(slice)
3016 #[stable(feature = "inclusive_range", since = "1.26.0")]
3017 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
3021 fn get(self, slice: &[T]) -> Option<&[T]> {
3022 (0..=self.end).get(slice)
3026 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3027 (0..=self.end).get_mut(slice)
3031 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
3032 (0..=self.end).get_unchecked(slice)
3036 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
3037 (0..=self.end).get_unchecked_mut(slice)
3041 fn index(self, slice: &[T]) -> &[T] {
3042 (0..=self.end).index(slice)
3046 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3047 (0..=self.end).index_mut(slice)
3051 ////////////////////////////////////////////////////////////////////////////////
3053 ////////////////////////////////////////////////////////////////////////////////
3055 #[stable(feature = "rust1", since = "1.0.0")]
3056 impl<T> Default for &[T] {
3057 /// Creates an empty slice.
3058 fn default() -> Self { &[] }
3061 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3062 impl<T> Default for &mut [T] {
3063 /// Creates a mutable empty slice.
3064 fn default() -> Self { &mut [] }
3071 #[stable(feature = "rust1", since = "1.0.0")]
3072 impl<'a, T> IntoIterator for &'a [T] {
3074 type IntoIter = Iter<'a, T>;
3076 fn into_iter(self) -> Iter<'a, T> {
3081 #[stable(feature = "rust1", since = "1.0.0")]
3082 impl<'a, T> IntoIterator for &'a mut [T] {
3083 type Item = &'a mut T;
3084 type IntoIter = IterMut<'a, T>;
3086 fn into_iter(self) -> IterMut<'a, T> {
3091 // Macro helper functions
3093 fn size_from_ptr<T>(_: *const T) -> usize {
3097 // Inlining is_empty and len makes a huge performance difference
3098 macro_rules! is_empty {
3099 // The way we encode the length of a ZST iterator, this works both for ZST
3101 ($self: ident) => {$self.ptr == $self.end}
3103 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
3104 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
3106 ($self: ident) => {{
3107 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
3109 let start = $self.ptr;
3110 let size = size_from_ptr(start);
3112 // This _cannot_ use `unchecked_sub` because we depend on wrapping
3113 // to represent the length of long ZST slice iterators.
3114 ($self.end as usize).wrapping_sub(start as usize)
3116 // We know that `start <= end`, so can do better than `offset_from`,
3117 // which needs to deal in signed. By setting appropriate flags here
3118 // we can tell LLVM this, which helps it remove bounds checks.
3119 // SAFETY: By the type invariant, `start <= end`
3120 let diff = unsafe { unchecked_sub($self.end as usize, start as usize) };
3121 // By also telling LLVM that the pointers are apart by an exact
3122 // multiple of the type size, it can optimize `len() == 0` down to
3123 // `start == end` instead of `(end - start) < size`.
3124 // SAFETY: By the type invariant, the pointers are aligned so the
3125 // distance between them must be a multiple of pointee size
3126 unsafe { exact_div(diff, size) }
3131 // The shared definition of the `Iter` and `IterMut` iterators
3132 macro_rules! iterator {
3134 struct $name:ident -> $ptr:ty,
3140 // Returns the first element and moves the start of the iterator forwards by 1.
3141 // Greatly improves performance compared to an inlined function. The iterator
3142 // must not be empty.
3143 macro_rules! next_unchecked {
3144 ($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
3147 // Returns the last element and moves the end of the iterator backwards by 1.
3148 // Greatly improves performance compared to an inlined function. The iterator
3149 // must not be empty.
3150 macro_rules! next_back_unchecked {
3151 ($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
3154 // Shrinks the iterator when T is a ZST, by moving the end of the iterator
3155 // backwards by `n`. `n` must not exceed `self.len()`.
3156 macro_rules! zst_shrink {
3157 ($self: ident, $n: ident) => {
3158 $self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
3162 impl<'a, T> $name<'a, T> {
3163 // Helper function for creating a slice from the iterator.
3165 fn make_slice(&self) -> &'a [T] {
3166 unsafe { from_raw_parts(self.ptr, len!(self)) }
3169 // Helper function for moving the start of the iterator forwards by `offset` elements,
3170 // returning the old start.
3171 // Unsafe because the offset must not exceed `self.len()`.
3173 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3174 if mem::size_of::<T>() == 0 {
3175 zst_shrink!(self, offset);
3179 self.ptr = self.ptr.offset(offset);
3184 // Helper function for moving the end of the iterator backwards by `offset` elements,
3185 // returning the new end.
3186 // Unsafe because the offset must not exceed `self.len()`.
3188 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3189 if mem::size_of::<T>() == 0 {
3190 zst_shrink!(self, offset);
3193 self.end = self.end.offset(-offset);
3199 #[stable(feature = "rust1", since = "1.0.0")]
3200 impl<T> ExactSizeIterator for $name<'_, T> {
3202 fn len(&self) -> usize {
3207 fn is_empty(&self) -> bool {
3212 #[stable(feature = "rust1", since = "1.0.0")]
3213 impl<'a, T> Iterator for $name<'a, T> {
3217 fn next(&mut self) -> Option<$elem> {
3218 // could be implemented with slices, but this avoids bounds checks
3220 assume(!self.ptr.is_null());
3221 if mem::size_of::<T>() != 0 {
3222 assume(!self.end.is_null());
3224 if is_empty!(self) {
3227 Some(next_unchecked!(self))
3233 fn size_hint(&self) -> (usize, Option<usize>) {
3234 let exact = len!(self);
3235 (exact, Some(exact))
3239 fn count(self) -> usize {
3244 fn nth(&mut self, n: usize) -> Option<$elem> {
3245 if n >= len!(self) {
3246 // This iterator is now empty.
3247 if mem::size_of::<T>() == 0 {
3248 // We have to do it this way as `ptr` may never be 0, but `end`
3249 // could be (due to wrapping).
3250 self.end = self.ptr;
3252 self.ptr = self.end;
3256 // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
3258 self.post_inc_start(n as isize);
3259 Some(next_unchecked!(self))
3264 fn last(mut self) -> Option<$elem> {
3269 #[rustc_inherit_overflow_checks]
3270 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3272 P: FnMut(Self::Item) -> bool,
3274 // The addition might panic on overflow.
3276 self.try_fold(0, move |i, x| {
3277 if predicate(x) { Err(i) }
3281 unsafe { assume(i < n) };
3287 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3288 P: FnMut(Self::Item) -> bool,
3289 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3291 // No need for an overflow check here, because `ExactSizeIterator`
3293 self.try_rfold(n, move |i, x| {
3295 if predicate(x) { Err(i) }
3299 unsafe { assume(i < n) };
3307 #[stable(feature = "rust1", since = "1.0.0")]
3308 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3310 fn next_back(&mut self) -> Option<$elem> {
3311 // could be implemented with slices, but this avoids bounds checks
3313 assume(!self.ptr.is_null());
3314 if mem::size_of::<T>() != 0 {
3315 assume(!self.end.is_null());
3317 if is_empty!(self) {
3320 Some(next_back_unchecked!(self))
3326 fn nth_back(&mut self, n: usize) -> Option<$elem> {
3327 if n >= len!(self) {
3328 // This iterator is now empty.
3329 self.end = self.ptr;
3332 // We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
3334 self.pre_dec_end(n as isize);
3335 Some(next_back_unchecked!(self))
3340 #[stable(feature = "fused", since = "1.26.0")]
3341 impl<T> FusedIterator for $name<'_, T> {}
3343 #[unstable(feature = "trusted_len", issue = "37572")]
3344 unsafe impl<T> TrustedLen for $name<'_, T> {}
3348 /// Immutable slice iterator
3350 /// This struct is created by the [`iter`] method on [slices].
3357 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3358 /// let slice = &[1, 2, 3];
3360 /// // Then, we iterate over it:
3361 /// for element in slice.iter() {
3362 /// println!("{}", element);
3366 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3367 /// [slices]: ../../std/primitive.slice.html
3368 #[stable(feature = "rust1", since = "1.0.0")]
3369 pub struct Iter<'a, T: 'a> {
3371 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3372 // ptr == end is a quick test for the Iterator being empty, that works
3373 // for both ZST and non-ZST.
3374 _marker: marker::PhantomData<&'a T>,
3377 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3378 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3380 f.debug_tuple("Iter")
3381 .field(&self.as_slice())
3386 #[stable(feature = "rust1", since = "1.0.0")]
3387 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3388 #[stable(feature = "rust1", since = "1.0.0")]
3389 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3391 impl<'a, T> Iter<'a, T> {
3392 /// Views the underlying data as a subslice of the original data.
3394 /// This has the same lifetime as the original slice, and so the
3395 /// iterator can continue to be used while this exists.
3402 /// // First, we declare a type which has the `iter` method to get the `Iter`
3403 /// // struct (&[usize here]):
3404 /// let slice = &[1, 2, 3];
3406 /// // Then, we get the iterator:
3407 /// let mut iter = slice.iter();
3408 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3409 /// println!("{:?}", iter.as_slice());
3411 /// // Next, we move to the second element of the slice:
3413 /// // Now `as_slice` returns "[2, 3]":
3414 /// println!("{:?}", iter.as_slice());
3416 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3417 pub fn as_slice(&self) -> &'a [T] {
3422 iterator!{struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3423 fn is_sorted_by<F>(self, mut compare: F) -> bool
3426 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3428 self.as_slice().windows(2).all(|w| {
3429 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3434 #[stable(feature = "rust1", since = "1.0.0")]
3435 impl<T> Clone for Iter<'_, T> {
3436 fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3439 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3440 impl<T> AsRef<[T]> for Iter<'_, T> {
3441 fn as_ref(&self) -> &[T] {
3446 /// Mutable slice iterator.
3448 /// This struct is created by the [`iter_mut`] method on [slices].
3455 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3456 /// // struct (&[usize here]):
3457 /// let mut slice = &mut [1, 2, 3];
3459 /// // Then, we iterate over it and increment each element value:
3460 /// for element in slice.iter_mut() {
3464 /// // We now have "[2, 3, 4]":
3465 /// println!("{:?}", slice);
3468 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3469 /// [slices]: ../../std/primitive.slice.html
3470 #[stable(feature = "rust1", since = "1.0.0")]
3471 pub struct IterMut<'a, T: 'a> {
3473 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3474 // ptr == end is a quick test for the Iterator being empty, that works
3475 // for both ZST and non-ZST.
3476 _marker: marker::PhantomData<&'a mut T>,
3479 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3480 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3482 f.debug_tuple("IterMut")
3483 .field(&self.make_slice())
3488 #[stable(feature = "rust1", since = "1.0.0")]
3489 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3490 #[stable(feature = "rust1", since = "1.0.0")]
3491 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3493 impl<'a, T> IterMut<'a, T> {
3494 /// Views the underlying data as a subslice of the original data.
3496 /// To avoid creating `&mut` references that alias, this is forced
3497 /// to consume the iterator.
3504 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3505 /// // struct (&[usize here]):
3506 /// let mut slice = &mut [1, 2, 3];
3509 /// // Then, we get the iterator:
3510 /// let mut iter = slice.iter_mut();
3511 /// // We move to next element:
3513 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3514 /// println!("{:?}", iter.into_slice());
3517 /// // Now let's modify a value of the slice:
3519 /// // First we get back the iterator:
3520 /// let mut iter = slice.iter_mut();
3521 /// // We change the value of the first element of the slice returned by the `next` method:
3522 /// *iter.next().unwrap() += 1;
3524 /// // Now slice is "[2, 2, 3]":
3525 /// println!("{:?}", slice);
3527 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3528 pub fn into_slice(self) -> &'a mut [T] {
3529 unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3532 /// Views the underlying data as a subslice of the original data.
3534 /// To avoid creating `&mut [T]` references that alias, the returned slice
3535 /// borrows its lifetime from the iterator the method is applied on.
3542 /// # #![feature(slice_iter_mut_as_slice)]
3543 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3545 /// // First, we get the iterator:
3546 /// let mut iter = slice.iter_mut();
3547 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3548 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3550 /// // Next, we move to the second element of the slice:
3552 /// // Now `as_slice` returns "[2, 3]":
3553 /// assert_eq!(iter.as_slice(), &[2, 3]);
3555 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3556 pub fn as_slice(&self) -> &[T] {
3561 iterator!{struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3563 /// An internal abstraction over the splitting iterators, so that
3564 /// splitn, splitn_mut etc can be implemented once.
3566 trait SplitIter: DoubleEndedIterator {
3567 /// Marks the underlying iterator as complete, extracting the remaining
3568 /// portion of the slice.
3569 fn finish(&mut self) -> Option<Self::Item>;
3572 /// An iterator over subslices separated by elements that match a predicate
3575 /// This struct is created by the [`split`] method on [slices].
3577 /// [`split`]: ../../std/primitive.slice.html#method.split
3578 /// [slices]: ../../std/primitive.slice.html
3579 #[stable(feature = "rust1", since = "1.0.0")]
3580 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3586 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3587 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3588 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3589 f.debug_struct("Split")
3590 .field("v", &self.v)
3591 .field("finished", &self.finished)
3596 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3597 #[stable(feature = "rust1", since = "1.0.0")]
3598 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3599 fn clone(&self) -> Self {
3602 pred: self.pred.clone(),
3603 finished: self.finished,
3608 #[stable(feature = "rust1", since = "1.0.0")]
3609 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3610 type Item = &'a [T];
3613 fn next(&mut self) -> Option<&'a [T]> {
3614 if self.finished { return None; }
3616 match self.v.iter().position(|x| (self.pred)(x)) {
3617 None => self.finish(),
3619 let ret = Some(&self.v[..idx]);
3620 self.v = &self.v[idx + 1..];
3627 fn size_hint(&self) -> (usize, Option<usize>) {
3631 (1, Some(self.v.len() + 1))
3636 #[stable(feature = "rust1", since = "1.0.0")]
3637 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3639 fn next_back(&mut self) -> Option<&'a [T]> {
3640 if self.finished { return None; }
3642 match self.v.iter().rposition(|x| (self.pred)(x)) {
3643 None => self.finish(),
3645 let ret = Some(&self.v[idx + 1..]);
3646 self.v = &self.v[..idx];
3653 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3655 fn finish(&mut self) -> Option<&'a [T]> {
3656 if self.finished { None } else { self.finished = true; Some(self.v) }
3660 #[stable(feature = "fused", since = "1.26.0")]
3661 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3663 /// An iterator over the subslices of the vector which are separated
3664 /// by elements that match `pred`.
3666 /// This struct is created by the [`split_mut`] method on [slices].
3668 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3669 /// [slices]: ../../std/primitive.slice.html
3670 #[stable(feature = "rust1", since = "1.0.0")]
3671 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3677 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3678 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3680 f.debug_struct("SplitMut")
3681 .field("v", &self.v)
3682 .field("finished", &self.finished)
3687 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3689 fn finish(&mut self) -> Option<&'a mut [T]> {
3693 self.finished = true;
3694 Some(mem::replace(&mut self.v, &mut []))
3699 #[stable(feature = "rust1", since = "1.0.0")]
3700 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3701 type Item = &'a mut [T];
3704 fn next(&mut self) -> Option<&'a mut [T]> {
3705 if self.finished { return None; }
3707 let idx_opt = { // work around borrowck limitations
3708 let pred = &mut self.pred;
3709 self.v.iter().position(|x| (*pred)(x))
3712 None => self.finish(),
3714 let tmp = mem::replace(&mut self.v, &mut []);
3715 let (head, tail) = tmp.split_at_mut(idx);
3716 self.v = &mut tail[1..];
3723 fn size_hint(&self) -> (usize, Option<usize>) {
3727 // if the predicate doesn't match anything, we yield one slice
3728 // if it matches every element, we yield len+1 empty slices.
3729 (1, Some(self.v.len() + 1))
3734 #[stable(feature = "rust1", since = "1.0.0")]
3735 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3736 P: FnMut(&T) -> bool,
3739 fn next_back(&mut self) -> Option<&'a mut [T]> {
3740 if self.finished { return None; }
3742 let idx_opt = { // work around borrowck limitations
3743 let pred = &mut self.pred;
3744 self.v.iter().rposition(|x| (*pred)(x))
3747 None => self.finish(),
3749 let tmp = mem::replace(&mut self.v, &mut []);
3750 let (head, tail) = tmp.split_at_mut(idx);
3752 Some(&mut tail[1..])
3758 #[stable(feature = "fused", since = "1.26.0")]
3759 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3761 /// An iterator over subslices separated by elements that match a predicate
3762 /// function, starting from the end of the slice.
3764 /// This struct is created by the [`rsplit`] method on [slices].
3766 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3767 /// [slices]: ../../std/primitive.slice.html
3768 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3769 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3770 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3771 inner: Split<'a, T, P>
3774 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3775 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3776 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3777 f.debug_struct("RSplit")
3778 .field("v", &self.inner.v)
3779 .field("finished", &self.inner.finished)
3784 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3785 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3786 type Item = &'a [T];
3789 fn next(&mut self) -> Option<&'a [T]> {
3790 self.inner.next_back()
3794 fn size_hint(&self) -> (usize, Option<usize>) {
3795 self.inner.size_hint()
3799 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3800 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3802 fn next_back(&mut self) -> Option<&'a [T]> {
3807 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3808 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3810 fn finish(&mut self) -> Option<&'a [T]> {
3815 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3816 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3818 /// An iterator over the subslices of the vector which are separated
3819 /// by elements that match `pred`, starting from the end of the slice.
3821 /// This struct is created by the [`rsplit_mut`] method on [slices].
3823 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3824 /// [slices]: ../../std/primitive.slice.html
3825 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3826 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3827 inner: SplitMut<'a, T, P>
3830 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3831 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3833 f.debug_struct("RSplitMut")
3834 .field("v", &self.inner.v)
3835 .field("finished", &self.inner.finished)
3840 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3841 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3843 fn finish(&mut self) -> Option<&'a mut [T]> {
3848 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3849 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3850 type Item = &'a mut [T];
3853 fn next(&mut self) -> Option<&'a mut [T]> {
3854 self.inner.next_back()
3858 fn size_hint(&self) -> (usize, Option<usize>) {
3859 self.inner.size_hint()
3863 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3864 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3865 P: FnMut(&T) -> bool,
3868 fn next_back(&mut self) -> Option<&'a mut [T]> {
3873 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3874 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3876 /// An private iterator over subslices separated by elements that
3877 /// match a predicate function, splitting at most a fixed number of
3880 struct GenericSplitN<I> {
3885 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3889 fn next(&mut self) -> Option<T> {
3892 1 => { self.count -= 1; self.iter.finish() }
3893 _ => { self.count -= 1; self.iter.next() }
3898 fn size_hint(&self) -> (usize, Option<usize>) {
3899 let (lower, upper_opt) = self.iter.size_hint();
3900 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3904 /// An iterator over subslices separated by elements that match a predicate
3905 /// function, limited to a given number of splits.
3907 /// This struct is created by the [`splitn`] method on [slices].
3909 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3910 /// [slices]: ../../std/primitive.slice.html
3911 #[stable(feature = "rust1", since = "1.0.0")]
3912 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3913 inner: GenericSplitN<Split<'a, T, P>>
3916 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3917 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3918 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3919 f.debug_struct("SplitN")
3920 .field("inner", &self.inner)
3925 /// An iterator over subslices separated by elements that match a
3926 /// predicate function, limited to a given number of splits, starting
3927 /// from the end of the slice.
3929 /// This struct is created by the [`rsplitn`] method on [slices].
3931 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3932 /// [slices]: ../../std/primitive.slice.html
3933 #[stable(feature = "rust1", since = "1.0.0")]
3934 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3935 inner: GenericSplitN<RSplit<'a, T, P>>
3938 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3939 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3941 f.debug_struct("RSplitN")
3942 .field("inner", &self.inner)
3947 /// An iterator over subslices separated by elements that match a predicate
3948 /// function, limited to a given number of splits.
3950 /// This struct is created by the [`splitn_mut`] method on [slices].
3952 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3953 /// [slices]: ../../std/primitive.slice.html
3954 #[stable(feature = "rust1", since = "1.0.0")]
3955 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3956 inner: GenericSplitN<SplitMut<'a, T, P>>
3959 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3960 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3962 f.debug_struct("SplitNMut")
3963 .field("inner", &self.inner)
3968 /// An iterator over subslices separated by elements that match a
3969 /// predicate function, limited to a given number of splits, starting
3970 /// from the end of the slice.
3972 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3974 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3975 /// [slices]: ../../std/primitive.slice.html
3976 #[stable(feature = "rust1", since = "1.0.0")]
3977 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3978 inner: GenericSplitN<RSplitMut<'a, T, P>>
3981 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3982 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3983 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3984 f.debug_struct("RSplitNMut")
3985 .field("inner", &self.inner)
3990 macro_rules! forward_iterator {
3991 ($name:ident: $elem:ident, $iter_of:ty) => {
3992 #[stable(feature = "rust1", since = "1.0.0")]
3993 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3994 P: FnMut(&T) -> bool
3996 type Item = $iter_of;
3999 fn next(&mut self) -> Option<$iter_of> {
4004 fn size_hint(&self) -> (usize, Option<usize>) {
4005 self.inner.size_hint()
4009 #[stable(feature = "fused", since = "1.26.0")]
4010 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
4011 where P: FnMut(&T) -> bool {}
4015 forward_iterator! { SplitN: T, &'a [T] }
4016 forward_iterator! { RSplitN: T, &'a [T] }
4017 forward_iterator! { SplitNMut: T, &'a mut [T] }
4018 forward_iterator! { RSplitNMut: T, &'a mut [T] }
4020 /// An iterator over overlapping subslices of length `size`.
4022 /// This struct is created by the [`windows`] method on [slices].
4024 /// [`windows`]: ../../std/primitive.slice.html#method.windows
4025 /// [slices]: ../../std/primitive.slice.html
4027 #[stable(feature = "rust1", since = "1.0.0")]
4028 pub struct Windows<'a, T:'a> {
4033 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4034 #[stable(feature = "rust1", since = "1.0.0")]
4035 impl<T> Clone for Windows<'_, T> {
4036 fn clone(&self) -> Self {
4044 #[stable(feature = "rust1", since = "1.0.0")]
4045 impl<'a, T> Iterator for Windows<'a, T> {
4046 type Item = &'a [T];
4049 fn next(&mut self) -> Option<&'a [T]> {
4050 if self.size > self.v.len() {
4053 let ret = Some(&self.v[..self.size]);
4054 self.v = &self.v[1..];
4060 fn size_hint(&self) -> (usize, Option<usize>) {
4061 if self.size > self.v.len() {
4064 let size = self.v.len() - self.size + 1;
4070 fn count(self) -> usize {
4075 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4076 let (end, overflow) = self.size.overflowing_add(n);
4077 if end > self.v.len() || overflow {
4081 let nth = &self.v[n..end];
4082 self.v = &self.v[n+1..];
4088 fn last(self) -> Option<Self::Item> {
4089 if self.size > self.v.len() {
4092 let start = self.v.len() - self.size;
4093 Some(&self.v[start..])
4098 #[stable(feature = "rust1", since = "1.0.0")]
4099 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4101 fn next_back(&mut self) -> Option<&'a [T]> {
4102 if self.size > self.v.len() {
4105 let ret = Some(&self.v[self.v.len()-self.size..]);
4106 self.v = &self.v[..self.v.len()-1];
4112 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4113 let (end, overflow) = self.v.len().overflowing_sub(n);
4114 if end < self.size || overflow {
4118 let ret = &self.v[end-self.size..end];
4119 self.v = &self.v[..end-1];
4125 #[stable(feature = "rust1", since = "1.0.0")]
4126 impl<T> ExactSizeIterator for Windows<'_, T> {}
4128 #[unstable(feature = "trusted_len", issue = "37572")]
4129 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4131 #[stable(feature = "fused", since = "1.26.0")]
4132 impl<T> FusedIterator for Windows<'_, T> {}
4135 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4136 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4137 from_raw_parts(self.v.as_ptr().add(i), self.size)
4139 fn may_have_side_effect() -> bool { false }
4142 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4143 /// time), starting at the beginning of the slice.
4145 /// When the slice len is not evenly divided by the chunk size, the last slice
4146 /// of the iteration will be the remainder.
4148 /// This struct is created by the [`chunks`] method on [slices].
4150 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4151 /// [slices]: ../../std/primitive.slice.html
4153 #[stable(feature = "rust1", since = "1.0.0")]
4154 pub struct Chunks<'a, T:'a> {
4159 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4160 #[stable(feature = "rust1", since = "1.0.0")]
4161 impl<T> Clone for Chunks<'_, T> {
4162 fn clone(&self) -> Self {
4165 chunk_size: self.chunk_size,
4170 #[stable(feature = "rust1", since = "1.0.0")]
4171 impl<'a, T> Iterator for Chunks<'a, T> {
4172 type Item = &'a [T];
4175 fn next(&mut self) -> Option<&'a [T]> {
4176 if self.v.is_empty() {
4179 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4180 let (fst, snd) = self.v.split_at(chunksz);
4187 fn size_hint(&self) -> (usize, Option<usize>) {
4188 if self.v.is_empty() {
4191 let n = self.v.len() / self.chunk_size;
4192 let rem = self.v.len() % self.chunk_size;
4193 let n = if rem > 0 { n+1 } else { n };
4199 fn count(self) -> usize {
4204 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4205 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4206 if start >= self.v.len() || overflow {
4210 let end = match start.checked_add(self.chunk_size) {
4211 Some(sum) => cmp::min(self.v.len(), sum),
4212 None => self.v.len(),
4214 let nth = &self.v[start..end];
4215 self.v = &self.v[end..];
4221 fn last(self) -> Option<Self::Item> {
4222 if self.v.is_empty() {
4225 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4226 Some(&self.v[start..])
4231 #[stable(feature = "rust1", since = "1.0.0")]
4232 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4234 fn next_back(&mut self) -> Option<&'a [T]> {
4235 if self.v.is_empty() {
4238 let remainder = self.v.len() % self.chunk_size;
4239 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4240 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4247 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4248 let len = self.len();
4253 let start = (len - 1 - n) * self.chunk_size;
4254 let end = match start.checked_add(self.chunk_size) {
4255 Some(res) => cmp::min(res, self.v.len()),
4256 None => self.v.len(),
4258 let nth_back = &self.v[start..end];
4259 self.v = &self.v[..start];
4265 #[stable(feature = "rust1", since = "1.0.0")]
4266 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4268 #[unstable(feature = "trusted_len", issue = "37572")]
4269 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4271 #[stable(feature = "fused", since = "1.26.0")]
4272 impl<T> FusedIterator for Chunks<'_, T> {}
4275 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4276 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4277 let start = i * self.chunk_size;
4278 let end = match start.checked_add(self.chunk_size) {
4279 None => self.v.len(),
4280 Some(end) => cmp::min(end, self.v.len()),
4282 from_raw_parts(self.v.as_ptr().add(start), end - start)
4284 fn may_have_side_effect() -> bool { false }
4287 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4288 /// elements at a time), starting at the beginning of the slice.
4290 /// When the slice len is not evenly divided by the chunk size, the last slice
4291 /// of the iteration will be the remainder.
4293 /// This struct is created by the [`chunks_mut`] method on [slices].
4295 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
4296 /// [slices]: ../../std/primitive.slice.html
4298 #[stable(feature = "rust1", since = "1.0.0")]
4299 pub struct ChunksMut<'a, T:'a> {
4304 #[stable(feature = "rust1", since = "1.0.0")]
4305 impl<'a, T> Iterator for ChunksMut<'a, T> {
4306 type Item = &'a mut [T];
4309 fn next(&mut self) -> Option<&'a mut [T]> {
4310 if self.v.is_empty() {
4313 let sz = cmp::min(self.v.len(), self.chunk_size);
4314 let tmp = mem::replace(&mut self.v, &mut []);
4315 let (head, tail) = tmp.split_at_mut(sz);
4322 fn size_hint(&self) -> (usize, Option<usize>) {
4323 if self.v.is_empty() {
4326 let n = self.v.len() / self.chunk_size;
4327 let rem = self.v.len() % self.chunk_size;
4328 let n = if rem > 0 { n + 1 } else { n };
4334 fn count(self) -> usize {
4339 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4340 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4341 if start >= self.v.len() || overflow {
4345 let end = match start.checked_add(self.chunk_size) {
4346 Some(sum) => cmp::min(self.v.len(), sum),
4347 None => self.v.len(),
4349 let tmp = mem::replace(&mut self.v, &mut []);
4350 let (head, tail) = tmp.split_at_mut(end);
4351 let (_, nth) = head.split_at_mut(start);
4358 fn last(self) -> Option<Self::Item> {
4359 if self.v.is_empty() {
4362 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4363 Some(&mut self.v[start..])
4368 #[stable(feature = "rust1", since = "1.0.0")]
4369 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
4371 fn next_back(&mut self) -> Option<&'a mut [T]> {
4372 if self.v.is_empty() {
4375 let remainder = self.v.len() % self.chunk_size;
4376 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4377 let tmp = mem::replace(&mut self.v, &mut []);
4378 let tmp_len = tmp.len();
4379 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4386 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4387 let len = self.len();
4392 let start = (len - 1 - n) * self.chunk_size;
4393 let end = match start.checked_add(self.chunk_size) {
4394 Some(res) => cmp::min(res, self.v.len()),
4395 None => self.v.len(),
4397 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4398 let (head, nth_back) = temp.split_at_mut(start);
4405 #[stable(feature = "rust1", since = "1.0.0")]
4406 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
4408 #[unstable(feature = "trusted_len", issue = "37572")]
4409 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
4411 #[stable(feature = "fused", since = "1.26.0")]
4412 impl<T> FusedIterator for ChunksMut<'_, T> {}
4415 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
4416 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4417 let start = i * self.chunk_size;
4418 let end = match start.checked_add(self.chunk_size) {
4419 None => self.v.len(),
4420 Some(end) => cmp::min(end, self.v.len()),
4422 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4424 fn may_have_side_effect() -> bool { false }
4427 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4428 /// time), starting at the beginning of the slice.
4430 /// When the slice len is not evenly divided by the chunk size, the last
4431 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4432 /// the [`remainder`] function from the iterator.
4434 /// This struct is created by the [`chunks_exact`] method on [slices].
4436 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4437 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4438 /// [slices]: ../../std/primitive.slice.html
4440 #[stable(feature = "chunks_exact", since = "1.31.0")]
4441 pub struct ChunksExact<'a, T:'a> {
4447 impl<'a, T> ChunksExact<'a, T> {
4448 /// Returns the remainder of the original slice that is not going to be
4449 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4451 #[stable(feature = "chunks_exact", since = "1.31.0")]
4452 pub fn remainder(&self) -> &'a [T] {
4457 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4458 #[stable(feature = "chunks_exact", since = "1.31.0")]
4459 impl<T> Clone for ChunksExact<'_, T> {
4460 fn clone(&self) -> Self {
4464 chunk_size: self.chunk_size,
4469 #[stable(feature = "chunks_exact", since = "1.31.0")]
4470 impl<'a, T> Iterator for ChunksExact<'a, T> {
4471 type Item = &'a [T];
4474 fn next(&mut self) -> Option<&'a [T]> {
4475 if self.v.len() < self.chunk_size {
4478 let (fst, snd) = self.v.split_at(self.chunk_size);
4485 fn size_hint(&self) -> (usize, Option<usize>) {
4486 let n = self.v.len() / self.chunk_size;
4491 fn count(self) -> usize {
4496 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4497 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4498 if start >= self.v.len() || overflow {
4502 let (_, snd) = self.v.split_at(start);
4509 fn last(mut self) -> Option<Self::Item> {
4514 #[stable(feature = "chunks_exact", since = "1.31.0")]
4515 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4517 fn next_back(&mut self) -> Option<&'a [T]> {
4518 if self.v.len() < self.chunk_size {
4521 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4528 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4529 let len = self.len();
4534 let start = (len - 1 - n) * self.chunk_size;
4535 let end = start + self.chunk_size;
4536 let nth_back = &self.v[start..end];
4537 self.v = &self.v[..start];
4543 #[stable(feature = "chunks_exact", since = "1.31.0")]
4544 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4545 fn is_empty(&self) -> bool {
4550 #[unstable(feature = "trusted_len", issue = "37572")]
4551 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4553 #[stable(feature = "chunks_exact", since = "1.31.0")]
4554 impl<T> FusedIterator for ChunksExact<'_, T> {}
4557 #[stable(feature = "chunks_exact", since = "1.31.0")]
4558 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4559 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4560 let start = i * self.chunk_size;
4561 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4563 fn may_have_side_effect() -> bool { false }
4566 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4567 /// elements at a time), starting at the beginning of the slice.
4569 /// When the slice len is not evenly divided by the chunk size, the last up to
4570 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4571 /// [`into_remainder`] function from the iterator.
4573 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4575 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4576 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4577 /// [slices]: ../../std/primitive.slice.html
4579 #[stable(feature = "chunks_exact", since = "1.31.0")]
4580 pub struct ChunksExactMut<'a, T:'a> {
4586 impl<'a, T> ChunksExactMut<'a, T> {
4587 /// Returns the remainder of the original slice that is not going to be
4588 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4590 #[stable(feature = "chunks_exact", since = "1.31.0")]
4591 pub fn into_remainder(self) -> &'a mut [T] {
4596 #[stable(feature = "chunks_exact", since = "1.31.0")]
4597 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4598 type Item = &'a mut [T];
4601 fn next(&mut self) -> Option<&'a mut [T]> {
4602 if self.v.len() < self.chunk_size {
4605 let tmp = mem::replace(&mut self.v, &mut []);
4606 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4613 fn size_hint(&self) -> (usize, Option<usize>) {
4614 let n = self.v.len() / self.chunk_size;
4619 fn count(self) -> usize {
4624 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4625 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4626 if start >= self.v.len() || overflow {
4630 let tmp = mem::replace(&mut self.v, &mut []);
4631 let (_, snd) = tmp.split_at_mut(start);
4638 fn last(mut self) -> Option<Self::Item> {
4643 #[stable(feature = "chunks_exact", since = "1.31.0")]
4644 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4646 fn next_back(&mut self) -> Option<&'a mut [T]> {
4647 if self.v.len() < self.chunk_size {
4650 let tmp = mem::replace(&mut self.v, &mut []);
4651 let tmp_len = tmp.len();
4652 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4659 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4660 let len = self.len();
4665 let start = (len - 1 - n) * self.chunk_size;
4666 let end = start + self.chunk_size;
4667 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4668 let (head, nth_back) = temp.split_at_mut(start);
4675 #[stable(feature = "chunks_exact", since = "1.31.0")]
4676 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4677 fn is_empty(&self) -> bool {
4682 #[unstable(feature = "trusted_len", issue = "37572")]
4683 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4685 #[stable(feature = "chunks_exact", since = "1.31.0")]
4686 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4689 #[stable(feature = "chunks_exact", since = "1.31.0")]
4690 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4691 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4692 let start = i * self.chunk_size;
4693 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4695 fn may_have_side_effect() -> bool { false }
4698 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4699 /// time), starting at the end of the slice.
4701 /// When the slice len is not evenly divided by the chunk size, the last slice
4702 /// of the iteration will be the remainder.
4704 /// This struct is created by the [`rchunks`] method on [slices].
4706 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4707 /// [slices]: ../../std/primitive.slice.html
4709 #[stable(feature = "rchunks", since = "1.31.0")]
4710 pub struct RChunks<'a, T:'a> {
4715 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4716 #[stable(feature = "rchunks", since = "1.31.0")]
4717 impl<T> Clone for RChunks<'_, T> {
4718 fn clone(&self) -> Self {
4721 chunk_size: self.chunk_size,
4726 #[stable(feature = "rchunks", since = "1.31.0")]
4727 impl<'a, T> Iterator for RChunks<'a, T> {
4728 type Item = &'a [T];
4731 fn next(&mut self) -> Option<&'a [T]> {
4732 if self.v.is_empty() {
4735 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4736 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4743 fn size_hint(&self) -> (usize, Option<usize>) {
4744 if self.v.is_empty() {
4747 let n = self.v.len() / self.chunk_size;
4748 let rem = self.v.len() % self.chunk_size;
4749 let n = if rem > 0 { n+1 } else { n };
4755 fn count(self) -> usize {
4760 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4761 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4762 if end >= self.v.len() || overflow {
4766 // Can't underflow because of the check above
4767 let end = self.v.len() - end;
4768 let start = match end.checked_sub(self.chunk_size) {
4772 let nth = &self.v[start..end];
4773 self.v = &self.v[0..start];
4779 fn last(self) -> Option<Self::Item> {
4780 if self.v.is_empty() {
4783 let rem = self.v.len() % self.chunk_size;
4784 let end = if rem == 0 { self.chunk_size } else { rem };
4785 Some(&self.v[0..end])
4790 #[stable(feature = "rchunks", since = "1.31.0")]
4791 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4793 fn next_back(&mut self) -> Option<&'a [T]> {
4794 if self.v.is_empty() {
4797 let remainder = self.v.len() % self.chunk_size;
4798 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4799 let (fst, snd) = self.v.split_at(chunksz);
4806 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4807 let len = self.len();
4812 // can't underflow because `n < len`
4813 let offset_from_end = (len - 1 - n) * self.chunk_size;
4814 let end = self.v.len() - offset_from_end;
4815 let start = end.saturating_sub(self.chunk_size);
4816 let nth_back = &self.v[start..end];
4817 self.v = &self.v[end..];
4823 #[stable(feature = "rchunks", since = "1.31.0")]
4824 impl<T> ExactSizeIterator for RChunks<'_, T> {}
4826 #[unstable(feature = "trusted_len", issue = "37572")]
4827 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
4829 #[stable(feature = "rchunks", since = "1.31.0")]
4830 impl<T> FusedIterator for RChunks<'_, T> {}
4833 #[stable(feature = "rchunks", since = "1.31.0")]
4834 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4835 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4836 let end = self.v.len() - i * self.chunk_size;
4837 let start = match end.checked_sub(self.chunk_size) {
4839 Some(start) => start,
4841 from_raw_parts(self.v.as_ptr().add(start), end - start)
4843 fn may_have_side_effect() -> bool { false }
4846 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4847 /// elements at a time), starting at the end of the slice.
4849 /// When the slice len is not evenly divided by the chunk size, the last slice
4850 /// of the iteration will be the remainder.
4852 /// This struct is created by the [`rchunks_mut`] method on [slices].
4854 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4855 /// [slices]: ../../std/primitive.slice.html
4857 #[stable(feature = "rchunks", since = "1.31.0")]
4858 pub struct RChunksMut<'a, T:'a> {
4863 #[stable(feature = "rchunks", since = "1.31.0")]
4864 impl<'a, T> Iterator for RChunksMut<'a, T> {
4865 type Item = &'a mut [T];
4868 fn next(&mut self) -> Option<&'a mut [T]> {
4869 if self.v.is_empty() {
4872 let sz = cmp::min(self.v.len(), self.chunk_size);
4873 let tmp = mem::replace(&mut self.v, &mut []);
4874 let tmp_len = tmp.len();
4875 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4882 fn size_hint(&self) -> (usize, Option<usize>) {
4883 if self.v.is_empty() {
4886 let n = self.v.len() / self.chunk_size;
4887 let rem = self.v.len() % self.chunk_size;
4888 let n = if rem > 0 { n + 1 } else { n };
4894 fn count(self) -> usize {
4899 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4900 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4901 if end >= self.v.len() || overflow {
4905 // Can't underflow because of the check above
4906 let end = self.v.len() - end;
4907 let start = match end.checked_sub(self.chunk_size) {
4911 let tmp = mem::replace(&mut self.v, &mut []);
4912 let (head, tail) = tmp.split_at_mut(start);
4913 let (nth, _) = tail.split_at_mut(end - start);
4920 fn last(self) -> Option<Self::Item> {
4921 if self.v.is_empty() {
4924 let rem = self.v.len() % self.chunk_size;
4925 let end = if rem == 0 { self.chunk_size } else { rem };
4926 Some(&mut self.v[0..end])
4931 #[stable(feature = "rchunks", since = "1.31.0")]
4932 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4934 fn next_back(&mut self) -> Option<&'a mut [T]> {
4935 if self.v.is_empty() {
4938 let remainder = self.v.len() % self.chunk_size;
4939 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4940 let tmp = mem::replace(&mut self.v, &mut []);
4941 let (head, tail) = tmp.split_at_mut(sz);
4948 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4949 let len = self.len();
4954 // can't underflow because `n < len`
4955 let offset_from_end = (len - 1 - n) * self.chunk_size;
4956 let end = self.v.len() - offset_from_end;
4957 let start = end.saturating_sub(self.chunk_size);
4958 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
4959 let (_, nth_back) = tmp.split_at_mut(start);
4966 #[stable(feature = "rchunks", since = "1.31.0")]
4967 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
4969 #[unstable(feature = "trusted_len", issue = "37572")]
4970 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
4972 #[stable(feature = "rchunks", since = "1.31.0")]
4973 impl<T> FusedIterator for RChunksMut<'_, T> {}
4976 #[stable(feature = "rchunks", since = "1.31.0")]
4977 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4978 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4979 let end = self.v.len() - i * self.chunk_size;
4980 let start = match end.checked_sub(self.chunk_size) {
4982 Some(start) => start,
4984 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4986 fn may_have_side_effect() -> bool { false }
4989 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4990 /// time), starting at the end of the slice.
4992 /// When the slice len is not evenly divided by the chunk size, the last
4993 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4994 /// the [`remainder`] function from the iterator.
4996 /// This struct is created by the [`rchunks_exact`] method on [slices].
4998 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4999 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5000 /// [slices]: ../../std/primitive.slice.html
5002 #[stable(feature = "rchunks", since = "1.31.0")]
5003 pub struct RChunksExact<'a, T:'a> {
5009 impl<'a, T> RChunksExact<'a, T> {
5010 /// Returns the remainder of the original slice that is not going to be
5011 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5013 #[stable(feature = "rchunks", since = "1.31.0")]
5014 pub fn remainder(&self) -> &'a [T] {
5019 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5020 #[stable(feature = "rchunks", since = "1.31.0")]
5021 impl<'a, T> Clone for RChunksExact<'a, T> {
5022 fn clone(&self) -> RChunksExact<'a, T> {
5026 chunk_size: self.chunk_size,
5031 #[stable(feature = "rchunks", since = "1.31.0")]
5032 impl<'a, T> Iterator for RChunksExact<'a, T> {
5033 type Item = &'a [T];
5036 fn next(&mut self) -> Option<&'a [T]> {
5037 if self.v.len() < self.chunk_size {
5040 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5047 fn size_hint(&self) -> (usize, Option<usize>) {
5048 let n = self.v.len() / self.chunk_size;
5053 fn count(self) -> usize {
5058 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5059 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5060 if end >= self.v.len() || overflow {
5064 let (fst, _) = self.v.split_at(self.v.len() - end);
5071 fn last(mut self) -> Option<Self::Item> {
5076 #[stable(feature = "rchunks", since = "1.31.0")]
5077 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
5079 fn next_back(&mut self) -> Option<&'a [T]> {
5080 if self.v.len() < self.chunk_size {
5083 let (fst, snd) = self.v.split_at(self.chunk_size);
5090 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5091 let len = self.len();
5096 // now that we know that `n` corresponds to a chunk,
5097 // none of these operations can underflow/overflow
5098 let offset = (len - n) * self.chunk_size;
5099 let start = self.v.len() - offset;
5100 let end = start + self.chunk_size;
5101 let nth_back = &self.v[start..end];
5102 self.v = &self.v[end..];
5108 #[stable(feature = "rchunks", since = "1.31.0")]
5109 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
5110 fn is_empty(&self) -> bool {
5115 #[unstable(feature = "trusted_len", issue = "37572")]
5116 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
5118 #[stable(feature = "rchunks", since = "1.31.0")]
5119 impl<T> FusedIterator for RChunksExact<'_, T> {}
5122 #[stable(feature = "rchunks", since = "1.31.0")]
5123 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
5124 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5125 let end = self.v.len() - i * self.chunk_size;
5126 let start = end - self.chunk_size;
5127 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
5129 fn may_have_side_effect() -> bool { false }
5132 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5133 /// elements at a time), starting at the end of the slice.
5135 /// When the slice len is not evenly divided by the chunk size, the last up to
5136 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5137 /// [`into_remainder`] function from the iterator.
5139 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5141 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5142 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5143 /// [slices]: ../../std/primitive.slice.html
5145 #[stable(feature = "rchunks", since = "1.31.0")]
5146 pub struct RChunksExactMut<'a, T:'a> {
5152 impl<'a, T> RChunksExactMut<'a, T> {
5153 /// Returns the remainder of the original slice that is not going to be
5154 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5156 #[stable(feature = "rchunks", since = "1.31.0")]
5157 pub fn into_remainder(self) -> &'a mut [T] {
5162 #[stable(feature = "rchunks", since = "1.31.0")]
5163 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5164 type Item = &'a mut [T];
5167 fn next(&mut self) -> Option<&'a mut [T]> {
5168 if self.v.len() < self.chunk_size {
5171 let tmp = mem::replace(&mut self.v, &mut []);
5172 let tmp_len = tmp.len();
5173 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5180 fn size_hint(&self) -> (usize, Option<usize>) {
5181 let n = self.v.len() / self.chunk_size;
5186 fn count(self) -> usize {
5191 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5192 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5193 if end >= self.v.len() || overflow {
5197 let tmp = mem::replace(&mut self.v, &mut []);
5198 let tmp_len = tmp.len();
5199 let (fst, _) = tmp.split_at_mut(tmp_len - end);
5206 fn last(mut self) -> Option<Self::Item> {
5211 #[stable(feature = "rchunks", since = "1.31.0")]
5212 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5214 fn next_back(&mut self) -> Option<&'a mut [T]> {
5215 if self.v.len() < self.chunk_size {
5218 let tmp = mem::replace(&mut self.v, &mut []);
5219 let (head, tail) = tmp.split_at_mut(self.chunk_size);
5226 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5227 let len = self.len();
5232 // now that we know that `n` corresponds to a chunk,
5233 // none of these operations can underflow/overflow
5234 let offset = (len - n) * self.chunk_size;
5235 let start = self.v.len() - offset;
5236 let end = start + self.chunk_size;
5237 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5238 let (_, nth_back) = tmp.split_at_mut(start);
5245 #[stable(feature = "rchunks", since = "1.31.0")]
5246 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5247 fn is_empty(&self) -> bool {
5252 #[unstable(feature = "trusted_len", issue = "37572")]
5253 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5255 #[stable(feature = "rchunks", since = "1.31.0")]
5256 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5259 #[stable(feature = "rchunks", since = "1.31.0")]
5260 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5261 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5262 let end = self.v.len() - i * self.chunk_size;
5263 let start = end - self.chunk_size;
5264 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
5266 fn may_have_side_effect() -> bool { false }
5273 /// Forms a slice from a pointer and a length.
5275 /// The `len` argument is the number of **elements**, not the number of bytes.
5279 /// Behavior is undefined if any of the following conditions are violated:
5281 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
5282 /// and it must be properly aligned. This means in particular:
5284 /// * The entire memory range of this slice must be contained within a single allocated object!
5285 /// Slices can never span across multiple allocated objects.
5286 /// * `data` must be non-null and aligned even for zero-length slices. One
5287 /// reason for this is that enum layout optimizations may rely on references
5288 /// (including slices of any length) being aligned and non-null to distinguish
5289 /// them from other data. You can obtain a pointer that is usable as `data`
5290 /// for zero-length slices using [`NonNull::dangling()`].
5292 /// * The memory referenced by the returned slice must not be mutated for the duration
5293 /// of lifetime `'a`, except inside an `UnsafeCell`.
5295 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
5296 /// See the safety documentation of [`pointer::offset`].
5300 /// The lifetime for the returned slice is inferred from its usage. To
5301 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
5302 /// source lifetime is safe in the context, such as by providing a helper
5303 /// function taking the lifetime of a host value for the slice, or by explicit
5311 /// // manifest a slice for a single element
5313 /// let ptr = &x as *const _;
5314 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
5315 /// assert_eq!(slice[0], 42);
5318 /// [valid]: ../../std/ptr/index.html#safety
5319 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5320 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5322 #[stable(feature = "rust1", since = "1.0.0")]
5323 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
5324 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
5325 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5326 "attempt to create slice covering at least half the address space");
5327 &*ptr::slice_from_raw_parts(data, len)
5330 /// Performs the same functionality as [`from_raw_parts`], except that a
5331 /// mutable slice is returned.
5335 /// Behavior is undefined if any of the following conditions are violated:
5337 /// * `data` must be [valid] for writes for `len * mem::size_of::<T>()` many bytes,
5338 /// and it must be properly aligned. This means in particular:
5340 /// * The entire memory range of this slice must be contained within a single allocated object!
5341 /// Slices can never span across multiple allocated objects.
5342 /// * `data` must be non-null and aligned even for zero-length slices. One
5343 /// reason for this is that enum layout optimizations may rely on references
5344 /// (including slices of any length) being aligned and non-null to distinguish
5345 /// them from other data. You can obtain a pointer that is usable as `data`
5346 /// for zero-length slices using [`NonNull::dangling()`].
5348 /// * The memory referenced by the returned slice must not be accessed through any other pointer
5349 /// (not derived from the return value) for the duration of lifetime `'a`.
5350 /// Both read and write accesses are forbidden.
5352 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
5353 /// See the safety documentation of [`pointer::offset`].
5355 /// [valid]: ../../std/ptr/index.html#safety
5356 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
5357 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
5358 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
5360 #[stable(feature = "rust1", since = "1.0.0")]
5361 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
5362 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
5363 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
5364 "attempt to create slice covering at least half the address space");
5365 &mut *ptr::slice_from_raw_parts_mut(data, len)
5368 /// Converts a reference to T into a slice of length 1 (without copying).
5369 #[stable(feature = "from_ref", since = "1.28.0")]
5370 pub fn from_ref<T>(s: &T) -> &[T] {
5372 from_raw_parts(s, 1)
5376 /// Converts a reference to T into a slice of length 1 (without copying).
5377 #[stable(feature = "from_ref", since = "1.28.0")]
5378 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
5380 from_raw_parts_mut(s, 1)
5384 // This function is public only because there is no other way to unit test heapsort.
5385 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
5387 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
5388 where F: FnMut(&T, &T) -> bool
5390 sort::heapsort(v, &mut is_less);
5394 // Comparison traits
5398 /// Calls implementation provided memcmp.
5400 /// Interprets the data as u8.
5402 /// Returns 0 for equal, < 0 for less than and > 0 for greater
5404 // FIXME(#32610): Return type should be c_int
5405 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
5408 #[stable(feature = "rust1", since = "1.0.0")]
5409 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
5410 fn eq(&self, other: &[B]) -> bool {
5411 SlicePartialEq::equal(self, other)
5414 fn ne(&self, other: &[B]) -> bool {
5415 SlicePartialEq::not_equal(self, other)
5419 #[stable(feature = "rust1", since = "1.0.0")]
5420 impl<T: Eq> Eq for [T] {}
5422 /// Implements comparison of vectors lexicographically.
5423 #[stable(feature = "rust1", since = "1.0.0")]
5424 impl<T: Ord> Ord for [T] {
5425 fn cmp(&self, other: &[T]) -> Ordering {
5426 SliceOrd::compare(self, other)
5430 /// Implements comparison of vectors lexicographically.
5431 #[stable(feature = "rust1", since = "1.0.0")]
5432 impl<T: PartialOrd> PartialOrd for [T] {
5433 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
5434 SlicePartialOrd::partial_compare(self, other)
5439 // intermediate trait for specialization of slice's PartialEq
5440 trait SlicePartialEq<B> {
5441 fn equal(&self, other: &[B]) -> bool;
5443 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
5446 // Generic slice equality
5447 impl<A, B> SlicePartialEq<B> for [A]
5448 where A: PartialEq<B>
5450 default fn equal(&self, other: &[B]) -> bool {
5451 if self.len() != other.len() {
5455 self.iter().zip(other.iter()).all(|(x, y)| x == y)
5459 // Use an equal-pointer optimization when types are `Eq`
5460 impl<A> SlicePartialEq<A> for [A]
5461 where A: PartialEq<A> + Eq
5463 default fn equal(&self, other: &[A]) -> bool {
5464 if self.len() != other.len() {
5468 if self.as_ptr() == other.as_ptr() {
5472 self.iter().zip(other.iter()).all(|(x, y)| x == y)
5476 // Use memcmp for bytewise equality when the types allow
5477 impl<A> SlicePartialEq<A> for [A]
5478 where A: PartialEq<A> + BytewiseEquality
5480 fn equal(&self, other: &[A]) -> bool {
5481 if self.len() != other.len() {
5484 if self.as_ptr() == other.as_ptr() {
5488 let size = mem::size_of_val(self);
5489 memcmp(self.as_ptr() as *const u8,
5490 other.as_ptr() as *const u8, size) == 0
5496 // intermediate trait for specialization of slice's PartialOrd
5497 trait SlicePartialOrd<B> {
5498 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
5501 impl<A> SlicePartialOrd<A> for [A]
5504 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5505 let l = cmp::min(self.len(), other.len());
5507 // Slice to the loop iteration range to enable bound check
5508 // elimination in the compiler
5509 let lhs = &self[..l];
5510 let rhs = &other[..l];
5513 match lhs[i].partial_cmp(&rhs[i]) {
5514 Some(Ordering::Equal) => (),
5515 non_eq => return non_eq,
5519 self.len().partial_cmp(&other.len())
5523 impl<A> SlicePartialOrd<A> for [A]
5526 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
5527 Some(SliceOrd::compare(self, other))
5532 // intermediate trait for specialization of slice's Ord
5534 fn compare(&self, other: &[B]) -> Ordering;
5537 impl<A> SliceOrd<A> for [A]
5540 default fn compare(&self, other: &[A]) -> Ordering {
5541 let l = cmp::min(self.len(), other.len());
5543 // Slice to the loop iteration range to enable bound check
5544 // elimination in the compiler
5545 let lhs = &self[..l];
5546 let rhs = &other[..l];
5549 match lhs[i].cmp(&rhs[i]) {
5550 Ordering::Equal => (),
5551 non_eq => return non_eq,
5555 self.len().cmp(&other.len())
5559 // memcmp compares a sequence of unsigned bytes lexicographically.
5560 // this matches the order we want for [u8], but no others (not even [i8]).
5561 impl SliceOrd<u8> for [u8] {
5563 fn compare(&self, other: &[u8]) -> Ordering {
5564 let order = unsafe {
5565 memcmp(self.as_ptr(), other.as_ptr(),
5566 cmp::min(self.len(), other.len()))
5569 self.len().cmp(&other.len())
5570 } else if order < 0 {
5579 /// Trait implemented for types that can be compared for equality using
5580 /// their bytewise representation
5581 trait BytewiseEquality: Eq + Copy { }
5583 macro_rules! impl_marker_for {
5584 ($traitname:ident, $($ty:ty)*) => {
5586 impl $traitname for $ty { }
5591 impl_marker_for!(BytewiseEquality,
5592 u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
5595 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5596 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5599 fn may_have_side_effect() -> bool { false }
5603 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5604 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5605 &mut *self.ptr.add(i)
5607 fn may_have_side_effect() -> bool { false }
5610 trait SliceContains: Sized {
5611 fn slice_contains(&self, x: &[Self]) -> bool;
5614 impl<T> SliceContains for T where T: PartialEq {
5615 default fn slice_contains(&self, x: &[Self]) -> bool {
5616 x.iter().any(|y| *y == *self)
5620 impl SliceContains for u8 {
5621 fn slice_contains(&self, x: &[Self]) -> bool {
5622 memchr::memchr(*self, x).is_some()
5626 impl SliceContains for i8 {
5627 fn slice_contains(&self, x: &[Self]) -> bool {
5628 let byte = *self as u8;
5629 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5630 memchr::memchr(byte, bytes).is_some()