1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Slice management and manipulation
13 //! For more details see [`std::slice`].
15 //! [`std::slice`]: ../../std/slice/index.html
17 #![stable(feature = "rust1", since = "1.0.0")]
19 // How this module is organized.
21 // The library infrastructure for slices is fairly messy. There's
22 // a lot of stuff defined here. Let's keep it clean.
24 // The layout of this file is thus:
26 // * Inherent methods. This is where most of the slice API resides.
27 // * Implementations of a few common traits with important slice ops.
28 // * Definitions of a bunch of iterators.
30 // * The `raw` and `bytes` submodules.
31 // * Boilerplate trait implementations.
33 use cmp::Ordering::{self, Less, Equal, Greater};
36 use intrinsics::assume;
39 use ops::{FnMut, Try, self};
41 use option::Option::{None, Some};
43 use result::Result::{Ok, Err};
46 use marker::{Copy, Send, Sync, Sized, self};
47 use iter_private::TrustedRandomAccess;
49 #[unstable(feature = "slice_internals", issue = "0",
50 reason = "exposed from core to be reused in std; use the memchr crate")]
51 /// Pure rust memchr implementation, taken from rust-memchr
58 union Repr<'a, T: 'a> {
60 rust_mut: &'a mut [T],
77 /// Returns the number of elements in the slice.
82 /// let a = [1, 2, 3];
83 /// assert_eq!(a.len(), 3);
85 #[stable(feature = "rust1", since = "1.0.0")]
87 #[rustc_const_unstable(feature = "const_slice_len")]
88 pub const fn len(&self) -> usize {
90 Repr { rust: self }.raw.len
94 /// Returns `true` if the slice has a length of 0.
99 /// let a = [1, 2, 3];
100 /// assert!(!a.is_empty());
102 #[stable(feature = "rust1", since = "1.0.0")]
104 #[rustc_const_unstable(feature = "const_slice_len")]
105 pub const fn is_empty(&self) -> bool {
109 /// Returns the first element of the slice, or `None` if it is empty.
114 /// let v = [10, 40, 30];
115 /// assert_eq!(Some(&10), v.first());
117 /// let w: &[i32] = &[];
118 /// assert_eq!(None, w.first());
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn first(&self) -> Option<&T> {
126 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
131 /// let x = &mut [0, 1, 2];
133 /// if let Some(first) = x.first_mut() {
136 /// assert_eq!(x, &[5, 1, 2]);
138 #[stable(feature = "rust1", since = "1.0.0")]
140 pub fn first_mut(&mut self) -> Option<&mut T> {
144 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
149 /// let x = &[0, 1, 2];
151 /// if let Some((first, elements)) = x.split_first() {
152 /// assert_eq!(first, &0);
153 /// assert_eq!(elements, &[1, 2]);
156 #[stable(feature = "slice_splits", since = "1.5.0")]
158 pub fn split_first(&self) -> Option<(&T, &[T])> {
159 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
162 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
167 /// let x = &mut [0, 1, 2];
169 /// if let Some((first, elements)) = x.split_first_mut() {
174 /// assert_eq!(x, &[3, 4, 5]);
176 #[stable(feature = "slice_splits", since = "1.5.0")]
178 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
179 if self.is_empty() { None } else {
180 let split = self.split_at_mut(1);
181 Some((&mut split.0[0], split.1))
185 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
190 /// let x = &[0, 1, 2];
192 /// if let Some((last, elements)) = x.split_last() {
193 /// assert_eq!(last, &2);
194 /// assert_eq!(elements, &[0, 1]);
197 #[stable(feature = "slice_splits", since = "1.5.0")]
199 pub fn split_last(&self) -> Option<(&T, &[T])> {
200 let len = self.len();
201 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
204 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
209 /// let x = &mut [0, 1, 2];
211 /// if let Some((last, elements)) = x.split_last_mut() {
216 /// assert_eq!(x, &[4, 5, 3]);
218 #[stable(feature = "slice_splits", since = "1.5.0")]
220 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
221 let len = self.len();
222 if len == 0 { None } else {
223 let split = self.split_at_mut(len - 1);
224 Some((&mut split.1[0], split.0))
229 /// Returns the last element of the slice, or `None` if it is empty.
234 /// let v = [10, 40, 30];
235 /// assert_eq!(Some(&30), v.last());
237 /// let w: &[i32] = &[];
238 /// assert_eq!(None, w.last());
240 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn last(&self) -> Option<&T> {
243 let last_idx = self.len().checked_sub(1)?;
247 /// Returns a mutable pointer to the last item in the slice.
252 /// let x = &mut [0, 1, 2];
254 /// if let Some(last) = x.last_mut() {
257 /// assert_eq!(x, &[0, 1, 10]);
259 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn last_mut(&mut self) -> Option<&mut T> {
262 let last_idx = self.len().checked_sub(1)?;
263 self.get_mut(last_idx)
266 /// Returns a reference to an element or subslice depending on the type of
269 /// - If given a position, returns a reference to the element at that
270 /// position or `None` if out of bounds.
271 /// - If given a range, returns the subslice corresponding to that range,
272 /// or `None` if out of bounds.
277 /// let v = [10, 40, 30];
278 /// assert_eq!(Some(&40), v.get(1));
279 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
280 /// assert_eq!(None, v.get(3));
281 /// assert_eq!(None, v.get(0..4));
283 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn get<I>(&self, index: I) -> Option<&I::Output>
286 where I: SliceIndex<Self>
291 /// Returns a mutable reference to an element or subslice depending on the
292 /// type of index (see [`get`]) or `None` if the index is out of bounds.
294 /// [`get`]: #method.get
299 /// let x = &mut [0, 1, 2];
301 /// if let Some(elem) = x.get_mut(1) {
304 /// assert_eq!(x, &[0, 42, 2]);
306 #[stable(feature = "rust1", since = "1.0.0")]
308 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
309 where I: SliceIndex<Self>
314 /// Returns a reference to an element or subslice, without doing bounds
317 /// This is generally not recommended, use with caution! For a safe
318 /// alternative see [`get`].
320 /// [`get`]: #method.get
325 /// let x = &[1, 2, 4];
328 /// assert_eq!(x.get_unchecked(1), &2);
331 #[stable(feature = "rust1", since = "1.0.0")]
333 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
334 where I: SliceIndex<Self>
336 index.get_unchecked(self)
339 /// Returns a mutable reference to an element or subslice, without doing
342 /// This is generally not recommended, use with caution! For a safe
343 /// alternative see [`get_mut`].
345 /// [`get_mut`]: #method.get_mut
350 /// let x = &mut [1, 2, 4];
353 /// let elem = x.get_unchecked_mut(1);
356 /// assert_eq!(x, &[1, 13, 4]);
358 #[stable(feature = "rust1", since = "1.0.0")]
360 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
361 where I: SliceIndex<Self>
363 index.get_unchecked_mut(self)
366 /// Returns a raw pointer to the slice's buffer.
368 /// The caller must ensure that the slice outlives the pointer this
369 /// function returns, or else it will end up pointing to garbage.
371 /// Modifying the container referenced by this slice may cause its buffer
372 /// to be reallocated, which would also make any pointers to it invalid.
377 /// let x = &[1, 2, 4];
378 /// let x_ptr = x.as_ptr();
381 /// for i in 0..x.len() {
382 /// assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
386 #[stable(feature = "rust1", since = "1.0.0")]
388 pub const fn as_ptr(&self) -> *const T {
389 self as *const [T] as *const T
392 /// Returns an unsafe mutable pointer to the slice's buffer.
394 /// The caller must ensure that the slice outlives the pointer this
395 /// function returns, or else it will end up pointing to garbage.
397 /// Modifying the container referenced by this slice may cause its buffer
398 /// to be reallocated, which would also make any pointers to it invalid.
403 /// let x = &mut [1, 2, 4];
404 /// let x_ptr = x.as_mut_ptr();
407 /// for i in 0..x.len() {
408 /// *x_ptr.add(i) += 2;
411 /// assert_eq!(x, &[3, 4, 6]);
413 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn as_mut_ptr(&mut self) -> *mut T {
416 self as *mut [T] as *mut T
419 /// Swaps two elements in the slice.
423 /// * a - The index of the first element
424 /// * b - The index of the second element
428 /// Panics if `a` or `b` are out of bounds.
433 /// let mut v = ["a", "b", "c", "d"];
435 /// assert!(v == ["a", "d", "c", "b"]);
437 #[stable(feature = "rust1", since = "1.0.0")]
439 pub fn swap(&mut self, a: usize, b: usize) {
441 // Can't take two mutable loans from one vector, so instead just cast
442 // them to their raw pointers to do the swap
443 let pa: *mut T = &mut self[a];
444 let pb: *mut T = &mut self[b];
449 /// Reverses the order of elements in the slice, in place.
454 /// let mut v = [1, 2, 3];
456 /// assert!(v == [3, 2, 1]);
458 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn reverse(&mut self) {
461 let mut i: usize = 0;
464 // For very small types, all the individual reads in the normal
465 // path perform poorly. We can do better, given efficient unaligned
466 // load/store, by loading a larger chunk and reversing a register.
468 // Ideally LLVM would do this for us, as it knows better than we do
469 // whether unaligned reads are efficient (since that changes between
470 // different ARM versions, for example) and what the best chunk size
471 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
472 // the loop, so we need to do this ourselves. (Hypothesis: reverse
473 // is troublesome because the sides can be aligned differently --
474 // will be, when the length is odd -- so there's no way of emitting
475 // pre- and postludes to use fully-aligned SIMD in the middle.)
478 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
480 if fast_unaligned && mem::size_of::<T>() == 1 {
481 // Use the llvm.bswap intrinsic to reverse u8s in a usize
482 let chunk = mem::size_of::<usize>();
483 while i + chunk - 1 < ln / 2 {
485 let pa: *mut T = self.get_unchecked_mut(i);
486 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
487 let va = ptr::read_unaligned(pa as *mut usize);
488 let vb = ptr::read_unaligned(pb as *mut usize);
489 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
490 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
496 if fast_unaligned && mem::size_of::<T>() == 2 {
497 // Use rotate-by-16 to reverse u16s in a u32
498 let chunk = mem::size_of::<u32>() / 2;
499 while i + chunk - 1 < ln / 2 {
501 let pa: *mut T = self.get_unchecked_mut(i);
502 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
503 let va = ptr::read_unaligned(pa as *mut u32);
504 let vb = ptr::read_unaligned(pb as *mut u32);
505 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
506 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
513 // Unsafe swap to avoid the bounds check in safe swap.
515 let pa: *mut T = self.get_unchecked_mut(i);
516 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
523 /// Returns an iterator over the slice.
528 /// let x = &[1, 2, 4];
529 /// let mut iterator = x.iter();
531 /// assert_eq!(iterator.next(), Some(&1));
532 /// assert_eq!(iterator.next(), Some(&2));
533 /// assert_eq!(iterator.next(), Some(&4));
534 /// assert_eq!(iterator.next(), None);
536 #[stable(feature = "rust1", since = "1.0.0")]
538 pub fn iter(&self) -> Iter<T> {
540 let ptr = self.as_ptr();
541 assume(!ptr.is_null());
543 let end = if mem::size_of::<T>() == 0 {
544 (ptr as *const u8).wrapping_add(self.len()) as *const T
552 _marker: marker::PhantomData
557 /// Returns an iterator that allows modifying each value.
562 /// let x = &mut [1, 2, 4];
563 /// for elem in x.iter_mut() {
566 /// assert_eq!(x, &[3, 4, 6]);
568 #[stable(feature = "rust1", since = "1.0.0")]
570 pub fn iter_mut(&mut self) -> IterMut<T> {
572 let ptr = self.as_mut_ptr();
573 assume(!ptr.is_null());
575 let end = if mem::size_of::<T>() == 0 {
576 (ptr as *mut u8).wrapping_add(self.len()) as *mut T
584 _marker: marker::PhantomData
589 /// Returns an iterator over all contiguous windows of length
590 /// `size`. The windows overlap. If the slice is shorter than
591 /// `size`, the iterator returns no values.
595 /// Panics if `size` is 0.
600 /// let slice = ['r', 'u', 's', 't'];
601 /// let mut iter = slice.windows(2);
602 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
603 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
604 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
605 /// assert!(iter.next().is_none());
608 /// If the slice is shorter than `size`:
611 /// let slice = ['f', 'o', 'o'];
612 /// let mut iter = slice.windows(4);
613 /// assert!(iter.next().is_none());
615 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn windows(&self, size: usize) -> Windows<T> {
619 Windows { v: self, size }
622 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
623 /// beginning of the slice.
625 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
626 /// slice, then the last chunk will not have length `chunk_size`.
628 /// See [`chunks_exact`] for a variant of this iterator that returns chunks of always exactly
629 /// `chunk_size` elements, and [`rchunks`] for the same iterator but starting at the end of the
630 /// slice of the slice.
634 /// Panics if `chunk_size` is 0.
639 /// let slice = ['l', 'o', 'r', 'e', 'm'];
640 /// let mut iter = slice.chunks(2);
641 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
642 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
643 /// assert_eq!(iter.next().unwrap(), &['m']);
644 /// assert!(iter.next().is_none());
647 /// [`chunks_exact`]: #method.chunks_exact
648 /// [`rchunks`]: #method.rchunks
649 #[stable(feature = "rust1", since = "1.0.0")]
651 pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
652 assert!(chunk_size != 0);
653 Chunks { v: self, chunk_size }
656 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
657 /// beginning of the slice.
659 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
660 /// length of the slice, then the last chunk will not have length `chunk_size`.
662 /// See [`chunks_exact_mut`] for a variant of this iterator that returns chunks of always
663 /// exactly `chunk_size` elements, and [`rchunks_mut`] for the same iterator but starting at
664 /// the end of the slice of the slice.
668 /// Panics if `chunk_size` is 0.
673 /// let v = &mut [0, 0, 0, 0, 0];
674 /// let mut count = 1;
676 /// for chunk in v.chunks_mut(2) {
677 /// for elem in chunk.iter_mut() {
682 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
685 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
686 /// [`rchunks_mut`]: #method.rchunks_mut
687 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
690 assert!(chunk_size != 0);
691 ChunksMut { v: self, chunk_size }
694 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
695 /// beginning of the slice.
697 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
698 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
699 /// from the `remainder` function of the iterator.
701 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
702 /// resulting code better than in the case of [`chunks`].
704 /// See [`chunks`] for a variant of this iterator that also returns the remainder as a smaller
705 /// chunk, and [`rchunks_exact`] for the same iterator but starting at the end of the slice of
710 /// Panics if `chunk_size` is 0.
715 /// let slice = ['l', 'o', 'r', 'e', 'm'];
716 /// let mut iter = slice.chunks_exact(2);
717 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
718 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
719 /// assert!(iter.next().is_none());
720 /// assert_eq!(iter.remainder(), &['m']);
723 /// [`chunks`]: #method.chunks
724 /// [`rchunks_exact`]: #method.rchunks_exact
725 #[stable(feature = "chunks_exact", since = "1.31.0")]
727 pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<T> {
728 assert!(chunk_size != 0);
729 let rem = self.len() % chunk_size;
730 let len = self.len() - rem;
731 let (fst, snd) = self.split_at(len);
732 ChunksExact { v: fst, rem: snd, chunk_size }
735 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
736 /// beginning of the slice.
738 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
739 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
740 /// retrieved from the `into_remainder` function of the iterator.
742 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
743 /// resulting code better than in the case of [`chunks_mut`].
745 /// See [`chunks_mut`] for a variant of this iterator that also returns the remainder as a
746 /// smaller chunk, and [`rchunks_exact_mut`] for the same iterator but starting at the end of
747 /// the slice of the slice.
751 /// Panics if `chunk_size` is 0.
756 /// let v = &mut [0, 0, 0, 0, 0];
757 /// let mut count = 1;
759 /// for chunk in v.chunks_exact_mut(2) {
760 /// for elem in chunk.iter_mut() {
765 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
768 /// [`chunks_mut`]: #method.chunks_mut
769 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
770 #[stable(feature = "chunks_exact", since = "1.31.0")]
772 pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<T> {
773 assert!(chunk_size != 0);
774 let rem = self.len() % chunk_size;
775 let len = self.len() - rem;
776 let (fst, snd) = self.split_at_mut(len);
777 ChunksExactMut { v: fst, rem: snd, chunk_size }
780 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
783 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
784 /// slice, then the last chunk will not have length `chunk_size`.
786 /// See [`rchunks_exact`] for a variant of this iterator that returns chunks of always exactly
787 /// `chunk_size` elements, and [`chunks`] for the same iterator but starting at the beginning
792 /// Panics if `chunk_size` is 0.
797 /// let slice = ['l', 'o', 'r', 'e', 'm'];
798 /// let mut iter = slice.rchunks(2);
799 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
800 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
801 /// assert_eq!(iter.next().unwrap(), &['l']);
802 /// assert!(iter.next().is_none());
805 /// [`rchunks_exact`]: #method.rchunks_exact
806 /// [`chunks`]: #method.chunks
807 #[stable(feature = "rchunks", since = "1.31.0")]
809 pub fn rchunks(&self, chunk_size: usize) -> RChunks<T> {
810 assert!(chunk_size != 0);
811 RChunks { v: self, chunk_size }
814 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
817 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
818 /// length of the slice, then the last chunk will not have length `chunk_size`.
820 /// See [`rchunks_exact_mut`] for a variant of this iterator that returns chunks of always
821 /// exactly `chunk_size` elements, and [`chunks_mut`] for the same iterator but starting at the
822 /// beginning of the slice.
826 /// Panics if `chunk_size` is 0.
831 /// let v = &mut [0, 0, 0, 0, 0];
832 /// let mut count = 1;
834 /// for chunk in v.rchunks_mut(2) {
835 /// for elem in chunk.iter_mut() {
840 /// assert_eq!(v, &[3, 2, 2, 1, 1]);
843 /// [`rchunks_exact_mut`]: #method.rchunks_exact_mut
844 /// [`chunks_mut`]: #method.chunks_mut
845 #[stable(feature = "rchunks", since = "1.31.0")]
847 pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<T> {
848 assert!(chunk_size != 0);
849 RChunksMut { v: self, chunk_size }
852 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the
853 /// beginning of the slice.
855 /// The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the
856 /// slice, then the last up to `chunk_size-1` elements will be omitted and can be retrieved
857 /// from the `remainder` function of the iterator.
859 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
860 /// resulting code better than in the case of [`chunks`].
862 /// See [`rchunks`] for a variant of this iterator that also returns the remainder as a smaller
863 /// chunk, and [`chunks_exact`] for the same iterator but starting at the beginning of the
864 /// slice of the slice.
868 /// Panics if `chunk_size` is 0.
873 /// let slice = ['l', 'o', 'r', 'e', 'm'];
874 /// let mut iter = slice.rchunks_exact(2);
875 /// assert_eq!(iter.next().unwrap(), &['e', 'm']);
876 /// assert_eq!(iter.next().unwrap(), &['o', 'r']);
877 /// assert!(iter.next().is_none());
878 /// assert_eq!(iter.remainder(), &['l']);
881 /// [`rchunks`]: #method.rchunks
882 /// [`chunks_exact`]: #method.chunks_exact
883 #[stable(feature = "rchunks", since = "1.31.0")]
885 pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<T> {
886 assert!(chunk_size != 0);
887 let rem = self.len() % chunk_size;
888 let (fst, snd) = self.split_at(rem);
889 RChunksExact { v: snd, rem: fst, chunk_size }
892 /// Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end
895 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does not divide the
896 /// length of the slice, then the last up to `chunk_size-1` elements will be omitted and can be
897 /// retrieved from the `into_remainder` function of the iterator.
899 /// Due to each chunk having exactly `chunk_size` elements, the compiler can often optimize the
900 /// resulting code better than in the case of [`chunks_mut`].
902 /// See [`rchunks_mut`] for a variant of this iterator that also returns the remainder as a
903 /// smaller chunk, and [`chunks_exact_mut`] for the same iterator but starting at the beginning
904 /// of the slice of the slice.
908 /// Panics if `chunk_size` is 0.
913 /// let v = &mut [0, 0, 0, 0, 0];
914 /// let mut count = 1;
916 /// for chunk in v.rchunks_exact_mut(2) {
917 /// for elem in chunk.iter_mut() {
922 /// assert_eq!(v, &[0, 2, 2, 1, 1]);
925 /// [`rchunks_mut`]: #method.rchunks_mut
926 /// [`chunks_exact_mut`]: #method.chunks_exact_mut
927 #[stable(feature = "rchunks", since = "1.31.0")]
929 pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<T> {
930 assert!(chunk_size != 0);
931 let rem = self.len() % chunk_size;
932 let (fst, snd) = self.split_at_mut(rem);
933 RChunksExactMut { v: snd, rem: fst, chunk_size }
936 /// Divides one slice into two at an index.
938 /// The first will contain all indices from `[0, mid)` (excluding
939 /// the index `mid` itself) and the second will contain all
940 /// indices from `[mid, len)` (excluding the index `len` itself).
944 /// Panics if `mid > len`.
949 /// let v = [1, 2, 3, 4, 5, 6];
952 /// let (left, right) = v.split_at(0);
953 /// assert!(left == []);
954 /// assert!(right == [1, 2, 3, 4, 5, 6]);
958 /// let (left, right) = v.split_at(2);
959 /// assert!(left == [1, 2]);
960 /// assert!(right == [3, 4, 5, 6]);
964 /// let (left, right) = v.split_at(6);
965 /// assert!(left == [1, 2, 3, 4, 5, 6]);
966 /// assert!(right == []);
969 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
972 (&self[..mid], &self[mid..])
975 /// Divides one mutable slice into two at an index.
977 /// The first will contain all indices from `[0, mid)` (excluding
978 /// the index `mid` itself) and the second will contain all
979 /// indices from `[mid, len)` (excluding the index `len` itself).
983 /// Panics if `mid > len`.
988 /// let mut v = [1, 0, 3, 0, 5, 6];
989 /// // scoped to restrict the lifetime of the borrows
991 /// let (left, right) = v.split_at_mut(2);
992 /// assert!(left == [1, 0]);
993 /// assert!(right == [3, 0, 5, 6]);
997 /// assert!(v == [1, 2, 3, 4, 5, 6]);
999 #[stable(feature = "rust1", since = "1.0.0")]
1001 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1002 let len = self.len();
1003 let ptr = self.as_mut_ptr();
1006 assert!(mid <= len);
1008 (from_raw_parts_mut(ptr, mid),
1009 from_raw_parts_mut(ptr.add(mid), len - mid))
1013 /// Returns an iterator over subslices separated by elements that match
1014 /// `pred`. The matched element is not contained in the subslices.
1019 /// let slice = [10, 40, 33, 20];
1020 /// let mut iter = slice.split(|num| num % 3 == 0);
1022 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1023 /// assert_eq!(iter.next().unwrap(), &[20]);
1024 /// assert!(iter.next().is_none());
1027 /// If the first element is matched, an empty slice will be the first item
1028 /// returned by the iterator. Similarly, if the last element in the slice
1029 /// is matched, an empty slice will be the last item returned by the
1033 /// let slice = [10, 40, 33];
1034 /// let mut iter = slice.split(|num| num % 3 == 0);
1036 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1037 /// assert_eq!(iter.next().unwrap(), &[]);
1038 /// assert!(iter.next().is_none());
1041 /// If two matched elements are directly adjacent, an empty slice will be
1042 /// present between them:
1045 /// let slice = [10, 6, 33, 20];
1046 /// let mut iter = slice.split(|num| num % 3 == 0);
1048 /// assert_eq!(iter.next().unwrap(), &[10]);
1049 /// assert_eq!(iter.next().unwrap(), &[]);
1050 /// assert_eq!(iter.next().unwrap(), &[20]);
1051 /// assert!(iter.next().is_none());
1053 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn split<F>(&self, pred: F) -> Split<T, F>
1056 where F: FnMut(&T) -> bool
1065 /// Returns an iterator over mutable subslices separated by elements that
1066 /// match `pred`. The matched element is not contained in the subslices.
1071 /// let mut v = [10, 40, 30, 20, 60, 50];
1073 /// for group in v.split_mut(|num| *num % 3 == 0) {
1076 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1078 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
1081 where F: FnMut(&T) -> bool
1083 SplitMut { v: self, pred, finished: false }
1086 /// Returns an iterator over subslices separated by elements that match
1087 /// `pred`, starting at the end of the slice and working backwards.
1088 /// The matched element is not contained in the subslices.
1093 /// let slice = [11, 22, 33, 0, 44, 55];
1094 /// let mut iter = slice.rsplit(|num| *num == 0);
1096 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1097 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1098 /// assert_eq!(iter.next(), None);
1101 /// As with `split()`, if the first or last element is matched, an empty
1102 /// slice will be the first (or last) item returned by the iterator.
1105 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1106 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1107 /// assert_eq!(it.next().unwrap(), &[]);
1108 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1109 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1110 /// assert_eq!(it.next().unwrap(), &[]);
1111 /// assert_eq!(it.next(), None);
1113 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1115 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
1116 where F: FnMut(&T) -> bool
1118 RSplit { inner: self.split(pred) }
1121 /// Returns an iterator over mutable subslices separated by elements that
1122 /// match `pred`, starting at the end of the slice and working
1123 /// backwards. The matched element is not contained in the subslices.
1128 /// let mut v = [100, 400, 300, 200, 600, 500];
1130 /// let mut count = 0;
1131 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1133 /// group[0] = count;
1135 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1138 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1140 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
1141 where F: FnMut(&T) -> bool
1143 RSplitMut { inner: self.split_mut(pred) }
1146 /// Returns an iterator over subslices separated by elements that match
1147 /// `pred`, limited to returning at most `n` items. The matched element is
1148 /// not contained in the subslices.
1150 /// The last element returned, if any, will contain the remainder of the
1155 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
1156 /// `[20, 60, 50]`):
1159 /// let v = [10, 40, 30, 20, 60, 50];
1161 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1162 /// println!("{:?}", group);
1165 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
1168 where F: FnMut(&T) -> bool
1171 inner: GenericSplitN {
1172 iter: self.split(pred),
1178 /// Returns an iterator over subslices separated by elements that match
1179 /// `pred`, limited to returning at most `n` items. The matched element is
1180 /// not contained in the subslices.
1182 /// The last element returned, if any, will contain the remainder of the
1188 /// let mut v = [10, 40, 30, 20, 60, 50];
1190 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1193 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1197 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1198 where F: FnMut(&T) -> bool
1201 inner: GenericSplitN {
1202 iter: self.split_mut(pred),
1208 /// Returns an iterator over subslices separated by elements that match
1209 /// `pred` limited to returning at most `n` items. This starts at the end of
1210 /// the slice and works backwards. The matched element is not contained in
1213 /// The last element returned, if any, will contain the remainder of the
1218 /// Print the slice split once, starting from the end, by numbers divisible
1219 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1222 /// let v = [10, 40, 30, 20, 60, 50];
1224 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1225 /// println!("{:?}", group);
1228 #[stable(feature = "rust1", since = "1.0.0")]
1230 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1231 where F: FnMut(&T) -> bool
1234 inner: GenericSplitN {
1235 iter: self.rsplit(pred),
1241 /// Returns an iterator over subslices separated by elements that match
1242 /// `pred` limited to returning at most `n` items. This starts at the end of
1243 /// the slice and works backwards. The matched element is not contained in
1246 /// The last element returned, if any, will contain the remainder of the
1252 /// let mut s = [10, 40, 30, 20, 60, 50];
1254 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1257 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1259 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1262 where F: FnMut(&T) -> bool
1265 inner: GenericSplitN {
1266 iter: self.rsplit_mut(pred),
1272 /// Returns `true` if the slice contains an element with the given value.
1277 /// let v = [10, 40, 30];
1278 /// assert!(v.contains(&30));
1279 /// assert!(!v.contains(&50));
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 pub fn contains(&self, x: &T) -> bool
1285 x.slice_contains(self)
1288 /// Returns `true` if `needle` is a prefix of the slice.
1293 /// let v = [10, 40, 30];
1294 /// assert!(v.starts_with(&[10]));
1295 /// assert!(v.starts_with(&[10, 40]));
1296 /// assert!(!v.starts_with(&[50]));
1297 /// assert!(!v.starts_with(&[10, 50]));
1300 /// Always returns `true` if `needle` is an empty slice:
1303 /// let v = &[10, 40, 30];
1304 /// assert!(v.starts_with(&[]));
1305 /// let v: &[u8] = &[];
1306 /// assert!(v.starts_with(&[]));
1308 #[stable(feature = "rust1", since = "1.0.0")]
1309 pub fn starts_with(&self, needle: &[T]) -> bool
1312 let n = needle.len();
1313 self.len() >= n && needle == &self[..n]
1316 /// Returns `true` if `needle` is a suffix of the slice.
1321 /// let v = [10, 40, 30];
1322 /// assert!(v.ends_with(&[30]));
1323 /// assert!(v.ends_with(&[40, 30]));
1324 /// assert!(!v.ends_with(&[50]));
1325 /// assert!(!v.ends_with(&[50, 30]));
1328 /// Always returns `true` if `needle` is an empty slice:
1331 /// let v = &[10, 40, 30];
1332 /// assert!(v.ends_with(&[]));
1333 /// let v: &[u8] = &[];
1334 /// assert!(v.ends_with(&[]));
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 pub fn ends_with(&self, needle: &[T]) -> bool
1340 let (m, n) = (self.len(), needle.len());
1341 m >= n && needle == &self[m-n..]
1344 /// Binary searches this sorted slice for a given element.
1346 /// If the value is found then [`Result::Ok`] is returned, containing the
1347 /// index of the matching element. If there are multiple matches, then any
1348 /// one of the matches could be returned. If the value is not found then
1349 /// [`Result::Err`] is returned, containing the index where a matching
1350 /// element could be inserted while maintaining sorted order.
1354 /// Looks up a series of four elements. The first is found, with a
1355 /// uniquely determined position; the second and third are not
1356 /// found; the fourth could match any position in `[1, 4]`.
1359 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1361 /// assert_eq!(s.binary_search(&13), Ok(9));
1362 /// assert_eq!(s.binary_search(&4), Err(7));
1363 /// assert_eq!(s.binary_search(&100), Err(13));
1364 /// let r = s.binary_search(&1);
1365 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1371 self.binary_search_by(|p| p.cmp(x))
1374 /// Binary searches this sorted slice with a comparator function.
1376 /// The comparator function should implement an order consistent
1377 /// with the sort order of the underlying slice, returning an
1378 /// order code that indicates whether its argument is `Less`,
1379 /// `Equal` or `Greater` the desired target.
1381 /// If the value is found then [`Result::Ok`] is returned, containing the
1382 /// index of the matching element. If there are multiple matches, then any
1383 /// one of the matches could be returned. If the value is not found then
1384 /// [`Result::Err`] is returned, containing the index where a matching
1385 /// element could be inserted while maintaining sorted order.
1389 /// Looks up a series of four elements. The first is found, with a
1390 /// uniquely determined position; the second and third are not
1391 /// found; the fourth could match any position in `[1, 4]`.
1394 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1397 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1399 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1401 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1403 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1404 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1406 #[stable(feature = "rust1", since = "1.0.0")]
1408 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1409 where F: FnMut(&'a T) -> Ordering
1412 let mut size = s.len();
1416 let mut base = 0usize;
1418 let half = size / 2;
1419 let mid = base + half;
1420 // mid is always in [0, size), that means mid is >= 0 and < size.
1421 // mid >= 0: by definition
1422 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1423 let cmp = f(unsafe { s.get_unchecked(mid) });
1424 base = if cmp == Greater { base } else { mid };
1427 // base is always in [0, size) because base <= mid.
1428 let cmp = f(unsafe { s.get_unchecked(base) });
1429 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1433 /// Binary searches this sorted slice with a key extraction function.
1435 /// Assumes that the slice is sorted by the key, for instance with
1436 /// [`sort_by_key`] using the same key extraction function.
1438 /// If the value is found then [`Result::Ok`] is returned, containing the
1439 /// index of the matching element. If there are multiple matches, then any
1440 /// one of the matches could be returned. If the value is not found then
1441 /// [`Result::Err`] is returned, containing the index where a matching
1442 /// element could be inserted while maintaining sorted order.
1444 /// [`sort_by_key`]: #method.sort_by_key
1448 /// Looks up a series of four elements in a slice of pairs sorted by
1449 /// their second elements. The first is found, with a uniquely
1450 /// determined position; the second and third are not found; the
1451 /// fourth could match any position in `[1, 4]`.
1454 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1455 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1456 /// (1, 21), (2, 34), (4, 55)];
1458 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1459 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1460 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1461 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1462 /// assert!(match r { Ok(1..=4) => true, _ => false, });
1464 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1466 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1467 where F: FnMut(&'a T) -> B,
1470 self.binary_search_by(|k| f(k).cmp(b))
1473 /// Sorts the slice, but may not preserve the order of equal elements.
1475 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1476 /// and `O(n log n)` worst-case.
1478 /// # Current implementation
1480 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1481 /// which combines the fast average case of randomized quicksort with the fast worst case of
1482 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1483 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1484 /// deterministic behavior.
1486 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1487 /// slice consists of several concatenated sorted sequences.
1492 /// let mut v = [-5, 4, 1, -3, 2];
1494 /// v.sort_unstable();
1495 /// assert!(v == [-5, -3, 1, 2, 4]);
1498 /// [pdqsort]: https://github.com/orlp/pdqsort
1499 #[stable(feature = "sort_unstable", since = "1.20.0")]
1501 pub fn sort_unstable(&mut self)
1504 sort::quicksort(self, |a, b| a.lt(b));
1507 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1510 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1511 /// and `O(n log n)` worst-case.
1513 /// # Current implementation
1515 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1516 /// which combines the fast average case of randomized quicksort with the fast worst case of
1517 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1518 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1519 /// deterministic behavior.
1521 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1522 /// slice consists of several concatenated sorted sequences.
1527 /// let mut v = [5, 4, 1, 3, 2];
1528 /// v.sort_unstable_by(|a, b| a.cmp(b));
1529 /// assert!(v == [1, 2, 3, 4, 5]);
1531 /// // reverse sorting
1532 /// v.sort_unstable_by(|a, b| b.cmp(a));
1533 /// assert!(v == [5, 4, 3, 2, 1]);
1536 /// [pdqsort]: https://github.com/orlp/pdqsort
1537 #[stable(feature = "sort_unstable", since = "1.20.0")]
1539 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1540 where F: FnMut(&T, &T) -> Ordering
1542 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1545 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1548 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1549 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1551 /// # Current implementation
1553 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1554 /// which combines the fast average case of randomized quicksort with the fast worst case of
1555 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1556 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1557 /// deterministic behavior.
1562 /// let mut v = [-5i32, 4, 1, -3, 2];
1564 /// v.sort_unstable_by_key(|k| k.abs());
1565 /// assert!(v == [1, 2, -3, 4, -5]);
1568 /// [pdqsort]: https://github.com/orlp/pdqsort
1569 #[stable(feature = "sort_unstable", since = "1.20.0")]
1571 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1572 where F: FnMut(&T) -> K, K: Ord
1574 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1577 /// Moves all consecutive repeated elements to the end of the slice according to the
1578 /// [`PartialEq`] trait implementation.
1580 /// Returns two slices. The first contains no consecutive repeated elements.
1581 /// The second contains all the duplicates in no specified order.
1583 /// If the slice is sorted, the first returned slice contains no duplicates.
1588 /// #![feature(slice_partition_dedup)]
1590 /// let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
1592 /// let (dedup, duplicates) = slice.partition_dedup();
1594 /// assert_eq!(dedup, [1, 2, 3, 2, 1]);
1595 /// assert_eq!(duplicates, [2, 3, 1]);
1597 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1599 pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])
1602 self.partition_dedup_by(|a, b| a == b)
1605 /// Moves all but the first of consecutive elements to the end of the slice satisfying
1606 /// a given equality relation.
1608 /// Returns two slices. The first contains no consecutive repeated elements.
1609 /// The second contains all the duplicates in no specified order.
1611 /// The `same_bucket` function is passed references to two elements from the slice and
1612 /// must determine if the elements compare equal. The elements are passed in opposite order
1613 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is moved
1614 /// at the end of the slice.
1616 /// If the slice is sorted, the first returned slice contains no duplicates.
1621 /// #![feature(slice_partition_dedup)]
1623 /// let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
1625 /// let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1627 /// assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
1628 /// assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
1630 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1632 pub fn partition_dedup_by<F>(&mut self, mut same_bucket: F) -> (&mut [T], &mut [T])
1633 where F: FnMut(&mut T, &mut T) -> bool
1635 // Although we have a mutable reference to `self`, we cannot make
1636 // *arbitrary* changes. The `same_bucket` calls could panic, so we
1637 // must ensure that the slice is in a valid state at all times.
1639 // The way that we handle this is by using swaps; we iterate
1640 // over all the elements, swapping as we go so that at the end
1641 // the elements we wish to keep are in the front, and those we
1642 // wish to reject are at the back. We can then split the slice.
1643 // This operation is still O(n).
1645 // Example: We start in this state, where `r` represents "next
1646 // read" and `w` represents "next_write`.
1649 // +---+---+---+---+---+---+
1650 // | 0 | 1 | 1 | 2 | 3 | 3 |
1651 // +---+---+---+---+---+---+
1654 // Comparing self[r] against self[w-1], this is not a duplicate, so
1655 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1656 // r and w, leaving us with:
1659 // +---+---+---+---+---+---+
1660 // | 0 | 1 | 1 | 2 | 3 | 3 |
1661 // +---+---+---+---+---+---+
1664 // Comparing self[r] against self[w-1], this value is a duplicate,
1665 // so we increment `r` but leave everything else unchanged:
1668 // +---+---+---+---+---+---+
1669 // | 0 | 1 | 1 | 2 | 3 | 3 |
1670 // +---+---+---+---+---+---+
1673 // Comparing self[r] against self[w-1], this is not a duplicate,
1674 // so swap self[r] and self[w] and advance r and w:
1677 // +---+---+---+---+---+---+
1678 // | 0 | 1 | 2 | 1 | 3 | 3 |
1679 // +---+---+---+---+---+---+
1682 // Not a duplicate, repeat:
1685 // +---+---+---+---+---+---+
1686 // | 0 | 1 | 2 | 3 | 1 | 3 |
1687 // +---+---+---+---+---+---+
1690 // Duplicate, advance r. End of slice. Split at w.
1692 let len = self.len();
1694 return (self, &mut [])
1697 let ptr = self.as_mut_ptr();
1698 let mut next_read: usize = 1;
1699 let mut next_write: usize = 1;
1702 // Avoid bounds checks by using raw pointers.
1703 while next_read < len {
1704 let ptr_read = ptr.add(next_read);
1705 let prev_ptr_write = ptr.add(next_write - 1);
1706 if !same_bucket(&mut *ptr_read, &mut *prev_ptr_write) {
1707 if next_read != next_write {
1708 let ptr_write = prev_ptr_write.offset(1);
1709 mem::swap(&mut *ptr_read, &mut *ptr_write);
1717 self.split_at_mut(next_write)
1720 /// Moves all but the first of consecutive elements to the end of the slice that resolve
1721 /// to the same key.
1723 /// Returns two slices. The first contains no consecutive repeated elements.
1724 /// The second contains all the duplicates in no specified order.
1726 /// If the slice is sorted, the first returned slice contains no duplicates.
1731 /// #![feature(slice_partition_dedup)]
1733 /// let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
1735 /// let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
1737 /// assert_eq!(dedup, [10, 20, 30, 20, 11]);
1738 /// assert_eq!(duplicates, [21, 30, 13]);
1740 #[unstable(feature = "slice_partition_dedup", issue = "54279")]
1742 pub fn partition_dedup_by_key<K, F>(&mut self, mut key: F) -> (&mut [T], &mut [T])
1743 where F: FnMut(&mut T) -> K,
1746 self.partition_dedup_by(|a, b| key(a) == key(b))
1749 /// Rotates the slice in-place such that the first `mid` elements of the
1750 /// slice move to the end while the last `self.len() - mid` elements move to
1751 /// the front. After calling `rotate_left`, the element previously at index
1752 /// `mid` will become the first element in the slice.
1756 /// This function will panic if `mid` is greater than the length of the
1757 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1762 /// Takes linear (in `self.len()`) time.
1767 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1768 /// a.rotate_left(2);
1769 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1772 /// Rotating a subslice:
1775 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1776 /// a[1..5].rotate_left(1);
1777 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1779 #[stable(feature = "slice_rotate", since = "1.26.0")]
1780 pub fn rotate_left(&mut self, mid: usize) {
1781 assert!(mid <= self.len());
1782 let k = self.len() - mid;
1785 let p = self.as_mut_ptr();
1786 rotate::ptr_rotate(mid, p.add(mid), k);
1790 /// Rotates the slice in-place such that the first `self.len() - k`
1791 /// elements of the slice move to the end while the last `k` elements move
1792 /// to the front. After calling `rotate_right`, the element previously at
1793 /// index `self.len() - k` will become the first element in the slice.
1797 /// This function will panic if `k` is greater than the length of the
1798 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1803 /// Takes linear (in `self.len()`) time.
1808 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1809 /// a.rotate_right(2);
1810 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1813 /// Rotate a subslice:
1816 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1817 /// a[1..5].rotate_right(1);
1818 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1820 #[stable(feature = "slice_rotate", since = "1.26.0")]
1821 pub fn rotate_right(&mut self, k: usize) {
1822 assert!(k <= self.len());
1823 let mid = self.len() - k;
1826 let p = self.as_mut_ptr();
1827 rotate::ptr_rotate(mid, p.add(mid), k);
1831 /// Copies the elements from `src` into `self`.
1833 /// The length of `src` must be the same as `self`.
1835 /// If `src` implements `Copy`, it can be more performant to use
1836 /// [`copy_from_slice`].
1840 /// This function will panic if the two slices have different lengths.
1844 /// Cloning two elements from a slice into another:
1847 /// let src = [1, 2, 3, 4];
1848 /// let mut dst = [0, 0];
1850 /// // Because the slices have to be the same length,
1851 /// // we slice the source slice from four elements
1852 /// // to two. It will panic if we don't do this.
1853 /// dst.clone_from_slice(&src[2..]);
1855 /// assert_eq!(src, [1, 2, 3, 4]);
1856 /// assert_eq!(dst, [3, 4]);
1859 /// Rust enforces that there can only be one mutable reference with no
1860 /// immutable references to a particular piece of data in a particular
1861 /// scope. Because of this, attempting to use `clone_from_slice` on a
1862 /// single slice will result in a compile failure:
1865 /// let mut slice = [1, 2, 3, 4, 5];
1867 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1870 /// To work around this, we can use [`split_at_mut`] to create two distinct
1871 /// sub-slices from a slice:
1874 /// let mut slice = [1, 2, 3, 4, 5];
1877 /// let (left, right) = slice.split_at_mut(2);
1878 /// left.clone_from_slice(&right[1..]);
1881 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1884 /// [`copy_from_slice`]: #method.copy_from_slice
1885 /// [`split_at_mut`]: #method.split_at_mut
1886 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1887 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1888 assert!(self.len() == src.len(),
1889 "destination and source slices have different lengths");
1890 // NOTE: We need to explicitly slice them to the same length
1891 // for bounds checking to be elided, and the optimizer will
1892 // generate memcpy for simple cases (for example T = u8).
1893 let len = self.len();
1894 let src = &src[..len];
1896 self[i].clone_from(&src[i]);
1901 /// Copies all elements from `src` into `self`, using a memcpy.
1903 /// The length of `src` must be the same as `self`.
1905 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1909 /// This function will panic if the two slices have different lengths.
1913 /// Copying two elements from a slice into another:
1916 /// let src = [1, 2, 3, 4];
1917 /// let mut dst = [0, 0];
1919 /// // Because the slices have to be the same length,
1920 /// // we slice the source slice from four elements
1921 /// // to two. It will panic if we don't do this.
1922 /// dst.copy_from_slice(&src[2..]);
1924 /// assert_eq!(src, [1, 2, 3, 4]);
1925 /// assert_eq!(dst, [3, 4]);
1928 /// Rust enforces that there can only be one mutable reference with no
1929 /// immutable references to a particular piece of data in a particular
1930 /// scope. Because of this, attempting to use `copy_from_slice` on a
1931 /// single slice will result in a compile failure:
1934 /// let mut slice = [1, 2, 3, 4, 5];
1936 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1939 /// To work around this, we can use [`split_at_mut`] to create two distinct
1940 /// sub-slices from a slice:
1943 /// let mut slice = [1, 2, 3, 4, 5];
1946 /// let (left, right) = slice.split_at_mut(2);
1947 /// left.copy_from_slice(&right[1..]);
1950 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1953 /// [`clone_from_slice`]: #method.clone_from_slice
1954 /// [`split_at_mut`]: #method.split_at_mut
1955 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1956 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1957 assert_eq!(self.len(), src.len(),
1958 "destination and source slices have different lengths");
1960 ptr::copy_nonoverlapping(
1961 src.as_ptr(), self.as_mut_ptr(), self.len());
1965 /// Copies elements from one part of the slice to another part of itself,
1966 /// using a memmove.
1968 /// `src` is the range within `self` to copy from. `dest` is the starting
1969 /// index of the range within `self` to copy to, which will have the same
1970 /// length as `src`. The two ranges may overlap. The ends of the two ranges
1971 /// must be less than or equal to `self.len()`.
1975 /// This function will panic if either range exceeds the end of the slice,
1976 /// or if the end of `src` is before the start.
1980 /// Copying four bytes within a slice:
1983 /// # #![feature(copy_within)]
1984 /// let mut bytes = *b"Hello, World!";
1986 /// bytes.copy_within(1..5, 8);
1988 /// assert_eq!(&bytes, b"Hello, Wello!");
1990 #[unstable(feature = "copy_within", issue = "54236")]
1991 pub fn copy_within<R: ops::RangeBounds<usize>>(&mut self, src: R, dest: usize)
1995 let src_start = match src.start_bound() {
1996 ops::Bound::Included(&n) => n,
1997 ops::Bound::Excluded(&n) => n
1999 .unwrap_or_else(|| slice_index_overflow_fail()),
2000 ops::Bound::Unbounded => 0,
2002 let src_end = match src.end_bound() {
2003 ops::Bound::Included(&n) => n
2005 .unwrap_or_else(|| slice_index_overflow_fail()),
2006 ops::Bound::Excluded(&n) => n,
2007 ops::Bound::Unbounded => self.len(),
2009 assert!(src_start <= src_end, "src end is before src start");
2010 assert!(src_end <= self.len(), "src is out of bounds");
2011 let count = src_end - src_start;
2012 assert!(dest <= self.len() - count, "dest is out of bounds");
2015 self.get_unchecked(src_start),
2016 self.get_unchecked_mut(dest),
2022 /// Swaps all elements in `self` with those in `other`.
2024 /// The length of `other` must be the same as `self`.
2028 /// This function will panic if the two slices have different lengths.
2032 /// Swapping two elements across slices:
2035 /// let mut slice1 = [0, 0];
2036 /// let mut slice2 = [1, 2, 3, 4];
2038 /// slice1.swap_with_slice(&mut slice2[2..]);
2040 /// assert_eq!(slice1, [3, 4]);
2041 /// assert_eq!(slice2, [1, 2, 0, 0]);
2044 /// Rust enforces that there can only be one mutable reference to a
2045 /// particular piece of data in a particular scope. Because of this,
2046 /// attempting to use `swap_with_slice` on a single slice will result in
2047 /// a compile failure:
2050 /// let mut slice = [1, 2, 3, 4, 5];
2051 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2054 /// To work around this, we can use [`split_at_mut`] to create two distinct
2055 /// mutable sub-slices from a slice:
2058 /// let mut slice = [1, 2, 3, 4, 5];
2061 /// let (left, right) = slice.split_at_mut(2);
2062 /// left.swap_with_slice(&mut right[1..]);
2065 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2068 /// [`split_at_mut`]: #method.split_at_mut
2069 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2070 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2071 assert!(self.len() == other.len(),
2072 "destination and source slices have different lengths");
2074 ptr::swap_nonoverlapping(
2075 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
2079 /// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
2080 fn align_to_offsets<U>(&self) -> (usize, usize) {
2081 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
2082 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
2084 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
2085 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
2086 // place of every 3 Ts in the `rest` slice. A bit more complicated.
2088 // Formula to calculate this is:
2090 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
2091 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
2093 // Expanded and simplified:
2095 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
2096 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
2098 // Luckily since all this is constant-evaluated... performance here matters not!
2100 fn gcd(a: usize, b: usize) -> usize {
2101 // iterative stein’s algorithm
2102 // We should still make this `const fn` (and revert to recursive algorithm if we do)
2103 // because relying on llvm to consteval all this is… well, it makes me uncomfortable.
2104 let (ctz_a, mut ctz_b) = unsafe {
2105 if a == 0 { return b; }
2106 if b == 0 { return a; }
2107 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
2109 let k = ctz_a.min(ctz_b);
2110 let mut a = a >> ctz_a;
2113 // remove all factors of 2 from b
2116 ::mem::swap(&mut a, &mut b);
2123 ctz_b = ::intrinsics::cttz_nonzero(b);
2128 let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
2129 let ts: usize = ::mem::size_of::<U>() / gcd;
2130 let us: usize = ::mem::size_of::<T>() / gcd;
2132 // Armed with this knowledge, we can find how many `U`s we can fit!
2133 let us_len = self.len() / ts * us;
2134 // And how many `T`s will be in the trailing slice!
2135 let ts_len = self.len() % ts;
2139 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2142 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2143 /// slice of a new type, and the suffix slice. The method does a best effort to make the
2144 /// middle slice the greatest length possible for a given type and input slice, but only
2145 /// your algorithm's performance should depend on that, not its correctness.
2147 /// This method has no purpose when either input element `T` or output element `U` are
2148 /// zero-sized and will return the original slice without splitting anything.
2152 /// This method is essentially a `transmute` with respect to the elements in the returned
2153 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2161 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2162 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
2163 /// // less_efficient_algorithm_for_bytes(prefix);
2164 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2165 /// // less_efficient_algorithm_for_bytes(suffix);
2168 #[stable(feature = "slice_align_to", since = "1.30.0")]
2169 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
2170 // Note that most of this function will be constant-evaluated,
2171 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2172 // handle ZSTs specially, which is – don't handle them at all.
2173 return (self, &[], &[]);
2176 // First, find at what point do we split between the first and 2nd slice. Easy with
2177 // ptr.align_offset.
2178 let ptr = self.as_ptr();
2179 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2180 if offset > self.len() {
2183 let (left, rest) = self.split_at(offset);
2184 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2185 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2187 from_raw_parts(rest.as_ptr() as *const U, us_len),
2188 from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len))
2192 /// Transmute the slice to a slice of another type, ensuring alignment of the types is
2195 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
2196 /// slice of a new type, and the suffix slice. The method does a best effort to make the
2197 /// middle slice the greatest length possible for a given type and input slice, but only
2198 /// your algorithm's performance should depend on that, not its correctness.
2200 /// This method has no purpose when either input element `T` or output element `U` are
2201 /// zero-sized and will return the original slice without splitting anything.
2205 /// This method is essentially a `transmute` with respect to the elements in the returned
2206 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
2214 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
2215 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
2216 /// // less_efficient_algorithm_for_bytes(prefix);
2217 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
2218 /// // less_efficient_algorithm_for_bytes(suffix);
2221 #[stable(feature = "slice_align_to", since = "1.30.0")]
2222 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
2223 // Note that most of this function will be constant-evaluated,
2224 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
2225 // handle ZSTs specially, which is – don't handle them at all.
2226 return (self, &mut [], &mut []);
2229 // First, find at what point do we split between the first and 2nd slice. Easy with
2230 // ptr.align_offset.
2231 let ptr = self.as_ptr();
2232 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
2233 if offset > self.len() {
2234 (self, &mut [], &mut [])
2236 let (left, rest) = self.split_at_mut(offset);
2237 // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay
2238 let (us_len, ts_len) = rest.align_to_offsets::<U>();
2239 let mut_ptr = rest.as_mut_ptr();
2241 from_raw_parts_mut(mut_ptr as *mut U, us_len),
2242 from_raw_parts_mut(mut_ptr.add(rest.len() - ts_len), ts_len))
2247 #[lang = "slice_u8"]
2250 /// Checks if all bytes in this slice are within the ASCII range.
2251 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2253 pub fn is_ascii(&self) -> bool {
2254 self.iter().all(|b| b.is_ascii())
2257 /// Checks that two slices are an ASCII case-insensitive match.
2259 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2260 /// but without allocating and copying temporaries.
2261 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2263 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2264 self.len() == other.len() &&
2265 self.iter().zip(other).all(|(a, b)| {
2266 a.eq_ignore_ascii_case(b)
2270 /// Converts this slice to its ASCII upper case equivalent in-place.
2272 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2273 /// but non-ASCII letters are unchanged.
2275 /// To return a new uppercased value without modifying the existing one, use
2276 /// [`to_ascii_uppercase`].
2278 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2279 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2281 pub fn make_ascii_uppercase(&mut self) {
2283 byte.make_ascii_uppercase();
2287 /// Converts this slice to its ASCII lower case equivalent in-place.
2289 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2290 /// but non-ASCII letters are unchanged.
2292 /// To return a new lowercased value without modifying the existing one, use
2293 /// [`to_ascii_lowercase`].
2295 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2296 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2298 pub fn make_ascii_lowercase(&mut self) {
2300 byte.make_ascii_lowercase();
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2308 impl<T, I> ops::Index<I> for [T]
2309 where I: SliceIndex<[T]>
2311 type Output = I::Output;
2314 fn index(&self, index: I) -> &I::Output {
2319 #[stable(feature = "rust1", since = "1.0.0")]
2320 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2321 impl<T, I> ops::IndexMut<I> for [T]
2322 where I: SliceIndex<[T]>
2325 fn index_mut(&mut self, index: I) -> &mut I::Output {
2326 index.index_mut(self)
2332 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2333 panic!("index {} out of range for slice of length {}", index, len);
2338 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2339 panic!("slice index starts at {} but ends at {}", index, end);
2344 fn slice_index_overflow_fail() -> ! {
2345 panic!("attempted to index slice up to maximum usize");
2348 mod private_slice_index {
2350 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2353 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2354 impl Sealed for usize {}
2355 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2356 impl Sealed for ops::Range<usize> {}
2357 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2358 impl Sealed for ops::RangeTo<usize> {}
2359 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2360 impl Sealed for ops::RangeFrom<usize> {}
2361 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2362 impl Sealed for ops::RangeFull {}
2363 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2364 impl Sealed for ops::RangeInclusive<usize> {}
2365 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2366 impl Sealed for ops::RangeToInclusive<usize> {}
2369 /// A helper trait used for indexing operations.
2370 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2371 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2372 pub trait SliceIndex<T: ?Sized>: private_slice_index::Sealed {
2373 /// The output type returned by methods.
2374 #[stable(feature = "slice_get_slice", since = "1.28.0")]
2375 type Output: ?Sized;
2377 /// Returns a shared reference to the output at this location, if in
2379 #[unstable(feature = "slice_index_methods", issue = "0")]
2380 fn get(self, slice: &T) -> Option<&Self::Output>;
2382 /// Returns a mutable reference to the output at this location, if in
2384 #[unstable(feature = "slice_index_methods", issue = "0")]
2385 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2387 /// Returns a shared reference to the output at this location, without
2388 /// performing any bounds checking.
2389 #[unstable(feature = "slice_index_methods", issue = "0")]
2390 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2392 /// Returns a mutable reference to the output at this location, without
2393 /// performing any bounds checking.
2394 #[unstable(feature = "slice_index_methods", issue = "0")]
2395 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2397 /// Returns a shared reference to the output at this location, panicking
2398 /// if out of bounds.
2399 #[unstable(feature = "slice_index_methods", issue = "0")]
2400 fn index(self, slice: &T) -> &Self::Output;
2402 /// Returns a mutable reference to the output at this location, panicking
2403 /// if out of bounds.
2404 #[unstable(feature = "slice_index_methods", issue = "0")]
2405 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2408 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2409 impl<T> SliceIndex<[T]> for usize {
2413 fn get(self, slice: &[T]) -> Option<&T> {
2414 if self < slice.len() {
2416 Some(self.get_unchecked(slice))
2424 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2425 if self < slice.len() {
2427 Some(self.get_unchecked_mut(slice))
2435 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2436 &*slice.as_ptr().add(self)
2440 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2441 &mut *slice.as_mut_ptr().add(self)
2445 fn index(self, slice: &[T]) -> &T {
2446 // NB: use intrinsic indexing
2451 fn index_mut(self, slice: &mut [T]) -> &mut T {
2452 // NB: use intrinsic indexing
2457 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2458 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2462 fn get(self, slice: &[T]) -> Option<&[T]> {
2463 if self.start > self.end || self.end > slice.len() {
2467 Some(self.get_unchecked(slice))
2473 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2474 if self.start > self.end || self.end > slice.len() {
2478 Some(self.get_unchecked_mut(slice))
2484 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2485 from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start)
2489 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2490 from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start)
2494 fn index(self, slice: &[T]) -> &[T] {
2495 if self.start > self.end {
2496 slice_index_order_fail(self.start, self.end);
2497 } else if self.end > slice.len() {
2498 slice_index_len_fail(self.end, slice.len());
2501 self.get_unchecked(slice)
2506 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2507 if self.start > self.end {
2508 slice_index_order_fail(self.start, self.end);
2509 } else if self.end > slice.len() {
2510 slice_index_len_fail(self.end, slice.len());
2513 self.get_unchecked_mut(slice)
2518 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2519 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2523 fn get(self, slice: &[T]) -> Option<&[T]> {
2524 (0..self.end).get(slice)
2528 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2529 (0..self.end).get_mut(slice)
2533 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2534 (0..self.end).get_unchecked(slice)
2538 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2539 (0..self.end).get_unchecked_mut(slice)
2543 fn index(self, slice: &[T]) -> &[T] {
2544 (0..self.end).index(slice)
2548 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2549 (0..self.end).index_mut(slice)
2553 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2554 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2558 fn get(self, slice: &[T]) -> Option<&[T]> {
2559 (self.start..slice.len()).get(slice)
2563 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2564 (self.start..slice.len()).get_mut(slice)
2568 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2569 (self.start..slice.len()).get_unchecked(slice)
2573 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2574 (self.start..slice.len()).get_unchecked_mut(slice)
2578 fn index(self, slice: &[T]) -> &[T] {
2579 (self.start..slice.len()).index(slice)
2583 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2584 (self.start..slice.len()).index_mut(slice)
2588 #[stable(feature = "slice_get_slice_impls", since = "1.15.0")]
2589 impl<T> SliceIndex<[T]> for ops::RangeFull {
2593 fn get(self, slice: &[T]) -> Option<&[T]> {
2598 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2603 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2608 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2613 fn index(self, slice: &[T]) -> &[T] {
2618 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2624 #[stable(feature = "inclusive_range", since = "1.26.0")]
2625 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2629 fn get(self, slice: &[T]) -> Option<&[T]> {
2630 if *self.end() == usize::max_value() { None }
2631 else { (*self.start()..self.end() + 1).get(slice) }
2635 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2636 if *self.end() == usize::max_value() { None }
2637 else { (*self.start()..self.end() + 1).get_mut(slice) }
2641 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2642 (*self.start()..self.end() + 1).get_unchecked(slice)
2646 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2647 (*self.start()..self.end() + 1).get_unchecked_mut(slice)
2651 fn index(self, slice: &[T]) -> &[T] {
2652 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2653 (*self.start()..self.end() + 1).index(slice)
2657 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2658 if *self.end() == usize::max_value() { slice_index_overflow_fail(); }
2659 (*self.start()..self.end() + 1).index_mut(slice)
2663 #[stable(feature = "inclusive_range", since = "1.26.0")]
2664 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2668 fn get(self, slice: &[T]) -> Option<&[T]> {
2669 (0..=self.end).get(slice)
2673 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2674 (0..=self.end).get_mut(slice)
2678 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2679 (0..=self.end).get_unchecked(slice)
2683 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2684 (0..=self.end).get_unchecked_mut(slice)
2688 fn index(self, slice: &[T]) -> &[T] {
2689 (0..=self.end).index(slice)
2693 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2694 (0..=self.end).index_mut(slice)
2698 ////////////////////////////////////////////////////////////////////////////////
2700 ////////////////////////////////////////////////////////////////////////////////
2702 #[stable(feature = "rust1", since = "1.0.0")]
2703 impl<T> Default for &[T] {
2704 /// Creates an empty slice.
2705 fn default() -> Self { &[] }
2708 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2709 impl<T> Default for &mut [T] {
2710 /// Creates a mutable empty slice.
2711 fn default() -> Self { &mut [] }
2718 #[stable(feature = "rust1", since = "1.0.0")]
2719 impl<'a, T> IntoIterator for &'a [T] {
2721 type IntoIter = Iter<'a, T>;
2723 fn into_iter(self) -> Iter<'a, T> {
2728 #[stable(feature = "rust1", since = "1.0.0")]
2729 impl<'a, T> IntoIterator for &'a mut [T] {
2730 type Item = &'a mut T;
2731 type IntoIter = IterMut<'a, T>;
2733 fn into_iter(self) -> IterMut<'a, T> {
2738 // Macro helper functions
2740 const fn size_from_ptr<T>(_: *const T) -> usize {
2744 // Inlining is_empty and len makes a huge performance difference
2745 macro_rules! is_empty {
2746 // The way we encode the length of a ZST iterator, this works both for ZST
2748 ($self: ident) => {$self.ptr == $self.end}
2750 // To get rid of some bounds checks (see `position`), we compute the length in a somewhat
2751 // unexpected way. (Tested by `codegen/slice-position-bounds-check`.)
2753 ($self: ident) => {{
2754 let start = $self.ptr;
2755 let diff = ($self.end as usize).wrapping_sub(start as usize);
2756 let size = size_from_ptr(start);
2760 // Using division instead of `offset_from` helps LLVM remove bounds checks
2766 // The shared definition of the `Iter` and `IterMut` iterators
2767 macro_rules! iterator {
2768 (struct $name:ident -> $ptr:ty, $elem:ty, $raw_mut:tt, $( $mut_:tt )*) => {
2769 impl<'a, T> $name<'a, T> {
2770 // Helper function for creating a slice from the iterator.
2772 fn make_slice(&self) -> &'a [T] {
2773 unsafe { from_raw_parts(self.ptr, len!(self)) }
2776 // Helper function for moving the start of the iterator forwards by `offset` elements,
2777 // returning the old start.
2778 // Unsafe because the offset must be in-bounds or one-past-the-end.
2780 unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T {
2781 if mem::size_of::<T>() == 0 {
2782 // This is *reducing* the length. `ptr` never changes with ZST.
2783 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2787 self.ptr = self.ptr.offset(offset);
2792 // Helper function for moving the end of the iterator backwards by `offset` elements,
2793 // returning the new end.
2794 // Unsafe because the offset must be in-bounds or one-past-the-end.
2796 unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T {
2797 if mem::size_of::<T>() == 0 {
2798 self.end = (self.end as * $raw_mut u8).wrapping_offset(-offset) as * $raw_mut T;
2801 self.end = self.end.offset(-offset);
2807 #[stable(feature = "rust1", since = "1.0.0")]
2808 impl<'a, T> ExactSizeIterator for $name<'a, T> {
2810 fn len(&self) -> usize {
2815 fn is_empty(&self) -> bool {
2820 #[stable(feature = "rust1", since = "1.0.0")]
2821 impl<'a, T> Iterator for $name<'a, T> {
2825 fn next(&mut self) -> Option<$elem> {
2826 // could be implemented with slices, but this avoids bounds checks
2828 assume(!self.ptr.is_null());
2829 if mem::size_of::<T>() != 0 {
2830 assume(!self.end.is_null());
2832 if is_empty!(self) {
2835 Some(& $( $mut_ )* *self.post_inc_start(1))
2841 fn size_hint(&self) -> (usize, Option<usize>) {
2842 let exact = len!(self);
2843 (exact, Some(exact))
2847 fn count(self) -> usize {
2852 fn nth(&mut self, n: usize) -> Option<$elem> {
2853 if n >= len!(self) {
2854 // This iterator is now empty.
2855 if mem::size_of::<T>() == 0 {
2856 // We have to do it this way as `ptr` may never be 0, but `end`
2857 // could be (due to wrapping).
2858 self.end = self.ptr;
2860 self.ptr = self.end;
2864 // We are in bounds. `offset` does the right thing even for ZSTs.
2866 let elem = Some(& $( $mut_ )* *self.ptr.add(n));
2867 self.post_inc_start((n as isize).wrapping_add(1));
2873 fn last(mut self) -> Option<$elem> {
2878 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2879 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2881 // manual unrolling is needed when there are conditional exits from the loop
2882 let mut accum = init;
2884 while len!(self) >= 4 {
2885 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2886 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2887 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2888 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2890 while !is_empty!(self) {
2891 accum = f(accum, & $( $mut_ )* *self.post_inc_start(1))?;
2898 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2899 where Fold: FnMut(Acc, Self::Item) -> Acc,
2901 // Let LLVM unroll this, rather than using the default
2902 // impl that would force the manual unrolling above
2903 let mut accum = init;
2904 while let Some(x) = self.next() {
2905 accum = f(accum, x);
2911 #[rustc_inherit_overflow_checks]
2912 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2914 P: FnMut(Self::Item) -> bool,
2916 // The addition might panic on overflow.
2918 self.try_fold(0, move |i, x| {
2919 if predicate(x) { Err(i) }
2923 unsafe { assume(i < n) };
2929 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2930 P: FnMut(Self::Item) -> bool,
2931 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2933 // No need for an overflow check here, because `ExactSizeIterator`
2935 self.try_rfold(n, move |i, x| {
2937 if predicate(x) { Err(i) }
2941 unsafe { assume(i < n) };
2947 #[stable(feature = "rust1", since = "1.0.0")]
2948 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2950 fn next_back(&mut self) -> Option<$elem> {
2951 // could be implemented with slices, but this avoids bounds checks
2953 assume(!self.ptr.is_null());
2954 if mem::size_of::<T>() != 0 {
2955 assume(!self.end.is_null());
2957 if is_empty!(self) {
2960 Some(& $( $mut_ )* *self.pre_dec_end(1))
2966 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2967 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2969 // manual unrolling is needed when there are conditional exits from the loop
2970 let mut accum = init;
2972 while len!(self) >= 4 {
2973 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2974 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2975 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2976 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2978 // inlining is_empty everywhere makes a huge performance difference
2979 while !is_empty!(self) {
2980 accum = f(accum, & $( $mut_ )* *self.pre_dec_end(1))?;
2987 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2988 where Fold: FnMut(Acc, Self::Item) -> Acc,
2990 // Let LLVM unroll this, rather than using the default
2991 // impl that would force the manual unrolling above
2992 let mut accum = init;
2993 while let Some(x) = self.next_back() {
2994 accum = f(accum, x);
3000 #[stable(feature = "fused", since = "1.26.0")]
3001 impl<'a, T> FusedIterator for $name<'a, T> {}
3003 #[unstable(feature = "trusted_len", issue = "37572")]
3004 unsafe impl<'a, T> TrustedLen for $name<'a, T> {}
3008 /// Immutable slice iterator
3010 /// This struct is created by the [`iter`] method on [slices].
3017 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
3018 /// let slice = &[1, 2, 3];
3020 /// // Then, we iterate over it:
3021 /// for element in slice.iter() {
3022 /// println!("{}", element);
3026 /// [`iter`]: ../../std/primitive.slice.html#method.iter
3027 /// [slices]: ../../std/primitive.slice.html
3028 #[stable(feature = "rust1", since = "1.0.0")]
3029 pub struct Iter<'a, T: 'a> {
3031 end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3032 // ptr == end is a quick test for the Iterator being empty, that works
3033 // for both ZST and non-ZST.
3034 _marker: marker::PhantomData<&'a T>,
3037 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3038 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
3039 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3040 f.debug_tuple("Iter")
3041 .field(&self.as_slice())
3046 #[stable(feature = "rust1", since = "1.0.0")]
3047 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
3048 #[stable(feature = "rust1", since = "1.0.0")]
3049 unsafe impl<T: Sync> Send for Iter<'_, T> {}
3051 impl<'a, T> Iter<'a, T> {
3052 /// View the underlying data as a subslice of the original data.
3054 /// This has the same lifetime as the original slice, and so the
3055 /// iterator can continue to be used while this exists.
3062 /// // First, we declare a type which has the `iter` method to get the `Iter`
3063 /// // struct (&[usize here]):
3064 /// let slice = &[1, 2, 3];
3066 /// // Then, we get the iterator:
3067 /// let mut iter = slice.iter();
3068 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
3069 /// println!("{:?}", iter.as_slice());
3071 /// // Next, we move to the second element of the slice:
3073 /// // Now `as_slice` returns "[2, 3]":
3074 /// println!("{:?}", iter.as_slice());
3076 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3077 pub fn as_slice(&self) -> &'a [T] {
3082 iterator!{struct Iter -> *const T, &'a T, const, /* no mut */}
3084 #[stable(feature = "rust1", since = "1.0.0")]
3085 impl<T> Clone for Iter<'_, T> {
3086 fn clone(&self) -> Self { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
3089 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
3090 impl<T> AsRef<[T]> for Iter<'_, T> {
3091 fn as_ref(&self) -> &[T] {
3096 /// Mutable slice iterator.
3098 /// This struct is created by the [`iter_mut`] method on [slices].
3105 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3106 /// // struct (&[usize here]):
3107 /// let mut slice = &mut [1, 2, 3];
3109 /// // Then, we iterate over it and increment each element value:
3110 /// for element in slice.iter_mut() {
3114 /// // We now have "[2, 3, 4]":
3115 /// println!("{:?}", slice);
3118 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
3119 /// [slices]: ../../std/primitive.slice.html
3120 #[stable(feature = "rust1", since = "1.0.0")]
3121 pub struct IterMut<'a, T: 'a> {
3123 end: *mut T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
3124 // ptr == end is a quick test for the Iterator being empty, that works
3125 // for both ZST and non-ZST.
3126 _marker: marker::PhantomData<&'a mut T>,
3129 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3130 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
3131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3132 f.debug_tuple("IterMut")
3133 .field(&self.make_slice())
3138 #[stable(feature = "rust1", since = "1.0.0")]
3139 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
3140 #[stable(feature = "rust1", since = "1.0.0")]
3141 unsafe impl<T: Send> Send for IterMut<'_, T> {}
3143 impl<'a, T> IterMut<'a, T> {
3144 /// View the underlying data as a subslice of the original data.
3146 /// To avoid creating `&mut` references that alias, this is forced
3147 /// to consume the iterator.
3154 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3155 /// // struct (&[usize here]):
3156 /// let mut slice = &mut [1, 2, 3];
3159 /// // Then, we get the iterator:
3160 /// let mut iter = slice.iter_mut();
3161 /// // We move to next element:
3163 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3164 /// println!("{:?}", iter.into_slice());
3167 /// // Now let's modify a value of the slice:
3169 /// // First we get back the iterator:
3170 /// let mut iter = slice.iter_mut();
3171 /// // We change the value of the first element of the slice returned by the `next` method:
3172 /// *iter.next().unwrap() += 1;
3174 /// // Now slice is "[2, 2, 3]":
3175 /// println!("{:?}", slice);
3177 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3178 pub fn into_slice(self) -> &'a mut [T] {
3179 unsafe { from_raw_parts_mut(self.ptr, len!(self)) }
3183 iterator!{struct IterMut -> *mut T, &'a mut T, mut, mut}
3185 /// An internal abstraction over the splitting iterators, so that
3186 /// splitn, splitn_mut etc can be implemented once.
3188 trait SplitIter: DoubleEndedIterator {
3189 /// Marks the underlying iterator as complete, extracting the remaining
3190 /// portion of the slice.
3191 fn finish(&mut self) -> Option<Self::Item>;
3194 /// An iterator over subslices separated by elements that match a predicate
3197 /// This struct is created by the [`split`] method on [slices].
3199 /// [`split`]: ../../std/primitive.slice.html#method.split
3200 /// [slices]: ../../std/primitive.slice.html
3201 #[stable(feature = "rust1", since = "1.0.0")]
3202 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3208 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3209 impl<T: fmt::Debug, P> fmt::Debug for Split<'_, T, P> where P: FnMut(&T) -> bool {
3210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3211 f.debug_struct("Split")
3212 .field("v", &self.v)
3213 .field("finished", &self.finished)
3218 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3219 #[stable(feature = "rust1", since = "1.0.0")]
3220 impl<T, P> Clone for Split<'_, T, P> where P: Clone + FnMut(&T) -> bool {
3221 fn clone(&self) -> Self {
3224 pred: self.pred.clone(),
3225 finished: self.finished,
3230 #[stable(feature = "rust1", since = "1.0.0")]
3231 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3232 type Item = &'a [T];
3235 fn next(&mut self) -> Option<&'a [T]> {
3236 if self.finished { return None; }
3238 match self.v.iter().position(|x| (self.pred)(x)) {
3239 None => self.finish(),
3241 let ret = Some(&self.v[..idx]);
3242 self.v = &self.v[idx + 1..];
3249 fn size_hint(&self) -> (usize, Option<usize>) {
3253 (1, Some(self.v.len() + 1))
3258 #[stable(feature = "rust1", since = "1.0.0")]
3259 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3261 fn next_back(&mut self) -> Option<&'a [T]> {
3262 if self.finished { return None; }
3264 match self.v.iter().rposition(|x| (self.pred)(x)) {
3265 None => self.finish(),
3267 let ret = Some(&self.v[idx + 1..]);
3268 self.v = &self.v[..idx];
3275 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3277 fn finish(&mut self) -> Option<&'a [T]> {
3278 if self.finished { None } else { self.finished = true; Some(self.v) }
3282 #[stable(feature = "fused", since = "1.26.0")]
3283 impl<T, P> FusedIterator for Split<'_, T, P> where P: FnMut(&T) -> bool {}
3285 /// An iterator over the subslices of the vector which are separated
3286 /// by elements that match `pred`.
3288 /// This struct is created by the [`split_mut`] method on [slices].
3290 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3291 /// [slices]: ../../std/primitive.slice.html
3292 #[stable(feature = "rust1", since = "1.0.0")]
3293 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3299 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3300 impl<T: fmt::Debug, P> fmt::Debug for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3302 f.debug_struct("SplitMut")
3303 .field("v", &self.v)
3304 .field("finished", &self.finished)
3309 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3311 fn finish(&mut self) -> Option<&'a mut [T]> {
3315 self.finished = true;
3316 Some(mem::replace(&mut self.v, &mut []))
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3323 type Item = &'a mut [T];
3326 fn next(&mut self) -> Option<&'a mut [T]> {
3327 if self.finished { return None; }
3329 let idx_opt = { // work around borrowck limitations
3330 let pred = &mut self.pred;
3331 self.v.iter().position(|x| (*pred)(x))
3334 None => self.finish(),
3336 let tmp = mem::replace(&mut self.v, &mut []);
3337 let (head, tail) = tmp.split_at_mut(idx);
3338 self.v = &mut tail[1..];
3345 fn size_hint(&self) -> (usize, Option<usize>) {
3349 // if the predicate doesn't match anything, we yield one slice
3350 // if it matches every element, we yield len+1 empty slices.
3351 (1, Some(self.v.len() + 1))
3356 #[stable(feature = "rust1", since = "1.0.0")]
3357 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3358 P: FnMut(&T) -> bool,
3361 fn next_back(&mut self) -> Option<&'a mut [T]> {
3362 if self.finished { return None; }
3364 let idx_opt = { // work around borrowck limitations
3365 let pred = &mut self.pred;
3366 self.v.iter().rposition(|x| (*pred)(x))
3369 None => self.finish(),
3371 let tmp = mem::replace(&mut self.v, &mut []);
3372 let (head, tail) = tmp.split_at_mut(idx);
3374 Some(&mut tail[1..])
3380 #[stable(feature = "fused", since = "1.26.0")]
3381 impl<T, P> FusedIterator for SplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3383 /// An iterator over subslices separated by elements that match a predicate
3384 /// function, starting from the end of the slice.
3386 /// This struct is created by the [`rsplit`] method on [slices].
3388 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3389 /// [slices]: ../../std/primitive.slice.html
3390 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3391 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3392 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3393 inner: Split<'a, T, P>
3396 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3397 impl<T: fmt::Debug, P> fmt::Debug for RSplit<'_, T, P> where P: FnMut(&T) -> bool {
3398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3399 f.debug_struct("RSplit")
3400 .field("v", &self.inner.v)
3401 .field("finished", &self.inner.finished)
3406 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3407 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3408 type Item = &'a [T];
3411 fn next(&mut self) -> Option<&'a [T]> {
3412 self.inner.next_back()
3416 fn size_hint(&self) -> (usize, Option<usize>) {
3417 self.inner.size_hint()
3421 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3422 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3424 fn next_back(&mut self) -> Option<&'a [T]> {
3429 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3430 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3432 fn finish(&mut self) -> Option<&'a [T]> {
3437 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3438 impl<T, P> FusedIterator for RSplit<'_, T, P> where P: FnMut(&T) -> bool {}
3440 /// An iterator over the subslices of the vector which are separated
3441 /// by elements that match `pred`, starting from the end of the slice.
3443 /// This struct is created by the [`rsplit_mut`] method on [slices].
3445 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3446 /// [slices]: ../../std/primitive.slice.html
3447 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3448 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3449 inner: SplitMut<'a, T, P>
3452 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3453 impl<T: fmt::Debug, P> fmt::Debug for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {
3454 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3455 f.debug_struct("RSplitMut")
3456 .field("v", &self.inner.v)
3457 .field("finished", &self.inner.finished)
3462 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3463 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3465 fn finish(&mut self) -> Option<&'a mut [T]> {
3470 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3471 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3472 type Item = &'a mut [T];
3475 fn next(&mut self) -> Option<&'a mut [T]> {
3476 self.inner.next_back()
3480 fn size_hint(&self) -> (usize, Option<usize>) {
3481 self.inner.size_hint()
3485 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3486 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3487 P: FnMut(&T) -> bool,
3490 fn next_back(&mut self) -> Option<&'a mut [T]> {
3495 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3496 impl<T, P> FusedIterator for RSplitMut<'_, T, P> where P: FnMut(&T) -> bool {}
3498 /// An private iterator over subslices separated by elements that
3499 /// match a predicate function, splitting at most a fixed number of
3502 struct GenericSplitN<I> {
3507 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3511 fn next(&mut self) -> Option<T> {
3514 1 => { self.count -= 1; self.iter.finish() }
3515 _ => { self.count -= 1; self.iter.next() }
3520 fn size_hint(&self) -> (usize, Option<usize>) {
3521 let (lower, upper_opt) = self.iter.size_hint();
3522 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3526 /// An iterator over subslices separated by elements that match a predicate
3527 /// function, limited to a given number of splits.
3529 /// This struct is created by the [`splitn`] method on [slices].
3531 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3532 /// [slices]: ../../std/primitive.slice.html
3533 #[stable(feature = "rust1", since = "1.0.0")]
3534 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3535 inner: GenericSplitN<Split<'a, T, P>>
3538 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3539 impl<T: fmt::Debug, P> fmt::Debug for SplitN<'_, T, P> where P: FnMut(&T) -> bool {
3540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3541 f.debug_struct("SplitN")
3542 .field("inner", &self.inner)
3547 /// An iterator over subslices separated by elements that match a
3548 /// predicate function, limited to a given number of splits, starting
3549 /// from the end of the slice.
3551 /// This struct is created by the [`rsplitn`] method on [slices].
3553 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3554 /// [slices]: ../../std/primitive.slice.html
3555 #[stable(feature = "rust1", since = "1.0.0")]
3556 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3557 inner: GenericSplitN<RSplit<'a, T, P>>
3560 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3561 impl<T: fmt::Debug, P> fmt::Debug for RSplitN<'_, T, P> where P: FnMut(&T) -> bool {
3562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563 f.debug_struct("RSplitN")
3564 .field("inner", &self.inner)
3569 /// An iterator over subslices separated by elements that match a predicate
3570 /// function, limited to a given number of splits.
3572 /// This struct is created by the [`splitn_mut`] method on [slices].
3574 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3575 /// [slices]: ../../std/primitive.slice.html
3576 #[stable(feature = "rust1", since = "1.0.0")]
3577 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3578 inner: GenericSplitN<SplitMut<'a, T, P>>
3581 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3582 impl<T: fmt::Debug, P> fmt::Debug for SplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3583 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3584 f.debug_struct("SplitNMut")
3585 .field("inner", &self.inner)
3590 /// An iterator over subslices separated by elements that match a
3591 /// predicate function, limited to a given number of splits, starting
3592 /// from the end of the slice.
3594 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3596 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3597 /// [slices]: ../../std/primitive.slice.html
3598 #[stable(feature = "rust1", since = "1.0.0")]
3599 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3600 inner: GenericSplitN<RSplitMut<'a, T, P>>
3603 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3604 impl<T: fmt::Debug, P> fmt::Debug for RSplitNMut<'_, T, P> where P: FnMut(&T) -> bool {
3605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3606 f.debug_struct("RSplitNMut")
3607 .field("inner", &self.inner)
3612 macro_rules! forward_iterator {
3613 ($name:ident: $elem:ident, $iter_of:ty) => {
3614 #[stable(feature = "rust1", since = "1.0.0")]
3615 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3616 P: FnMut(&T) -> bool
3618 type Item = $iter_of;
3621 fn next(&mut self) -> Option<$iter_of> {
3626 fn size_hint(&self) -> (usize, Option<usize>) {
3627 self.inner.size_hint()
3631 #[stable(feature = "fused", since = "1.26.0")]
3632 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3633 where P: FnMut(&T) -> bool {}
3637 forward_iterator! { SplitN: T, &'a [T] }
3638 forward_iterator! { RSplitN: T, &'a [T] }
3639 forward_iterator! { SplitNMut: T, &'a mut [T] }
3640 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3642 /// An iterator over overlapping subslices of length `size`.
3644 /// This struct is created by the [`windows`] method on [slices].
3646 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3647 /// [slices]: ../../std/primitive.slice.html
3649 #[stable(feature = "rust1", since = "1.0.0")]
3650 pub struct Windows<'a, T:'a> {
3655 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3656 #[stable(feature = "rust1", since = "1.0.0")]
3657 impl<T> Clone for Windows<'_, T> {
3658 fn clone(&self) -> Self {
3666 #[stable(feature = "rust1", since = "1.0.0")]
3667 impl<'a, T> Iterator for Windows<'a, T> {
3668 type Item = &'a [T];
3671 fn next(&mut self) -> Option<&'a [T]> {
3672 if self.size > self.v.len() {
3675 let ret = Some(&self.v[..self.size]);
3676 self.v = &self.v[1..];
3682 fn size_hint(&self) -> (usize, Option<usize>) {
3683 if self.size > self.v.len() {
3686 let size = self.v.len() - self.size + 1;
3692 fn count(self) -> usize {
3697 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3698 let (end, overflow) = self.size.overflowing_add(n);
3699 if end > self.v.len() || overflow {
3703 let nth = &self.v[n..end];
3704 self.v = &self.v[n+1..];
3710 fn last(self) -> Option<Self::Item> {
3711 if self.size > self.v.len() {
3714 let start = self.v.len() - self.size;
3715 Some(&self.v[start..])
3720 #[stable(feature = "rust1", since = "1.0.0")]
3721 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3723 fn next_back(&mut self) -> Option<&'a [T]> {
3724 if self.size > self.v.len() {
3727 let ret = Some(&self.v[self.v.len()-self.size..]);
3728 self.v = &self.v[..self.v.len()-1];
3734 #[stable(feature = "rust1", since = "1.0.0")]
3735 impl<T> ExactSizeIterator for Windows<'_, T> {}
3737 #[unstable(feature = "trusted_len", issue = "37572")]
3738 unsafe impl<T> TrustedLen for Windows<'_, T> {}
3740 #[stable(feature = "fused", since = "1.26.0")]
3741 impl<T> FusedIterator for Windows<'_, T> {}
3744 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3745 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3746 from_raw_parts(self.v.as_ptr().add(i), self.size)
3748 fn may_have_side_effect() -> bool { false }
3751 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3752 /// time), starting at the beginning of the slice.
3754 /// When the slice len is not evenly divided by the chunk size, the last slice
3755 /// of the iteration will be the remainder.
3757 /// This struct is created by the [`chunks`] method on [slices].
3759 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3760 /// [slices]: ../../std/primitive.slice.html
3762 #[stable(feature = "rust1", since = "1.0.0")]
3763 pub struct Chunks<'a, T:'a> {
3768 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3769 #[stable(feature = "rust1", since = "1.0.0")]
3770 impl<T> Clone for Chunks<'_, T> {
3771 fn clone(&self) -> Self {
3774 chunk_size: self.chunk_size,
3779 #[stable(feature = "rust1", since = "1.0.0")]
3780 impl<'a, T> Iterator for Chunks<'a, T> {
3781 type Item = &'a [T];
3784 fn next(&mut self) -> Option<&'a [T]> {
3785 if self.v.is_empty() {
3788 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3789 let (fst, snd) = self.v.split_at(chunksz);
3796 fn size_hint(&self) -> (usize, Option<usize>) {
3797 if self.v.is_empty() {
3800 let n = self.v.len() / self.chunk_size;
3801 let rem = self.v.len() % self.chunk_size;
3802 let n = if rem > 0 { n+1 } else { n };
3808 fn count(self) -> usize {
3813 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3814 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3815 if start >= self.v.len() || overflow {
3819 let end = match start.checked_add(self.chunk_size) {
3820 Some(sum) => cmp::min(self.v.len(), sum),
3821 None => self.v.len(),
3823 let nth = &self.v[start..end];
3824 self.v = &self.v[end..];
3830 fn last(self) -> Option<Self::Item> {
3831 if self.v.is_empty() {
3834 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3835 Some(&self.v[start..])
3840 #[stable(feature = "rust1", since = "1.0.0")]
3841 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3843 fn next_back(&mut self) -> Option<&'a [T]> {
3844 if self.v.is_empty() {
3847 let remainder = self.v.len() % self.chunk_size;
3848 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3849 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3856 #[stable(feature = "rust1", since = "1.0.0")]
3857 impl<T> ExactSizeIterator for Chunks<'_, T> {}
3859 #[unstable(feature = "trusted_len", issue = "37572")]
3860 unsafe impl<T> TrustedLen for Chunks<'_, T> {}
3862 #[stable(feature = "fused", since = "1.26.0")]
3863 impl<T> FusedIterator for Chunks<'_, T> {}
3866 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3867 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3868 let start = i * self.chunk_size;
3869 let end = match start.checked_add(self.chunk_size) {
3870 None => self.v.len(),
3871 Some(end) => cmp::min(end, self.v.len()),
3873 from_raw_parts(self.v.as_ptr().add(start), end - start)
3875 fn may_have_side_effect() -> bool { false }
3878 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3879 /// elements at a time), starting at the beginning of the slice.
3881 /// When the slice len is not evenly divided by the chunk size, the last slice
3882 /// of the iteration will be the remainder.
3884 /// This struct is created by the [`chunks_mut`] method on [slices].
3886 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3887 /// [slices]: ../../std/primitive.slice.html
3889 #[stable(feature = "rust1", since = "1.0.0")]
3890 pub struct ChunksMut<'a, T:'a> {
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 impl<'a, T> Iterator for ChunksMut<'a, T> {
3897 type Item = &'a mut [T];
3900 fn next(&mut self) -> Option<&'a mut [T]> {
3901 if self.v.is_empty() {
3904 let sz = cmp::min(self.v.len(), self.chunk_size);
3905 let tmp = mem::replace(&mut self.v, &mut []);
3906 let (head, tail) = tmp.split_at_mut(sz);
3913 fn size_hint(&self) -> (usize, Option<usize>) {
3914 if self.v.is_empty() {
3917 let n = self.v.len() / self.chunk_size;
3918 let rem = self.v.len() % self.chunk_size;
3919 let n = if rem > 0 { n + 1 } else { n };
3925 fn count(self) -> usize {
3930 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3931 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3932 if start >= self.v.len() || overflow {
3936 let end = match start.checked_add(self.chunk_size) {
3937 Some(sum) => cmp::min(self.v.len(), sum),
3938 None => self.v.len(),
3940 let tmp = mem::replace(&mut self.v, &mut []);
3941 let (head, tail) = tmp.split_at_mut(end);
3942 let (_, nth) = head.split_at_mut(start);
3949 fn last(self) -> Option<Self::Item> {
3950 if self.v.is_empty() {
3953 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3954 Some(&mut self.v[start..])
3959 #[stable(feature = "rust1", since = "1.0.0")]
3960 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3962 fn next_back(&mut self) -> Option<&'a mut [T]> {
3963 if self.v.is_empty() {
3966 let remainder = self.v.len() % self.chunk_size;
3967 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3968 let tmp = mem::replace(&mut self.v, &mut []);
3969 let tmp_len = tmp.len();
3970 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3977 #[stable(feature = "rust1", since = "1.0.0")]
3978 impl<T> ExactSizeIterator for ChunksMut<'_, T> {}
3980 #[unstable(feature = "trusted_len", issue = "37572")]
3981 unsafe impl<T> TrustedLen for ChunksMut<'_, T> {}
3983 #[stable(feature = "fused", since = "1.26.0")]
3984 impl<T> FusedIterator for ChunksMut<'_, T> {}
3987 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3988 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3989 let start = i * self.chunk_size;
3990 let end = match start.checked_add(self.chunk_size) {
3991 None => self.v.len(),
3992 Some(end) => cmp::min(end, self.v.len()),
3994 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
3996 fn may_have_side_effect() -> bool { false }
3999 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4000 /// time), starting at the beginning of the slice.
4002 /// When the slice len is not evenly divided by the chunk size, the last
4003 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4004 /// the [`remainder`] function from the iterator.
4006 /// This struct is created by the [`chunks_exact`] method on [slices].
4008 /// [`chunks_exact`]: ../../std/primitive.slice.html#method.chunks_exact
4009 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4010 /// [slices]: ../../std/primitive.slice.html
4012 #[stable(feature = "chunks_exact", since = "1.31.0")]
4013 pub struct ChunksExact<'a, T:'a> {
4019 impl<'a, T> ChunksExact<'a, T> {
4020 /// Return the remainder of the original slice that is not going to be
4021 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4023 #[stable(feature = "chunks_exact", since = "1.31.0")]
4024 pub fn remainder(&self) -> &'a [T] {
4029 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4030 #[stable(feature = "chunks_exact", since = "1.31.0")]
4031 impl<T> Clone for ChunksExact<'_, T> {
4032 fn clone(&self) -> Self {
4036 chunk_size: self.chunk_size,
4041 #[stable(feature = "chunks_exact", since = "1.31.0")]
4042 impl<'a, T> Iterator for ChunksExact<'a, T> {
4043 type Item = &'a [T];
4046 fn next(&mut self) -> Option<&'a [T]> {
4047 if self.v.len() < self.chunk_size {
4050 let (fst, snd) = self.v.split_at(self.chunk_size);
4057 fn size_hint(&self) -> (usize, Option<usize>) {
4058 let n = self.v.len() / self.chunk_size;
4063 fn count(self) -> usize {
4068 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4069 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4070 if start >= self.v.len() || overflow {
4074 let (_, snd) = self.v.split_at(start);
4081 fn last(mut self) -> Option<Self::Item> {
4086 #[stable(feature = "chunks_exact", since = "1.31.0")]
4087 impl<'a, T> DoubleEndedIterator for ChunksExact<'a, T> {
4089 fn next_back(&mut self) -> Option<&'a [T]> {
4090 if self.v.len() < self.chunk_size {
4093 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4100 #[stable(feature = "chunks_exact", since = "1.31.0")]
4101 impl<T> ExactSizeIterator for ChunksExact<'_, T> {
4102 fn is_empty(&self) -> bool {
4107 #[unstable(feature = "trusted_len", issue = "37572")]
4108 unsafe impl<T> TrustedLen for ChunksExact<'_, T> {}
4110 #[stable(feature = "chunks_exact", since = "1.31.0")]
4111 impl<T> FusedIterator for ChunksExact<'_, T> {}
4114 #[stable(feature = "chunks_exact", since = "1.31.0")]
4115 unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> {
4116 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4117 let start = i * self.chunk_size;
4118 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4120 fn may_have_side_effect() -> bool { false }
4123 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4124 /// elements at a time), starting at the beginning of the slice.
4126 /// When the slice len is not evenly divided by the chunk size, the last up to
4127 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4128 /// [`into_remainder`] function from the iterator.
4130 /// This struct is created by the [`chunks_exact_mut`] method on [slices].
4132 /// [`chunks_exact_mut`]: ../../std/primitive.slice.html#method.chunks_exact_mut
4133 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4134 /// [slices]: ../../std/primitive.slice.html
4136 #[stable(feature = "chunks_exact", since = "1.31.0")]
4137 pub struct ChunksExactMut<'a, T:'a> {
4143 impl<'a, T> ChunksExactMut<'a, T> {
4144 /// Return the remainder of the original slice that is not going to be
4145 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4147 #[stable(feature = "chunks_exact", since = "1.31.0")]
4148 pub fn into_remainder(self) -> &'a mut [T] {
4153 #[stable(feature = "chunks_exact", since = "1.31.0")]
4154 impl<'a, T> Iterator for ChunksExactMut<'a, T> {
4155 type Item = &'a mut [T];
4158 fn next(&mut self) -> Option<&'a mut [T]> {
4159 if self.v.len() < self.chunk_size {
4162 let tmp = mem::replace(&mut self.v, &mut []);
4163 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4170 fn size_hint(&self) -> (usize, Option<usize>) {
4171 let n = self.v.len() / self.chunk_size;
4176 fn count(self) -> usize {
4181 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4182 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4183 if start >= self.v.len() || overflow {
4187 let tmp = mem::replace(&mut self.v, &mut []);
4188 let (_, snd) = tmp.split_at_mut(start);
4195 fn last(mut self) -> Option<Self::Item> {
4200 #[stable(feature = "chunks_exact", since = "1.31.0")]
4201 impl<'a, T> DoubleEndedIterator for ChunksExactMut<'a, T> {
4203 fn next_back(&mut self) -> Option<&'a mut [T]> {
4204 if self.v.len() < self.chunk_size {
4207 let tmp = mem::replace(&mut self.v, &mut []);
4208 let tmp_len = tmp.len();
4209 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4216 #[stable(feature = "chunks_exact", since = "1.31.0")]
4217 impl<T> ExactSizeIterator for ChunksExactMut<'_, T> {
4218 fn is_empty(&self) -> bool {
4223 #[unstable(feature = "trusted_len", issue = "37572")]
4224 unsafe impl<T> TrustedLen for ChunksExactMut<'_, T> {}
4226 #[stable(feature = "chunks_exact", since = "1.31.0")]
4227 impl<T> FusedIterator for ChunksExactMut<'_, T> {}
4230 #[stable(feature = "chunks_exact", since = "1.31.0")]
4231 unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> {
4232 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4233 let start = i * self.chunk_size;
4234 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4236 fn may_have_side_effect() -> bool { false }
4239 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4240 /// time), starting at the end of the slice.
4242 /// When the slice len is not evenly divided by the chunk size, the last slice
4243 /// of the iteration will be the remainder.
4245 /// This struct is created by the [`rchunks`] method on [slices].
4247 /// [`rchunks`]: ../../std/primitive.slice.html#method.rchunks
4248 /// [slices]: ../../std/primitive.slice.html
4250 #[stable(feature = "rchunks", since = "1.31.0")]
4251 pub struct RChunks<'a, T:'a> {
4256 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4257 #[stable(feature = "rchunks", since = "1.31.0")]
4258 impl<'a, T> Clone for RChunks<'a, T> {
4259 fn clone(&self) -> RChunks<'a, T> {
4262 chunk_size: self.chunk_size,
4267 #[stable(feature = "rchunks", since = "1.31.0")]
4268 impl<'a, T> Iterator for RChunks<'a, T> {
4269 type Item = &'a [T];
4272 fn next(&mut self) -> Option<&'a [T]> {
4273 if self.v.is_empty() {
4276 let chunksz = cmp::min(self.v.len(), self.chunk_size);
4277 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
4284 fn size_hint(&self) -> (usize, Option<usize>) {
4285 if self.v.is_empty() {
4288 let n = self.v.len() / self.chunk_size;
4289 let rem = self.v.len() % self.chunk_size;
4290 let n = if rem > 0 { n+1 } else { n };
4296 fn count(self) -> usize {
4301 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4302 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4303 if end >= self.v.len() || overflow {
4307 // Can't underflow because of the check above
4308 let end = self.v.len() - end;
4309 let start = match end.checked_sub(self.chunk_size) {
4313 let nth = &self.v[start..end];
4314 self.v = &self.v[0..start];
4320 fn last(self) -> Option<Self::Item> {
4321 if self.v.is_empty() {
4324 let rem = self.v.len() % self.chunk_size;
4325 let end = if rem == 0 { self.chunk_size } else { rem };
4326 Some(&self.v[0..end])
4331 #[stable(feature = "rchunks", since = "1.31.0")]
4332 impl<'a, T> DoubleEndedIterator for RChunks<'a, T> {
4334 fn next_back(&mut self) -> Option<&'a [T]> {
4335 if self.v.is_empty() {
4338 let remainder = self.v.len() % self.chunk_size;
4339 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
4340 let (fst, snd) = self.v.split_at(chunksz);
4347 #[stable(feature = "rchunks", since = "1.31.0")]
4348 impl<'a, T> ExactSizeIterator for RChunks<'a, T> {}
4350 #[unstable(feature = "trusted_len", issue = "37572")]
4351 unsafe impl<'a, T> TrustedLen for RChunks<'a, T> {}
4353 #[stable(feature = "rchunks", since = "1.31.0")]
4354 impl<'a, T> FusedIterator for RChunks<'a, T> {}
4357 #[stable(feature = "rchunks", since = "1.31.0")]
4358 unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> {
4359 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4360 let end = self.v.len() - i * self.chunk_size;
4361 let start = match end.checked_sub(self.chunk_size) {
4363 Some(start) => start,
4365 from_raw_parts(self.v.as_ptr().add(start), end - start)
4367 fn may_have_side_effect() -> bool { false }
4370 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4371 /// elements at a time), starting at the end of the slice.
4373 /// When the slice len is not evenly divided by the chunk size, the last slice
4374 /// of the iteration will be the remainder.
4376 /// This struct is created by the [`rchunks_mut`] method on [slices].
4378 /// [`rchunks_mut`]: ../../std/primitive.slice.html#method.rchunks_mut
4379 /// [slices]: ../../std/primitive.slice.html
4381 #[stable(feature = "rchunks", since = "1.31.0")]
4382 pub struct RChunksMut<'a, T:'a> {
4387 #[stable(feature = "rchunks", since = "1.31.0")]
4388 impl<'a, T> Iterator for RChunksMut<'a, T> {
4389 type Item = &'a mut [T];
4392 fn next(&mut self) -> Option<&'a mut [T]> {
4393 if self.v.is_empty() {
4396 let sz = cmp::min(self.v.len(), self.chunk_size);
4397 let tmp = mem::replace(&mut self.v, &mut []);
4398 let tmp_len = tmp.len();
4399 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
4406 fn size_hint(&self) -> (usize, Option<usize>) {
4407 if self.v.is_empty() {
4410 let n = self.v.len() / self.chunk_size;
4411 let rem = self.v.len() % self.chunk_size;
4412 let n = if rem > 0 { n + 1 } else { n };
4418 fn count(self) -> usize {
4423 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4424 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4425 if end >= self.v.len() || overflow {
4429 // Can't underflow because of the check above
4430 let end = self.v.len() - end;
4431 let start = match end.checked_sub(self.chunk_size) {
4435 let tmp = mem::replace(&mut self.v, &mut []);
4436 let (head, tail) = tmp.split_at_mut(start);
4437 let (nth, _) = tail.split_at_mut(end - start);
4444 fn last(self) -> Option<Self::Item> {
4445 if self.v.is_empty() {
4448 let rem = self.v.len() % self.chunk_size;
4449 let end = if rem == 0 { self.chunk_size } else { rem };
4450 Some(&mut self.v[0..end])
4455 #[stable(feature = "rchunks", since = "1.31.0")]
4456 impl<'a, T> DoubleEndedIterator for RChunksMut<'a, T> {
4458 fn next_back(&mut self) -> Option<&'a mut [T]> {
4459 if self.v.is_empty() {
4462 let remainder = self.v.len() % self.chunk_size;
4463 let sz = if remainder != 0 { remainder } else { self.chunk_size };
4464 let tmp = mem::replace(&mut self.v, &mut []);
4465 let (head, tail) = tmp.split_at_mut(sz);
4472 #[stable(feature = "rchunks", since = "1.31.0")]
4473 impl<'a, T> ExactSizeIterator for RChunksMut<'a, T> {}
4475 #[unstable(feature = "trusted_len", issue = "37572")]
4476 unsafe impl<'a, T> TrustedLen for RChunksMut<'a, T> {}
4478 #[stable(feature = "rchunks", since = "1.31.0")]
4479 impl<'a, T> FusedIterator for RChunksMut<'a, T> {}
4482 #[stable(feature = "rchunks", since = "1.31.0")]
4483 unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> {
4484 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4485 let end = self.v.len() - i * self.chunk_size;
4486 let start = match end.checked_sub(self.chunk_size) {
4488 Some(start) => start,
4490 from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start)
4492 fn may_have_side_effect() -> bool { false }
4495 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
4496 /// time), starting at the end of the slice.
4498 /// When the slice len is not evenly divided by the chunk size, the last
4499 /// up to `chunk_size-1` elements will be omitted but can be retrieved from
4500 /// the [`remainder`] function from the iterator.
4502 /// This struct is created by the [`rchunks_exact`] method on [slices].
4504 /// [`rchunks_exact`]: ../../std/primitive.slice.html#method.rchunks_exact
4505 /// [`remainder`]: ../../std/slice/struct.ChunksExact.html#method.remainder
4506 /// [slices]: ../../std/primitive.slice.html
4508 #[stable(feature = "rchunks", since = "1.31.0")]
4509 pub struct RChunksExact<'a, T:'a> {
4515 impl<'a, T> RChunksExact<'a, T> {
4516 /// Return the remainder of the original slice that is not going to be
4517 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4519 #[stable(feature = "rchunks", since = "1.31.0")]
4520 pub fn remainder(&self) -> &'a [T] {
4525 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
4526 #[stable(feature = "rchunks", since = "1.31.0")]
4527 impl<'a, T> Clone for RChunksExact<'a, T> {
4528 fn clone(&self) -> RChunksExact<'a, T> {
4532 chunk_size: self.chunk_size,
4537 #[stable(feature = "rchunks", since = "1.31.0")]
4538 impl<'a, T> Iterator for RChunksExact<'a, T> {
4539 type Item = &'a [T];
4542 fn next(&mut self) -> Option<&'a [T]> {
4543 if self.v.len() < self.chunk_size {
4546 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4553 fn size_hint(&self) -> (usize, Option<usize>) {
4554 let n = self.v.len() / self.chunk_size;
4559 fn count(self) -> usize {
4564 fn nth(&mut self, n: usize) -> Option<Self::Item> {
4565 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4566 if end >= self.v.len() || overflow {
4570 let (fst, _) = self.v.split_at(self.v.len() - end);
4577 fn last(mut self) -> Option<Self::Item> {
4582 #[stable(feature = "rchunks", since = "1.31.0")]
4583 impl<'a, T> DoubleEndedIterator for RChunksExact<'a, T> {
4585 fn next_back(&mut self) -> Option<&'a [T]> {
4586 if self.v.len() < self.chunk_size {
4589 let (fst, snd) = self.v.split_at(self.chunk_size);
4596 #[stable(feature = "rchunks", since = "1.31.0")]
4597 impl<'a, T> ExactSizeIterator for RChunksExact<'a, T> {
4598 fn is_empty(&self) -> bool {
4603 #[unstable(feature = "trusted_len", issue = "37572")]
4604 unsafe impl<'a, T> TrustedLen for RChunksExact<'a, T> {}
4606 #[stable(feature = "rchunks", since = "1.31.0")]
4607 impl<'a, T> FusedIterator for RChunksExact<'a, T> {}
4610 #[stable(feature = "rchunks", since = "1.31.0")]
4611 unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> {
4612 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4613 let end = self.v.len() - i * self.chunk_size;
4614 let start = end - self.chunk_size;
4615 from_raw_parts(self.v.as_ptr().add(start), self.chunk_size)
4617 fn may_have_side_effect() -> bool { false }
4620 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4621 /// elements at a time), starting at the end of the slice.
4623 /// When the slice len is not evenly divided by the chunk size, the last up to
4624 /// `chunk_size-1` elements will be omitted but can be retrieved from the
4625 /// [`into_remainder`] function from the iterator.
4627 /// This struct is created by the [`rchunks_exact_mut`] method on [slices].
4629 /// [`rchunks_exact_mut`]: ../../std/primitive.slice.html#method.rchunks_exact_mut
4630 /// [`into_remainder`]: ../../std/slice/struct.ChunksExactMut.html#method.into_remainder
4631 /// [slices]: ../../std/primitive.slice.html
4633 #[stable(feature = "rchunks", since = "1.31.0")]
4634 pub struct RChunksExactMut<'a, T:'a> {
4640 impl<'a, T> RChunksExactMut<'a, T> {
4641 /// Return the remainder of the original slice that is not going to be
4642 /// returned by the iterator. The returned slice has at most `chunk_size-1`
4644 #[stable(feature = "rchunks", since = "1.31.0")]
4645 pub fn into_remainder(self) -> &'a mut [T] {
4650 #[stable(feature = "rchunks", since = "1.31.0")]
4651 impl<'a, T> Iterator for RChunksExactMut<'a, T> {
4652 type Item = &'a mut [T];
4655 fn next(&mut self) -> Option<&'a mut [T]> {
4656 if self.v.len() < self.chunk_size {
4659 let tmp = mem::replace(&mut self.v, &mut []);
4660 let tmp_len = tmp.len();
4661 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4668 fn size_hint(&self) -> (usize, Option<usize>) {
4669 let n = self.v.len() / self.chunk_size;
4674 fn count(self) -> usize {
4679 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4680 let (end, overflow) = n.overflowing_mul(self.chunk_size);
4681 if end >= self.v.len() || overflow {
4685 let tmp = mem::replace(&mut self.v, &mut []);
4686 let tmp_len = tmp.len();
4687 let (fst, _) = tmp.split_at_mut(tmp_len - end);
4694 fn last(mut self) -> Option<Self::Item> {
4699 #[stable(feature = "rchunks", since = "1.31.0")]
4700 impl<'a, T> DoubleEndedIterator for RChunksExactMut<'a, T> {
4702 fn next_back(&mut self) -> Option<&'a mut [T]> {
4703 if self.v.len() < self.chunk_size {
4706 let tmp = mem::replace(&mut self.v, &mut []);
4707 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4714 #[stable(feature = "rchunks", since = "1.31.0")]
4715 impl<'a, T> ExactSizeIterator for RChunksExactMut<'a, T> {
4716 fn is_empty(&self) -> bool {
4721 #[unstable(feature = "trusted_len", issue = "37572")]
4722 unsafe impl<'a, T> TrustedLen for RChunksExactMut<'a, T> {}
4724 #[stable(feature = "rchunks", since = "1.31.0")]
4725 impl<'a, T> FusedIterator for RChunksExactMut<'a, T> {}
4728 #[stable(feature = "rchunks", since = "1.31.0")]
4729 unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> {
4730 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4731 let end = self.v.len() - i * self.chunk_size;
4732 let start = end - self.chunk_size;
4733 from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size)
4735 fn may_have_side_effect() -> bool { false }
4742 /// Forms a slice from a pointer and a length.
4744 /// The `len` argument is the number of **elements**, not the number of bytes.
4748 /// This function is unsafe as there is no guarantee that the given pointer is
4749 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4750 /// lifetime for the returned slice.
4752 /// `data` must be non-null and aligned, even for zero-length slices. One
4753 /// reason for this is that enum layout optimizations may rely on references
4754 /// (including slices of any length) being aligned and non-null to distinguish
4755 /// them from other data. You can obtain a pointer that is usable as `data`
4756 /// for zero-length slices using [`NonNull::dangling()`].
4758 /// The total size of the slice must be no larger than `isize::MAX` **bytes**
4759 /// in memory. See the safety documentation of [`pointer::offset`].
4763 /// The lifetime for the returned slice is inferred from its usage. To
4764 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4765 /// source lifetime is safe in the context, such as by providing a helper
4766 /// function taking the lifetime of a host value for the slice, or by explicit
4774 /// // manifest a slice for a single element
4776 /// let ptr = &x as *const _;
4777 /// let slice = unsafe { slice::from_raw_parts(ptr, 1) };
4778 /// assert_eq!(slice[0], 42);
4781 /// [`NonNull::dangling()`]: ../../std/ptr/struct.NonNull.html#method.dangling
4782 /// [`pointer::offset`]: ../../std/primitive.pointer.html#method.offset
4784 #[stable(feature = "rust1", since = "1.0.0")]
4785 pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] {
4786 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4787 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4788 "attempt to create slice covering half the address space");
4789 Repr { raw: FatPtr { data, len } }.rust
4792 /// Performs the same functionality as [`from_raw_parts`], except that a
4793 /// mutable slice is returned.
4795 /// This function is unsafe for the same reasons as [`from_raw_parts`], as well
4796 /// as not being able to provide a non-aliasing guarantee of the returned
4797 /// mutable slice. `data` must be non-null and aligned even for zero-length
4798 /// slices as with [`from_raw_parts`]. The total size of the slice must be no
4799 /// larger than `isize::MAX` **bytes** in memory.
4801 /// See the documentation of [`from_raw_parts`] for more details.
4803 /// [`from_raw_parts`]: ../../std/slice/fn.from_raw_parts.html
4805 #[stable(feature = "rust1", since = "1.0.0")]
4806 pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] {
4807 debug_assert!(data as usize % mem::align_of::<T>() == 0, "attempt to create unaligned slice");
4808 debug_assert!(mem::size_of::<T>().saturating_mul(len) <= isize::MAX as usize,
4809 "attempt to create slice covering half the address space");
4810 Repr { raw: FatPtr { data, len } }.rust_mut
4813 /// Converts a reference to T into a slice of length 1 (without copying).
4814 #[stable(feature = "from_ref", since = "1.28.0")]
4815 pub fn from_ref<T>(s: &T) -> &[T] {
4817 from_raw_parts(s, 1)
4821 /// Converts a reference to T into a slice of length 1 (without copying).
4822 #[stable(feature = "from_ref", since = "1.28.0")]
4823 pub fn from_mut<T>(s: &mut T) -> &mut [T] {
4825 from_raw_parts_mut(s, 1)
4829 // This function is public only because there is no other way to unit test heapsort.
4830 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4832 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4833 where F: FnMut(&T, &T) -> bool
4835 sort::heapsort(v, &mut is_less);
4839 // Comparison traits
4843 /// Calls implementation provided memcmp.
4845 /// Interprets the data as u8.
4847 /// Returns 0 for equal, < 0 for less than and > 0 for greater
4849 // FIXME(#32610): Return type should be c_int
4850 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4853 #[stable(feature = "rust1", since = "1.0.0")]
4854 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4855 fn eq(&self, other: &[B]) -> bool {
4856 SlicePartialEq::equal(self, other)
4859 fn ne(&self, other: &[B]) -> bool {
4860 SlicePartialEq::not_equal(self, other)
4864 #[stable(feature = "rust1", since = "1.0.0")]
4865 impl<T: Eq> Eq for [T] {}
4867 /// Implements comparison of vectors lexicographically.
4868 #[stable(feature = "rust1", since = "1.0.0")]
4869 impl<T: Ord> Ord for [T] {
4870 fn cmp(&self, other: &[T]) -> Ordering {
4871 SliceOrd::compare(self, other)
4875 /// Implements comparison of vectors lexicographically.
4876 #[stable(feature = "rust1", since = "1.0.0")]
4877 impl<T: PartialOrd> PartialOrd for [T] {
4878 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4879 SlicePartialOrd::partial_compare(self, other)
4884 // intermediate trait for specialization of slice's PartialEq
4885 trait SlicePartialEq<B> {
4886 fn equal(&self, other: &[B]) -> bool;
4888 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4891 // Generic slice equality
4892 impl<A, B> SlicePartialEq<B> for [A]
4893 where A: PartialEq<B>
4895 default fn equal(&self, other: &[B]) -> bool {
4896 if self.len() != other.len() {
4900 for i in 0..self.len() {
4901 if !self[i].eq(&other[i]) {
4910 // Use memcmp for bytewise equality when the types allow
4911 impl<A> SlicePartialEq<A> for [A]
4912 where A: PartialEq<A> + BytewiseEquality
4914 fn equal(&self, other: &[A]) -> bool {
4915 if self.len() != other.len() {
4918 if self.as_ptr() == other.as_ptr() {
4922 let size = mem::size_of_val(self);
4923 memcmp(self.as_ptr() as *const u8,
4924 other.as_ptr() as *const u8, size) == 0
4930 // intermediate trait for specialization of slice's PartialOrd
4931 trait SlicePartialOrd<B> {
4932 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4935 impl<A> SlicePartialOrd<A> for [A]
4938 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4939 let l = cmp::min(self.len(), other.len());
4941 // Slice to the loop iteration range to enable bound check
4942 // elimination in the compiler
4943 let lhs = &self[..l];
4944 let rhs = &other[..l];
4947 match lhs[i].partial_cmp(&rhs[i]) {
4948 Some(Ordering::Equal) => (),
4949 non_eq => return non_eq,
4953 self.len().partial_cmp(&other.len())
4957 impl<A> SlicePartialOrd<A> for [A]
4960 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4961 Some(SliceOrd::compare(self, other))
4966 // intermediate trait for specialization of slice's Ord
4968 fn compare(&self, other: &[B]) -> Ordering;
4971 impl<A> SliceOrd<A> for [A]
4974 default fn compare(&self, other: &[A]) -> Ordering {
4975 let l = cmp::min(self.len(), other.len());
4977 // Slice to the loop iteration range to enable bound check
4978 // elimination in the compiler
4979 let lhs = &self[..l];
4980 let rhs = &other[..l];
4983 match lhs[i].cmp(&rhs[i]) {
4984 Ordering::Equal => (),
4985 non_eq => return non_eq,
4989 self.len().cmp(&other.len())
4993 // memcmp compares a sequence of unsigned bytes lexicographically.
4994 // this matches the order we want for [u8], but no others (not even [i8]).
4995 impl SliceOrd<u8> for [u8] {
4997 fn compare(&self, other: &[u8]) -> Ordering {
4998 let order = unsafe {
4999 memcmp(self.as_ptr(), other.as_ptr(),
5000 cmp::min(self.len(), other.len()))
5003 self.len().cmp(&other.len())
5004 } else if order < 0 {
5013 /// Trait implemented for types that can be compared for equality using
5014 /// their bytewise representation
5015 trait BytewiseEquality { }
5017 macro_rules! impl_marker_for {
5018 ($traitname:ident, $($ty:ty)*) => {
5020 impl $traitname for $ty { }
5025 impl_marker_for!(BytewiseEquality,
5026 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
5029 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
5030 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
5033 fn may_have_side_effect() -> bool { false }
5037 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
5038 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
5039 &mut *self.ptr.add(i)
5041 fn may_have_side_effect() -> bool { false }
5044 trait SliceContains: Sized {
5045 fn slice_contains(&self, x: &[Self]) -> bool;
5048 impl<T> SliceContains for T where T: PartialEq {
5049 default fn slice_contains(&self, x: &[Self]) -> bool {
5050 x.iter().any(|y| *y == *self)
5054 impl SliceContains for u8 {
5055 fn slice_contains(&self, x: &[Self]) -> bool {
5056 memchr::memchr(*self, x).is_some()
5060 impl SliceContains for i8 {
5061 fn slice_contains(&self, x: &[Self]) -> bool {
5062 let byte = *self as u8;
5063 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
5064 memchr::memchr(byte, bytes).is_some()