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.
27 use crate::cmp::Ordering::{self, Equal, Greater, Less};
29 use crate::intrinsics::{assume, exact_div, is_aligned_and_not_null, unchecked_sub};
31 use crate::marker::{self, Copy, Send, Sized, Sync};
33 use crate::ops::{self, FnMut, Range};
34 use crate::option::Option;
35 use crate::option::Option::{None, Some};
36 use crate::ptr::{self, NonNull};
37 use crate::result::Result;
38 use crate::result::Result::{Err, Ok};
41 feature = "slice_internals",
43 reason = "exposed from core to be reused in std; use the memchr crate"
45 /// Pure rust memchr implementation, taken from rust-memchr
58 /// Returns the number of elements in the slice.
63 /// let a = [1, 2, 3];
64 /// assert_eq!(a.len(), 3);
66 #[stable(feature = "rust1", since = "1.0.0")]
67 #[rustc_const_stable(feature = "const_slice_len", since = "1.32.0")]
69 // SAFETY: const sound because we transmute out the length field as a usize (which it must be)
70 #[allow(unused_attributes)]
71 #[allow_internal_unstable(const_fn_union)]
72 pub const fn len(&self) -> usize {
73 unsafe { 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> {
105 if let [first, ..] = self { Some(first) } else { None }
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> {
123 if let [first, ..] = self { Some(first) } else { None }
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 let [first, tail @ ..] = self { Some((first, tail)) } else { None }
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 let [first, tail @ ..] = self { Some((first, tail)) } else { None }
164 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
169 /// let x = &[0, 1, 2];
171 /// if let Some((last, elements)) = x.split_last() {
172 /// assert_eq!(last, &2);
173 /// assert_eq!(elements, &[0, 1]);
176 #[stable(feature = "slice_splits", since = "1.5.0")]
178 pub fn split_last(&self) -> Option<(&T, &[T])> {
179 if let [init @ .., last] = self { Some((last, init)) } else { None }
182 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
187 /// let x = &mut [0, 1, 2];
189 /// if let Some((last, elements)) = x.split_last_mut() {
194 /// assert_eq!(x, &[4, 5, 3]);
196 #[stable(feature = "slice_splits", since = "1.5.0")]
198 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
199 if let [init @ .., last] = self { Some((last, init)) } else { None }
202 /// Returns the last element of the slice, or `None` if it is empty.
207 /// let v = [10, 40, 30];
208 /// assert_eq!(Some(&30), v.last());
210 /// let w: &[i32] = &[];
211 /// assert_eq!(None, w.last());
213 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn last(&self) -> Option<&T> {
216 if let [.., last] = self { Some(last) } else { None }
219 /// Returns a mutable pointer to the last item in the slice.
224 /// let x = &mut [0, 1, 2];
226 /// if let Some(last) = x.last_mut() {
229 /// assert_eq!(x, &[0, 1, 10]);
231 #[stable(feature = "rust1", since = "1.0.0")]
233 pub fn last_mut(&mut self) -> Option<&mut T> {
234 if let [.., last] = self { Some(last) } else { None }
237 /// Returns a reference to an element or subslice depending on the type of
240 /// - If given a position, returns a reference to the element at that
241 /// position or `None` if out of bounds.
242 /// - If given a range, returns the subslice corresponding to that range,
243 /// or `None` if out of bounds.
248 /// let v = [10, 40, 30];
249 /// assert_eq!(Some(&40), v.get(1));
250 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
251 /// assert_eq!(None, v.get(3));
252 /// assert_eq!(None, v.get(0..4));
254 #[stable(feature = "rust1", since = "1.0.0")]
256 pub fn get<I>(&self, index: I) -> Option<&I::Output>
263 /// Returns a mutable reference to an element or subslice depending on the
264 /// type of index (see [`get`]) or `None` if the index is out of bounds.
266 /// [`get`]: #method.get
271 /// let x = &mut [0, 1, 2];
273 /// if let Some(elem) = x.get_mut(1) {
276 /// assert_eq!(x, &[0, 42, 2]);
278 #[stable(feature = "rust1", since = "1.0.0")]
280 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
287 /// Returns a reference to an element or subslice, without doing bounds
290 /// This is generally not recommended, use with caution!
291 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
292 /// even if the resulting reference is not used.
293 /// For a safe alternative see [`get`].
295 /// [`get`]: #method.get
296 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
301 /// let x = &[1, 2, 4];
304 /// assert_eq!(x.get_unchecked(1), &2);
307 #[stable(feature = "rust1", since = "1.0.0")]
309 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
313 // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`;
314 // the slice is dereferencable because `self` is a safe reference.
315 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
316 unsafe { &*index.get_unchecked(self) }
319 /// Returns a mutable reference to an element or subslice, without doing
322 /// This is generally not recommended, use with caution!
323 /// Calling this method with an out-of-bounds index is *[undefined behavior]*
324 /// even if the resulting reference is not used.
325 /// For a safe alternative see [`get_mut`].
327 /// [`get_mut`]: #method.get_mut
328 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
333 /// let x = &mut [1, 2, 4];
336 /// let elem = x.get_unchecked_mut(1);
339 /// assert_eq!(x, &[1, 13, 4]);
341 #[stable(feature = "rust1", since = "1.0.0")]
343 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
347 // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`;
348 // the slice is dereferencable because `self` is a safe reference.
349 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
350 unsafe { &mut *index.get_unchecked_mut(self) }
353 /// Returns a raw pointer to the slice's buffer.
355 /// The caller must ensure that the slice outlives the pointer this
356 /// function returns, or else it will end up pointing to garbage.
358 /// The caller must also ensure that the memory the pointer (non-transitively) points to
359 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
360 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
362 /// Modifying the container referenced by this slice may cause its buffer
363 /// to be reallocated, which would also make any pointers to it invalid.
368 /// let x = &[1, 2, 4];
369 /// let x_ptr = x.as_ptr();
372 /// for i in 0..x.len() {
373 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
378 /// [`as_mut_ptr`]: #method.as_mut_ptr
379 #[stable(feature = "rust1", since = "1.0.0")]
380 #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")]
382 pub const fn as_ptr(&self) -> *const T {
383 self as *const [T] as *const T
386 /// Returns an unsafe mutable pointer to the slice's buffer.
388 /// The caller must ensure that the slice outlives the pointer this
389 /// function returns, or else it will end up pointing to garbage.
391 /// Modifying the container referenced by this slice may cause its buffer
392 /// to be reallocated, which would also make any pointers to it invalid.
397 /// let x = &mut [1, 2, 4];
398 /// let x_ptr = x.as_mut_ptr();
401 /// for i in 0..x.len() {
402 /// *x_ptr.add(i) += 2;
405 /// assert_eq!(x, &[3, 4, 6]);
407 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn as_mut_ptr(&mut self) -> *mut T {
410 self as *mut [T] as *mut T
413 /// Returns the two raw pointers spanning the slice.
415 /// The returned range is half-open, which means that the end pointer
416 /// points *one past* the last element of the slice. This way, an empty
417 /// slice is represented by two equal pointers, and the difference between
418 /// the two pointers represents the size of the slice.
420 /// See [`as_ptr`] for warnings on using these pointers. The end pointer
421 /// requires extra caution, as it does not point to a valid element in the
424 /// This function is useful for interacting with foreign interfaces which
425 /// use two pointers to refer to a range of elements in memory, as is
428 /// It can also be useful to check if a pointer to an element refers to an
429 /// element of this slice:
432 /// #![feature(slice_ptr_range)]
434 /// let a = [1, 2, 3];
435 /// let x = &a[1] as *const _;
436 /// let y = &5 as *const _;
438 /// assert!(a.as_ptr_range().contains(&x));
439 /// assert!(!a.as_ptr_range().contains(&y));
442 /// [`as_ptr`]: #method.as_ptr
443 #[unstable(feature = "slice_ptr_range", issue = "65807")]
445 pub fn as_ptr_range(&self) -> Range<*const T> {
446 // The `add` here is safe, because:
448 // - Both pointers are part of the same object, as pointing directly
449 // past the object also counts.
451 // - The size of the slice is never larger than isize::MAX bytes, as
453 // - https://github.com/rust-lang/unsafe-code-guidelines/issues/102#issuecomment-473340447
454 // - https://doc.rust-lang.org/reference/behavior-considered-undefined.html
455 // - https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html#safety
456 // (This doesn't seem normative yet, but the very same assumption is
457 // made in many places, including the Index implementation of slices.)
459 // - There is no wrapping around involved, as slices do not wrap past
460 // the end of the address space.
462 // See the documentation of pointer::add.
463 let start = self.as_ptr();
464 let end = unsafe { start.add(self.len()) };
468 /// Returns the two unsafe mutable pointers spanning the slice.
470 /// The returned range is half-open, which means that the end pointer
471 /// points *one past* the last element of the slice. This way, an empty
472 /// slice is represented by two equal pointers, and the difference between
473 /// the two pointers represents the size of the slice.
475 /// See [`as_mut_ptr`] for warnings on using these pointers. The end
476 /// pointer requires extra caution, as it does not point to a valid element
479 /// This function is useful for interacting with foreign interfaces which
480 /// use two pointers to refer to a range of elements in memory, as is
483 /// [`as_mut_ptr`]: #method.as_mut_ptr
484 #[unstable(feature = "slice_ptr_range", issue = "65807")]
486 pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> {
487 // See as_ptr_range() above for why `add` here is safe.
488 let start = self.as_mut_ptr();
489 let end = unsafe { start.add(self.len()) };
493 /// Swaps two elements in the slice.
497 /// * a - The index of the first element
498 /// * b - The index of the second element
502 /// Panics if `a` or `b` are out of bounds.
507 /// let mut v = ["a", "b", "c", "d"];
509 /// assert!(v == ["a", "d", "c", "b"]);
511 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn swap(&mut self, a: usize, b: usize) {
515 // Can't take two mutable loans from one vector, so instead just cast
516 // them to their raw pointers to do the swap
517 let pa: *mut T = &mut self[a];
518 let pb: *mut T = &mut self[b];
523 /// Reverses the order of elements in the slice, in place.
528 /// let mut v = [1, 2, 3];
530 /// assert!(v == [3, 2, 1]);
532 #[stable(feature = "rust1", since = "1.0.0")]
534 pub fn reverse(&mut self) {
535 let mut i: usize = 0;
538 // For very small types, all the individual reads in the normal
539 // path perform poorly. We can do better, given efficient unaligned
540 // load/store, by loading a larger chunk and reversing a register.
542 // Ideally LLVM would do this for us, as it knows better than we do
543 // whether unaligned reads are efficient (since that changes between
544 // different ARM versions, for example) and what the best chunk size
545 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
546 // the loop, so we need to do this ourselves. (Hypothesis: reverse
547 // is troublesome because the sides can be aligned differently --
548 // will be, when the length is odd -- so there's no way of emitting
549 // pre- and postludes to use fully-aligned SIMD in the middle.)
551 let fast_unaligned = cfg!(any(target_arch = "x86", target_arch = "x86_64"));
553 if fast_unaligned && mem::size_of::<T>() == 1 {
554 // Use the llvm.bswap intrinsic to reverse u8s in a usize
555 let chunk = mem::size_of::<usize>();
556 while i + chunk - 1 < ln / 2 {
558 let pa: *mut T = self.get_unchecked_mut(i);
559 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
560 let va = ptr::read_unaligned(pa as *mut usize);
561 let vb = ptr::read_unaligned(pb as *mut usize);
562 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
563 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
569 if fast_unaligned && mem::size_of::<T>() == 2 {
570 // Use rotate-by-16 to reverse u16s in a u32
571 let chunk = mem::size_of::<u32>() / 2;
572 while i + chunk - 1 < ln / 2 {
574 let pa: *mut T = self.get_unchecked_mut(i);
575 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
576 let va = ptr::read_unaligned(pa as *mut u32);
577 let vb = ptr::read_unaligned(pb as *mut u32);
578 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
579 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
586 // Unsafe swap to avoid the bounds check in safe swap.
588 let pa: *mut T = self.get_unchecked_mut(i);
589 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
596 /// Returns an iterator over the slice.
601 /// let x = &[1, 2, 4];
602 /// let mut iterator = x.iter();
604 /// assert_eq!(iterator.next(), Some(&1));
605 /// assert_eq!(iterator.next(), Some(&2));
606 /// assert_eq!(iterator.next(), Some(&4));
607 /// assert_eq!(iterator.next(), None);
609 #[stable(feature = "rust1", since = "1.0.0")]
611 pub fn iter(&self) -> Iter<'_, T> {
613 let ptr = self.as_ptr();
614 assume(!ptr.is_null());
616 let end = if mem::size_of::<T>() == 0 {
617 (ptr as *const u8).wrapping_add(self.len()) as *const T
622 Iter { ptr: NonNull::new_unchecked(ptr as *mut T), end, _marker: marker::PhantomData }
626 /// Returns an iterator that allows modifying each value.
631 /// let x = &mut [1, 2, 4];
632 /// for elem in x.iter_mut() {
635 /// assert_eq!(x, &[3, 4, 6]);
637 #[stable(feature = "rust1", since = "1.0.0")]
639 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
641 let ptr = self.as_mut_ptr();
642 assume(!ptr.is_null());
644 let end = if mem::size_of::<T>() == 0 {
645 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
650 IterMut { ptr: NonNull::new_unchecked(ptr), end, _marker: marker::PhantomData }
654 /// Returns an iterator over all contiguous windows of length
655 /// `size`. The windows overlap. If the slice is shorter than
656 /// `size`, the iterator returns no values.
660 /// Panics if `size` is 0.
665 /// let slice = ['r', 'u', 's', 't'];
666 /// let mut iter = slice.windows(2);
667 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
668 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
669 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
670 /// assert!(iter.next().is_none());
673 /// If the slice is shorter than `size`:
676 /// let slice = ['f', 'o', 'o'];
677 /// let mut iter = slice.windows(4);
678 /// assert!(iter.next().is_none());
680 #[stable(feature = "rust1", since = "1.0.0")]
682 pub fn windows(&self, size: usize) -> Windows<'_, T> {
684 Windows { v: self, size }
687 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
688 /// beginning of the slice.
690 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
691 /// slice, then the last chunk will not have length `chunk_size`.
693 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
694 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
699 /// Panics if `chunk_size` is 0.
704 /// let slice = ['l', 'o', 'r', 'e', 'm'];
705 /// let mut iter = slice.chunks(2);
706 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
707 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
708 /// assert_eq!(iter.next().unwrap(), &['m']);
709 /// assert!(iter.next().is_none());
712 /// [`chunks_exact`]: #method.chunks_exact
713 /// [`rchunks`]: #method.rchunks
714 #[stable(feature = "rust1", since = "1.0.0")]
716 pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T> {
717 assert!(chunk_size != 0);
718 Chunks { v: self, chunk_size }
721 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
722 /// beginning of the slice.
724 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
725 /// length of the slice, then the last chunk will not have length `chunk_size`.
727 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
728 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
729 /// the end of the slice.
733 /// Panics if `chunk_size` is 0.
738 /// let v = &mut [0, 0, 0, 0, 0];
739 /// let mut count = 1;
741 /// for chunk in v.chunks_mut(2) {
742 /// for elem in chunk.iter_mut() {
747 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
750 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
751 /// [`rchunks_mut`]: #method.rchunks_mut
752 #[stable(feature = "rust1", since = "1.0.0")]
754 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T> {
755 assert!(chunk_size != 0);
756 ChunksMut { v: self, chunk_size }
759 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
760 /// beginning of the slice.
762 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
763 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
764 /// from the `remainder` function of the iterator.
766 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
767 /// resulting code better than in the case of [`chunks`].
769 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
770 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice.
774 /// Panics if `chunk_size` is 0.
779 /// let slice = ['l', 'o', 'r', 'e', 'm'];
780 /// let mut iter = slice.chunks_exact(2);
781 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
782 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
783 /// assert!(iter.next().is_none());
784 /// assert_eq!(iter.remainder(), &['m']);
787 /// [`chunks`]: #method.chunks
788 /// [`rchunks_exact`]: #method.rchunks_exact
789 #[stable(feature = "chunks_exact", since = "1.31.0")]
791 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T> {
792 assert!(chunk_size != 0);
793 let rem = self.len() % chunk_size;
794 let len = self.len() - rem;
795 let (fst, snd) = self.split_at(len);
796 ChunksExact { v: fst, rem: snd, chunk_size }
799 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
800 /// beginning of the slice.
802 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
803 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
804 /// retrieved from the `into_remainder` function of the iterator.
806 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
807 /// resulting code better than in the case of [`chunks_mut`].
809 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
810 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
815 /// Panics if `chunk_size` is 0.
820 /// let v = &mut [0, 0, 0, 0, 0];
821 /// let mut count = 1;
823 /// for chunk in v.chunks_exact_mut(2) {
824 /// for elem in chunk.iter_mut() {
829 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
832 /// [`chunks_mut`]: #method.chunks_mut
833 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
834 #[stable(feature = "chunks_exact", since = "1.31.0")]
836 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T> {
837 assert!(chunk_size != 0);
838 let rem = self.len() % chunk_size;
839 let len = self.len() - rem;
840 let (fst, snd) = self.split_at_mut(len);
841 ChunksExactMut { v: fst, rem: snd, chunk_size }
844 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
847 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
848 /// slice, then the last chunk will not have length `chunk_size`.
850 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
851 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
856 /// Panics if `chunk_size` is 0.
861 /// let slice = ['l', 'o', 'r', 'e', 'm'];
862 /// let mut iter = slice.rchunks(2);
863 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
864 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
865 /// assert_eq!(iter.next().unwrap(), &['l']);
866 /// assert!(iter.next().is_none());
869 /// [`rchunks_exact`]: #method.rchunks_exact
870 /// [`chunks`]: #method.chunks
871 #[stable(feature = "rchunks", since = "1.31.0")]
873 pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> {
874 assert!(chunk_size != 0);
875 RChunks { v: self, chunk_size }
878 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
881 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
882 /// length of the slice, then the last chunk will not have length `chunk_size`.
884 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
885 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
886 /// beginning of the slice.
890 /// Panics if `chunk_size` is 0.
895 /// let v = &mut [0, 0, 0, 0, 0];
896 /// let mut count = 1;
898 /// for chunk in v.rchunks_mut(2) {
899 /// for elem in chunk.iter_mut() {
904 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
907 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
908 /// [`chunks_mut`]: #method.chunks_mut
909 #[stable(feature = "rchunks", since = "1.31.0")]
911 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T> {
912 assert!(chunk_size != 0);
913 RChunksMut { v: self, chunk_size }
916 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
917 /// end of the slice.
919 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
920 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
921 /// from the `remainder` function of the iterator.
923 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
924 /// resulting code better than in the case of [`chunks`].
926 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
927 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
932 /// Panics if `chunk_size` is 0.
937 /// let slice = ['l', 'o', 'r', 'e', 'm'];
938 /// let mut iter = slice.rchunks_exact(2);
939 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
940 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
941 /// assert!(iter.next().is_none());
942 /// assert_eq!(iter.remainder(), &['l']);
945 /// [`chunks`]: #method.chunks
946 /// [`rchunks`]: #method.rchunks
947 /// [`chunks_exact`]: #method.chunks_exact
948 #[stable(feature = "rchunks", since = "1.31.0")]
950 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T> {
951 assert!(chunk_size != 0);
952 let rem = self.len() % chunk_size;
953 let (fst, snd) = self.split_at(rem);
954 RChunksExact { v: snd, rem: fst, chunk_size }
957 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
960 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
961 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
962 /// retrieved from the `into_remainder` function of the iterator.
964 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
965 /// resulting code better than in the case of [`chunks_mut`].
967 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
968 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
973 /// Panics if `chunk_size` is 0.
978 /// let v = &mut [0, 0, 0, 0, 0];
979 /// let mut count = 1;
981 /// for chunk in v.rchunks_exact_mut(2) {
982 /// for elem in chunk.iter_mut() {
987 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
990 /// [`chunks_mut`]: #method.chunks_mut
991 /// [`rchunks_mut`]: #method.rchunks_mut
992 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
993 #[stable(feature = "rchunks", since = "1.31.0")]
995 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T> {
996 assert!(chunk_size != 0);
997 let rem = self.len() % chunk_size;
998 let (fst, snd) = self.split_at_mut(rem);
999 RChunksExactMut { v: snd, rem: fst, chunk_size }
1002 /// Divides one slice into two at an index.
1004 /// The first will contain all indices from `[0, mid)` (excluding
1005 /// the index `mid` itself) and the second will contain all
1006 /// indices from `[mid, len)` (excluding the index `len` itself).
1010 /// Panics if `mid > len`.
1015 /// let v = [1, 2, 3, 4, 5, 6];
1018 /// let (left, right) = v.split_at(0);
1019 /// assert!(left == []);
1020 /// assert!(right == [1, 2, 3, 4, 5, 6]);
1024 /// let (left, right) = v.split_at(2);
1025 /// assert!(left == [1, 2]);
1026 /// assert!(right == [3, 4, 5, 6]);
1030 /// let (left, right) = v.split_at(6);
1031 /// assert!(left == [1, 2, 3, 4, 5, 6]);
1032 /// assert!(right == []);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1037 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1038 (&self[..mid], &self[mid..])
1041 /// Divides one mutable slice into two at an index.
1043 /// The first will contain all indices from `[0, mid)` (excluding
1044 /// the index `mid` itself) and the second will contain all
1045 /// indices from `[mid, len)` (excluding the index `len` itself).
1049 /// Panics if `mid > len`.
1054 /// let mut v = [1, 0, 3, 0, 5, 6];
1055 /// // scoped to restrict the lifetime of the borrows
1057 /// let (left, right) = v.split_at_mut(2);
1058 /// assert!(left == [1, 0]);
1059 /// assert!(right == [3, 0, 5, 6]);
1063 /// assert!(v == [1, 2, 3, 4, 5, 6]);
1065 #[stable(feature = "rust1", since = "1.0.0")]
1067 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1068 let len = self.len();
1069 let ptr = self.as_mut_ptr();
1072 assert!(mid <= len);
1074 (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid))
1078 /// Returns an iterator over subslices separated by elements that match
1079 /// `pred`. The matched element is not contained in the subslices.
1084 /// let slice = [10, 40, 33, 20];
1085 /// let mut iter = slice.split(|num| num % 3 == 0);
1087 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1088 /// assert_eq!(iter.next().unwrap(), &[20]);
1089 /// assert!(iter.next().is_none());
1092 /// If the first element is matched, an empty slice will be the first item
1093 /// returned by the iterator. Similarly, if the last element in the slice
1094 /// is matched, an empty slice will be the last item returned by the
1098 /// let slice = [10, 40, 33];
1099 /// let mut iter = slice.split(|num| num % 3 == 0);
1101 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1102 /// assert_eq!(iter.next().unwrap(), &[]);
1103 /// assert!(iter.next().is_none());
1106 /// If two matched elements are directly adjacent, an empty slice will be
1107 /// present between them:
1110 /// let slice = [10, 6, 33, 20];
1111 /// let mut iter = slice.split(|num| num % 3 == 0);
1113 /// assert_eq!(iter.next().unwrap(), &[10]);
1114 /// assert_eq!(iter.next().unwrap(), &[]);
1115 /// assert_eq!(iter.next().unwrap(), &[20]);
1116 /// assert!(iter.next().is_none());
1118 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
1122 F: FnMut(&T) -> bool,
1124 Split { v: self, pred, finished: false }
1127 /// Returns an iterator over mutable subslices separated by elements that
1128 /// match `pred`. The matched element is not contained in the subslices.
1133 /// let mut v = [10, 40, 30, 20, 60, 50];
1135 /// for group in v.split_mut(|num| *num % 3 == 0) {
1138 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
1144 F: FnMut(&T) -> bool,
1146 SplitMut { v: self, pred, finished: false }
1149 /// Returns an iterator over subslices separated by elements that match
1150 /// `pred`. The matched element is contained in the end of the previous
1151 /// subslice as a terminator.
1156 /// #![feature(split_inclusive)]
1157 /// let slice = [10, 40, 33, 20];
1158 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1160 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1161 /// assert_eq!(iter.next().unwrap(), &[20]);
1162 /// assert!(iter.next().is_none());
1165 /// If the last element of the slice is matched,
1166 /// that element will be considered the terminator of the preceding slice.
1167 /// That slice will be the last item returned by the iterator.
1170 /// #![feature(split_inclusive)]
1171 /// let slice = [3, 10, 40, 33];
1172 /// let mut iter = slice.split_inclusive(|num| num % 3 == 0);
1174 /// assert_eq!(iter.next().unwrap(), &[3]);
1175 /// assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
1176 /// assert!(iter.next().is_none());
1178 #[unstable(feature = "split_inclusive", issue = "72360")]
1180 pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
1182 F: FnMut(&T) -> bool,
1184 SplitInclusive { v: self, pred, finished: false }
1187 /// Returns an iterator over mutable subslices separated by elements that
1188 /// match `pred`. The matched element is contained in the previous
1189 /// subslice as a terminator.
1194 /// #![feature(split_inclusive)]
1195 /// let mut v = [10, 40, 30, 20, 60, 50];
1197 /// for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
1198 /// let terminator_idx = group.len()-1;
1199 /// group[terminator_idx] = 1;
1201 /// assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1203 #[unstable(feature = "split_inclusive", issue = "72360")]
1205 pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
1207 F: FnMut(&T) -> bool,
1209 SplitInclusiveMut { v: self, pred, finished: false }
1212 /// Returns an iterator over subslices separated by elements that match
1213 /// `pred`, starting at the end of the slice and working backwards.
1214 /// The matched element is not contained in the subslices.
1219 /// let slice = [11, 22, 33, 0, 44, 55];
1220 /// let mut iter = slice.rsplit(|num| *num == 0);
1222 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1223 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1224 /// assert_eq!(iter.next(), None);
1227 /// As with `split()`, if the first or last element is matched, an empty
1228 /// slice will be the first (or last) item returned by the iterator.
1231 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1232 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1233 /// assert_eq!(it.next().unwrap(), &[]);
1234 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1235 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1236 /// assert_eq!(it.next().unwrap(), &[]);
1237 /// assert_eq!(it.next(), None);
1239 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1241 pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
1243 F: FnMut(&T) -> bool,
1245 RSplit { inner: self.split(pred) }
1248 /// Returns an iterator over mutable subslices separated by elements that
1249 /// match `pred`, starting at the end of the slice and working
1250 /// backwards. The matched element is not contained in the subslices.
1255 /// let mut v = [100, 400, 300, 200, 600, 500];
1257 /// let mut count = 0;
1258 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1260 /// group[0] = count;
1262 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1265 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1267 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
1269 F: FnMut(&T) -> bool,
1271 RSplitMut { inner: self.split_mut(pred) }
1274 /// Returns an iterator over subslices separated by elements that match
1275 /// `pred`, limited to returning at most `n` items. The matched element is
1276 /// not contained in the subslices.
1278 /// The last element returned, if any, will contain the remainder of the
1283 /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`,
1284 /// `[20, 60, 50]`):
1287 /// let v = [10, 40, 30, 20, 60, 50];
1289 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1290 /// println!("{:?}", group);
1293 #[stable(feature = "rust1", since = "1.0.0")]
1295 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
1297 F: FnMut(&T) -> bool,
1299 SplitN { inner: GenericSplitN { iter: self.split(pred), count: n } }
1302 /// Returns an iterator over subslices separated by elements that match
1303 /// `pred`, limited to returning at most `n` items. The matched element is
1304 /// not contained in the subslices.
1306 /// The last element returned, if any, will contain the remainder of the
1312 /// let mut v = [10, 40, 30, 20, 60, 50];
1314 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1317 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1319 #[stable(feature = "rust1", since = "1.0.0")]
1321 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
1323 F: FnMut(&T) -> bool,
1325 SplitNMut { inner: GenericSplitN { iter: self.split_mut(pred), count: n } }
1328 /// Returns an iterator over subslices separated by elements that match
1329 /// `pred` limited to returning at most `n` items. This starts at the end of
1330 /// the slice and works backwards. The matched element is not contained in
1333 /// The last element returned, if any, will contain the remainder of the
1338 /// Print the slice split once, starting from the end, by numbers divisible
1339 /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`):
1342 /// let v = [10, 40, 30, 20, 60, 50];
1344 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1345 /// println!("{:?}", group);
1348 #[stable(feature = "rust1", since = "1.0.0")]
1350 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
1352 F: FnMut(&T) -> bool,
1354 RSplitN { inner: GenericSplitN { iter: self.rsplit(pred), count: n } }
1357 /// Returns an iterator over subslices separated by elements that match
1358 /// `pred` limited to returning at most `n` items. This starts at the end of
1359 /// the slice and works backwards. The matched element is not contained in
1362 /// The last element returned, if any, will contain the remainder of the
1368 /// let mut s = [10, 40, 30, 20, 60, 50];
1370 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1373 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1377 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
1379 F: FnMut(&T) -> bool,
1381 RSplitNMut { inner: GenericSplitN { iter: self.rsplit_mut(pred), count: n } }
1384 /// Returns `true` if the slice contains an element with the given value.
1389 /// let v = [10, 40, 30];
1390 /// assert!(v.contains(&30));
1391 /// assert!(!v.contains(&50));
1394 /// If you do not have an `&T`, but just an `&U` such that `T: Borrow<U>`
1395 /// (e.g. `String: Borrow<str>`), you can use `iter().any`:
1398 /// let v = [String::from("hello"), String::from("world")]; // slice of `String`
1399 /// assert!(v.iter().any(|e| e == "hello")); // search with `&str`
1400 /// assert!(!v.iter().any(|e| e == "hi"));
1402 #[stable(feature = "rust1", since = "1.0.0")]
1403 pub fn contains(&self, x: &T) -> bool
1407 x.slice_contains(self)
1410 /// Returns `true` if `needle` is a prefix of the slice.
1415 /// let v = [10, 40, 30];
1416 /// assert!(v.starts_with(&[10]));
1417 /// assert!(v.starts_with(&[10, 40]));
1418 /// assert!(!v.starts_with(&[50]));
1419 /// assert!(!v.starts_with(&[10, 50]));
1422 /// Always returns `true` if `needle` is an empty slice:
1425 /// let v = &[10, 40, 30];
1426 /// assert!(v.starts_with(&[]));
1427 /// let v: &[u8] = &[];
1428 /// assert!(v.starts_with(&[]));
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 pub fn starts_with(&self, needle: &[T]) -> bool
1435 let n = needle.len();
1436 self.len() >= n && needle == &self[..n]
1439 /// Returns `true` if `needle` is a suffix of the slice.
1444 /// let v = [10, 40, 30];
1445 /// assert!(v.ends_with(&[30]));
1446 /// assert!(v.ends_with(&[40, 30]));
1447 /// assert!(!v.ends_with(&[50]));
1448 /// assert!(!v.ends_with(&[50, 30]));
1451 /// Always returns `true` if `needle` is an empty slice:
1454 /// let v = &[10, 40, 30];
1455 /// assert!(v.ends_with(&[]));
1456 /// let v: &[u8] = &[];
1457 /// assert!(v.ends_with(&[]));
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 pub fn ends_with(&self, needle: &[T]) -> bool
1464 let (m, n) = (self.len(), needle.len());
1465 m >= n && needle == &self[m - n..]
1468 /// Returns a subslice with the prefix removed.
1470 /// This method returns [`None`] if slice does not start with `prefix`.
1471 /// Also it returns the original slice if `prefix` is an empty slice.
1476 /// #![feature(slice_strip)]
1477 /// let v = &[10, 40, 30];
1478 /// assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
1479 /// assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
1480 /// assert_eq!(v.strip_prefix(&[50]), None);
1481 /// assert_eq!(v.strip_prefix(&[10, 50]), None);
1483 #[must_use = "returns the subslice without modifying the original"]
1484 #[unstable(feature = "slice_strip", issue = "73413")]
1485 pub fn strip_prefix(&self, prefix: &[T]) -> Option<&[T]>
1489 let n = prefix.len();
1490 if n <= self.len() {
1491 let (head, tail) = self.split_at(n);
1499 /// Returns a subslice with the suffix removed.
1501 /// This method returns [`None`] if slice does not end with `suffix`.
1502 /// Also it returns the original slice if `suffix` is an empty slice
1507 /// #![feature(slice_strip)]
1508 /// let v = &[10, 40, 30];
1509 /// assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
1510 /// assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
1511 /// assert_eq!(v.strip_suffix(&[50]), None);
1512 /// assert_eq!(v.strip_suffix(&[50, 30]), None);
1514 #[must_use = "returns the subslice without modifying the original"]
1515 #[unstable(feature = "slice_strip", issue = "73413")]
1516 pub fn strip_suffix(&self, suffix: &[T]) -> Option<&[T]>
1520 let (len, n) = (self.len(), suffix.len());
1522 let (head, tail) = self.split_at(len - n);
1530 /// Binary searches this sorted slice for a given element.
1532 /// If the value is found then [`Result::Ok`] is returned, containing the
1533 /// index of the matching element. If there are multiple matches, then any
1534 /// one of the matches could be returned. If the value is not found then
1535 /// [`Result::Err`] is returned, containing the index where a matching
1536 /// element could be inserted while maintaining sorted order.
1540 /// Looks up a series of four elements. The first is found, with a
1541 /// uniquely determined position; the second and third are not
1542 /// found; the fourth could match any position in `[1, 4]`.
1545 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1547 /// assert_eq!(s.binary_search(&13), Ok(9));
1548 /// assert_eq!(s.binary_search(&4), Err(7));
1549 /// assert_eq!(s.binary_search(&100), Err(13));
1550 /// let r = s.binary_search(&1);
1551 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1554 /// If you want to insert an item to a sorted vector, while maintaining
1558 /// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1560 /// let idx = s.binary_search(&num).unwrap_or_else(|x| x);
1561 /// s.insert(idx, num);
1562 /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1564 #[stable(feature = "rust1", since = "1.0.0")]
1565 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1569 self.binary_search_by(|p| p.cmp(x))
1572 /// Binary searches this sorted slice with a comparator function.
1574 /// The comparator function should implement an order consistent
1575 /// with the sort order of the underlying slice, returning an
1576 /// order code that indicates whether its argument is `Less`,
1577 /// `Equal` or `Greater` the desired target.
1579 /// If the value is found then [`Result::Ok`] is returned, containing the
1580 /// index of the matching element. If there are multiple matches, then any
1581 /// one of the matches could be returned. If the value is not found then
1582 /// [`Result::Err`] is returned, containing the index where a matching
1583 /// element could be inserted while maintaining sorted order.
1587 /// Looks up a series of four elements. The first is found, with a
1588 /// uniquely determined position; the second and third are not
1589 /// found; the fourth could match any position in `[1, 4]`.
1592 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1595 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1597 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1599 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1601 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1602 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1604 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1608 F: FnMut(&'a T) -> Ordering,
1611 let mut size = s.len();
1615 let mut base = 0usize;
1617 let half = size / 2;
1618 let mid = base + half;
1619 // mid is always in [0, size), that means mid is >= 0 and < size.
1620 // mid >= 0: by definition
1621 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1622 let cmp = f(unsafe { s.get_unchecked(mid) });
1623 base = if cmp == Greater { base } else { mid };
1626 // base is always in [0, size) because base <= mid.
1627 let cmp = f(unsafe { s.get_unchecked(base) });
1628 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1631 /// Binary searches this sorted slice with a key extraction function.
1633 /// Assumes that the slice is sorted by the key, for instance with
1634 /// [`sort_by_key`] using the same key extraction function.
1636 /// If the value is found then [`Result::Ok`] is returned, containing the
1637 /// index of the matching element. If there are multiple matches, then any
1638 /// one of the matches could be returned. If the value is not found then
1639 /// [`Result::Err`] is returned, containing the index where a matching
1640 /// element could be inserted while maintaining sorted order.
1642 /// [`sort_by_key`]: #method.sort_by_key
1646 /// Looks up a series of four elements in a slice of pairs sorted by
1647 /// their second elements. The first is found, with a uniquely
1648 /// determined position; the second and third are not found; the
1649 /// fourth could match any position in `[1, 4]`.
1652 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1653 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1654 /// (1, 21), (2, 34), (4, 55)];
1656 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1657 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1658 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1659 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1660 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1662 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1664 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1666 F: FnMut(&'a T) -> B,
1669 self.binary_search_by(|k| f(k).cmp(b))
1672 /// Sorts the slice, but may not preserve the order of equal elements.
1674 /// This sort is unstable (i.e., may reorder equal elements), in-place
1675 /// (i.e., does not allocate), and `O(n * log(n))` worst-case.
1677 /// # Current implementation
1679 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1680 /// which combines the fast average case of randomized quicksort with the fast worst case of
1681 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1682 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1683 /// deterministic behavior.
1685 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1686 /// slice consists of several concatenated sorted sequences.
1691 /// let mut v = [-5, 4, 1, -3, 2];
1693 /// v.sort_unstable();
1694 /// assert!(v == [-5, -3, 1, 2, 4]);
1697 /// [pdqsort]: https://github.com/orlp/pdqsort
1698 #[stable(feature = "sort_unstable", since = "1.20.0")]
1700 pub fn sort_unstable(&mut self)
1704 sort::quicksort(self, |a, b| a.lt(b));
1707 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1710 /// This sort is unstable (i.e., may reorder equal elements), in-place
1711 /// (i.e., does not allocate), and `O(n * log(n))` worst-case.
1713 /// The comparator function must define a total ordering for the elements in the slice. If
1714 /// the ordering is not total, the order of the elements is unspecified. An order is a
1715 /// total order if it is (for all a, b and c):
1717 /// * total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
1718 /// * transitive, a < b and b < c implies a < c. The same must hold for both == and >.
1720 /// For example, while [`f64`] doesn't implement [`Ord`] because `NaN != NaN`, we can use
1721 /// `partial_cmp` as our sort function when we know the slice doesn't contain a `NaN`.
1724 /// let mut floats = [5f64, 4.0, 1.0, 3.0, 2.0];
1725 /// floats.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap());
1726 /// assert_eq!(floats, [1.0, 2.0, 3.0, 4.0, 5.0]);
1729 /// # Current implementation
1731 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1732 /// which combines the fast average case of randomized quicksort with the fast worst case of
1733 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1734 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1735 /// deterministic behavior.
1737 /// It is typically faster than stable sorting, except in a few special cases, e.g., when the
1738 /// slice consists of several concatenated sorted sequences.
1743 /// let mut v = [5, 4, 1, 3, 2];
1744 /// v.sort_unstable_by(|a, b| a.cmp(b));
1745 /// assert!(v == [1, 2, 3, 4, 5]);
1747 /// // reverse sorting
1748 /// v.sort_unstable_by(|a, b| b.cmp(a));
1749 /// assert!(v == [5, 4, 3, 2, 1]);
1752 /// [pdqsort]: https://github.com/orlp/pdqsort
1753 #[stable(feature = "sort_unstable", since = "1.20.0")]
1755 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1757 F: FnMut(&T, &T) -> Ordering,
1759 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1762 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1765 /// This sort is unstable (i.e., may reorder equal elements), in-place
1766 /// (i.e., does not allocate), and `O(m * n * log(n))` worst-case, where the key function is
1769 /// # Current implementation
1771 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1772 /// which combines the fast average case of randomized quicksort with the fast worst case of
1773 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1774 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1775 /// deterministic behavior.
1777 /// Due to its key calling strategy, [`sort_unstable_by_key`](#method.sort_unstable_by_key)
1778 /// is likely to be slower than [`sort_by_cached_key`](#method.sort_by_cached_key) in
1779 /// cases where the key function is expensive.
1784 /// let mut v = [-5i32, 4, 1, -3, 2];
1786 /// v.sort_unstable_by_key(|k| k.abs());
1787 /// assert!(v == [1, 2, -3, 4, -5]);
1790 /// [pdqsort]: https://github.com/orlp/pdqsort
1791 #[stable(feature = "sort_unstable", since = "1.20.0")]
1793 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1798 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1801 /// Reorder the slice such that the element at `index` is at its final sorted position.
1803 /// This reordering has the additional property that any value at position `i < index` will be
1804 /// less than or equal to any value at a position `j > index`. Additionally, this reordering is
1805 /// unstable (i.e. any number of equal elements may end up at position `index`), in-place
1806 /// (i.e. does not allocate), and `O(n)` worst-case. This function is also/ known as "kth
1807 /// element" in other libraries. It returns a triplet of the following values: all elements less
1808 /// than the one at the given index, the value at the given index, and all elements greater than
1809 /// the one at the given index.
1811 /// # Current implementation
1813 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1814 /// used for [`sort_unstable`].
1816 /// [`sort_unstable`]: #method.sort_unstable
1820 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1825 /// #![feature(slice_partition_at_index)]
1827 /// let mut v = [-5i32, 4, 1, -3, 2];
1829 /// // Find the median
1830 /// v.partition_at_index(2);
1832 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1833 /// // about the specified index.
1834 /// assert!(v == [-3, -5, 1, 2, 4] ||
1835 /// v == [-5, -3, 1, 2, 4] ||
1836 /// v == [-3, -5, 1, 4, 2] ||
1837 /// v == [-5, -3, 1, 4, 2]);
1839 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1841 pub fn partition_at_index(&mut self, index: usize) -> (&mut [T], &mut T, &mut [T])
1845 let mut f = |a: &T, b: &T| a.lt(b);
1846 sort::partition_at_index(self, index, &mut f)
1849 /// Reorder the slice with a comparator function such that the element at `index` is at its
1850 /// final sorted position.
1852 /// This reordering has the additional property that any value at position `i < index` will be
1853 /// less than or equal to any value at a position `j > index` using the comparator function.
1854 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1855 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1856 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1857 /// values: all elements less than the one at the given index, the value at the given index,
1858 /// and all elements greater than the one at the given index, using the provided comparator
1861 /// # Current implementation
1863 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1864 /// used for [`sort_unstable`].
1866 /// [`sort_unstable`]: #method.sort_unstable
1870 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1875 /// #![feature(slice_partition_at_index)]
1877 /// let mut v = [-5i32, 4, 1, -3, 2];
1879 /// // Find the median as if the slice were sorted in descending order.
1880 /// v.partition_at_index_by(2, |a, b| b.cmp(a));
1882 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1883 /// // about the specified index.
1884 /// assert!(v == [2, 4, 1, -5, -3] ||
1885 /// v == [2, 4, 1, -3, -5] ||
1886 /// v == [4, 2, 1, -5, -3] ||
1887 /// v == [4, 2, 1, -3, -5]);
1889 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1891 pub fn partition_at_index_by<F>(
1895 ) -> (&mut [T], &mut T, &mut [T])
1897 F: FnMut(&T, &T) -> Ordering,
1899 let mut f = |a: &T, b: &T| compare(a, b) == Less;
1900 sort::partition_at_index(self, index, &mut f)
1903 /// Reorder the slice with a key extraction function such that the element at `index` is at its
1904 /// final sorted position.
1906 /// This reordering has the additional property that any value at position `i < index` will be
1907 /// less than or equal to any value at a position `j > index` using the key extraction function.
1908 /// Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
1909 /// position `index`), in-place (i.e. does not allocate), and `O(n)` worst-case. This function
1910 /// is also known as "kth element" in other libraries. It returns a triplet of the following
1911 /// values: all elements less than the one at the given index, the value at the given index, and
1912 /// all elements greater than the one at the given index, using the provided key extraction
1915 /// # Current implementation
1917 /// The current algorithm is based on the quickselect portion of the same quicksort algorithm
1918 /// used for [`sort_unstable`].
1920 /// [`sort_unstable`]: #method.sort_unstable
1924 /// Panics when `index >= len()`, meaning it always panics on empty slices.
1929 /// #![feature(slice_partition_at_index)]
1931 /// let mut v = [-5i32, 4, 1, -3, 2];
1933 /// // Return the median as if the array were sorted according to absolute value.
1934 /// v.partition_at_index_by_key(2, |a| a.abs());
1936 /// // We are only guaranteed the slice will be one of the following, based on the way we sort
1937 /// // about the specified index.
1938 /// assert!(v == [1, 2, -3, 4, -5] ||
1939 /// v == [1, 2, -3, -5, 4] ||
1940 /// v == [2, 1, -3, 4, -5] ||
1941 /// v == [2, 1, -3, -5, 4]);
1943 #[unstable(feature = "slice_partition_at_index", issue = "55300")]
1945 pub fn partition_at_index_by_key<K, F>(
1949 ) -> (&mut [T], &mut T, &mut [T])
1954 let mut g = |a: &T, b: &T| f(a).lt(&f(b));
1955 sort::partition_at_index(self, index, &mut g)
1958 /// Moves all consecutive repeated elements to the end of the slice according to the
1959 /// [`PartialEq`] trait implementation.
1961 /// Returns two slices. The first contains no consecutive repeated elements.
1962 /// The second contains all the duplicates in no specified order.
1964 /// If the slice is sorted, the first returned slice contains no duplicates.
1969 /// #![feature(slice_partition_dedup)]
1971 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1973 /// let (dedup, duplicates) = slice.partition_dedup();
1975 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1976 /// assert_eq!(duplicates, [2, 3, 1]);
1978 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1980 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1984 self.partition_dedup_by(|a, b| a == b)
1987 /// Moves all but the first of consecutive elements to the end of the slice satisfying
1988 /// a given equality relation.
1990 /// Returns two slices. The first contains no consecutive repeated elements.
1991 /// The second contains all the duplicates in no specified order.
1993 /// The `same_bucket` function is passed references to two elements from the slice and
1994 /// must determine if the elements compare equal. The elements are passed in opposite order
1995 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1996 /// at the end of the slice.
1998 /// If the slice is sorted, the first returned slice contains no duplicates.
2003 /// #![feature(slice_partition_dedup)]
2005 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
2007 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2009 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
2010 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
2012 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2014 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
2016 F: FnMut(&mut T, &mut T) -> bool,
2018 // Although we have a mutable reference to `self`, we cannot make
2019 // *arbitrary* changes. The `same_bucket` calls could panic, so we
2020 // must ensure that the slice is in a valid state at all times.
2022 // The way that we handle this is by using swaps; we iterate
2023 // over all the elements, swapping as we go so that at the end
2024 // the elements we wish to keep are in the front, and those we
2025 // wish to reject are at the back. We can then split the slice.
2026 // This operation is still `O(n)`.
2028 // Example: We start in this state, where `r` represents "next
2029 // read" and `w` represents "next_write`.
2032 // +---+---+---+---+---+---+
2033 // | 0 | 1 | 1 | 2 | 3 | 3 |
2034 // +---+---+---+---+---+---+
2037 // Comparing self[r] against self[w-1], this is not a duplicate, so
2038 // we swap self[r] and self[w] (no effect as r==w) and then increment both
2039 // r and w, leaving us with:
2042 // +---+---+---+---+---+---+
2043 // | 0 | 1 | 1 | 2 | 3 | 3 |
2044 // +---+---+---+---+---+---+
2047 // Comparing self[r] against self[w-1], this value is a duplicate,
2048 // so we increment `r` but leave everything else unchanged:
2051 // +---+---+---+---+---+---+
2052 // | 0 | 1 | 1 | 2 | 3 | 3 |
2053 // +---+---+---+---+---+---+
2056 // Comparing self[r] against self[w-1], this is not a duplicate,
2057 // so swap self[r] and self[w] and advance r and w:
2060 // +---+---+---+---+---+---+
2061 // | 0 | 1 | 2 | 1 | 3 | 3 |
2062 // +---+---+---+---+---+---+
2065 // Not a duplicate, repeat:
2068 // +---+---+---+---+---+---+
2069 // | 0 | 1 | 2 | 3 | 1 | 3 |
2070 // +---+---+---+---+---+---+
2073 // Duplicate, advance r. End of slice. Split at w.
2075 let len = self.len();
2077 return (self, &mut []);
2080 let ptr = self.as_mut_ptr();
2081 let mut next_read: usize = 1;
2082 let mut next_write: usize = 1;
2085 // Avoid bounds checks by using raw pointers.
2086 while next_read < len {
2087 let ptr_read = ptr.add(next_read);
2088 let prev_ptr_write = ptr.add(next_write - 1);
2089 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
2090 if next_read != next_write {
2091 let ptr_write = prev_ptr_write.offset(1);
2092 mem::swap(&mut *ptr_read, &mut *ptr_write);
2100 self.split_at_mut(next_write)
2103 /// Moves all but the first of consecutive elements to the end of the slice that resolve
2104 /// to the same key.
2106 /// Returns two slices. The first contains no consecutive repeated elements.
2107 /// The second contains all the duplicates in no specified order.
2109 /// If the slice is sorted, the first returned slice contains no duplicates.
2114 /// #![feature(slice_partition_dedup)]
2116 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
2118 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
2120 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
2121 /// assert_eq!(duplicates, [21, 30, 13]);
2123 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
2125 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
2127 F: FnMut(&mut T) -> K,
2130 self.partition_dedup_by(|a, b| key(a) == key(b))
2133 /// Rotates the slice in-place such that the first `mid` elements of the
2134 /// slice move to the end while the last `self.len() - mid` elements move to
2135 /// the front. After calling `rotate_left`, the element previously at index
2136 /// `mid` will become the first element in the slice.
2140 /// This function will panic if `mid` is greater than the length of the
2141 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
2146 /// Takes linear (in `self.len()`) time.
2151 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2152 /// a.rotate_left(2);
2153 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
2156 /// Rotating a subslice:
2159 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2160 /// a[1..5].rotate_left(1);
2161 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
2163 #[stable(feature = "slice_rotate", since = "1.26.0")]
2164 pub fn rotate_left(&mut self, mid: usize) {
2165 assert!(mid <= self.len());
2166 let k = self.len() - mid;
2169 let p = self.as_mut_ptr();
2170 rotate::ptr_rotate(mid, p.add(mid), k);
2174 /// Rotates the slice in-place such that the first `self.len() - k`
2175 /// elements of the slice move to the end while the last `k` elements move
2176 /// to the front. After calling `rotate_right`, the element previously at
2177 /// index `self.len() - k` will become the first element in the slice.
2181 /// This function will panic if `k` is greater than the length of the
2182 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
2187 /// Takes linear (in `self.len()`) time.
2192 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2193 /// a.rotate_right(2);
2194 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
2197 /// Rotate a subslice:
2200 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
2201 /// a[1..5].rotate_right(1);
2202 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
2204 #[stable(feature = "slice_rotate", since = "1.26.0")]
2205 pub fn rotate_right(&mut self, k: usize) {
2206 assert!(k <= self.len());
2207 let mid = self.len() - k;
2210 let p = self.as_mut_ptr();
2211 rotate::ptr_rotate(mid, p.add(mid), k);
2215 /// Fills `self` with elements by cloning `value`.
2220 /// #![feature(slice_fill)]
2222 /// let mut buf = vec![0; 10];
2224 /// assert_eq!(buf, vec![1; 10]);
2226 #[unstable(feature = "slice_fill", issue = "70758")]
2227 pub fn fill(&mut self, value: T)
2231 if let Some((last, elems)) = self.split_last_mut() {
2233 el.clone_from(&value);
2240 /// Copies the elements from `src` into `self`.
2242 /// The length of `src` must be the same as `self`.
2244 /// If `T` implements `Copy`, it can be more performant to use
2245 /// [`copy_from_slice`].
2249 /// This function will panic if the two slices have different lengths.
2253 /// Cloning two elements from a slice into another:
2256 /// let src = [1, 2, 3, 4];
2257 /// let mut dst = [0, 0];
2259 /// // Because the slices have to be the same length,
2260 /// // we slice the source slice from four elements
2261 /// // to two. It will panic if we don't do this.
2262 /// dst.clone_from_slice(&src[2..]);
2264 /// assert_eq!(src, [1, 2, 3, 4]);
2265 /// assert_eq!(dst, [3, 4]);
2268 /// Rust enforces that there can only be one mutable reference with no
2269 /// immutable references to a particular piece of data in a particular
2270 /// scope. Because of this, attempting to use `clone_from_slice` on a
2271 /// single slice will result in a compile failure:
2274 /// let mut slice = [1, 2, 3, 4, 5];
2276 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2279 /// To work around this, we can use [`split_at_mut`] to create two distinct
2280 /// sub-slices from a slice:
2283 /// let mut slice = [1, 2, 3, 4, 5];
2286 /// let (left, right) = slice.split_at_mut(2);
2287 /// left.clone_from_slice(&right[1..]);
2290 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2293 /// [`copy_from_slice`]: #method.copy_from_slice
2294 /// [`split_at_mut`]: #method.split_at_mut
2295 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2296 pub fn clone_from_slice(&mut self, src: &[T])
2300 assert!(self.len() == src.len(), "destination and source slices have different lengths");
2301 // NOTE: We need to explicitly slice them to the same length
2302 // for bounds checking to be elided, and the optimizer will
2303 // generate memcpy for simple cases (for example T = u8).
2304 let len = self.len();
2305 let src = &src[..len];
2307 self[i].clone_from(&src[i]);
2311 /// Copies all elements from `src` into `self`, using a memcpy.
2313 /// The length of `src` must be the same as `self`.
2315 /// If `T` does not implement `Copy`, use [`clone_from_slice`].
2319 /// This function will panic if the two slices have different lengths.
2323 /// Copying two elements from a slice into another:
2326 /// let src = [1, 2, 3, 4];
2327 /// let mut dst = [0, 0];
2329 /// // Because the slices have to be the same length,
2330 /// // we slice the source slice from four elements
2331 /// // to two. It will panic if we don't do this.
2332 /// dst.copy_from_slice(&src[2..]);
2334 /// assert_eq!(src, [1, 2, 3, 4]);
2335 /// assert_eq!(dst, [3, 4]);
2338 /// Rust enforces that there can only be one mutable reference with no
2339 /// immutable references to a particular piece of data in a particular
2340 /// scope. Because of this, attempting to use `copy_from_slice` on a
2341 /// single slice will result in a compile failure:
2344 /// let mut slice = [1, 2, 3, 4, 5];
2346 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2349 /// To work around this, we can use [`split_at_mut`] to create two distinct
2350 /// sub-slices from a slice:
2353 /// let mut slice = [1, 2, 3, 4, 5];
2356 /// let (left, right) = slice.split_at_mut(2);
2357 /// left.copy_from_slice(&right[1..]);
2360 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2363 /// [`clone_from_slice`]: #method.clone_from_slice
2364 /// [`split_at_mut`]: #method.split_at_mut
2365 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2366 pub fn copy_from_slice(&mut self, src: &[T])
2370 assert_eq!(self.len(), src.len(), "destination and source slices have different lengths");
2372 ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len());
2376 /// Copies elements from one part of the slice to another part of itself,
2377 /// using a memmove.
2379 /// `src` is the range within `self` to copy from. `dest` is the starting
2380 /// index of the range within `self` to copy to, which will have the same
2381 /// length as `src`. The two ranges may overlap. The ends of the two ranges
2382 /// must be less than or equal to `self.len()`.
2386 /// This function will panic if either range exceeds the end of the slice,
2387 /// or if the end of `src` is before the start.
2391 /// Copying four bytes within a slice:
2394 /// let mut bytes = *b"Hello, World!";
2396 /// bytes.copy_within(1..5, 8);
2398 /// assert_eq!(&bytes, b"Hello, Wello!");
2400 #[stable(feature = "copy_within", since = "1.37.0")]
2402 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
2406 let src_start = match src.start_bound() {
2407 ops::Bound::Included(&n) => n,
2408 ops::Bound::Excluded(&n) => {
2409 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2411 ops::Bound::Unbounded => 0,
2413 let src_end = match src.end_bound() {
2414 ops::Bound::Included(&n) => {
2415 n.checked_add(1).unwrap_or_else(|| slice_index_overflow_fail())
2417 ops::Bound::Excluded(&n) => n,
2418 ops::Bound::Unbounded => self.len(),
2420 assert!(src_start <= src_end, "src end is before src start");
2421 assert!(src_end <= self.len(), "src is out of bounds");
2422 let count = src_end - src_start;
2423 assert!(dest <= self.len() - count, "dest is out of bounds");
2425 ptr::copy(self.as_ptr().add(src_start), self.as_mut_ptr().add(dest), count);
2429 /// Swaps all elements in `self` with those in `other`.
2431 /// The length of `other` must be the same as `self`.
2435 /// This function will panic if the two slices have different lengths.
2439 /// Swapping two elements across slices:
2442 /// let mut slice1 = [0, 0];
2443 /// let mut slice2 = [1, 2, 3, 4];
2445 /// slice1.swap_with_slice(&mut slice2[2..]);
2447 /// assert_eq!(slice1, [3, 4]);
2448 /// assert_eq!(slice2, [1, 2, 0, 0]);
2451 /// Rust enforces that there can only be one mutable reference to a
2452 /// particular piece of data in a particular scope. Because of this,
2453 /// attempting to use `swap_with_slice` on a single slice will result in
2454 /// a compile failure:
2457 /// let mut slice = [1, 2, 3, 4, 5];
2458 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2461 /// To work around this, we can use [`split_at_mut`] to create two distinct
2462 /// mutable sub-slices from a slice:
2465 /// let mut slice = [1, 2, 3, 4, 5];
2468 /// let (left, right) = slice.split_at_mut(2);
2469 /// left.swap_with_slice(&mut right[1..]);
2472 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2475 /// [`split_at_mut`]: #method.split_at_mut
2476 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2477 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2478 assert!(self.len() == other.len(), "destination and source slices have different lengths");
2480 ptr::swap_nonoverlapping(self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2484 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2485 fn align_to_offsets<U>(&self) -> (usize, usize) {
2486 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2487 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2489 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2490 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2491 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2493 // Formula to calculate this is:
2495 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2496 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2498 // Expanded and simplified:
2500 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2501 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2503 // Luckily since all this is constant-evaluated... performance here matters not!
2505 fn gcd(a: usize, b: usize) -> usize {
2506 use crate::intrinsics;
2507 // iterative stein’s algorithm
2508 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2509 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2510 let (ctz_a, mut ctz_b) = unsafe {
2517 (intrinsics::cttz_nonzero(a), intrinsics::cttz_nonzero(b))
2519 let k = ctz_a.min(ctz_b);
2520 let mut a = a >> ctz_a;
2523 // remove all factors of 2 from b
2526 mem::swap(&mut a, &mut b);
2533 ctz_b = intrinsics::cttz_nonzero(b);
2538 let gcd: usize = gcd(mem::size_of::<T>(), mem::size_of::<U>());
2539 let ts: usize = mem::size_of::<U>() / gcd;
2540 let us: usize = mem::size_of::<T>() / gcd;
2542 // Armed with this knowledge, we can find how many `U`s we can fit!
2543 let us_len = self.len() / ts * us;
2544 // And how many `T`s will be in the trailing slice!
2545 let ts_len = self.len() % ts;
2549 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2552 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2553 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2554 /// length possible for a given type and input slice, but only your algorithm's performance
2555 /// should depend on that, not its correctness. It is permissible for all of the input data to
2556 /// be returned as the prefix or suffix slice.
2558 /// This method has no purpose when either input element `T` or output element `U` are
2559 /// zero-sized and will return the original slice without splitting anything.
2563 /// This method is essentially a `transmute` with respect to the elements in the returned
2564 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2572 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2573 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2574 /// // less_efficient_algorithm_for_bytes(prefix);
2575 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2576 /// // less_efficient_algorithm_for_bytes(suffix);
2579 #[stable(feature = "slice_align_to", since = "1.30.0")]
2580 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2581 // Note that most of this function will be constant-evaluated,
2582 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2583 // handle ZSTs specially, which is – don't handle them at all.
2584 return (self, &[], &[]);
2587 // First, find at what point do we split between the first and 2nd slice. Easy with
2588 // ptr.align_offset.
2589 let ptr = self.as_ptr();
2590 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2591 if offset > self.len() {
2594 let (left, rest) = self.split_at(offset);
2595 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2596 // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay,
2597 // since the caller guarantees that we can transmute `T` to `U` safely.
2601 from_raw_parts(rest.as_ptr() as *const U, us_len),
2602 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len),
2608 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2611 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2612 /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest
2613 /// length possible for a given type and input slice, but only your algorithm's performance
2614 /// should depend on that, not its correctness. It is permissible for all of the input data to
2615 /// be returned as the prefix or suffix slice.
2617 /// This method has no purpose when either input element `T` or output element `U` are
2618 /// zero-sized and will return the original slice without splitting anything.
2622 /// This method is essentially a `transmute` with respect to the elements in the returned
2623 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2631 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2632 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2633 /// // less_efficient_algorithm_for_bytes(prefix);
2634 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2635 /// // less_efficient_algorithm_for_bytes(suffix);
2638 #[stable(feature = "slice_align_to", since = "1.30.0")]
2639 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2640 // Note that most of this function will be constant-evaluated,
2641 if mem::size_of::<U>() == 0 || mem::size_of::<T>() == 0 {
2642 // handle ZSTs specially, which is – don't handle them at all.
2643 return (self, &mut [], &mut []);
2646 // First, find at what point do we split between the first and 2nd slice. Easy with
2647 // ptr.align_offset.
2648 let ptr = self.as_ptr();
2649 let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::<U>()) };
2650 if offset > self.len() {
2651 (self, &mut [], &mut [])
2653 let (left, rest) = self.split_at_mut(offset);
2654 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2655 let rest_len = rest.len();
2656 let mut_ptr = rest.as_mut_ptr();
2657 // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`!
2658 // SAFETY: see comments for `align_to`.
2662 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2663 from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len),
2669 /// Checks if the elements of this slice are sorted.
2671 /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the
2672 /// slice yields exactly zero or one element, `true` is returned.
2674 /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition
2675 /// implies that this function returns `false` if any two consecutive items are not
2681 /// #![feature(is_sorted)]
2682 /// let empty: [i32; 0] = [];
2684 /// assert!([1, 2, 2, 9].is_sorted());
2685 /// assert!(![1, 3, 2, 4].is_sorted());
2686 /// assert!([0].is_sorted());
2687 /// assert!(empty.is_sorted());
2688 /// assert!(![0.0, 1.0, f32::NAN].is_sorted());
2691 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2692 pub fn is_sorted(&self) -> bool
2696 self.is_sorted_by(|a, b| a.partial_cmp(b))
2699 /// Checks if the elements of this slice are sorted using the given comparator function.
2701 /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare`
2702 /// function to determine the ordering of two elements. Apart from that, it's equivalent to
2703 /// [`is_sorted`]; see its documentation for more information.
2705 /// [`is_sorted`]: #method.is_sorted
2706 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2707 pub fn is_sorted_by<F>(&self, mut compare: F) -> bool
2709 F: FnMut(&T, &T) -> Option<Ordering>,
2711 self.iter().is_sorted_by(|a, b| compare(*a, *b))
2714 /// Checks if the elements of this slice are sorted using the given key extraction function.
2716 /// Instead of comparing the slice's elements directly, this function compares the keys of the
2717 /// elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see its
2718 /// documentation for more information.
2720 /// [`is_sorted`]: #method.is_sorted
2725 /// #![feature(is_sorted)]
2727 /// assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
2728 /// assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
2731 #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")]
2732 pub fn is_sorted_by_key<F, K>(&self, f: F) -> bool
2737 self.iter().is_sorted_by_key(f)
2740 /// Returns the index of the partition point according to the given predicate
2741 /// (the index of the first element of the second partition).
2743 /// The slice is assumed to be partitioned according to the given predicate.
2744 /// This means that all elements for which the predicate returns true are at the start of the slice
2745 /// and all elements for which the predicate returns false are at the end.
2746 /// For example, [7, 15, 3, 5, 4, 12, 6] is a partitioned under the predicate x % 2 != 0
2747 /// (all odd numbers are at the start, all even at the end).
2749 /// If this slice is not partitioned, the returned result is unspecified and meaningless,
2750 /// as this method performs a kind of binary search.
2755 /// #![feature(partition_point)]
2757 /// let v = [1, 2, 3, 3, 5, 6, 7];
2758 /// let i = v.partition_point(|&x| x < 5);
2760 /// assert_eq!(i, 4);
2761 /// assert!(v[..i].iter().all(|&x| x < 5));
2762 /// assert!(v[i..].iter().all(|&x| !(x < 5)));
2764 #[unstable(feature = "partition_point", reason = "new API", issue = "73831")]
2765 pub fn partition_point<P>(&self, mut pred: P) -> usize
2767 P: FnMut(&T) -> bool,
2770 let mut right = self.len();
2772 while left != right {
2773 let mid = left + (right - left) / 2;
2775 // When left < right, left <= mid < right.
2776 // Therefore left always increases and right always decreases,
2777 // and eigher of them is selected.
2778 // In both cases left <= right is satisfied.
2779 // Therefore if left < right in a step,
2780 // left <= right is satisfied in the next step.
2781 // Therefore as long as left != right, 0 <= left < right <= len is satisfied
2782 // and if this case 0 <= mid < len is satisfied too.
2783 let value = unsafe { self.get_unchecked(mid) };
2795 #[lang = "slice_u8"]
2798 /// Checks if all bytes in this slice are within the ASCII range.
2799 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2801 pub fn is_ascii(&self) -> bool {
2805 /// Checks that two slices are an ASCII case-insensitive match.
2807 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2808 /// but without allocating and copying temporaries.
2809 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2811 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2812 self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq_ignore_ascii_case(b))
2815 /// Converts this slice to its ASCII upper case equivalent in-place.
2817 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2818 /// but non-ASCII letters are unchanged.
2820 /// To return a new uppercased value without modifying the existing one, use
2821 /// [`to_ascii_uppercase`].
2823 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2824 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2826 pub fn make_ascii_uppercase(&mut self) {
2828 byte.make_ascii_uppercase();
2832 /// Converts this slice to its ASCII lower case equivalent in-place.
2834 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2835 /// but non-ASCII letters are unchanged.
2837 /// To return a new lowercased value without modifying the existing one, use
2838 /// [`to_ascii_lowercase`].
2840 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2841 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2843 pub fn make_ascii_lowercase(&mut self) {
2845 byte.make_ascii_lowercase();
2850 /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
2851 /// from `../str/mod.rs`, which does something similar for utf8 validation.
2853 fn contains_nonascii(v: usize) -> bool {
2854 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
2855 (NONASCII_MASK & v) != 0
2858 /// Optimized ASCII test that will use usize-at-a-time operations instead of
2859 /// byte-at-a-time operations (when possible).
2861 /// The algorithm we use here is pretty simple. If `s` is too short, we just
2862 /// check each byte and be done with it. Otherwise:
2864 /// - Read the first word with an unaligned load.
2865 /// - Align the pointer, read subsequent words until end with aligned loads.
2866 /// - If there's a tail, the last `usize` from `s` with an unaligned load.
2868 /// If any of these loads produces something for which `contains_nonascii`
2869 /// (above) returns true, then we know the answer is false.
2871 fn is_ascii(s: &[u8]) -> bool {
2872 const USIZE_SIZE: usize = mem::size_of::<usize>();
2875 let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
2877 // If we wouldn't gain anything from the word-at-a-time implementation, fall
2878 // back to a scalar loop.
2880 // We also do this for architectures where `size_of::<usize>()` isn't
2881 // sufficient alignment for `usize`, because it's a weird edge case.
2882 if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
2883 return s.iter().all(|b| b.is_ascii());
2886 // We always read the first word unaligned, which means `align_offset` is
2887 // 0, we'd read the same value again for the aligned read.
2888 let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
2890 let start = s.as_ptr();
2891 // SAFETY: We verify `len < USIZE_SIZE` above.
2892 let first_word = unsafe { (start as *const usize).read_unaligned() };
2894 if contains_nonascii(first_word) {
2897 // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
2898 // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
2900 debug_assert!(offset_to_aligned <= len);
2902 // word_ptr is the (properly aligned) usize ptr we use to read the middle chunk of the slice.
2903 let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
2905 // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
2906 let mut byte_pos = offset_to_aligned;
2908 // Paranoia check about alignment, since we're about to do a bunch of
2909 // unaligned loads. In practice this should be impossible barring a bug in
2910 // `align_offset` though.
2911 debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
2913 while byte_pos <= len - USIZE_SIZE {
2915 // Sanity check that the read is in bounds
2916 (word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
2917 // And that our assumptions about `byte_pos` hold.
2918 (word_ptr as usize) - (start as usize) == byte_pos
2921 // Safety: We know `word_ptr` is properly aligned (because of
2922 // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
2923 let word = unsafe { word_ptr.read() };
2924 if contains_nonascii(word) {
2928 byte_pos += USIZE_SIZE;
2929 // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
2930 // after this `add`, `word_ptr` will be at most one-past-the-end.
2931 word_ptr = unsafe { word_ptr.add(1) };
2934 // If we have anything left over, it should be at-most 1 usize worth of bytes,
2935 // which we check with a read_unaligned.
2936 if byte_pos == len {
2940 // Sanity check to ensure there really is only one `usize` left. This should
2941 // be guaranteed by our loop condition.
2942 debug_assert!(byte_pos < len && len - byte_pos < USIZE_SIZE);
2944 // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
2945 let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
2947 !contains_nonascii(last_word)
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 impl<T, I> ops::Index<I> for [T]
2955 type Output = I::Output;
2958 fn index(&self, index: I) -> &I::Output {
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 impl<T, I> ops::IndexMut<I> for [T]
2969 fn index_mut(&mut self, index: I) -> &mut I::Output {
2970 index.index_mut(self)
2977 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2978 panic!("index {} out of range for slice of length {}", index, len);
2984 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2985 panic!("slice index starts at {} but ends at {}", index, end);
2991 fn slice_index_overflow_fail() -> ! {
2992 panic!("attempted to index slice up to maximum usize");
2995 mod private_slice_index {
2997 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3000 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3001 impl Sealed for usize {}
3002 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3003 impl Sealed for ops::Range<usize> {}
3004 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3005 impl Sealed for ops::RangeTo<usize> {}
3006 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3007 impl Sealed for ops::RangeFrom<usize> {}
3008 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3009 impl Sealed for ops::RangeFull {}
3010 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3011 impl Sealed for ops::RangeInclusive<usize> {}
3012 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3013 impl Sealed for ops::RangeToInclusive<usize> {}
3016 /// A helper trait used for indexing operations.
3018 /// Implementations of this trait have to promise that if the argument
3019 /// to `get_(mut_)unchecked` is a safe reference, then so is the result.
3020 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3021 #[rustc_on_unimplemented(
3022 on(T = "str", label = "string indices are ranges of `usize`",),
3024 all(any(T = "str", T = "&str", T = "std::string::String"), _Self = "{integer}"),
3025 note = "you can use `.chars().nth()` or `.bytes().nth()`
3026 see chapter in The Book <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>"
3028 message = "the type `{T}` cannot be indexed by `{Self}`",
3029 label = "slice indices are of type `usize` or ranges of `usize`"
3031 pub unsafe trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
3032 /// The output type returned by methods.
3033 #[stable(feature = "slice_get_slice", since = "1.28.0")]
3034 type Output: ?Sized;
3036 /// Returns a shared reference to the output at this location, if in
3038 #[unstable(feature = "slice_index_methods", issue = "none")]
3039 fn get(self, slice: &T) -> Option<&Self::Output>;
3041 /// Returns a mutable reference to the output at this location, if in
3043 #[unstable(feature = "slice_index_methods", issue = "none")]
3044 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
3046 /// Returns a shared reference to the output at this location, without
3047 /// performing any bounds checking.
3048 /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
3049 /// is *[undefined behavior]* even if the resulting reference is not used.
3051 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
3052 #[unstable(feature = "slice_index_methods", issue = "none")]
3053 unsafe fn get_unchecked(self, slice: *const T) -> *const Self::Output;
3055 /// Returns a mutable reference to the output at this location, without
3056 /// performing any bounds checking.
3057 /// Calling this method with an out-of-bounds index or a dangling `slice` pointer
3058 /// is *[undefined behavior]* even if the resulting reference is not used.
3060 /// [undefined behavior]: ../../reference/behavior-considered-undefined.html
3061 #[unstable(feature = "slice_index_methods", issue = "none")]
3062 unsafe fn get_unchecked_mut(self, slice: *mut T) -> *mut Self::Output;
3064 /// Returns a shared reference to the output at this location, panicking
3065 /// if out of bounds.
3066 #[unstable(feature = "slice_index_methods", issue = "none")]
3068 fn index(self, slice: &T) -> &Self::Output;
3070 /// Returns a mutable reference to the output at this location, panicking
3071 /// if out of bounds.
3072 #[unstable(feature = "slice_index_methods", issue = "none")]
3074 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
3077 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3078 unsafe impl<T> SliceIndex<[T]> for usize {
3082 fn get(self, slice: &[T]) -> Option<&T> {
3083 if self < slice.len() { unsafe { Some(&*self.get_unchecked(slice)) } } else { None }
3087 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
3088 if self < slice.len() { unsafe { Some(&mut *self.get_unchecked_mut(slice)) } } else { None }
3092 unsafe fn get_unchecked(self, slice: *const [T]) -> *const T {
3093 // SAFETY: the caller guarantees that `slice` is not dangling, so it
3094 // cannot be longer than `isize::MAX`. They also guarantee that
3095 // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
3096 // so the call to `add` is safe.
3097 unsafe { slice.as_ptr().add(self) }
3101 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T {
3102 // SAFETY: see comments for `get_unchecked` above.
3103 unsafe { slice.as_mut_ptr().add(self) }
3107 fn index(self, slice: &[T]) -> &T {
3108 // N.B., use intrinsic indexing
3113 fn index_mut(self, slice: &mut [T]) -> &mut T {
3114 // N.B., use intrinsic indexing
3119 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3120 unsafe impl<T> SliceIndex<[T]> for ops::Range<usize> {
3124 fn get(self, slice: &[T]) -> Option<&[T]> {
3125 if self.start > self.end || self.end > slice.len() {
3128 unsafe { Some(&*self.get_unchecked(slice)) }
3133 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3134 if self.start > self.end || self.end > slice.len() {
3137 unsafe { Some(&mut *self.get_unchecked_mut(slice)) }
3142 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3143 // SAFETY: the caller guarantees that `slice` is not dangling, so it
3144 // cannot be longer than `isize::MAX`. They also guarantee that
3145 // `self` is in bounds of `slice` so `self` cannot overflow an `isize`,
3146 // so the call to `add` is safe.
3147 unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) }
3151 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3152 // SAFETY: see comments for `get_unchecked` above.
3154 ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
3159 fn index(self, slice: &[T]) -> &[T] {
3160 if self.start > self.end {
3161 slice_index_order_fail(self.start, self.end);
3162 } else if self.end > slice.len() {
3163 slice_index_len_fail(self.end, slice.len());
3165 unsafe { &*self.get_unchecked(slice) }
3169 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3170 if self.start > self.end {
3171 slice_index_order_fail(self.start, self.end);
3172 } else if self.end > slice.len() {
3173 slice_index_len_fail(self.end, slice.len());
3175 unsafe { &mut *self.get_unchecked_mut(slice) }
3179 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3180 unsafe impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
3184 fn get(self, slice: &[T]) -> Option<&[T]> {
3185 (0..self.end).get(slice)
3189 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3190 (0..self.end).get_mut(slice)
3194 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3195 // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3196 unsafe { (0..self.end).get_unchecked(slice) }
3200 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3201 // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3202 unsafe { (0..self.end).get_unchecked_mut(slice) }
3206 fn index(self, slice: &[T]) -> &[T] {
3207 (0..self.end).index(slice)
3211 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3212 (0..self.end).index_mut(slice)
3216 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3217 unsafe impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
3221 fn get(self, slice: &[T]) -> Option<&[T]> {
3222 (self.start..slice.len()).get(slice)
3226 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3227 (self.start..slice.len()).get_mut(slice)
3231 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3232 // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3233 unsafe { (self.start..slice.len()).get_unchecked(slice) }
3237 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3238 // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3239 unsafe { (self.start..slice.len()).get_unchecked_mut(slice) }
3243 fn index(self, slice: &[T]) -> &[T] {
3244 (self.start..slice.len()).index(slice)
3248 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3249 (self.start..slice.len()).index_mut(slice)
3253 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
3254 unsafe impl<T> SliceIndex<[T]> for ops::RangeFull {
3258 fn get(self, slice: &[T]) -> Option<&[T]> {
3263 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3268 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3273 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3278 fn index(self, slice: &[T]) -> &[T] {
3283 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3288 #[stable(feature = "inclusive_range", since = "1.26.0")]
3289 unsafe impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
3293 fn get(self, slice: &[T]) -> Option<&[T]> {
3294 if *self.end() == usize::MAX { None } else { (*self.start()..self.end() + 1).get(slice) }
3298 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3299 if *self.end() == usize::MAX {
3302 (*self.start()..self.end() + 1).get_mut(slice)
3307 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3308 // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3309 unsafe { (*self.start()..self.end() + 1).get_unchecked(slice) }
3313 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3314 // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3315 unsafe { (*self.start()..self.end() + 1).get_unchecked_mut(slice) }
3319 fn index(self, slice: &[T]) -> &[T] {
3320 if *self.end() == usize::MAX {
3321 slice_index_overflow_fail();
3323 (*self.start()..self.end() + 1).index(slice)
3327 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3328 if *self.end() == usize::MAX {
3329 slice_index_overflow_fail();
3331 (*self.start()..self.end() + 1).index_mut(slice)
3335 #[stable(feature = "inclusive_range", since = "1.26.0")]
3336 unsafe impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
3340 fn get(self, slice: &[T]) -> Option<&[T]> {
3341 (0..=self.end).get(slice)
3345 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
3346 (0..=self.end).get_mut(slice)
3350 unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] {
3351 // SAFETY: the caller has to uphold the safety contract for `get_unchecked`.
3352 unsafe { (0..=self.end).get_unchecked(slice) }
3356 unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] {
3357 // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`.
3358 unsafe { (0..=self.end).get_unchecked_mut(slice) }
3362 fn index(self, slice: &[T]) -> &[T] {
3363 (0..=self.end).index(slice)
3367 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
3368 (0..=self.end).index_mut(slice)
3372 ////////////////////////////////////////////////////////////////////////////////
3374 ////////////////////////////////////////////////////////////////////////////////
3376 #[stable(feature = "rust1", since = "1.0.0")]
3377 impl<T> Default for &[T] {
3378 /// Creates an empty slice.
3379 fn default() -> Self {
3384 #[stable(feature = "mut_slice_default", since = "1.5.0")]
3385 impl<T> Default for &mut [T] {
3386 /// Creates a mutable empty slice.
3387 fn default() -> Self {
3396 #[stable(feature = "rust1", since = "1.0.0")]
3397 impl<'a, T> IntoIterator for &'a [T] {
3399 type IntoIter = Iter<'a, T>;
3401 fn into_iter(self) -> Iter<'a, T> {
3406 #[stable(feature = "rust1", since = "1.0.0")]
3407 impl<'a, T> IntoIterator for &'a mut [T] {
3408 type Item = &'a mut T;
3409 type IntoIter = IterMut<'a, T>;
3411 fn into_iter(self) -> IterMut<'a, T> {
3416 // Macro helper functions
3418 fn size_from_ptr<T>(_: *const T) -> usize {
3422 // Inlining is_empty and len makes a huge performance difference
3423 macro_rules! is_empty {
3424 // The way we encode the length of a ZST iterator, this works both for ZST
3427 $self.ptr.as_ptr() as *const T == $self.end
3431 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
3432 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
3434 ($self: ident) => {{
3435 #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
3437 let start = $self.ptr;
3438 let size = size_from_ptr(start.as_ptr());
3440 // This _cannot_ use `unchecked_sub` because we depend on wrapping
3441 // to represent the length of long ZST slice iterators.
3442 ($self.end as usize).wrapping_sub(start.as_ptr() as usize)
3444 // We know that `start <= end`, so can do better than `offset_from`,
3445 // which needs to deal in signed. By setting appropriate flags here
3446 // we can tell LLVM this, which helps it remove bounds checks.
3447 // SAFETY: By the type invariant, `start <= end`
3448 let diff = unsafe { unchecked_sub($self.end as usize, start.as_ptr() as usize) };
3449 // By also telling LLVM that the pointers are apart by an exact
3450 // multiple of the type size, it can optimize `len() == 0` down to
3451 // `start == end` instead of `(end - start) < size`.
3452 // SAFETY: By the type invariant, the pointers are aligned so the
3453 // distance between them must be a multiple of pointee size
3454 unsafe { exact_div(diff, size) }
3459 // The shared definition of the `Iter` and `IterMut` iterators
3460 macro_rules! iterator {
3462 struct $name:ident -> $ptr:ty,
3468 // Returns the first element and moves the start of the iterator forwards by 1.
3469 // Greatly improves performance compared to an inlined function. The iterator
3470 // must not be empty.
3471 macro_rules! next_unchecked {
3472 ($self: ident) => {& $( $mut_ )* *$self.post_inc_start(1)}
3475 // Returns the last element and moves the end of the iterator backwards by 1.
3476 // Greatly improves performance compared to an inlined function. The iterator
3477 // must not be empty.
3478 macro_rules! next_back_unchecked {
3479 ($self: ident) => {& $( $mut_ )* *$self.pre_dec_end(1)}
3482 // Shrinks the iterator when T is a ZST, by moving the end of the iterator
3483 // backwards by `n`. `n` must not exceed `self.len()`.
3484 macro_rules! zst_shrink {
3485 ($self: ident, $n: ident) => {
3486 $self.end = ($self.end as * $raw_mut u8).wrapping_offset(-$n) as * $raw_mut T;
3490 impl<'a, T> $name<'a, T> {
3491 // Helper function for creating a slice from the iterator.
3493 fn make_slice(&self) -> &'a [T] {
3494 unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) }
3497 // Helper function for moving the start of the iterator forwards by `offset` elements,
3498 // returning the old start.
3499 // Unsafe because the offset must not exceed `self.len()`.
3501 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
3502 if mem::size_of::<T>() == 0 {
3503 zst_shrink!(self, offset);
3506 let old = self.ptr.as_ptr();
3507 // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
3508 // so this new pointer is inside `self` and thus guaranteed to be non-null.
3509 self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) };
3514 // Helper function for moving the end of the iterator backwards by `offset` elements,
3515 // returning the new end.
3516 // Unsafe because the offset must not exceed `self.len()`.
3518 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
3519 if mem::size_of::<T>() == 0 {
3520 zst_shrink!(self, offset);
3523 // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`,
3524 // which is guaranteed to not overflow an `isize`. Also, the resulting pointer
3525 // is in bounds of `slice`, which fulfills the other requirements for `offset`.
3526 self.end = unsafe { self.end.offset(-offset) };
3532 #[stable(feature = "rust1", since = "1.0.0")]
3533 impl<T> ExactSizeIterator for $name<'_, T> {
3535 fn len(&self) -> usize {
3540 fn is_empty(&self) -> bool {
3545 #[stable(feature = "rust1", since = "1.0.0")]
3546 impl<'a, T> Iterator for $name<'a, T> {
3550 fn next(&mut self) -> Option<$elem> {
3551 // could be implemented with slices, but this avoids bounds checks
3553 assume(!self.ptr.as_ptr().is_null());
3554 if mem::size_of::<T>() != 0 {
3555 assume(!self.end.is_null());
3557 if is_empty!(self) {
3560 Some(next_unchecked!(self))
3566 fn size_hint(&self) -> (usize, Option<usize>) {
3567 let exact = len!(self);
3568 (exact, Some(exact))
3572 fn count(self) -> usize {
3577 fn nth(&mut self, n: usize) -> Option<$elem> {
3578 if n >= len!(self) {
3579 // This iterator is now empty.
3580 if mem::size_of::<T>() == 0 {
3581 // We have to do it this way as `ptr` may never be 0, but `end`
3582 // could be (due to wrapping).
3583 self.end = self.ptr.as_ptr();
3586 // End can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr
3587 self.ptr = NonNull::new_unchecked(self.end as *mut T);
3592 // We are in bounds. `post_inc_start` does the right thing even for ZSTs.
3594 self.post_inc_start(n as isize);
3595 Some(next_unchecked!(self))
3600 fn last(mut self) -> Option<$elem> {
3604 // We override the default implementation, which uses `try_fold`,
3605 // because this simple implementation generates less LLVM IR and is
3606 // faster to compile.
3608 fn for_each<F>(mut self, mut f: F)
3611 F: FnMut(Self::Item),
3613 while let Some(x) = self.next() {
3618 // We override the default implementation, which uses `try_fold`,
3619 // because this simple implementation generates less LLVM IR and is
3620 // faster to compile.
3622 fn all<F>(&mut self, mut f: F) -> bool
3625 F: FnMut(Self::Item) -> bool,
3627 while let Some(x) = self.next() {
3635 // We override the default implementation, which uses `try_fold`,
3636 // because this simple implementation generates less LLVM IR and is
3637 // faster to compile.
3639 fn any<F>(&mut self, mut f: F) -> bool
3642 F: FnMut(Self::Item) -> bool,
3644 while let Some(x) = self.next() {
3652 // We override the default implementation, which uses `try_fold`,
3653 // because this simple implementation generates less LLVM IR and is
3654 // faster to compile.
3656 fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item>
3659 P: FnMut(&Self::Item) -> bool,
3661 while let Some(x) = self.next() {
3669 // We override the default implementation, which uses `try_fold`,
3670 // because this simple implementation generates less LLVM IR and is
3671 // faster to compile.
3673 fn find_map<B, F>(&mut self, mut f: F) -> Option<B>
3676 F: FnMut(Self::Item) -> Option<B>,
3678 while let Some(x) = self.next() {
3679 if let Some(y) = f(x) {
3686 // We override the default implementation, which uses `try_fold`,
3687 // because this simple implementation generates less LLVM IR and is
3688 // faster to compile. Also, the `assume` avoids a bounds check.
3690 #[rustc_inherit_overflow_checks]
3691 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
3693 P: FnMut(Self::Item) -> bool,
3697 while let Some(x) = self.next() {
3699 unsafe { assume(i < n) };
3707 // We override the default implementation, which uses `try_fold`,
3708 // because this simple implementation generates less LLVM IR and is
3709 // faster to compile. Also, the `assume` avoids a bounds check.
3711 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
3712 P: FnMut(Self::Item) -> bool,
3713 Self: Sized + ExactSizeIterator + DoubleEndedIterator
3717 while let Some(x) = self.next_back() {
3720 unsafe { assume(i < n) };
3730 #[stable(feature = "rust1", since = "1.0.0")]
3731 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
3733 fn next_back(&mut self) -> Option<$elem> {
3734 // could be implemented with slices, but this avoids bounds checks
3736 assume(!self.ptr.as_ptr().is_null());
3737 if mem::size_of::<T>() != 0 {
3738 assume(!self.end.is_null());
3740 if is_empty!(self) {
3743 Some(next_back_unchecked!(self))
3749 fn nth_back(&mut self, n: usize) -> Option<$elem> {
3750 if n >= len!(self) {
3751 // This iterator is now empty.
3752 self.end = self.ptr.as_ptr();
3755 // We are in bounds. `pre_dec_end` does the right thing even for ZSTs.
3757 self.pre_dec_end(n as isize);
3758 Some(next_back_unchecked!(self))
3763 #[stable(feature = "fused", since = "1.26.0")]
3764 impl<T> FusedIterator for $name<'_, T> {}
3766 #[unstable(feature = "trusted_len", issue = "37572")]
3767 unsafe impl<T> TrustedLen for $name<'_, T> {}
3771 /// Immutable slice iterator
3773 /// This struct is created by the [`iter`] method on [slices].
3780 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3781 /// let slice = &[1, 2, 3];
3783 /// // Then, we iterate over it:
3784 /// for element in slice.iter() {
3785 /// println!("{}", element);
3789 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3790 /// [slices]: ../../std/primitive.slice.html
3791 #[stable(feature = "rust1", since = "1.0.0")]
3792 pub struct Iter<'a, T: 'a> {
3794 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3795 // ptr == end is a quick test for the Iterator being empty, that works
3796 // for both ZST and non-ZST.
3797 _marker: marker::PhantomData<&'a T>,
3800 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3801 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3803 f.debug_tuple("Iter").field(&self.as_slice()).finish()
3807 #[stable(feature = "rust1", since = "1.0.0")]
3808 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3809 #[stable(feature = "rust1", since = "1.0.0")]
3810 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3812 impl<'a, T> Iter<'a, T> {
3813 /// Views the underlying data as a subslice of the original data.
3815 /// This has the same lifetime as the original slice, and so the
3816 /// iterator can continue to be used while this exists.
3823 /// // First, we declare a type which has the `iter` method to get the `Iter`
3824 /// // struct (&[usize here]):
3825 /// let slice = &[1, 2, 3];
3827 /// // Then, we get the iterator:
3828 /// let mut iter = slice.iter();
3829 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3830 /// println!("{:?}", iter.as_slice());
3832 /// // Next, we move to the second element of the slice:
3834 /// // Now `as_slice` returns "[2, 3]":
3835 /// println!("{:?}", iter.as_slice());
3837 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3838 pub fn as_slice(&self) -> &'a [T] {
3843 iterator! {struct Iter -> *const T, &'a T, const, {/* no mut */}, {
3844 fn is_sorted_by<F>(self, mut compare: F) -> bool
3847 F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>,
3849 self.as_slice().windows(2).all(|w| {
3850 compare(&&w[0], &&w[1]).map(|o| o != Ordering::Greater).unwrap_or(false)
3855 #[stable(feature = "rust1", since = "1.0.0")]
3856 impl<T> Clone for Iter<'_, T> {
3857 fn clone(&self) -> Self {
3858 Iter { ptr: self.ptr, end: self.end, _marker: self._marker }
3862 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3863 impl<T> AsRef<[T]> for Iter<'_, T> {
3864 fn as_ref(&self) -> &[T] {
3869 /// Mutable slice iterator.
3871 /// This struct is created by the [`iter_mut`] method on [slices].
3878 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3879 /// // struct (&[usize here]):
3880 /// let mut slice = &mut [1, 2, 3];
3882 /// // Then, we iterate over it and increment each element value:
3883 /// for element in slice.iter_mut() {
3887 /// // We now have "[2, 3, 4]":
3888 /// println!("{:?}", slice);
3891 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3892 /// [slices]: ../../std/primitive.slice.html
3893 #[stable(feature = "rust1", since = "1.0.0")]
3894 pub struct IterMut<'a, T: 'a> {
3896 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3897 // ptr == end is a quick test for the Iterator being empty, that works
3898 // for both ZST and non-ZST.
3899 _marker: marker::PhantomData<&'a mut T>,
3902 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3903 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3905 f.debug_tuple("IterMut").field(&self.make_slice()).finish()
3909 #[stable(feature = "rust1", since = "1.0.0")]
3910 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3911 #[stable(feature = "rust1", since = "1.0.0")]
3912 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3914 impl<'a, T> IterMut<'a, T> {
3915 /// Views the underlying data as a subslice of the original data.
3917 /// To avoid creating `&mut` references that alias, this is forced
3918 /// to consume the iterator.
3925 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3926 /// // struct (&[usize here]):
3927 /// let mut slice = &mut [1, 2, 3];
3930 /// // Then, we get the iterator:
3931 /// let mut iter = slice.iter_mut();
3932 /// // We move to next element:
3934 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3935 /// println!("{:?}", iter.into_slice());
3938 /// // Now let's modify a value of the slice:
3940 /// // First we get back the iterator:
3941 /// let mut iter = slice.iter_mut();
3942 /// // We change the value of the first element of the slice returned by the `next` method:
3943 /// *iter.next().unwrap() += 1;
3945 /// // Now slice is "[2, 2, 3]":
3946 /// println!("{:?}", slice);
3948 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3949 pub fn into_slice(self) -> &'a mut [T] {
3950 unsafe { from_raw_parts_mut(self.ptr.as_ptr(), len!(self)) }
3953 /// Views the underlying data as a subslice of the original data.
3955 /// To avoid creating `&mut [T]` references that alias, the returned slice
3956 /// borrows its lifetime from the iterator the method is applied on.
3963 /// # #![feature(slice_iter_mut_as_slice)]
3964 /// let mut slice: &mut [usize] = &mut [1, 2, 3];
3966 /// // First, we get the iterator:
3967 /// let mut iter = slice.iter_mut();
3968 /// // So if we check what the `as_slice` method returns here, we have "[1, 2, 3]":
3969 /// assert_eq!(iter.as_slice(), &[1, 2, 3]);
3971 /// // Next, we move to the second element of the slice:
3973 /// // Now `as_slice` returns "[2, 3]":
3974 /// assert_eq!(iter.as_slice(), &[2, 3]);
3976 #[unstable(feature = "slice_iter_mut_as_slice", reason = "recently added", issue = "58957")]
3977 pub fn as_slice(&self) -> &[T] {
3982 iterator! {struct IterMut -> *mut T, &'a mut T, mut, {mut}, {}}
3984 /// An internal abstraction over the splitting iterators, so that
3985 /// splitn, splitn_mut etc can be implemented once.
3987 trait SplitIter: DoubleEndedIterator {
3988 /// Marks the underlying iterator as complete, extracting the remaining
3989 /// portion of the slice.
3990 fn finish(&mut self) -> Option<Self::Item>;
3993 /// An iterator over subslices separated by elements that match a predicate
3996 /// This struct is created by the [`split`] method on [slices].
3998 /// [`split`]: ../../std/primitive.slice.html#method.split
3999 /// [slices]: ../../std/primitive.slice.html
4000 #[stable(feature = "rust1", since = "1.0.0")]
4001 pub struct Split<'a, T: 'a, P>
4003 P: FnMut(&T) -> bool,
4010 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4011 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P>
4013 P: FnMut(&T) -> bool,
4015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4016 f.debug_struct("Split").field("v", &self.v).field("finished", &self.finished).finish()
4020 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4021 #[stable(feature = "rust1", since = "1.0.0")]
4022 impl<T, P> Clone for Split<'_, T, P>
4024 P: Clone + FnMut(&T) -> bool,
4026 fn clone(&self) -> Self {
4027 Split { v: self.v, pred: self.pred.clone(), finished: self.finished }
4031 #[stable(feature = "rust1", since = "1.0.0")]
4032 impl<'a, T, P> Iterator for Split<'a, T, P>
4034 P: FnMut(&T) -> bool,
4036 type Item = &'a [T];
4039 fn next(&mut self) -> Option<&'a [T]> {
4044 match self.v.iter().position(|x| (self.pred)(x)) {
4045 None => self.finish(),
4047 let ret = Some(&self.v[..idx]);
4048 self.v = &self.v[idx + 1..];
4055 fn size_hint(&self) -> (usize, Option<usize>) {
4056 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
4060 #[stable(feature = "rust1", since = "1.0.0")]
4061 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P>
4063 P: FnMut(&T) -> bool,
4066 fn next_back(&mut self) -> Option<&'a [T]> {
4071 match self.v.iter().rposition(|x| (self.pred)(x)) {
4072 None => self.finish(),
4074 let ret = Some(&self.v[idx + 1..]);
4075 self.v = &self.v[..idx];
4082 impl<'a, T, P> SplitIter for Split<'a, T, P>
4084 P: FnMut(&T) -> bool,
4087 fn finish(&mut self) -> Option<&'a [T]> {
4091 self.finished = true;
4097 #[stable(feature = "fused", since = "1.26.0")]
4098 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
4100 /// An iterator over subslices separated by elements that match a predicate
4101 /// function. Unlike `Split`, it contains the matched part as a terminator
4102 /// of the subslice.
4104 /// This struct is created by the [`split_inclusive`] method on [slices].
4106 /// [`split_inclusive`]: ../../std/primitive.slice.html#method.split_inclusive
4107 /// [slices]: ../../std/primitive.slice.html
4108 #[unstable(feature = "split_inclusive", issue = "72360")]
4109 pub struct SplitInclusive<'a, T: 'a, P>
4111 P: FnMut(&T) -> bool,
4118 #[unstable(feature = "split_inclusive", issue = "72360")]
4119 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusive<'_, T, P>
4121 P: FnMut(&T) -> bool,
4123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4124 f.debug_struct("SplitInclusive")
4125 .field("v", &self.v)
4126 .field("finished", &self.finished)
4131 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4132 #[unstable(feature = "split_inclusive", issue = "72360")]
4133 impl<T, P> Clone for SplitInclusive<'_, T, P>
4135 P: Clone + FnMut(&T) -> bool,
4137 fn clone(&self) -> Self {
4138 SplitInclusive { v: self.v, pred: self.pred.clone(), finished: self.finished }
4142 #[unstable(feature = "split_inclusive", issue = "72360")]
4143 impl<'a, T, P> Iterator for SplitInclusive<'a, T, P>
4145 P: FnMut(&T) -> bool,
4147 type Item = &'a [T];
4150 fn next(&mut self) -> Option<&'a [T]> {
4156 self.v.iter().position(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(self.v.len());
4157 if idx == self.v.len() {
4158 self.finished = true;
4160 let ret = Some(&self.v[..idx]);
4161 self.v = &self.v[idx..];
4166 fn size_hint(&self) -> (usize, Option<usize>) {
4167 if self.finished { (0, Some(0)) } else { (1, Some(self.v.len() + 1)) }
4171 #[unstable(feature = "split_inclusive", issue = "72360")]
4172 impl<'a, T, P> DoubleEndedIterator for SplitInclusive<'a, T, P>
4174 P: FnMut(&T) -> bool,
4177 fn next_back(&mut self) -> Option<&'a [T]> {
4182 // The last index of self.v is already checked and found to match
4183 // by the last iteration, so we start searching a new match
4184 // one index to the left.
4185 let remainder = if self.v.is_empty() { &[] } else { &self.v[..(self.v.len() - 1)] };
4186 let idx = remainder.iter().rposition(|x| (self.pred)(x)).map(|idx| idx + 1).unwrap_or(0);
4188 self.finished = true;
4190 let ret = Some(&self.v[idx..]);
4191 self.v = &self.v[..idx];
4196 #[unstable(feature = "split_inclusive", issue = "72360")]
4197 impl<T, P> FusedIterator for SplitInclusive<'_, T, P> where P: FnMut(&T) -> bool {}
4199 /// An iterator over the mutable subslices of the vector which are separated
4200 /// by elements that match `pred`.
4202 /// This struct is created by the [`split_mut`] method on [slices].
4204 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
4205 /// [slices]: ../../std/primitive.slice.html
4206 #[stable(feature = "rust1", since = "1.0.0")]
4207 pub struct SplitMut<'a, T: 'a, P>
4209 P: FnMut(&T) -> bool,
4216 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4217 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P>
4219 P: FnMut(&T) -> bool,
4221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4222 f.debug_struct("SplitMut").field("v", &self.v).field("finished", &self.finished).finish()
4226 impl<'a, T, P> SplitIter for SplitMut<'a, T, P>
4228 P: FnMut(&T) -> bool,
4231 fn finish(&mut self) -> Option<&'a mut [T]> {
4235 self.finished = true;
4236 Some(mem::replace(&mut self.v, &mut []))
4241 #[stable(feature = "rust1", since = "1.0.0")]
4242 impl<'a, T, P> Iterator for SplitMut<'a, T, P>
4244 P: FnMut(&T) -> bool,
4246 type Item = &'a mut [T];
4249 fn next(&mut self) -> Option<&'a mut [T]> {
4255 // work around borrowck limitations
4256 let pred = &mut self.pred;
4257 self.v.iter().position(|x| (*pred)(x))
4260 None => self.finish(),
4262 let tmp = mem::replace(&mut self.v, &mut []);
4263 let (head, tail) = tmp.split_at_mut(idx);
4264 self.v = &mut tail[1..];
4271 fn size_hint(&self) -> (usize, Option<usize>) {
4275 // if the predicate doesn't match anything, we yield one slice
4276 // if it matches every element, we yield len+1 empty slices.
4277 (1, Some(self.v.len() + 1))
4282 #[stable(feature = "rust1", since = "1.0.0")]
4283 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P>
4285 P: FnMut(&T) -> bool,
4288 fn next_back(&mut self) -> Option<&'a mut [T]> {
4294 // work around borrowck limitations
4295 let pred = &mut self.pred;
4296 self.v.iter().rposition(|x| (*pred)(x))
4299 None => self.finish(),
4301 let tmp = mem::replace(&mut self.v, &mut []);
4302 let (head, tail) = tmp.split_at_mut(idx);
4304 Some(&mut tail[1..])
4310 #[stable(feature = "fused", since = "1.26.0")]
4311 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
4313 /// An iterator over the mutable subslices of the vector which are separated
4314 /// by elements that match `pred`. Unlike `SplitMut`, it contains the matched
4315 /// parts in the ends of the subslices.
4317 /// This struct is created by the [`split_inclusive_mut`] method on [slices].
4319 /// [`split_inclusive_mut`]: ../../std/primitive.slice.html#method.split_inclusive_mut
4320 /// [slices]: ../../std/primitive.slice.html
4321 #[unstable(feature = "split_inclusive", issue = "72360")]
4322 pub struct SplitInclusiveMut<'a, T: 'a, P>
4324 P: FnMut(&T) -> bool,
4331 #[unstable(feature = "split_inclusive", issue = "72360")]
4332 impl<T: fmt::Debug, P> fmt::Debug for SplitInclusiveMut<'_, T, P>
4334 P: FnMut(&T) -> bool,
4336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4337 f.debug_struct("SplitInclusiveMut")
4338 .field("v", &self.v)
4339 .field("finished", &self.finished)
4344 #[unstable(feature = "split_inclusive", issue = "72360")]
4345 impl<'a, T, P> Iterator for SplitInclusiveMut<'a, T, P>
4347 P: FnMut(&T) -> bool,
4349 type Item = &'a mut [T];
4352 fn next(&mut self) -> Option<&'a mut [T]> {
4358 // work around borrowck limitations
4359 let pred = &mut self.pred;
4360 self.v.iter().position(|x| (*pred)(x))
4362 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(self.v.len());
4363 if idx == self.v.len() {
4364 self.finished = true;
4366 let tmp = mem::replace(&mut self.v, &mut []);
4367 let (head, tail) = tmp.split_at_mut(idx);
4373 fn size_hint(&self) -> (usize, Option<usize>) {
4377 // if the predicate doesn't match anything, we yield one slice
4378 // if it matches every element, we yield len+1 empty slices.
4379 (1, Some(self.v.len() + 1))
4384 #[unstable(feature = "split_inclusive", issue = "72360")]
4385 impl<'a, T, P> DoubleEndedIterator for SplitInclusiveMut<'a, T, P>
4387 P: FnMut(&T) -> bool,
4390 fn next_back(&mut self) -> Option<&'a mut [T]> {
4395 let idx_opt = if self.v.is_empty() {
4398 // work around borrowck limitations
4399 let pred = &mut self.pred;
4401 // The last index of self.v is already checked and found to match
4402 // by the last iteration, so we start searching a new match
4403 // one index to the left.
4404 let remainder = &self.v[..(self.v.len() - 1)];
4405 remainder.iter().rposition(|x| (*pred)(x))
4407 let idx = idx_opt.map(|idx| idx + 1).unwrap_or(0);
4409 self.finished = true;
4411 let tmp = mem::replace(&mut self.v, &mut []);
4412 let (head, tail) = tmp.split_at_mut(idx);
4418 #[unstable(feature = "split_inclusive", issue = "72360")]
4419 impl<T, P> FusedIterator for SplitInclusiveMut<'_, T, P> where P: FnMut(&T) -> bool {}
4421 /// An iterator over subslices separated by elements that match a predicate
4422 /// function, starting from the end of the slice.
4424 /// This struct is created by the [`rsplit`] method on [slices].
4426 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
4427 /// [slices]: ../../std/primitive.slice.html
4428 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4429 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
4430 pub struct RSplit<'a, T: 'a, P>
4432 P: FnMut(&T) -> bool,
4434 inner: Split<'a, T, P>,
4437 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4438 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P>
4440 P: FnMut(&T) -> bool,
4442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4443 f.debug_struct("RSplit")
4444 .field("v", &self.inner.v)
4445 .field("finished", &self.inner.finished)
4450 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4451 impl<'a, T, P> Iterator for RSplit<'a, T, P>
4453 P: FnMut(&T) -> bool,
4455 type Item = &'a [T];
4458 fn next(&mut self) -> Option<&'a [T]> {
4459 self.inner.next_back()
4463 fn size_hint(&self) -> (usize, Option<usize>) {
4464 self.inner.size_hint()
4468 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4469 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P>
4471 P: FnMut(&T) -> bool,
4474 fn next_back(&mut self) -> Option<&'a [T]> {
4479 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4480 impl<'a, T, P> SplitIter for RSplit<'a, T, P>
4482 P: FnMut(&T) -> bool,
4485 fn finish(&mut self) -> Option<&'a [T]> {
4490 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4491 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
4493 /// An iterator over the subslices of the vector which are separated
4494 /// by elements that match `pred`, starting from the end of the slice.
4496 /// This struct is created by the [`rsplit_mut`] method on [slices].
4498 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
4499 /// [slices]: ../../std/primitive.slice.html
4500 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4501 pub struct RSplitMut<'a, T: 'a, P>
4503 P: FnMut(&T) -> bool,
4505 inner: SplitMut<'a, T, P>,
4508 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4509 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P>
4511 P: FnMut(&T) -> bool,
4513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4514 f.debug_struct("RSplitMut")
4515 .field("v", &self.inner.v)
4516 .field("finished", &self.inner.finished)
4521 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4522 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P>
4524 P: FnMut(&T) -> bool,
4527 fn finish(&mut self) -> Option<&'a mut [T]> {
4532 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4533 impl<'a, T, P> Iterator for RSplitMut<'a, T, P>
4535 P: FnMut(&T) -> bool,
4537 type Item = &'a mut [T];
4540 fn next(&mut self) -> Option<&'a mut [T]> {
4541 self.inner.next_back()
4545 fn size_hint(&self) -> (usize, Option<usize>) {
4546 self.inner.size_hint()
4550 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4551 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P>
4553 P: FnMut(&T) -> bool,
4556 fn next_back(&mut self) -> Option<&'a mut [T]> {
4561 #[stable(feature = "slice_rsplit", since = "1.27.0")]
4562 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
4564 /// An private iterator over subslices separated by elements that
4565 /// match a predicate function, splitting at most a fixed number of
4568 struct GenericSplitN<I> {
4573 impl<T, I: SplitIter<Item = T>> Iterator for GenericSplitN<I> {
4577 fn next(&mut self) -> Option<T> {
4592 fn size_hint(&self) -> (usize, Option<usize>) {
4593 let (lower, upper_opt) = self.iter.size_hint();
4594 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
4598 /// An iterator over subslices separated by elements that match a predicate
4599 /// function, limited to a given number of splits.
4601 /// This struct is created by the [`splitn`] method on [slices].
4603 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
4604 /// [slices]: ../../std/primitive.slice.html
4605 #[stable(feature = "rust1", since = "1.0.0")]
4606 pub struct SplitN<'a, T: 'a, P>
4608 P: FnMut(&T) -> bool,
4610 inner: GenericSplitN<Split<'a, T, P>>,
4613 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4614 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P>
4616 P: FnMut(&T) -> bool,
4618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4619 f.debug_struct("SplitN").field("inner", &self.inner).finish()
4623 /// An iterator over subslices separated by elements that match a
4624 /// predicate function, limited to a given number of splits, starting
4625 /// from the end of the slice.
4627 /// This struct is created by the [`rsplitn`] method on [slices].
4629 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
4630 /// [slices]: ../../std/primitive.slice.html
4631 #[stable(feature = "rust1", since = "1.0.0")]
4632 pub struct RSplitN<'a, T: 'a, P>
4634 P: FnMut(&T) -> bool,
4636 inner: GenericSplitN<RSplit<'a, T, P>>,
4639 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4640 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P>
4642 P: FnMut(&T) -> bool,
4644 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4645 f.debug_struct("RSplitN").field("inner", &self.inner).finish()
4649 /// An iterator over subslices separated by elements that match a predicate
4650 /// function, limited to a given number of splits.
4652 /// This struct is created by the [`splitn_mut`] method on [slices].
4654 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
4655 /// [slices]: ../../std/primitive.slice.html
4656 #[stable(feature = "rust1", since = "1.0.0")]
4657 pub struct SplitNMut<'a, T: 'a, P>
4659 P: FnMut(&T) -> bool,
4661 inner: GenericSplitN<SplitMut<'a, T, P>>,
4664 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4665 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P>
4667 P: FnMut(&T) -> bool,
4669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4670 f.debug_struct("SplitNMut").field("inner", &self.inner).finish()
4674 /// An iterator over subslices separated by elements that match a
4675 /// predicate function, limited to a given number of splits, starting
4676 /// from the end of the slice.
4678 /// This struct is created by the [`rsplitn_mut`] method on [slices].
4680 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
4681 /// [slices]: ../../std/primitive.slice.html
4682 #[stable(feature = "rust1", since = "1.0.0")]
4683 pub struct RSplitNMut<'a, T: 'a, P>
4685 P: FnMut(&T) -> bool,
4687 inner: GenericSplitN<RSplitMut<'a, T, P>>,
4690 #[stable(feature = "core_impl_debug", since = "1.9.0")]
4691 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P>
4693 P: FnMut(&T) -> bool,
4695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4696 f.debug_struct("RSplitNMut").field("inner", &self.inner).finish()
4700 macro_rules! forward_iterator {
4701 ($name:ident: $elem:ident, $iter_of:ty) => {
4702 #[stable(feature = "rust1", since = "1.0.0")]
4703 impl<'a, $elem, P> Iterator for $name<'a, $elem, P>
4705 P: FnMut(&T) -> bool,
4707 type Item = $iter_of;
4710 fn next(&mut self) -> Option<$iter_of> {
4715 fn size_hint(&self) -> (usize, Option<usize>) {
4716 self.inner.size_hint()
4720 #[stable(feature = "fused", since = "1.26.0")]
4721 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P> where P: FnMut(&T) -> bool {}
4725 forward_iterator! { SplitN: T, &'a [T] }
4726 forward_iterator! { RSplitN: T, &'a [T] }
4727 forward_iterator! { SplitNMut: T, &'a mut [T] }
4728 forward_iterator! { RSplitNMut: T, &'a mut [T] }
4730 /// An iterator over overlapping subslices of length `size`.
4732 /// This struct is created by the [`windows`] method on [slices].
4734 /// [`windows`]: ../../std/primitive.slice.html#method.windows
4735 /// [slices]: ../../std/primitive.slice.html
4737 #[stable(feature = "rust1", since = "1.0.0")]
4738 pub struct Windows<'a, T: 'a> {
4743 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4744 #[stable(feature = "rust1", since = "1.0.0")]
4745 impl<T> Clone for Windows<'_, T> {
4746 fn clone(&self) -> Self {
4747 Windows { v: self.v, size: self.size }
4751 #[stable(feature = "rust1", since = "1.0.0")]
4752 impl<'a, T> Iterator for Windows<'a, T> {
4753 type Item = &'a [T];
4756 fn next(&mut self) -> Option<&'a [T]> {
4757 if self.size > self.v.len() {
4760 let ret = Some(&self.v[..self.size]);
4761 self.v = &self.v[1..];
4767 fn size_hint(&self) -> (usize, Option<usize>) {
4768 if self.size > self.v.len() {
4771 let size = self.v.len() - self.size + 1;
4777 fn count(self) -> usize {
4782 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4783 let (end, overflow) = self.size.overflowing_add(n);
4784 if end > self.v.len() || overflow {
4788 let nth = &self.v[n..end];
4789 self.v = &self.v[n + 1..];
4795 fn last(self) -> Option<Self::Item> {
4796 if self.size > self.v.len() {
4799 let start = self.v.len() - self.size;
4800 Some(&self.v[start..])
4805 #[stable(feature = "rust1", since = "1.0.0")]
4806 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
4808 fn next_back(&mut self) -> Option<&'a [T]> {
4809 if self.size > self.v.len() {
4812 let ret = Some(&self.v[self.v.len() - self.size..]);
4813 self.v = &self.v[..self.v.len() - 1];
4819 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4820 let (end, overflow) = self.v.len().overflowing_sub(n);
4821 if end < self.size || overflow {
4825 let ret = &self.v[end - self.size..end];
4826 self.v = &self.v[..end - 1];
4832 #[stable(feature = "rust1", since = "1.0.0")]
4833 impl<T> ExactSizeIterator for Windows<'_, T> {}
4835 #[unstable(feature = "trusted_len", issue = "37572")]
4836 unsafe impl<T> TrustedLen for Windows<'_, T> {}
4838 #[stable(feature = "fused", since = "1.26.0")]
4839 impl<T> FusedIterator for Windows<'_, T> {}
4842 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
4843 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4844 // SAFETY: since the caller guarantees that `i` is in bounds,
4845 // which means that `i` cannot overflow an `isize`, and the
4846 // slice created by `from_raw_parts` is a subslice of `self.v`
4847 // thus is guaranteed to be valid for the lifetime `'a` of `self.v`.
4848 unsafe { from_raw_parts(self.v.as_ptr().add(i), self.size) }
4850 fn may_have_side_effect() -> bool {
4855 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4856 /// time), starting at the beginning of the slice.
4858 /// When the slice len is not evenly divided by the chunk size, the last slice
4859 /// of the iteration will be the remainder.
4861 /// This struct is created by the [`chunks`] method on [slices].
4863 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
4864 /// [slices]: ../../std/primitive.slice.html
4866 #[stable(feature = "rust1", since = "1.0.0")]
4867 pub struct Chunks<'a, T: 'a> {
4872 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4873 #[stable(feature = "rust1", since = "1.0.0")]
4874 impl<T> Clone for Chunks<'_, T> {
4875 fn clone(&self) -> Self {
4876 Chunks { v: self.v, chunk_size: self.chunk_size }
4880 #[stable(feature = "rust1", since = "1.0.0")]
4881 impl<'a, T> Iterator for Chunks<'a, T> {
4882 type Item = &'a [T];
4885 fn next(&mut self) -> Option<&'a [T]> {
4886 if self.v.is_empty() {
4889 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4890 let (fst, snd) = self.v.split_at(chunksz);
4897 fn size_hint(&self) -> (usize, Option<usize>) {
4898 if self.v.is_empty() {
4901 let n = self.v.len() / self.chunk_size;
4902 let rem = self.v.len() % self.chunk_size;
4903 let n = if rem > 0 { n + 1 } else { n };
4909 fn count(self) -> usize {
4914 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4915 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4916 if start >= self.v.len() || overflow {
4920 let end = match start.checked_add(self.chunk_size) {
4921 Some(sum) => cmp::min(self.v.len(), sum),
4922 None => self.v.len(),
4924 let nth = &self.v[start..end];
4925 self.v = &self.v[end..];
4931 fn last(self) -> Option<Self::Item> {
4932 if self.v.is_empty() {
4935 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
4936 Some(&self.v[start..])
4941 #[stable(feature = "rust1", since = "1.0.0")]
4942 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
4944 fn next_back(&mut self) -> Option<&'a [T]> {
4945 if self.v.is_empty() {
4948 let remainder = self.v.len() % self.chunk_size;
4949 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4950 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4957 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
4958 let len = self.len();
4963 let start = (len - 1 - n) * self.chunk_size;
4964 let end = match start.checked_add(self.chunk_size) {
4965 Some(res) => cmp::min(res, self.v.len()),
4966 None => self.v.len(),
4968 let nth_back = &self.v[start..end];
4969 self.v = &self.v[..start];
4975 #[stable(feature = "rust1", since = "1.0.0")]
4976 impl<T> ExactSizeIterator for Chunks<'_, T> {}
4978 #[unstable(feature = "trusted_len", issue = "37572")]
4979 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
4981 #[stable(feature = "fused", since = "1.26.0")]
4982 impl<T> FusedIterator for Chunks<'_, T> {}
4985 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
4986 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4987 let start = i * self.chunk_size;
4988 let end = match start.checked_add(self.chunk_size) {
4989 None => self.v.len(),
4990 Some(end) => cmp::min(end, self.v.len()),
4992 // SAFETY: the caller guarantees that `i` is in bounds,
4993 // which means that `start` must be in bounds of the
4994 // underlying `self.v` slice, and we made sure that `end`
4995 // is also in bounds of `self.v`. Thus, `start` cannot overflow
4996 // an `isize`, and the slice constructed by `from_raw_parts`
4997 // is a subslice of `self.v` which is guaranteed to be valid
4998 // for the lifetime `'a` of `self.v`.
4999 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
5001 fn may_have_side_effect() -> bool {
5006 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5007 /// elements at a time), starting at the beginning of the slice.
5009 /// When the slice len is not evenly divided by the chunk size, the last slice
5010 /// of the iteration will be the remainder.
5012 /// This struct is created by the [`chunks_mut`] method on [slices].
5014 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
5015 /// [slices]: ../../std/primitive.slice.html
5017 #[stable(feature = "rust1", since = "1.0.0")]
5018 pub struct ChunksMut<'a, T: 'a> {
5023 #[stable(feature = "rust1", since = "1.0.0")]
5024 impl<'a, T> Iterator for ChunksMut<'a, T> {
5025 type Item = &'a mut [T];
5028 fn next(&mut self) -> Option<&'a mut [T]> {
5029 if self.v.is_empty() {
5032 let sz = cmp::min(self.v.len(), self.chunk_size);
5033 let tmp = mem::replace(&mut self.v, &mut []);
5034 let (head, tail) = tmp.split_at_mut(sz);
5041 fn size_hint(&self) -> (usize, Option<usize>) {
5042 if self.v.is_empty() {
5045 let n = self.v.len() / self.chunk_size;
5046 let rem = self.v.len() % self.chunk_size;
5047 let n = if rem > 0 { n + 1 } else { n };
5053 fn count(self) -> usize {
5058 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5059 let (start, overflow) = n.overflowing_mul(self.chunk_size);
5060 if start >= self.v.len() || overflow {
5064 let end = match start.checked_add(self.chunk_size) {
5065 Some(sum) => cmp::min(self.v.len(), sum),
5066 None => self.v.len(),
5068 let tmp = mem::replace(&mut self.v, &mut []);
5069 let (head, tail) = tmp.split_at_mut(end);
5070 let (_, nth) = head.split_at_mut(start);
5077 fn last(self) -> Option<Self::Item> {
5078 if self.v.is_empty() {
5081 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
5082 Some(&mut self.v[start..])
5087 #[stable(feature = "rust1", since = "1.0.0")]
5088 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
5090 fn next_back(&mut self) -> Option<&'a mut [T]> {
5091 if self.v.is_empty() {
5094 let remainder = self.v.len() % self.chunk_size;
5095 let sz = if remainder != 0 { remainder } else { self.chunk_size };
5096 let tmp = mem::replace(&mut self.v, &mut []);
5097 let tmp_len = tmp.len();
5098 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
5105 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5106 let len = self.len();
5111 let start = (len - 1 - n) * self.chunk_size;
5112 let end = match start.checked_add(self.chunk_size) {
5113 Some(res) => cmp::min(res, self.v.len()),
5114 None => self.v.len(),
5116 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5117 let (head, nth_back) = temp.split_at_mut(start);
5124 #[stable(feature = "rust1", since = "1.0.0")]
5125 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
5127 #[unstable(feature = "trusted_len", issue = "37572")]
5128 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
5130 #[stable(feature = "fused", since = "1.26.0")]
5131 impl<T> FusedIterator for ChunksMut<'_, T> {}
5134 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
5135 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5136 let start = i * self.chunk_size;
5137 let end = match start.checked_add(self.chunk_size) {
5138 None => self.v.len(),
5139 Some(end) => cmp::min(end, self.v.len()),
5141 // SAFETY: see comments for `Chunks::get_unchecked`.
5142 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
5144 fn may_have_side_effect() -> bool {
5149 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5150 /// time), starting at the beginning of the slice.
5152 /// When the slice len is not evenly divided by the chunk size, the last
5153 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
5154 /// the [`remainder`] function from the iterator.
5156 /// This struct is created by the [`chunks_exact`] method on [slices].
5158 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
5159 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5160 /// [slices]: ../../std/primitive.slice.html
5162 #[stable(feature = "chunks_exact", since = "1.31.0")]
5163 pub struct ChunksExact<'a, T: 'a> {
5169 impl<'a, T> ChunksExact<'a, T> {
5170 /// Returns the remainder of the original slice that is not going to be
5171 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5173 #[stable(feature = "chunks_exact", since = "1.31.0")]
5174 pub fn remainder(&self) -> &'a [T] {
5179 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5180 #[stable(feature = "chunks_exact", since = "1.31.0")]
5181 impl<T> Clone for ChunksExact<'_, T> {
5182 fn clone(&self) -> Self {
5183 ChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
5187 #[stable(feature = "chunks_exact", since = "1.31.0")]
5188 impl<'a, T> Iterator for ChunksExact<'a, T> {
5189 type Item = &'a [T];
5192 fn next(&mut self) -> Option<&'a [T]> {
5193 if self.v.len() < self.chunk_size {
5196 let (fst, snd) = self.v.split_at(self.chunk_size);
5203 fn size_hint(&self) -> (usize, Option<usize>) {
5204 let n = self.v.len() / self.chunk_size;
5209 fn count(self) -> usize {
5214 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5215 let (start, overflow) = n.overflowing_mul(self.chunk_size);
5216 if start >= self.v.len() || overflow {
5220 let (_, snd) = self.v.split_at(start);
5227 fn last(mut self) -> Option<Self::Item> {
5232 #[stable(feature = "chunks_exact", since = "1.31.0")]
5233 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
5235 fn next_back(&mut self) -> Option<&'a [T]> {
5236 if self.v.len() < self.chunk_size {
5239 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5246 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5247 let len = self.len();
5252 let start = (len - 1 - n) * self.chunk_size;
5253 let end = start + self.chunk_size;
5254 let nth_back = &self.v[start..end];
5255 self.v = &self.v[..start];
5261 #[stable(feature = "chunks_exact", since = "1.31.0")]
5262 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
5263 fn is_empty(&self) -> bool {
5268 #[unstable(feature = "trusted_len", issue = "37572")]
5269 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
5271 #[stable(feature = "chunks_exact", since = "1.31.0")]
5272 impl<T> FusedIterator for ChunksExact<'_, T> {}
5275 #[stable(feature = "chunks_exact", since = "1.31.0")]
5276 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
5277 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5278 let start = i * self.chunk_size;
5279 // SAFETY: mostly identical to `Chunks::get_unchecked`.
5280 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
5282 fn may_have_side_effect() -> bool {
5287 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5288 /// elements at a time), starting at the beginning of the slice.
5290 /// When the slice len is not evenly divided by the chunk size, the last up to
5291 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5292 /// [`into_remainder`] function from the iterator.
5294 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
5296 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
5297 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5298 /// [slices]: ../../std/primitive.slice.html
5300 #[stable(feature = "chunks_exact", since = "1.31.0")]
5301 pub struct ChunksExactMut<'a, T: 'a> {
5307 impl<'a, T> ChunksExactMut<'a, T> {
5308 /// Returns the remainder of the original slice that is not going to be
5309 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5311 #[stable(feature = "chunks_exact", since = "1.31.0")]
5312 pub fn into_remainder(self) -> &'a mut [T] {
5317 #[stable(feature = "chunks_exact", since = "1.31.0")]
5318 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
5319 type Item = &'a mut [T];
5322 fn next(&mut self) -> Option<&'a mut [T]> {
5323 if self.v.len() < self.chunk_size {
5326 let tmp = mem::replace(&mut self.v, &mut []);
5327 let (head, tail) = tmp.split_at_mut(self.chunk_size);
5334 fn size_hint(&self) -> (usize, Option<usize>) {
5335 let n = self.v.len() / self.chunk_size;
5340 fn count(self) -> usize {
5345 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5346 let (start, overflow) = n.overflowing_mul(self.chunk_size);
5347 if start >= self.v.len() || overflow {
5351 let tmp = mem::replace(&mut self.v, &mut []);
5352 let (_, snd) = tmp.split_at_mut(start);
5359 fn last(mut self) -> Option<Self::Item> {
5364 #[stable(feature = "chunks_exact", since = "1.31.0")]
5365 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
5367 fn next_back(&mut self) -> Option<&'a mut [T]> {
5368 if self.v.len() < self.chunk_size {
5371 let tmp = mem::replace(&mut self.v, &mut []);
5372 let tmp_len = tmp.len();
5373 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5380 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5381 let len = self.len();
5386 let start = (len - 1 - n) * self.chunk_size;
5387 let end = start + self.chunk_size;
5388 let (temp, _tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5389 let (head, nth_back) = temp.split_at_mut(start);
5396 #[stable(feature = "chunks_exact", since = "1.31.0")]
5397 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
5398 fn is_empty(&self) -> bool {
5403 #[unstable(feature = "trusted_len", issue = "37572")]
5404 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
5406 #[stable(feature = "chunks_exact", since = "1.31.0")]
5407 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
5410 #[stable(feature = "chunks_exact", since = "1.31.0")]
5411 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
5412 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5413 let start = i * self.chunk_size;
5414 // SAFETY: see comments for `ChunksExactMut::get_unchecked`.
5415 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
5417 fn may_have_side_effect() -> bool {
5422 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5423 /// time), starting at the end of the slice.
5425 /// When the slice len is not evenly divided by the chunk size, the last slice
5426 /// of the iteration will be the remainder.
5428 /// This struct is created by the [`rchunks`] method on [slices].
5430 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
5431 /// [slices]: ../../std/primitive.slice.html
5433 #[stable(feature = "rchunks", since = "1.31.0")]
5434 pub struct RChunks<'a, T: 'a> {
5439 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5440 #[stable(feature = "rchunks", since = "1.31.0")]
5441 impl<T> Clone for RChunks<'_, T> {
5442 fn clone(&self) -> Self {
5443 RChunks { v: self.v, chunk_size: self.chunk_size }
5447 #[stable(feature = "rchunks", since = "1.31.0")]
5448 impl<'a, T> Iterator for RChunks<'a, T> {
5449 type Item = &'a [T];
5452 fn next(&mut self) -> Option<&'a [T]> {
5453 if self.v.is_empty() {
5456 let chunksz = cmp::min(self.v.len(), self.chunk_size);
5457 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
5464 fn size_hint(&self) -> (usize, Option<usize>) {
5465 if self.v.is_empty() {
5468 let n = self.v.len() / self.chunk_size;
5469 let rem = self.v.len() % self.chunk_size;
5470 let n = if rem > 0 { n + 1 } else { n };
5476 fn count(self) -> usize {
5481 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5482 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5483 if end >= self.v.len() || overflow {
5487 // Can't underflow because of the check above
5488 let end = self.v.len() - end;
5489 let start = match end.checked_sub(self.chunk_size) {
5493 let nth = &self.v[start..end];
5494 self.v = &self.v[0..start];
5500 fn last(self) -> Option<Self::Item> {
5501 if self.v.is_empty() {
5504 let rem = self.v.len() % self.chunk_size;
5505 let end = if rem == 0 { self.chunk_size } else { rem };
5506 Some(&self.v[0..end])
5511 #[stable(feature = "rchunks", since = "1.31.0")]
5512 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
5514 fn next_back(&mut self) -> Option<&'a [T]> {
5515 if self.v.is_empty() {
5518 let remainder = self.v.len() % self.chunk_size;
5519 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
5520 let (fst, snd) = self.v.split_at(chunksz);
5527 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5528 let len = self.len();
5533 // can't underflow because `n < len`
5534 let offset_from_end = (len - 1 - n) * self.chunk_size;
5535 let end = self.v.len() - offset_from_end;
5536 let start = end.saturating_sub(self.chunk_size);
5537 let nth_back = &self.v[start..end];
5538 self.v = &self.v[end..];
5544 #[stable(feature = "rchunks", since = "1.31.0")]
5545 impl<T> ExactSizeIterator for RChunks<'_, T> {}
5547 #[unstable(feature = "trusted_len", issue = "37572")]
5548 unsafe impl<T> TrustedLen for RChunks<'_, T> {}
5550 #[stable(feature = "rchunks", since = "1.31.0")]
5551 impl<T> FusedIterator for RChunks<'_, T> {}
5554 #[stable(feature = "rchunks", since = "1.31.0")]
5555 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
5556 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5557 let end = self.v.len() - i * self.chunk_size;
5558 let start = match end.checked_sub(self.chunk_size) {
5560 Some(start) => start,
5562 // SAFETY: mostly identical to `Chunks::get_unchecked`.
5563 unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) }
5565 fn may_have_side_effect() -> bool {
5570 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5571 /// elements at a time), starting at the end of the slice.
5573 /// When the slice len is not evenly divided by the chunk size, the last slice
5574 /// of the iteration will be the remainder.
5576 /// This struct is created by the [`rchunks_mut`] method on [slices].
5578 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
5579 /// [slices]: ../../std/primitive.slice.html
5581 #[stable(feature = "rchunks", since = "1.31.0")]
5582 pub struct RChunksMut<'a, T: 'a> {
5587 #[stable(feature = "rchunks", since = "1.31.0")]
5588 impl<'a, T> Iterator for RChunksMut<'a, T> {
5589 type Item = &'a mut [T];
5592 fn next(&mut self) -> Option<&'a mut [T]> {
5593 if self.v.is_empty() {
5596 let sz = cmp::min(self.v.len(), self.chunk_size);
5597 let tmp = mem::replace(&mut self.v, &mut []);
5598 let tmp_len = tmp.len();
5599 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
5606 fn size_hint(&self) -> (usize, Option<usize>) {
5607 if self.v.is_empty() {
5610 let n = self.v.len() / self.chunk_size;
5611 let rem = self.v.len() % self.chunk_size;
5612 let n = if rem > 0 { n + 1 } else { n };
5618 fn count(self) -> usize {
5623 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5624 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5625 if end >= self.v.len() || overflow {
5629 // Can't underflow because of the check above
5630 let end = self.v.len() - end;
5631 let start = match end.checked_sub(self.chunk_size) {
5635 let tmp = mem::replace(&mut self.v, &mut []);
5636 let (head, tail) = tmp.split_at_mut(start);
5637 let (nth, _) = tail.split_at_mut(end - start);
5644 fn last(self) -> Option<Self::Item> {
5645 if self.v.is_empty() {
5648 let rem = self.v.len() % self.chunk_size;
5649 let end = if rem == 0 { self.chunk_size } else { rem };
5650 Some(&mut self.v[0..end])
5655 #[stable(feature = "rchunks", since = "1.31.0")]
5656 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
5658 fn next_back(&mut self) -> Option<&'a mut [T]> {
5659 if self.v.is_empty() {
5662 let remainder = self.v.len() % self.chunk_size;
5663 let sz = if remainder != 0 { remainder } else { self.chunk_size };
5664 let tmp = mem::replace(&mut self.v, &mut []);
5665 let (head, tail) = tmp.split_at_mut(sz);
5672 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5673 let len = self.len();
5678 // can't underflow because `n < len`
5679 let offset_from_end = (len - 1 - n) * self.chunk_size;
5680 let end = self.v.len() - offset_from_end;
5681 let start = end.saturating_sub(self.chunk_size);
5682 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5683 let (_, nth_back) = tmp.split_at_mut(start);
5690 #[stable(feature = "rchunks", since = "1.31.0")]
5691 impl<T> ExactSizeIterator for RChunksMut<'_, T> {}
5693 #[unstable(feature = "trusted_len", issue = "37572")]
5694 unsafe impl<T> TrustedLen for RChunksMut<'_, T> {}
5696 #[stable(feature = "rchunks", since = "1.31.0")]
5697 impl<T> FusedIterator for RChunksMut<'_, T> {}
5700 #[stable(feature = "rchunks", since = "1.31.0")]
5701 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
5702 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5703 let end = self.v.len() - i * self.chunk_size;
5704 let start = match end.checked_sub(self.chunk_size) {
5706 Some(start) => start,
5708 // SAFETY: see comments for `RChunks::get_unchecked`.
5709 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) }
5711 fn may_have_side_effect() -> bool {
5716 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
5717 /// time), starting at the end of the slice.
5719 /// When the slice len is not evenly divided by the chunk size, the last
5720 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
5721 /// the [`remainder`] function from the iterator.
5723 /// This struct is created by the [`rchunks_exact`] method on [slices].
5725 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
5726 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
5727 /// [slices]: ../../std/primitive.slice.html
5729 #[stable(feature = "rchunks", since = "1.31.0")]
5730 pub struct RChunksExact<'a, T: 'a> {
5736 impl<'a, T> RChunksExact<'a, T> {
5737 /// Returns the remainder of the original slice that is not going to be
5738 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5740 #[stable(feature = "rchunks", since = "1.31.0")]
5741 pub fn remainder(&self) -> &'a [T] {
5746 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
5747 #[stable(feature = "rchunks", since = "1.31.0")]
5748 impl<'a, T> Clone for RChunksExact<'a, T> {
5749 fn clone(&self) -> RChunksExact<'a, T> {
5750 RChunksExact { v: self.v, rem: self.rem, chunk_size: self.chunk_size }
5754 #[stable(feature = "rchunks", since = "1.31.0")]
5755 impl<'a, T> Iterator for RChunksExact<'a, T> {
5756 type Item = &'a [T];
5759 fn next(&mut self) -> Option<&'a [T]> {
5760 if self.v.len() < self.chunk_size {
5763 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
5770 fn size_hint(&self) -> (usize, Option<usize>) {
5771 let n = self.v.len() / self.chunk_size;
5776 fn count(self) -> usize {
5781 fn nth(&mut self, n: usize) -> Option<Self::Item> {
5782 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5783 if end >= self.v.len() || overflow {
5787 let (fst, _) = self.v.split_at(self.v.len() - end);
5794 fn last(mut self) -> Option<Self::Item> {
5799 #[stable(feature = "rchunks", since = "1.31.0")]
5800 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
5802 fn next_back(&mut self) -> Option<&'a [T]> {
5803 if self.v.len() < self.chunk_size {
5806 let (fst, snd) = self.v.split_at(self.chunk_size);
5813 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5814 let len = self.len();
5819 // now that we know that `n` corresponds to a chunk,
5820 // none of these operations can underflow/overflow
5821 let offset = (len - n) * self.chunk_size;
5822 let start = self.v.len() - offset;
5823 let end = start + self.chunk_size;
5824 let nth_back = &self.v[start..end];
5825 self.v = &self.v[end..];
5831 #[stable(feature = "rchunks", since = "1.31.0")]
5832 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
5833 fn is_empty(&self) -> bool {
5838 #[unstable(feature = "trusted_len", issue = "37572")]
5839 unsafe impl<T> TrustedLen for RChunksExact<'_, T> {}
5841 #[stable(feature = "rchunks", since = "1.31.0")]
5842 impl<T> FusedIterator for RChunksExact<'_, T> {}
5845 #[stable(feature = "rchunks", since = "1.31.0")]
5846 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
5847 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
5848 let end = self.v.len() - i * self.chunk_size;
5849 let start = end - self.chunk_size;
5850 // SAFETY: mostmy identical to `Chunks::get_unchecked`.
5851 unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) }
5853 fn may_have_side_effect() -> bool {
5858 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
5859 /// elements at a time), starting at the end of the slice.
5861 /// When the slice len is not evenly divided by the chunk size, the last up to
5862 /// `chunk_size-1` elements will be omitted but can be retrieved from the
5863 /// [`into_remainder`] function from the iterator.
5865 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
5867 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
5868 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
5869 /// [slices]: ../../std/primitive.slice.html
5871 #[stable(feature = "rchunks", since = "1.31.0")]
5872 pub struct RChunksExactMut<'a, T: 'a> {
5878 impl<'a, T> RChunksExactMut<'a, T> {
5879 /// Returns the remainder of the original slice that is not going to be
5880 /// returned by the iterator. The returned slice has at most `chunk_size-1`
5882 #[stable(feature = "rchunks", since = "1.31.0")]
5883 pub fn into_remainder(self) -> &'a mut [T] {
5888 #[stable(feature = "rchunks", since = "1.31.0")]
5889 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
5890 type Item = &'a mut [T];
5893 fn next(&mut self) -> Option<&'a mut [T]> {
5894 if self.v.len() < self.chunk_size {
5897 let tmp = mem::replace(&mut self.v, &mut []);
5898 let tmp_len = tmp.len();
5899 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
5906 fn size_hint(&self) -> (usize, Option<usize>) {
5907 let n = self.v.len() / self.chunk_size;
5912 fn count(self) -> usize {
5917 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
5918 let (end, overflow) = n.overflowing_mul(self.chunk_size);
5919 if end >= self.v.len() || overflow {
5923 let tmp = mem::replace(&mut self.v, &mut []);
5924 let tmp_len = tmp.len();
5925 let (fst, _) = tmp.split_at_mut(tmp_len - end);
5932 fn last(mut self) -> Option<Self::Item> {
5937 #[stable(feature = "rchunks", since = "1.31.0")]
5938 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
5940 fn next_back(&mut self) -> Option<&'a mut [T]> {
5941 if self.v.len() < self.chunk_size {
5944 let tmp = mem::replace(&mut self.v, &mut []);
5945 let (head, tail) = tmp.split_at_mut(self.chunk_size);
5952 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
5953 let len = self.len();
5958 // now that we know that `n` corresponds to a chunk,
5959 // none of these operations can underflow/overflow
5960 let offset = (len - n) * self.chunk_size;
5961 let start = self.v.len() - offset;
5962 let end = start + self.chunk_size;
5963 let (tmp, tail) = mem::replace(&mut self.v, &mut []).split_at_mut(end);
5964 let (_, nth_back) = tmp.split_at_mut(start);
5971 #[stable(feature = "rchunks", since = "1.31.0")]
5972 impl<T> ExactSizeIterator for RChunksExactMut<'_, T> {
5973 fn is_empty(&self) -> bool {
5978 #[unstable(feature = "trusted_len", issue = "37572")]
5979 unsafe impl<T> TrustedLen for RChunksExactMut<'_, T> {}
5981 #[stable(feature = "rchunks", since = "1.31.0")]
5982 impl<T> FusedIterator for RChunksExactMut<'_, T> {}
5985 #[stable(feature = "rchunks", since = "1.31.0")]
5986 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
5987 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
5988 let end = self.v.len() - i * self.chunk_size;
5989 let start = end - self.chunk_size;
5990 // SAFETY: see comments for `RChunksExact::get_unchecked`.
5991 unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) }
5993 fn may_have_side_effect() -> bool {
6002 /// Forms a slice from a pointer and a length.
6004 /// The `len` argument is the number of **elements**, not the number of bytes.
6008 /// Behavior is undefined if any of the following conditions are violated:
6010 /// * `data` must be [valid] for reads for `len * mem::size_of::<T>()` many bytes,
6011 /// and it must be properly aligned. This means in particular:
6013 /// * The entire memory range of this slice must be contained within a single allocated object!
6014 /// Slices can never span across multiple allocated objects. See [below](#incorrect-usage)
6015 /// for an example incorrectly not taking this into account.
6016 /// * `data` must be non-null and aligned even for zero-length slices. One
6017 /// reason for this is that enum layout optimizations may rely on references
6018 /// (including slices of any length) being aligned and non-null to distinguish
6019 /// them from other data. You can obtain a pointer that is usable as `data`
6020 /// for zero-length slices using [`NonNull::dangling()`].
6022 /// * The memory referenced by the returned slice must not be mutated for the duration
6023 /// of lifetime `'a`, except inside an `UnsafeCell`.
6025 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
6026 /// See the safety documentation of [`pointer::offset`].
6030 /// The lifetime for the returned slice is inferred from its usage. To
6031 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
6032 /// source lifetime is safe in the context, such as by providing a helper
6033 /// function taking the lifetime of a host value for the slice, or by explicit
6041 /// // manifest a slice for a single element
6043 /// let ptr = &x as *const _;
6044 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
6045 /// assert_eq!(slice[0], 42);
6048 /// ### Incorrect usage
6050 /// The following `join_slices` function is **unsound** ⚠️
6055 /// fn join_slices<'a, T>(fst: &'a [T], snd: &'a [T]) -> &'a [T] {
6056 /// let fst_end = fst.as_ptr().wrapping_add(fst.len());
6057 /// let snd_start = snd.as_ptr();
6058 /// assert_eq!(fst_end, snd_start, "Slices must be contiguous!");
6060 /// // The assertion above ensures `fst` and `snd` are contiguous, but they might
6061 /// // still be contained within _different allocated objects_, in which case
6062 /// // creating this slice is undefined behavior.
6063 /// slice::from_raw_parts(fst.as_ptr(), fst.len() + snd.len())
6068 /// // `a` and `b` are different allocated objects...
6071 /// // ... which may nevertheless be laid out contiguously in memory: | a | b |
6072 /// let _ = join_slices(slice::from_ref(&a), slice::from_ref(&b)); // UB
6076 /// [valid]: ../../std/ptr/index.html#safety
6077 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
6078 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
6080 #[stable(feature = "rust1", since = "1.0.0")]
6081 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
6082 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
6084 mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
6085 "attempt to create slice covering at least half the address space"
6087 // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
6088 unsafe { &*ptr::slice_from_raw_parts(data, len) }
6091 /// Performs the same functionality as [`from_raw_parts`], except that a
6092 /// mutable slice is returned.
6096 /// Behavior is undefined if any of the following conditions are violated:
6098 /// * `data` must be [valid] for boths reads and writes for `len * mem::size_of::<T>()` many bytes,
6099 /// and it must be properly aligned. This means in particular:
6101 /// * The entire memory range of this slice must be contained within a single allocated object!
6102 /// Slices can never span across multiple allocated objects.
6103 /// * `data` must be non-null and aligned even for zero-length slices. One
6104 /// reason for this is that enum layout optimizations may rely on references
6105 /// (including slices of any length) being aligned and non-null to distinguish
6106 /// them from other data. You can obtain a pointer that is usable as `data`
6107 /// for zero-length slices using [`NonNull::dangling()`].
6109 /// * The memory referenced by the returned slice must not be accessed through any other pointer
6110 /// (not derived from the return value) for the duration of lifetime `'a`.
6111 /// Both read and write accesses are forbidden.
6113 /// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
6114 /// See the safety documentation of [`pointer::offset`].
6116 /// [valid]: ../../std/ptr/index.html#safety
6117 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
6118 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
6119 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
6121 #[stable(feature = "rust1", since = "1.0.0")]
6122 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
6123 debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice");
6125 mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
6126 "attempt to create slice covering at least half the address space"
6128 // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
6129 unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) }
6132 /// Converts a reference to T into a slice of length 1 (without copying).
6133 #[stable(feature = "from_ref", since = "1.28.0")]
6134 pub fn from_ref<T>(s: &T) -> &[T] {
6135 unsafe { from_raw_parts(s, 1) }
6138 /// Converts a reference to T into a slice of length 1 (without copying).
6139 #[stable(feature = "from_ref", since = "1.28.0")]
6140 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
6141 unsafe { from_raw_parts_mut(s, 1) }
6144 // This function is public only because there is no other way to unit test heapsort.
6145 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "none")]
6147 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
6149 F: FnMut(&T, &T) -> bool,
6151 sort::heapsort(v, &mut is_less);
6155 // Comparison traits
6159 /// Calls implementation provided memcmp.
6161 /// Interprets the data as u8.
6163 /// Returns 0 for equal, < 0 for less than and > 0 for greater
6165 // FIXME(#32610): Return type should be c_int
6166 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
6169 #[stable(feature = "rust1", since = "1.0.0")]
6170 impl<A, B> PartialEq<[B]> for [A]
6174 fn eq(&self, other: &[B]) -> bool {
6175 SlicePartialEq::equal(self, other)
6178 fn ne(&self, other: &[B]) -> bool {
6179 SlicePartialEq::not_equal(self, other)
6183 #[stable(feature = "rust1", since = "1.0.0")]
6184 impl<T: Eq> Eq for [T] {}
6186 /// Implements comparison of vectors lexicographically.
6187 #[stable(feature = "rust1", since = "1.0.0")]
6188 impl<T: Ord> Ord for [T] {
6189 fn cmp(&self, other: &[T]) -> Ordering {
6190 SliceOrd::compare(self, other)
6194 /// Implements comparison of vectors lexicographically.
6195 #[stable(feature = "rust1", since = "1.0.0")]
6196 impl<T: PartialOrd> PartialOrd for [T] {
6197 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
6198 SlicePartialOrd::partial_compare(self, other)
6203 // intermediate trait for specialization of slice's PartialEq
6204 trait SlicePartialEq<B> {
6205 fn equal(&self, other: &[B]) -> bool;
6207 fn not_equal(&self, other: &[B]) -> bool {
6212 // Generic slice equality
6213 impl<A, B> SlicePartialEq<B> for [A]
6217 default fn equal(&self, other: &[B]) -> bool {
6218 if self.len() != other.len() {
6222 self.iter().zip(other.iter()).all(|(x, y)| x == y)
6226 // Use an equal-pointer optimization when types are `Eq`
6227 impl<A> SlicePartialEq<A> for [A]
6229 A: PartialEq<A> + Eq,
6231 default fn equal(&self, other: &[A]) -> bool {
6232 if self.len() != other.len() {
6236 // While performance would suffer if `guaranteed_eq` just returned `false`
6237 // for all arguments, correctness and return value of this function are not affected.
6238 if self.as_ptr().guaranteed_eq(other.as_ptr()) {
6242 self.iter().zip(other.iter()).all(|(x, y)| x == y)
6246 // Use memcmp for bytewise equality when the types allow
6247 impl<A> SlicePartialEq<A> for [A]
6249 A: PartialEq<A> + BytewiseEquality,
6251 fn equal(&self, other: &[A]) -> bool {
6252 if self.len() != other.len() {
6256 // While performance would suffer if `guaranteed_eq` just returned `false`
6257 // for all arguments, correctness and return value of this function are not affected.
6258 if self.as_ptr().guaranteed_eq(other.as_ptr()) {
6262 let size = mem::size_of_val(self);
6263 memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0
6269 // intermediate trait for specialization of slice's PartialOrd
6270 trait SlicePartialOrd: Sized {
6271 fn partial_compare(left: &[Self], right: &[Self]) -> Option<Ordering>;
6274 impl<A: PartialOrd> SlicePartialOrd for A {
6275 default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6276 let l = cmp::min(left.len(), right.len());
6278 // Slice to the loop iteration range to enable bound check
6279 // elimination in the compiler
6280 let lhs = &left[..l];
6281 let rhs = &right[..l];
6284 match lhs[i].partial_cmp(&rhs[i]) {
6285 Some(Ordering::Equal) => (),
6286 non_eq => return non_eq,
6290 left.len().partial_cmp(&right.len())
6294 // This is the impl that we would like to have. Unfortunately it's not sound.
6295 // See `partial_ord_slice.rs`.
6297 impl<A> SlicePartialOrd for A
6301 default fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6302 Some(SliceOrd::compare(left, right))
6307 impl<A: AlwaysApplicableOrd> SlicePartialOrd for A {
6308 fn partial_compare(left: &[A], right: &[A]) -> Option<Ordering> {
6309 Some(SliceOrd::compare(left, right))
6313 trait AlwaysApplicableOrd: SliceOrd + Ord {}
6315 macro_rules! always_applicable_ord {
6316 ($([$($p:tt)*] $t:ty,)*) => {
6317 $(impl<$($p)*> AlwaysApplicableOrd for $t {})*
6321 always_applicable_ord! {
6322 [] u8, [] u16, [] u32, [] u64, [] u128, [] usize,
6323 [] i8, [] i16, [] i32, [] i64, [] i128, [] isize,
6325 [T: ?Sized] *const T, [T: ?Sized] *mut T,
6326 [T: AlwaysApplicableOrd] &T,
6327 [T: AlwaysApplicableOrd] &mut T,
6328 [T: AlwaysApplicableOrd] Option<T>,
6332 // intermediate trait for specialization of slice's Ord
6333 trait SliceOrd: Sized {
6334 fn compare(left: &[Self], right: &[Self]) -> Ordering;
6337 impl<A: Ord> SliceOrd for A {
6338 default fn compare(left: &[Self], right: &[Self]) -> Ordering {
6339 let l = cmp::min(left.len(), right.len());
6341 // Slice to the loop iteration range to enable bound check
6342 // elimination in the compiler
6343 let lhs = &left[..l];
6344 let rhs = &right[..l];
6347 match lhs[i].cmp(&rhs[i]) {
6348 Ordering::Equal => (),
6349 non_eq => return non_eq,
6353 left.len().cmp(&right.len())
6357 // memcmp compares a sequence of unsigned bytes lexicographically.
6358 // this matches the order we want for [u8], but no others (not even [i8]).
6359 impl SliceOrd for u8 {
6361 fn compare(left: &[Self], right: &[Self]) -> Ordering {
6363 unsafe { memcmp(left.as_ptr(), right.as_ptr(), cmp::min(left.len(), right.len())) };
6365 left.len().cmp(&right.len())
6366 } else if order < 0 {
6375 /// Trait implemented for types that can be compared for equality using
6376 /// their bytewise representation
6377 trait BytewiseEquality: Eq + Copy {}
6379 macro_rules! impl_marker_for {
6380 ($traitname:ident, $($ty:ty)*) => {
6382 impl $traitname for $ty { }
6387 impl_marker_for!(BytewiseEquality,
6388 u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize char bool);
6391 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
6392 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
6393 // SAFETY: the caller must guarantee that `i` is in bounds
6394 // of the underlying slice, so `i` cannot overflow an `isize`,
6395 // and the returned references is guaranteed to refer to an element
6396 // of the slice and thus guaranteed to be valid.
6397 unsafe { &*self.ptr.as_ptr().add(i) }
6399 fn may_have_side_effect() -> bool {
6405 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
6406 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
6407 // SAFETY: see comments for `Iter::get_unchecked`.
6408 unsafe { &mut *self.ptr.as_ptr().add(i) }
6410 fn may_have_side_effect() -> bool {
6415 trait SliceContains: Sized {
6416 fn slice_contains(&self, x: &[Self]) -> bool;
6419 impl<T> SliceContains for T
6423 default fn slice_contains(&self, x: &[Self]) -> bool {
6424 x.iter().any(|y| *y == *self)
6428 impl SliceContains for u8 {
6429 fn slice_contains(&self, x: &[Self]) -> bool {
6430 memchr::memchr(*self, x).is_some()
6434 impl SliceContains for i8 {
6435 fn slice_contains(&self, x: &[Self]) -> bool {
6436 let byte = *self as u8;
6437 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
6438 memchr::memchr(byte, bytes).is_some()