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 // Since slices don't support inherent methods; all operations
25 // on them are defined on traits, which are then re-exported from
26 // the prelude for convenience. So there are a lot of traits here.
28 // The layout of this file is thus:
30 // * Slice-specific 'extension' traits and their implementations. This
31 // is where most of the slice API resides.
32 // * Implementations of a few common traits with important slice ops.
33 // * Definitions of a bunch of iterators.
35 // * The `raw` and `bytes` submodules.
36 // * Boilerplate trait implementations.
38 use cmp::Ordering::{self, Less, Equal, Greater};
41 use intrinsics::assume;
43 use ops::{FnMut, Try, self};
45 use option::Option::{None, Some};
47 use result::Result::{Ok, Err};
50 use marker::{Copy, Send, Sync, Sized, self};
51 use iter_private::TrustedRandomAccess;
53 #[unstable(feature = "slice_internals", issue = "0",
54 reason = "exposed from core to be reused in std; use the memchr crate")]
55 /// Pure rust memchr implementation, taken from rust-memchr
71 // Use macros to be generic over const/mut
72 macro_rules! slice_offset {
73 ($ptr:expr, $by:expr) => {{
75 if size_from_ptr(ptr) == 0 {
76 (ptr as *mut i8).wrapping_offset($by) as _
83 // make a &T from a *const T
84 macro_rules! make_ref {
87 if size_from_ptr(ptr) == 0 {
88 // Use a non-null pointer value
96 // make a &mut T from a *mut T
97 macro_rules! make_ref_mut {
100 if size_from_ptr(ptr) == 0 {
101 // Use a non-null pointer value
112 /// Returns the number of elements in the slice.
117 /// let a = [1, 2, 3];
118 /// assert_eq!(a.len(), 3);
120 #[stable(feature = "rust1", since = "1.0.0")]
122 pub fn len(&self) -> usize {
124 mem::transmute::<&[T], Repr<T>>(self).len
128 /// Returns `true` if the slice has a length of 0.
133 /// let a = [1, 2, 3];
134 /// assert!(!a.is_empty());
136 #[stable(feature = "rust1", since = "1.0.0")]
138 pub fn is_empty(&self) -> bool {
142 /// Returns the first element of the slice, or `None` if it is empty.
147 /// let v = [10, 40, 30];
148 /// assert_eq!(Some(&10), v.first());
150 /// let w: &[i32] = &[];
151 /// assert_eq!(None, w.first());
153 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn first(&self) -> Option<&T> {
156 if self.is_empty() { None } else { Some(&self[0]) }
159 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
164 /// let x = &mut [0, 1, 2];
166 /// if let Some(first) = x.first_mut() {
169 /// assert_eq!(x, &[5, 1, 2]);
171 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn first_mut(&mut self) -> Option<&mut T> {
174 if self.is_empty() { None } else { Some(&mut self[0]) }
177 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
182 /// let x = &[0, 1, 2];
184 /// if let Some((first, elements)) = x.split_first() {
185 /// assert_eq!(first, &0);
186 /// assert_eq!(elements, &[1, 2]);
189 #[stable(feature = "slice_splits", since = "1.5.0")]
191 pub fn split_first(&self) -> Option<(&T, &[T])> {
192 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
195 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
200 /// let x = &mut [0, 1, 2];
202 /// if let Some((first, elements)) = x.split_first_mut() {
207 /// assert_eq!(x, &[3, 4, 5]);
209 #[stable(feature = "slice_splits", since = "1.5.0")]
211 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
212 if self.is_empty() { None } else {
213 let split = self.split_at_mut(1);
214 Some((&mut split.0[0], split.1))
218 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
223 /// let x = &[0, 1, 2];
225 /// if let Some((last, elements)) = x.split_last() {
226 /// assert_eq!(last, &2);
227 /// assert_eq!(elements, &[0, 1]);
230 #[stable(feature = "slice_splits", since = "1.5.0")]
232 pub fn split_last(&self) -> Option<(&T, &[T])> {
233 let len = self.len();
234 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
237 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
242 /// let x = &mut [0, 1, 2];
244 /// if let Some((last, elements)) = x.split_last_mut() {
249 /// assert_eq!(x, &[4, 5, 3]);
251 #[stable(feature = "slice_splits", since = "1.5.0")]
253 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
254 let len = self.len();
255 if len == 0 { None } else {
256 let split = self.split_at_mut(len - 1);
257 Some((&mut split.1[0], split.0))
262 /// Returns the last element of the slice, or `None` if it is empty.
267 /// let v = [10, 40, 30];
268 /// assert_eq!(Some(&30), v.last());
270 /// let w: &[i32] = &[];
271 /// assert_eq!(None, w.last());
273 #[stable(feature = "rust1", since = "1.0.0")]
275 pub fn last(&self) -> Option<&T> {
276 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
279 /// Returns a mutable pointer to the last item in the slice.
284 /// let x = &mut [0, 1, 2];
286 /// if let Some(last) = x.last_mut() {
289 /// assert_eq!(x, &[0, 1, 10]);
291 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn last_mut(&mut self) -> Option<&mut T> {
294 let len = self.len();
295 if len == 0 { return None; }
296 Some(&mut self[len - 1])
299 /// Returns a reference to an element or subslice depending on the type of
302 /// - If given a position, returns a reference to the element at that
303 /// position or `None` if out of bounds.
304 /// - If given a range, returns the subslice corresponding to that range,
305 /// or `None` if out of bounds.
310 /// let v = [10, 40, 30];
311 /// assert_eq!(Some(&40), v.get(1));
312 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
313 /// assert_eq!(None, v.get(3));
314 /// assert_eq!(None, v.get(0..4));
316 #[stable(feature = "rust1", since = "1.0.0")]
318 pub fn get<I>(&self, index: I) -> Option<&I::Output>
319 where I: SliceIndex<Self>
324 /// Returns a mutable reference to an element or subslice depending on the
325 /// type of index (see [`get`]) or `None` if the index is out of bounds.
327 /// [`get`]: #method.get
332 /// let x = &mut [0, 1, 2];
334 /// if let Some(elem) = x.get_mut(1) {
337 /// assert_eq!(x, &[0, 42, 2]);
339 #[stable(feature = "rust1", since = "1.0.0")]
341 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
342 where I: SliceIndex<Self>
347 /// Returns a reference to an element or subslice, without doing bounds
350 /// This is generally not recommended, use with caution! For a safe
351 /// alternative see [`get`].
353 /// [`get`]: #method.get
358 /// let x = &[1, 2, 4];
361 /// assert_eq!(x.get_unchecked(1), &2);
364 #[stable(feature = "rust1", since = "1.0.0")]
366 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
367 where I: SliceIndex<Self>
369 index.get_unchecked(self)
372 /// Returns a mutable reference to an element or subslice, without doing
375 /// This is generally not recommended, use with caution! For a safe
376 /// alternative see [`get_mut`].
378 /// [`get_mut`]: #method.get_mut
383 /// let x = &mut [1, 2, 4];
386 /// let elem = x.get_unchecked_mut(1);
389 /// assert_eq!(x, &[1, 13, 4]);
391 #[stable(feature = "rust1", since = "1.0.0")]
393 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
394 where I: SliceIndex<Self>
396 index.get_unchecked_mut(self)
399 /// Returns a raw pointer to the slice's buffer.
401 /// The caller must ensure that the slice outlives the pointer this
402 /// function returns, or else it will end up pointing to garbage.
404 /// Modifying the container referenced by this slice may cause its buffer
405 /// to be reallocated, which would also make any pointers to it invalid.
410 /// let x = &[1, 2, 4];
411 /// let x_ptr = x.as_ptr();
414 /// for i in 0..x.len() {
415 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
419 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn as_ptr(&self) -> *const T {
422 self as *const [T] as *const T
425 /// Returns an unsafe mutable pointer to the slice's buffer.
427 /// The caller must ensure that the slice outlives the pointer this
428 /// function returns, or else it will end up pointing to garbage.
430 /// Modifying the container referenced by this slice may cause its buffer
431 /// to be reallocated, which would also make any pointers to it invalid.
436 /// let x = &mut [1, 2, 4];
437 /// let x_ptr = x.as_mut_ptr();
440 /// for i in 0..x.len() {
441 /// *x_ptr.offset(i as isize) += 2;
444 /// assert_eq!(x, &[3, 4, 6]);
446 #[stable(feature = "rust1", since = "1.0.0")]
448 pub fn as_mut_ptr(&mut self) -> *mut T {
449 self as *mut [T] as *mut T
452 /// Swaps two elements in the slice.
456 /// * a - The index of the first element
457 /// * b - The index of the second element
461 /// Panics if `a` or `b` are out of bounds.
466 /// let mut v = ["a", "b", "c", "d"];
468 /// assert!(v == ["a", "d", "c", "b"]);
470 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn swap(&mut self, a: usize, b: usize) {
474 // Can't take two mutable loans from one vector, so instead just cast
475 // them to their raw pointers to do the swap
476 let pa: *mut T = &mut self[a];
477 let pb: *mut T = &mut self[b];
482 /// Reverses the order of elements in the slice, in place.
487 /// let mut v = [1, 2, 3];
489 /// assert!(v == [3, 2, 1]);
491 #[stable(feature = "rust1", since = "1.0.0")]
493 pub fn reverse(&mut self) {
494 let mut i: usize = 0;
497 // For very small types, all the individual reads in the normal
498 // path perform poorly. We can do better, given efficient unaligned
499 // load/store, by loading a larger chunk and reversing a register.
501 // Ideally LLVM would do this for us, as it knows better than we do
502 // whether unaligned reads are efficient (since that changes between
503 // different ARM versions, for example) and what the best chunk size
504 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
505 // the loop, so we need to do this ourselves. (Hypothesis: reverse
506 // is troublesome because the sides can be aligned differently --
507 // will be, when the length is odd -- so there's no way of emitting
508 // pre- and postludes to use fully-aligned SIMD in the middle.)
511 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
513 if fast_unaligned && mem::size_of::<T>() == 1 {
514 // Use the llvm.bswap intrinsic to reverse u8s in a usize
515 let chunk = mem::size_of::<usize>();
516 while i + chunk - 1 < ln / 2 {
518 let pa: *mut T = self.get_unchecked_mut(i);
519 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
520 let va = ptr::read_unaligned(pa as *mut usize);
521 let vb = ptr::read_unaligned(pb as *mut usize);
522 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
523 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
529 if fast_unaligned && mem::size_of::<T>() == 2 {
530 // Use rotate-by-16 to reverse u16s in a u32
531 let chunk = mem::size_of::<u32>() / 2;
532 while i + chunk - 1 < ln / 2 {
534 let pa: *mut T = self.get_unchecked_mut(i);
535 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
536 let va = ptr::read_unaligned(pa as *mut u32);
537 let vb = ptr::read_unaligned(pb as *mut u32);
538 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
539 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
546 // Unsafe swap to avoid the bounds check in safe swap.
548 let pa: *mut T = self.get_unchecked_mut(i);
549 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
556 /// Returns an iterator over the slice.
561 /// let x = &[1, 2, 4];
562 /// let mut iterator = x.iter();
564 /// assert_eq!(iterator.next(), Some(&1));
565 /// assert_eq!(iterator.next(), Some(&2));
566 /// assert_eq!(iterator.next(), Some(&4));
567 /// assert_eq!(iterator.next(), None);
569 #[stable(feature = "rust1", since = "1.0.0")]
571 pub fn iter(&self) -> Iter<T> {
573 let p = if mem::size_of::<T>() == 0 {
576 let p = self.as_ptr();
577 assume(!p.is_null());
583 end: slice_offset!(p, self.len() as isize),
584 _marker: marker::PhantomData
589 /// Returns an iterator that allows modifying each value.
594 /// let x = &mut [1, 2, 4];
595 /// for elem in x.iter_mut() {
598 /// assert_eq!(x, &[3, 4, 6]);
600 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn iter_mut(&mut self) -> IterMut<T> {
604 let p = if mem::size_of::<T>() == 0 {
607 let p = self.as_mut_ptr();
608 assume(!p.is_null());
614 end: slice_offset!(p, self.len() as isize),
615 _marker: marker::PhantomData
620 /// Returns an iterator over all contiguous windows of length
621 /// `size`. The windows overlap. If the slice is shorter than
622 /// `size`, the iterator returns no values.
626 /// Panics if `size` is 0.
631 /// let slice = ['r', 'u', 's', 't'];
632 /// let mut iter = slice.windows(2);
633 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
634 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
635 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
636 /// assert!(iter.next().is_none());
639 /// If the slice is shorter than `size`:
642 /// let slice = ['f', 'o', 'o'];
643 /// let mut iter = slice.windows(4);
644 /// assert!(iter.next().is_none());
646 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn windows(&self, size: usize) -> Windows<T> {
650 Windows { v: self, size: size }
653 /// Returns an iterator over `chunk_size` elements of the slice at a
654 /// time. The chunks are slices and do not overlap. If `chunk_size` does
655 /// not divide the length of the slice, then the last chunk will
656 /// not have length `chunk_size`.
658 /// See [`exact_chunks`] for a variant of this iterator that returns chunks
659 /// of always exactly `chunk_size` elements.
663 /// Panics if `chunk_size` is 0.
668 /// let slice = ['l', 'o', 'r', 'e', 'm'];
669 /// let mut iter = slice.chunks(2);
670 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
671 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
672 /// assert_eq!(iter.next().unwrap(), &['m']);
673 /// assert!(iter.next().is_none());
676 /// [`exact_chunks`]: #method.exact_chunks
677 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
680 assert!(chunk_size != 0);
681 Chunks { v: self, chunk_size: chunk_size }
684 /// Returns an iterator over `chunk_size` elements of the slice at a
685 /// time. The chunks are slices and do not overlap. If `chunk_size` does
686 /// not divide the length of the slice, then the last up to `chunk_size-1`
687 /// elements will be omitted.
689 /// Due to each chunk having exactly `chunk_size` elements, the compiler
690 /// can often optimize the resulting code better than in the case of
695 /// Panics if `chunk_size` is 0.
700 /// #![feature(exact_chunks)]
702 /// let slice = ['l', 'o', 'r', 'e', 'm'];
703 /// let mut iter = slice.exact_chunks(2);
704 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
705 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
706 /// assert!(iter.next().is_none());
709 /// [`chunks`]: #method.chunks
710 #[unstable(feature = "exact_chunks", issue = "47115")]
712 pub fn exact_chunks(&self, chunk_size: usize) -> ExactChunks<T> {
713 assert!(chunk_size != 0);
714 let rem = self.len() % chunk_size;
715 let len = self.len() - rem;
716 ExactChunks { v: &self[..len], chunk_size: chunk_size}
719 /// Returns an iterator over `chunk_size` elements of the slice at a time.
720 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
721 /// not divide the length of the slice, then the last chunk will not
722 /// have length `chunk_size`.
724 /// See [`exact_chunks_mut`] for a variant of this iterator that returns chunks
725 /// of always exactly `chunk_size` elements.
729 /// Panics if `chunk_size` is 0.
734 /// let v = &mut [0, 0, 0, 0, 0];
735 /// let mut count = 1;
737 /// for chunk in v.chunks_mut(2) {
738 /// for elem in chunk.iter_mut() {
743 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
746 /// [`exact_chunks_mut`]: #method.exact_chunks_mut
747 #[stable(feature = "rust1", since = "1.0.0")]
749 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
750 assert!(chunk_size != 0);
751 ChunksMut { v: self, chunk_size: chunk_size }
754 /// Returns an iterator over `chunk_size` elements of the slice at a time.
755 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
756 /// not divide the length of the slice, then the last up to `chunk_size-1`
757 /// elements will be omitted.
760 /// Due to each chunk having exactly `chunk_size` elements, the compiler
761 /// can often optimize the resulting code better than in the case of
766 /// Panics if `chunk_size` is 0.
771 /// #![feature(exact_chunks)]
773 /// let v = &mut [0, 0, 0, 0, 0];
774 /// let mut count = 1;
776 /// for chunk in v.exact_chunks_mut(2) {
777 /// for elem in chunk.iter_mut() {
782 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
785 /// [`chunks_mut`]: #method.chunks_mut
786 #[unstable(feature = "exact_chunks", issue = "47115")]
788 pub fn exact_chunks_mut(&mut self, chunk_size: usize) -> ExactChunksMut<T> {
789 assert!(chunk_size != 0);
790 let rem = self.len() % chunk_size;
791 let len = self.len() - rem;
792 ExactChunksMut { v: &mut self[..len], chunk_size: chunk_size}
795 /// Divides one slice into two at an index.
797 /// The first will contain all indices from `[0, mid)` (excluding
798 /// the index `mid` itself) and the second will contain all
799 /// indices from `[mid, len)` (excluding the index `len` itself).
803 /// Panics if `mid > len`.
808 /// let v = [1, 2, 3, 4, 5, 6];
811 /// let (left, right) = v.split_at(0);
812 /// assert!(left == []);
813 /// assert!(right == [1, 2, 3, 4, 5, 6]);
817 /// let (left, right) = v.split_at(2);
818 /// assert!(left == [1, 2]);
819 /// assert!(right == [3, 4, 5, 6]);
823 /// let (left, right) = v.split_at(6);
824 /// assert!(left == [1, 2, 3, 4, 5, 6]);
825 /// assert!(right == []);
828 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
831 (&self[..mid], &self[mid..])
834 /// Divides one mutable slice into two at an index.
836 /// The first will contain all indices from `[0, mid)` (excluding
837 /// the index `mid` itself) and the second will contain all
838 /// indices from `[mid, len)` (excluding the index `len` itself).
842 /// Panics if `mid > len`.
847 /// let mut v = [1, 0, 3, 0, 5, 6];
848 /// // scoped to restrict the lifetime of the borrows
850 /// let (left, right) = v.split_at_mut(2);
851 /// assert!(left == [1, 0]);
852 /// assert!(right == [3, 0, 5, 6]);
856 /// assert!(v == [1, 2, 3, 4, 5, 6]);
858 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
861 let len = self.len();
862 let ptr = self.as_mut_ptr();
867 (from_raw_parts_mut(ptr, mid),
868 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
872 /// Returns an iterator over subslices separated by elements that match
873 /// `pred`. The matched element is not contained in the subslices.
878 /// let slice = [10, 40, 33, 20];
879 /// let mut iter = slice.split(|num| num % 3 == 0);
881 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
882 /// assert_eq!(iter.next().unwrap(), &[20]);
883 /// assert!(iter.next().is_none());
886 /// If the first element is matched, an empty slice will be the first item
887 /// returned by the iterator. Similarly, if the last element in the slice
888 /// is matched, an empty slice will be the last item returned by the
892 /// let slice = [10, 40, 33];
893 /// let mut iter = slice.split(|num| num % 3 == 0);
895 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
896 /// assert_eq!(iter.next().unwrap(), &[]);
897 /// assert!(iter.next().is_none());
900 /// If two matched elements are directly adjacent, an empty slice will be
901 /// present between them:
904 /// let slice = [10, 6, 33, 20];
905 /// let mut iter = slice.split(|num| num % 3 == 0);
907 /// assert_eq!(iter.next().unwrap(), &[10]);
908 /// assert_eq!(iter.next().unwrap(), &[]);
909 /// assert_eq!(iter.next().unwrap(), &[20]);
910 /// assert!(iter.next().is_none());
912 #[stable(feature = "rust1", since = "1.0.0")]
914 pub fn split<F>(&self, pred: F) -> Split<T, F>
915 where F: FnMut(&T) -> bool
924 /// Returns an iterator over mutable subslices separated by elements that
925 /// match `pred`. The matched element is not contained in the subslices.
930 /// let mut v = [10, 40, 30, 20, 60, 50];
932 /// for group in v.split_mut(|num| *num % 3 == 0) {
935 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
937 #[stable(feature = "rust1", since = "1.0.0")]
939 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
940 where F: FnMut(&T) -> bool
942 SplitMut { v: self, pred: pred, finished: false }
945 /// Returns an iterator over subslices separated by elements that match
946 /// `pred`, starting at the end of the slice and working backwards.
947 /// The matched element is not contained in the subslices.
952 /// let slice = [11, 22, 33, 0, 44, 55];
953 /// let mut iter = slice.rsplit(|num| *num == 0);
955 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
956 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
957 /// assert_eq!(iter.next(), None);
960 /// As with `split()`, if the first or last element is matched, an empty
961 /// slice will be the first (or last) item returned by the iterator.
964 /// let v = &[0, 1, 1, 2, 3, 5, 8];
965 /// let mut it = v.rsplit(|n| *n % 2 == 0);
966 /// assert_eq!(it.next().unwrap(), &[]);
967 /// assert_eq!(it.next().unwrap(), &[3, 5]);
968 /// assert_eq!(it.next().unwrap(), &[1, 1]);
969 /// assert_eq!(it.next().unwrap(), &[]);
970 /// assert_eq!(it.next(), None);
972 #[stable(feature = "slice_rsplit", since = "1.27.0")]
974 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
975 where F: FnMut(&T) -> bool
977 RSplit { inner: self.split(pred) }
980 /// Returns an iterator over mutable subslices separated by elements that
981 /// match `pred`, starting at the end of the slice and working
982 /// backwards. The matched element is not contained in the subslices.
987 /// let mut v = [100, 400, 300, 200, 600, 500];
989 /// let mut count = 0;
990 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
992 /// group[0] = count;
994 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
997 #[stable(feature = "slice_rsplit", since = "1.27.0")]
999 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
1000 where F: FnMut(&T) -> bool
1002 RSplitMut { inner: self.split_mut(pred) }
1005 /// Returns an iterator over subslices separated by elements that match
1006 /// `pred`, limited to returning at most `n` items. The matched element is
1007 /// not contained in the subslices.
1009 /// The last element returned, if any, will contain the remainder of the
1014 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
1015 /// `[20, 60, 50]`):
1018 /// let v = [10, 40, 30, 20, 60, 50];
1020 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1021 /// println!("{:?}", group);
1024 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
1027 where F: FnMut(&T) -> bool
1030 inner: GenericSplitN {
1031 iter: self.split(pred),
1037 /// Returns an iterator over subslices separated by elements that match
1038 /// `pred`, limited to returning at most `n` items. The matched element is
1039 /// not contained in the subslices.
1041 /// The last element returned, if any, will contain the remainder of the
1047 /// let mut v = [10, 40, 30, 20, 60, 50];
1049 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1052 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1057 where F: FnMut(&T) -> bool
1060 inner: GenericSplitN {
1061 iter: self.split_mut(pred),
1067 /// Returns an iterator over subslices separated by elements that match
1068 /// `pred` limited to returning at most `n` items. This starts at the end of
1069 /// the slice and works backwards. The matched element is not contained in
1072 /// The last element returned, if any, will contain the remainder of the
1077 /// Print the slice split once, starting from the end, by numbers divisible
1078 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1081 /// let v = [10, 40, 30, 20, 60, 50];
1083 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1084 /// println!("{:?}", group);
1087 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1090 where F: FnMut(&T) -> bool
1093 inner: GenericSplitN {
1094 iter: self.rsplit(pred),
1100 /// Returns an iterator over subslices separated by elements that match
1101 /// `pred` limited to returning at most `n` items. This starts at the end of
1102 /// the slice and works backwards. The matched element is not contained in
1105 /// The last element returned, if any, will contain the remainder of the
1111 /// let mut s = [10, 40, 30, 20, 60, 50];
1113 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1116 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1118 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1121 where F: FnMut(&T) -> bool
1124 inner: GenericSplitN {
1125 iter: self.rsplit_mut(pred),
1131 /// Returns `true` if the slice contains an element with the given value.
1136 /// let v = [10, 40, 30];
1137 /// assert!(v.contains(&30));
1138 /// assert!(!v.contains(&50));
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 pub fn contains(&self, x: &T) -> bool
1144 x.slice_contains(self)
1147 /// Returns `true` if `needle` is a prefix of the slice.
1152 /// let v = [10, 40, 30];
1153 /// assert!(v.starts_with(&[10]));
1154 /// assert!(v.starts_with(&[10, 40]));
1155 /// assert!(!v.starts_with(&[50]));
1156 /// assert!(!v.starts_with(&[10, 50]));
1159 /// Always returns `true` if `needle` is an empty slice:
1162 /// let v = &[10, 40, 30];
1163 /// assert!(v.starts_with(&[]));
1164 /// let v: &[u8] = &[];
1165 /// assert!(v.starts_with(&[]));
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn starts_with(&self, needle: &[T]) -> bool
1171 let n = needle.len();
1172 self.len() >= n && needle == &self[..n]
1175 /// Returns `true` if `needle` is a suffix of the slice.
1180 /// let v = [10, 40, 30];
1181 /// assert!(v.ends_with(&[30]));
1182 /// assert!(v.ends_with(&[40, 30]));
1183 /// assert!(!v.ends_with(&[50]));
1184 /// assert!(!v.ends_with(&[50, 30]));
1187 /// Always returns `true` if `needle` is an empty slice:
1190 /// let v = &[10, 40, 30];
1191 /// assert!(v.ends_with(&[]));
1192 /// let v: &[u8] = &[];
1193 /// assert!(v.ends_with(&[]));
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn ends_with(&self, needle: &[T]) -> bool
1199 let (m, n) = (self.len(), needle.len());
1200 m >= n && needle == &self[m-n..]
1203 /// Binary searches this sorted slice for a given element.
1205 /// If the value is found then `Ok` is returned, containing the
1206 /// index of the matching element; if the value is not found then
1207 /// `Err` is returned, containing the index where a matching
1208 /// element could be inserted while maintaining sorted order.
1212 /// Looks up a series of four elements. The first is found, with a
1213 /// uniquely determined position; the second and third are not
1214 /// found; the fourth could match any position in `[1, 4]`.
1217 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1219 /// assert_eq!(s.binary_search(&13), Ok(9));
1220 /// assert_eq!(s.binary_search(&4), Err(7));
1221 /// assert_eq!(s.binary_search(&100), Err(13));
1222 /// let r = s.binary_search(&1);
1223 /// assert!(match r { Ok(1...4) => true, _ => false, });
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1229 self.binary_search_by(|p| p.cmp(x))
1232 /// Binary searches this sorted slice with a comparator function.
1234 /// The comparator function should implement an order consistent
1235 /// with the sort order of the underlying slice, returning an
1236 /// order code that indicates whether its argument is `Less`,
1237 /// `Equal` or `Greater` the desired target.
1239 /// If a matching value is found then returns `Ok`, containing
1240 /// the index for the matched element; if no match is found then
1241 /// `Err` is returned, containing the index where a matching
1242 /// element could be inserted while maintaining sorted order.
1246 /// Looks up a series of four elements. The first is found, with a
1247 /// uniquely determined position; the second and third are not
1248 /// found; the fourth could match any position in `[1, 4]`.
1251 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1254 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1256 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1258 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1260 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1261 /// assert!(match r { Ok(1...4) => true, _ => false, });
1263 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
1266 where F: FnMut(&'a T) -> Ordering
1269 let mut size = s.len();
1273 let mut base = 0usize;
1275 let half = size / 2;
1276 let mid = base + half;
1277 // mid is always in [0, size), that means mid is >= 0 and < size.
1278 // mid >= 0: by definition
1279 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
1280 let cmp = f(unsafe { s.get_unchecked(mid) });
1281 base = if cmp == Greater { base } else { mid };
1284 // base is always in [0, size) because base <= mid.
1285 let cmp = f(unsafe { s.get_unchecked(base) });
1286 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
1290 /// Binary searches this sorted slice with a key extraction function.
1292 /// Assumes that the slice is sorted by the key, for instance with
1293 /// [`sort_by_key`] using the same key extraction function.
1295 /// If a matching value is found then returns `Ok`, containing the
1296 /// index for the matched element; if no match is found then `Err`
1297 /// is returned, containing the index where a matching element could
1298 /// be inserted while maintaining sorted order.
1300 /// [`sort_by_key`]: #method.sort_by_key
1304 /// Looks up a series of four elements in a slice of pairs sorted by
1305 /// their second elements. The first is found, with a uniquely
1306 /// determined position; the second and third are not found; the
1307 /// fourth could match any position in `[1, 4]`.
1310 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1311 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1312 /// (1, 21), (2, 34), (4, 55)];
1314 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1315 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1316 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1317 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1318 /// assert!(match r { Ok(1...4) => true, _ => false, });
1320 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1322 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
1323 where F: FnMut(&'a T) -> B,
1326 self.binary_search_by(|k| f(k).cmp(b))
1329 /// Sorts the slice, but may not preserve the order of equal elements.
1331 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1332 /// and `O(n log n)` worst-case.
1334 /// # Current implementation
1336 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1337 /// which combines the fast average case of randomized quicksort with the fast worst case of
1338 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1339 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1340 /// deterministic behavior.
1342 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1343 /// slice consists of several concatenated sorted sequences.
1348 /// let mut v = [-5, 4, 1, -3, 2];
1350 /// v.sort_unstable();
1351 /// assert!(v == [-5, -3, 1, 2, 4]);
1354 /// [pdqsort]: https://github.com/orlp/pdqsort
1355 #[stable(feature = "sort_unstable", since = "1.20.0")]
1357 pub fn sort_unstable(&mut self)
1360 sort::quicksort(self, |a, b| a.lt(b));
1363 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1366 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1367 /// and `O(n log n)` worst-case.
1369 /// # Current implementation
1371 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1372 /// which combines the fast average case of randomized quicksort with the fast worst case of
1373 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1374 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1375 /// deterministic behavior.
1377 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1378 /// slice consists of several concatenated sorted sequences.
1383 /// let mut v = [5, 4, 1, 3, 2];
1384 /// v.sort_unstable_by(|a, b| a.cmp(b));
1385 /// assert!(v == [1, 2, 3, 4, 5]);
1387 /// // reverse sorting
1388 /// v.sort_unstable_by(|a, b| b.cmp(a));
1389 /// assert!(v == [5, 4, 3, 2, 1]);
1392 /// [pdqsort]: https://github.com/orlp/pdqsort
1393 #[stable(feature = "sort_unstable", since = "1.20.0")]
1395 pub fn sort_unstable_by<F>(&mut self, mut compare: F)
1396 where F: FnMut(&T, &T) -> Ordering
1398 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
1401 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1404 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1405 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1407 /// # Current implementation
1409 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1410 /// which combines the fast average case of randomized quicksort with the fast worst case of
1411 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1412 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1413 /// deterministic behavior.
1418 /// let mut v = [-5i32, 4, 1, -3, 2];
1420 /// v.sort_unstable_by_key(|k| k.abs());
1421 /// assert!(v == [1, 2, -3, 4, -5]);
1424 /// [pdqsort]: https://github.com/orlp/pdqsort
1425 #[stable(feature = "sort_unstable", since = "1.20.0")]
1427 pub fn sort_unstable_by_key<K, F>(&mut self, mut f: F)
1428 where F: FnMut(&T) -> K, K: Ord
1430 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
1433 /// Rotates the slice in-place such that the first `mid` elements of the
1434 /// slice move to the end while the last `self.len() - mid` elements move to
1435 /// the front. After calling `rotate_left`, the element previously at index
1436 /// `mid` will become the first element in the slice.
1440 /// This function will panic if `mid` is greater than the length of the
1441 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1446 /// Takes linear (in `self.len()`) time.
1451 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1452 /// a.rotate_left(2);
1453 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1456 /// Rotating a subslice:
1459 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1460 /// a[1..5].rotate_left(1);
1461 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1463 #[stable(feature = "slice_rotate", since = "1.26.0")]
1464 pub fn rotate_left(&mut self, mid: usize) {
1465 assert!(mid <= self.len());
1466 let k = self.len() - mid;
1469 let p = self.as_mut_ptr();
1470 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
1474 /// Rotates the slice in-place such that the first `self.len() - k`
1475 /// elements of the slice move to the end while the last `k` elements move
1476 /// to the front. After calling `rotate_right`, the element previously at
1477 /// index `self.len() - k` will become the first element in the slice.
1481 /// This function will panic if `k` is greater than the length of the
1482 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1487 /// Takes linear (in `self.len()`) time.
1492 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1493 /// a.rotate_right(2);
1494 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1497 /// Rotate a subslice:
1500 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1501 /// a[1..5].rotate_right(1);
1502 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1504 #[stable(feature = "slice_rotate", since = "1.26.0")]
1505 pub fn rotate_right(&mut self, k: usize) {
1506 assert!(k <= self.len());
1507 let mid = self.len() - k;
1510 let p = self.as_mut_ptr();
1511 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
1515 /// Copies the elements from `src` into `self`.
1517 /// The length of `src` must be the same as `self`.
1519 /// If `src` implements `Copy`, it can be more performant to use
1520 /// [`copy_from_slice`].
1524 /// This function will panic if the two slices have different lengths.
1528 /// Cloning two elements from a slice into another:
1531 /// let src = [1, 2, 3, 4];
1532 /// let mut dst = [0, 0];
1534 /// dst.clone_from_slice(&src[2..]);
1536 /// assert_eq!(src, [1, 2, 3, 4]);
1537 /// assert_eq!(dst, [3, 4]);
1540 /// Rust enforces that there can only be one mutable reference with no
1541 /// immutable references to a particular piece of data in a particular
1542 /// scope. Because of this, attempting to use `clone_from_slice` on a
1543 /// single slice will result in a compile failure:
1546 /// let mut slice = [1, 2, 3, 4, 5];
1548 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
1551 /// To work around this, we can use [`split_at_mut`] to create two distinct
1552 /// sub-slices from a slice:
1555 /// let mut slice = [1, 2, 3, 4, 5];
1558 /// let (left, right) = slice.split_at_mut(2);
1559 /// left.clone_from_slice(&right[1..]);
1562 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1565 /// [`copy_from_slice`]: #method.copy_from_slice
1566 /// [`split_at_mut`]: #method.split_at_mut
1567 #[stable(feature = "clone_from_slice", since = "1.7.0")]
1568 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
1569 assert!(self.len() == src.len(),
1570 "destination and source slices have different lengths");
1571 // NOTE: We need to explicitly slice them to the same length
1572 // for bounds checking to be elided, and the optimizer will
1573 // generate memcpy for simple cases (for example T = u8).
1574 let len = self.len();
1575 let src = &src[..len];
1577 self[i].clone_from(&src[i]);
1582 /// Copies all elements from `src` into `self`, using a memcpy.
1584 /// The length of `src` must be the same as `self`.
1586 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
1590 /// This function will panic if the two slices have different lengths.
1594 /// Copying two elements from a slice into another:
1597 /// let src = [1, 2, 3, 4];
1598 /// let mut dst = [0, 0];
1600 /// dst.copy_from_slice(&src[2..]);
1602 /// assert_eq!(src, [1, 2, 3, 4]);
1603 /// assert_eq!(dst, [3, 4]);
1606 /// Rust enforces that there can only be one mutable reference with no
1607 /// immutable references to a particular piece of data in a particular
1608 /// scope. Because of this, attempting to use `copy_from_slice` on a
1609 /// single slice will result in a compile failure:
1612 /// let mut slice = [1, 2, 3, 4, 5];
1614 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
1617 /// To work around this, we can use [`split_at_mut`] to create two distinct
1618 /// sub-slices from a slice:
1621 /// let mut slice = [1, 2, 3, 4, 5];
1624 /// let (left, right) = slice.split_at_mut(2);
1625 /// left.copy_from_slice(&right[1..]);
1628 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
1631 /// [`clone_from_slice`]: #method.clone_from_slice
1632 /// [`split_at_mut`]: #method.split_at_mut
1633 #[stable(feature = "copy_from_slice", since = "1.9.0")]
1634 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
1635 assert!(self.len() == src.len(),
1636 "destination and source slices have different lengths");
1638 ptr::copy_nonoverlapping(
1639 src.as_ptr(), self.as_mut_ptr(), self.len());
1643 /// Swaps all elements in `self` with those in `other`.
1645 /// The length of `other` must be the same as `self`.
1649 /// This function will panic if the two slices have different lengths.
1653 /// Swapping two elements across slices:
1656 /// let mut slice1 = [0, 0];
1657 /// let mut slice2 = [1, 2, 3, 4];
1659 /// slice1.swap_with_slice(&mut slice2[2..]);
1661 /// assert_eq!(slice1, [3, 4]);
1662 /// assert_eq!(slice2, [1, 2, 0, 0]);
1665 /// Rust enforces that there can only be one mutable reference to a
1666 /// particular piece of data in a particular scope. Because of this,
1667 /// attempting to use `swap_with_slice` on a single slice will result in
1668 /// a compile failure:
1671 /// let mut slice = [1, 2, 3, 4, 5];
1672 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
1675 /// To work around this, we can use [`split_at_mut`] to create two distinct
1676 /// mutable sub-slices from a slice:
1679 /// let mut slice = [1, 2, 3, 4, 5];
1682 /// let (left, right) = slice.split_at_mut(2);
1683 /// left.swap_with_slice(&mut right[1..]);
1686 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
1689 /// [`split_at_mut`]: #method.split_at_mut
1690 #[stable(feature = "swap_with_slice", since = "1.27.0")]
1691 pub fn swap_with_slice(&mut self, other: &mut [T]) {
1692 assert!(self.len() == other.len(),
1693 "destination and source slices have different lengths");
1695 ptr::swap_nonoverlapping(
1696 self.as_mut_ptr(), other.as_mut_ptr(), self.len());
1701 #[lang = "slice_u8"]
1704 /// Checks if all bytes in this slice are within the ASCII range.
1705 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1707 pub fn is_ascii(&self) -> bool {
1708 self.iter().all(|b| b.is_ascii())
1711 /// Checks that two slices are an ASCII case-insensitive match.
1713 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1714 /// but without allocating and copying temporaries.
1715 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1717 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
1718 self.len() == other.len() &&
1719 self.iter().zip(other).all(|(a, b)| {
1720 a.eq_ignore_ascii_case(b)
1724 /// Converts this slice to its ASCII upper case equivalent in-place.
1726 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1727 /// but non-ASCII letters are unchanged.
1729 /// To return a new uppercased value without modifying the existing one, use
1730 /// [`to_ascii_uppercase`].
1732 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1733 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1735 pub fn make_ascii_uppercase(&mut self) {
1737 byte.make_ascii_uppercase();
1741 /// Converts this slice to its ASCII lower case equivalent in-place.
1743 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1744 /// but non-ASCII letters are unchanged.
1746 /// To return a new lowercased value without modifying the existing one, use
1747 /// [`to_ascii_lowercase`].
1749 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1750 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1752 pub fn make_ascii_lowercase(&mut self) {
1754 byte.make_ascii_lowercase();
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1762 impl<T, I> ops::Index<I> for [T]
1763 where I: SliceIndex<[T]>
1765 type Output = I::Output;
1768 fn index(&self, index: I) -> &I::Output {
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1775 impl<T, I> ops::IndexMut<I> for [T]
1776 where I: SliceIndex<[T]>
1779 fn index_mut(&mut self, index: I) -> &mut I::Output {
1780 index.index_mut(self)
1786 fn slice_index_len_fail(index: usize, len: usize) -> ! {
1787 panic!("index {} out of range for slice of length {}", index, len);
1792 fn slice_index_order_fail(index: usize, end: usize) -> ! {
1793 panic!("slice index starts at {} but ends at {}", index, end);
1798 fn slice_index_overflow_fail() -> ! {
1799 panic!("attempted to index slice up to maximum usize");
1802 /// A helper trait used for indexing operations.
1803 #[unstable(feature = "slice_get_slice", issue = "35729")]
1804 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1805 pub trait SliceIndex<T: ?Sized> {
1806 /// The output type returned by methods.
1807 type Output: ?Sized;
1809 /// Returns a shared reference to the output at this location, if in
1811 fn get(self, slice: &T) -> Option<&Self::Output>;
1813 /// Returns a mutable reference to the output at this location, if in
1815 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
1817 /// Returns a shared reference to the output at this location, without
1818 /// performing any bounds checking.
1819 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
1821 /// Returns a mutable reference to the output at this location, without
1822 /// performing any bounds checking.
1823 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
1825 /// Returns a shared reference to the output at this location, panicking
1826 /// if out of bounds.
1827 fn index(self, slice: &T) -> &Self::Output;
1829 /// Returns a mutable reference to the output at this location, panicking
1830 /// if out of bounds.
1831 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
1834 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
1835 impl<T> SliceIndex<[T]> for usize {
1839 fn get(self, slice: &[T]) -> Option<&T> {
1840 if self < slice.len() {
1842 Some(self.get_unchecked(slice))
1850 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
1851 if self < slice.len() {
1853 Some(self.get_unchecked_mut(slice))
1861 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
1862 &*slice.as_ptr().offset(self as isize)
1866 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
1867 &mut *slice.as_mut_ptr().offset(self as isize)
1871 fn index(self, slice: &[T]) -> &T {
1872 // NB: use intrinsic indexing
1877 fn index_mut(self, slice: &mut [T]) -> &mut T {
1878 // NB: use intrinsic indexing
1883 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
1884 impl<T> SliceIndex<[T]> for ops::Range<usize> {
1888 fn get(self, slice: &[T]) -> Option<&[T]> {
1889 if self.start > self.end || self.end > slice.len() {
1893 Some(self.get_unchecked(slice))
1899 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1900 if self.start > self.end || self.end > slice.len() {
1904 Some(self.get_unchecked_mut(slice))
1910 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1911 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
1915 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1916 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
1920 fn index(self, slice: &[T]) -> &[T] {
1921 if self.start > self.end {
1922 slice_index_order_fail(self.start, self.end);
1923 } else if self.end > slice.len() {
1924 slice_index_len_fail(self.end, slice.len());
1927 self.get_unchecked(slice)
1932 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1933 if self.start > self.end {
1934 slice_index_order_fail(self.start, self.end);
1935 } else if self.end > slice.len() {
1936 slice_index_len_fail(self.end, slice.len());
1939 self.get_unchecked_mut(slice)
1944 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
1945 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
1949 fn get(self, slice: &[T]) -> Option<&[T]> {
1950 (0..self.end).get(slice)
1954 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1955 (0..self.end).get_mut(slice)
1959 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1960 (0..self.end).get_unchecked(slice)
1964 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
1965 (0..self.end).get_unchecked_mut(slice)
1969 fn index(self, slice: &[T]) -> &[T] {
1970 (0..self.end).index(slice)
1974 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
1975 (0..self.end).index_mut(slice)
1979 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
1980 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
1984 fn get(self, slice: &[T]) -> Option<&[T]> {
1985 (self.start..slice.len()).get(slice)
1989 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
1990 (self.start..slice.len()).get_mut(slice)
1994 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
1995 (self.start..slice.len()).get_unchecked(slice)
1999 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2000 (self.start..slice.len()).get_unchecked_mut(slice)
2004 fn index(self, slice: &[T]) -> &[T] {
2005 (self.start..slice.len()).index(slice)
2009 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2010 (self.start..slice.len()).index_mut(slice)
2014 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2015 impl<T> SliceIndex<[T]> for ops::RangeFull {
2019 fn get(self, slice: &[T]) -> Option<&[T]> {
2024 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2029 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2034 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2039 fn index(self, slice: &[T]) -> &[T] {
2044 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2050 #[stable(feature = "inclusive_range", since = "1.26.0")]
2051 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2055 fn get(self, slice: &[T]) -> Option<&[T]> {
2056 if self.end == usize::max_value() { None }
2057 else { (self.start..self.end + 1).get(slice) }
2061 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2062 if self.end == usize::max_value() { None }
2063 else { (self.start..self.end + 1).get_mut(slice) }
2067 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2068 (self.start..self.end + 1).get_unchecked(slice)
2072 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2073 (self.start..self.end + 1).get_unchecked_mut(slice)
2077 fn index(self, slice: &[T]) -> &[T] {
2078 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2079 (self.start..self.end + 1).index(slice)
2083 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2084 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2085 (self.start..self.end + 1).index_mut(slice)
2089 #[stable(feature = "inclusive_range", since = "1.26.0")]
2090 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2094 fn get(self, slice: &[T]) -> Option<&[T]> {
2095 (0..=self.end).get(slice)
2099 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2100 (0..=self.end).get_mut(slice)
2104 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2105 (0..=self.end).get_unchecked(slice)
2109 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2110 (0..=self.end).get_unchecked_mut(slice)
2114 fn index(self, slice: &[T]) -> &[T] {
2115 (0..=self.end).index(slice)
2119 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2120 (0..=self.end).index_mut(slice)
2124 ////////////////////////////////////////////////////////////////////////////////
2126 ////////////////////////////////////////////////////////////////////////////////
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 impl<'a, T> Default for &'a [T] {
2130 /// Creates an empty slice.
2131 fn default() -> &'a [T] { &[] }
2134 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2135 impl<'a, T> Default for &'a mut [T] {
2136 /// Creates a mutable empty slice.
2137 fn default() -> &'a mut [T] { &mut [] }
2144 #[stable(feature = "rust1", since = "1.0.0")]
2145 impl<'a, T> IntoIterator for &'a [T] {
2147 type IntoIter = Iter<'a, T>;
2149 fn into_iter(self) -> Iter<'a, T> {
2154 #[stable(feature = "rust1", since = "1.0.0")]
2155 impl<'a, T> IntoIterator for &'a mut [T] {
2156 type Item = &'a mut T;
2157 type IntoIter = IterMut<'a, T>;
2159 fn into_iter(self) -> IterMut<'a, T> {
2165 fn size_from_ptr<T>(_: *const T) -> usize {
2169 // The shared definition of the `Iter` and `IterMut` iterators
2170 macro_rules! iterator {
2171 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
2172 #[stable(feature = "rust1", since = "1.0.0")]
2173 impl<'a, T> Iterator for $name<'a, T> {
2177 fn next(&mut self) -> Option<$elem> {
2178 // could be implemented with slices, but this avoids bounds checks
2180 if mem::size_of::<T>() != 0 {
2181 assume(!self.ptr.is_null());
2182 assume(!self.end.is_null());
2184 if self.ptr == self.end {
2187 Some($mkref!(self.ptr.post_inc()))
2193 fn size_hint(&self) -> (usize, Option<usize>) {
2194 let exact = unsafe { ptrdistance(self.ptr, self.end) };
2195 (exact, Some(exact))
2199 fn count(self) -> usize {
2204 fn nth(&mut self, n: usize) -> Option<$elem> {
2205 // Call helper method. Can't put the definition here because mut versus const.
2210 fn last(mut self) -> Option<$elem> {
2215 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2216 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2218 // manual unrolling is needed when there are conditional exits from the loop
2219 let mut accum = init;
2221 while ptrdistance(self.ptr, self.end) >= 4 {
2222 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2223 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2224 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2225 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2227 while self.ptr != self.end {
2228 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2235 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2236 where Fold: FnMut(Acc, Self::Item) -> Acc,
2238 // Let LLVM unroll this, rather than using the default
2239 // impl that would force the manual unrolling above
2240 let mut accum = init;
2241 while let Some(x) = self.next() {
2242 accum = f(accum, x);
2248 #[rustc_inherit_overflow_checks]
2249 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2251 P: FnMut(Self::Item) -> bool,
2253 // The addition might panic on overflow
2254 // Use the len of the slice to hint optimizer to remove result index bounds check.
2255 let n = make_slice!(self.ptr, self.end).len();
2256 self.try_fold(0, move |i, x| {
2257 if predicate(x) { Err(i) }
2261 unsafe { assume(i < n) };
2267 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2268 P: FnMut(Self::Item) -> bool,
2269 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2271 // No need for an overflow check here, because `ExactSizeIterator`
2272 // implies that the number of elements fits into a `usize`.
2273 // Use the len of the slice to hint optimizer to remove result index bounds check.
2274 let n = make_slice!(self.ptr, self.end).len();
2275 self.try_rfold(n, move |i, x| {
2277 if predicate(x) { Err(i) }
2281 unsafe { assume(i < n) };
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2290 fn next_back(&mut self) -> Option<$elem> {
2291 // could be implemented with slices, but this avoids bounds checks
2293 if mem::size_of::<T>() != 0 {
2294 assume(!self.ptr.is_null());
2295 assume(!self.end.is_null());
2297 if self.end == self.ptr {
2300 Some($mkref!(self.end.pre_dec()))
2306 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2307 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2309 // manual unrolling is needed when there are conditional exits from the loop
2310 let mut accum = init;
2312 while ptrdistance(self.ptr, self.end) >= 4 {
2313 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2314 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2315 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2316 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2318 while self.ptr != self.end {
2319 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2326 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2327 where Fold: FnMut(Acc, Self::Item) -> Acc,
2329 // Let LLVM unroll this, rather than using the default
2330 // impl that would force the manual unrolling above
2331 let mut accum = init;
2332 while let Some(x) = self.next_back() {
2333 accum = f(accum, x);
2341 macro_rules! make_slice {
2342 ($start: expr, $end: expr) => {{
2344 let diff = ($end as usize).wrapping_sub(start as usize);
2345 if size_from_ptr(start) == 0 {
2346 // use a non-null pointer value
2347 unsafe { from_raw_parts(1 as *const _, diff) }
2349 let len = diff / size_from_ptr(start);
2350 unsafe { from_raw_parts(start, len) }
2355 macro_rules! make_mut_slice {
2356 ($start: expr, $end: expr) => {{
2358 let diff = ($end as usize).wrapping_sub(start as usize);
2359 if size_from_ptr(start) == 0 {
2360 // use a non-null pointer value
2361 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
2363 let len = diff / size_from_ptr(start);
2364 unsafe { from_raw_parts_mut(start, len) }
2369 /// Immutable slice iterator
2371 /// This struct is created by the [`iter`] method on [slices].
2378 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2379 /// let slice = &[1, 2, 3];
2381 /// // Then, we iterate over it:
2382 /// for element in slice.iter() {
2383 /// println!("{}", element);
2387 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2388 /// [slices]: ../../std/primitive.slice.html
2389 #[stable(feature = "rust1", since = "1.0.0")]
2390 pub struct Iter<'a, T: 'a> {
2393 _marker: marker::PhantomData<&'a T>,
2396 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2397 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2399 f.debug_tuple("Iter")
2400 .field(&self.as_slice())
2405 #[stable(feature = "rust1", since = "1.0.0")]
2406 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2410 impl<'a, T> Iter<'a, T> {
2411 /// View the underlying data as a subslice of the original data.
2413 /// This has the same lifetime as the original slice, and so the
2414 /// iterator can continue to be used while this exists.
2421 /// // First, we declare a type which has the `iter` method to get the `Iter`
2422 /// // struct (&[usize here]):
2423 /// let slice = &[1, 2, 3];
2425 /// // Then, we get the iterator:
2426 /// let mut iter = slice.iter();
2427 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2428 /// println!("{:?}", iter.as_slice());
2430 /// // Next, we move to the second element of the slice:
2432 /// // Now `as_slice` returns "[2, 3]":
2433 /// println!("{:?}", iter.as_slice());
2435 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2436 pub fn as_slice(&self) -> &'a [T] {
2437 make_slice!(self.ptr, self.end)
2440 // Helper function for Iter::nth
2441 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
2442 match self.as_slice().get(n) {
2443 Some(elem_ref) => unsafe {
2444 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2448 self.ptr = self.end;
2455 iterator!{struct Iter -> *const T, &'a T, make_ref}
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2459 fn is_empty(&self) -> bool {
2460 self.ptr == self.end
2464 #[stable(feature = "fused", since = "1.26.0")]
2465 impl<'a, T> FusedIterator for Iter<'a, T> {}
2467 #[unstable(feature = "trusted_len", issue = "37572")]
2468 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
2470 #[stable(feature = "rust1", since = "1.0.0")]
2471 impl<'a, T> Clone for Iter<'a, T> {
2472 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2475 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2476 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2477 fn as_ref(&self) -> &[T] {
2482 /// Mutable slice iterator.
2484 /// This struct is created by the [`iter_mut`] method on [slices].
2491 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2492 /// // struct (&[usize here]):
2493 /// let mut slice = &mut [1, 2, 3];
2495 /// // Then, we iterate over it and increment each element value:
2496 /// for element in slice.iter_mut() {
2500 /// // We now have "[2, 3, 4]":
2501 /// println!("{:?}", slice);
2504 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2505 /// [slices]: ../../std/primitive.slice.html
2506 #[stable(feature = "rust1", since = "1.0.0")]
2507 pub struct IterMut<'a, T: 'a> {
2510 _marker: marker::PhantomData<&'a mut T>,
2513 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2514 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2516 f.debug_tuple("IterMut")
2517 .field(&make_slice!(self.ptr, self.end))
2522 #[stable(feature = "rust1", since = "1.0.0")]
2523 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2524 #[stable(feature = "rust1", since = "1.0.0")]
2525 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2527 impl<'a, T> IterMut<'a, T> {
2528 /// View the underlying data as a subslice of the original data.
2530 /// To avoid creating `&mut` references that alias, this is forced
2531 /// to consume the iterator. Consider using the `Slice` and
2532 /// `SliceMut` implementations for obtaining slices with more
2533 /// restricted lifetimes that do not consume the iterator.
2540 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2541 /// // struct (&[usize here]):
2542 /// let mut slice = &mut [1, 2, 3];
2545 /// // Then, we get the iterator:
2546 /// let mut iter = slice.iter_mut();
2547 /// // We move to next element:
2549 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
2550 /// println!("{:?}", iter.into_slice());
2553 /// // Now let's modify a value of the slice:
2555 /// // First we get back the iterator:
2556 /// let mut iter = slice.iter_mut();
2557 /// // We change the value of the first element of the slice returned by the `next` method:
2558 /// *iter.next().unwrap() += 1;
2560 /// // Now slice is "[2, 2, 3]":
2561 /// println!("{:?}", slice);
2563 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2564 pub fn into_slice(self) -> &'a mut [T] {
2565 make_mut_slice!(self.ptr, self.end)
2568 // Helper function for IterMut::nth
2569 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
2570 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
2571 Some(elem_ref) => unsafe {
2572 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2576 self.ptr = self.end;
2583 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
2585 #[stable(feature = "rust1", since = "1.0.0")]
2586 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2587 fn is_empty(&self) -> bool {
2588 self.ptr == self.end
2592 #[stable(feature = "fused", since = "1.26.0")]
2593 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2595 #[unstable(feature = "trusted_len", issue = "37572")]
2596 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
2599 // Return the number of elements of `T` from `start` to `end`.
2600 // Return the arithmetic difference if `T` is zero size.
2602 unsafe fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
2603 if mem::size_of::<T>() == 0 {
2604 (end as usize).wrapping_sub(start as usize)
2606 end.offset_from(start) as usize
2610 // Extension methods for raw pointers, used by the iterators
2611 trait PointerExt : Copy {
2612 unsafe fn slice_offset(self, i: isize) -> Self;
2614 /// Increments `self` by 1, but returns the old value.
2616 unsafe fn post_inc(&mut self) -> Self {
2617 let current = *self;
2618 *self = self.slice_offset(1);
2622 /// Decrements `self` by 1, and returns the new value.
2624 unsafe fn pre_dec(&mut self) -> Self {
2625 *self = self.slice_offset(-1);
2630 impl<T> PointerExt for *const T {
2632 unsafe fn slice_offset(self, i: isize) -> Self {
2633 slice_offset!(self, i)
2637 impl<T> PointerExt for *mut T {
2639 unsafe fn slice_offset(self, i: isize) -> Self {
2640 slice_offset!(self, i)
2644 /// An internal abstraction over the splitting iterators, so that
2645 /// splitn, splitn_mut etc can be implemented once.
2647 trait SplitIter: DoubleEndedIterator {
2648 /// Marks the underlying iterator as complete, extracting the remaining
2649 /// portion of the slice.
2650 fn finish(&mut self) -> Option<Self::Item>;
2653 /// An iterator over subslices separated by elements that match a predicate
2656 /// This struct is created by the [`split`] method on [slices].
2658 /// [`split`]: ../../std/primitive.slice.html#method.split
2659 /// [slices]: ../../std/primitive.slice.html
2660 #[stable(feature = "rust1", since = "1.0.0")]
2661 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
2667 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2668 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
2669 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2670 f.debug_struct("Split")
2671 .field("v", &self.v)
2672 .field("finished", &self.finished)
2677 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2678 #[stable(feature = "rust1", since = "1.0.0")]
2679 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
2680 fn clone(&self) -> Split<'a, T, P> {
2683 pred: self.pred.clone(),
2684 finished: self.finished,
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2691 type Item = &'a [T];
2694 fn next(&mut self) -> Option<&'a [T]> {
2695 if self.finished { return None; }
2697 match self.v.iter().position(|x| (self.pred)(x)) {
2698 None => self.finish(),
2700 let ret = Some(&self.v[..idx]);
2701 self.v = &self.v[idx + 1..];
2708 fn size_hint(&self) -> (usize, Option<usize>) {
2712 (1, Some(self.v.len() + 1))
2717 #[stable(feature = "rust1", since = "1.0.0")]
2718 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2720 fn next_back(&mut self) -> Option<&'a [T]> {
2721 if self.finished { return None; }
2723 match self.v.iter().rposition(|x| (self.pred)(x)) {
2724 None => self.finish(),
2726 let ret = Some(&self.v[idx + 1..]);
2727 self.v = &self.v[..idx];
2734 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
2736 fn finish(&mut self) -> Option<&'a [T]> {
2737 if self.finished { None } else { self.finished = true; Some(self.v) }
2741 #[stable(feature = "fused", since = "1.26.0")]
2742 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
2744 /// An iterator over the subslices of the vector which are separated
2745 /// by elements that match `pred`.
2747 /// This struct is created by the [`split_mut`] method on [slices].
2749 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
2750 /// [slices]: ../../std/primitive.slice.html
2751 #[stable(feature = "rust1", since = "1.0.0")]
2752 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
2758 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2759 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2761 f.debug_struct("SplitMut")
2762 .field("v", &self.v)
2763 .field("finished", &self.finished)
2768 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2770 fn finish(&mut self) -> Option<&'a mut [T]> {
2774 self.finished = true;
2775 Some(mem::replace(&mut self.v, &mut []))
2780 #[stable(feature = "rust1", since = "1.0.0")]
2781 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2782 type Item = &'a mut [T];
2785 fn next(&mut self) -> Option<&'a mut [T]> {
2786 if self.finished { return None; }
2788 let idx_opt = { // work around borrowck limitations
2789 let pred = &mut self.pred;
2790 self.v.iter().position(|x| (*pred)(x))
2793 None => self.finish(),
2795 let tmp = mem::replace(&mut self.v, &mut []);
2796 let (head, tail) = tmp.split_at_mut(idx);
2797 self.v = &mut tail[1..];
2804 fn size_hint(&self) -> (usize, Option<usize>) {
2808 // if the predicate doesn't match anything, we yield one slice
2809 // if it matches every element, we yield len+1 empty slices.
2810 (1, Some(self.v.len() + 1))
2815 #[stable(feature = "rust1", since = "1.0.0")]
2816 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
2817 P: FnMut(&T) -> bool,
2820 fn next_back(&mut self) -> Option<&'a mut [T]> {
2821 if self.finished { return None; }
2823 let idx_opt = { // work around borrowck limitations
2824 let pred = &mut self.pred;
2825 self.v.iter().rposition(|x| (*pred)(x))
2828 None => self.finish(),
2830 let tmp = mem::replace(&mut self.v, &mut []);
2831 let (head, tail) = tmp.split_at_mut(idx);
2833 Some(&mut tail[1..])
2839 #[stable(feature = "fused", since = "1.26.0")]
2840 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
2842 /// An iterator over subslices separated by elements that match a predicate
2843 /// function, starting from the end of the slice.
2845 /// This struct is created by the [`rsplit`] method on [slices].
2847 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
2848 /// [slices]: ../../std/primitive.slice.html
2849 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2850 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
2851 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
2852 inner: Split<'a, T, P>
2855 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2856 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
2857 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2858 f.debug_struct("RSplit")
2859 .field("v", &self.inner.v)
2860 .field("finished", &self.inner.finished)
2865 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2866 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
2867 type Item = &'a [T];
2870 fn next(&mut self) -> Option<&'a [T]> {
2871 self.inner.next_back()
2875 fn size_hint(&self) -> (usize, Option<usize>) {
2876 self.inner.size_hint()
2880 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2881 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
2883 fn next_back(&mut self) -> Option<&'a [T]> {
2888 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2889 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
2891 fn finish(&mut self) -> Option<&'a [T]> {
2896 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2897 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
2899 /// An iterator over the subslices of the vector which are separated
2900 /// by elements that match `pred`, starting from the end of the slice.
2902 /// This struct is created by the [`rsplit_mut`] method on [slices].
2904 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
2905 /// [slices]: ../../std/primitive.slice.html
2906 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2907 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
2908 inner: SplitMut<'a, T, P>
2911 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2912 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2913 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2914 f.debug_struct("RSplitMut")
2915 .field("v", &self.inner.v)
2916 .field("finished", &self.inner.finished)
2921 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2922 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2924 fn finish(&mut self) -> Option<&'a mut [T]> {
2929 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2930 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2931 type Item = &'a mut [T];
2934 fn next(&mut self) -> Option<&'a mut [T]> {
2935 self.inner.next_back()
2939 fn size_hint(&self) -> (usize, Option<usize>) {
2940 self.inner.size_hint()
2944 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2945 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
2946 P: FnMut(&T) -> bool,
2949 fn next_back(&mut self) -> Option<&'a mut [T]> {
2954 #[stable(feature = "slice_rsplit", since = "1.27.0")]
2955 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
2957 /// An private iterator over subslices separated by elements that
2958 /// match a predicate function, splitting at most a fixed number of
2961 struct GenericSplitN<I> {
2966 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
2970 fn next(&mut self) -> Option<T> {
2973 1 => { self.count -= 1; self.iter.finish() }
2974 _ => { self.count -= 1; self.iter.next() }
2979 fn size_hint(&self) -> (usize, Option<usize>) {
2980 let (lower, upper_opt) = self.iter.size_hint();
2981 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
2985 /// An iterator over subslices separated by elements that match a predicate
2986 /// function, limited to a given number of splits.
2988 /// This struct is created by the [`splitn`] method on [slices].
2990 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
2991 /// [slices]: ../../std/primitive.slice.html
2992 #[stable(feature = "rust1", since = "1.0.0")]
2993 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
2994 inner: GenericSplitN<Split<'a, T, P>>
2997 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2998 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
2999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3000 f.debug_struct("SplitN")
3001 .field("inner", &self.inner)
3006 /// An iterator over subslices separated by elements that match a
3007 /// predicate function, limited to a given number of splits, starting
3008 /// from the end of the slice.
3010 /// This struct is created by the [`rsplitn`] method on [slices].
3012 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3013 /// [slices]: ../../std/primitive.slice.html
3014 #[stable(feature = "rust1", since = "1.0.0")]
3015 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3016 inner: GenericSplitN<RSplit<'a, T, P>>
3019 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3020 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3021 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3022 f.debug_struct("RSplitN")
3023 .field("inner", &self.inner)
3028 /// An iterator over subslices separated by elements that match a predicate
3029 /// function, limited to a given number of splits.
3031 /// This struct is created by the [`splitn_mut`] method on [slices].
3033 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3034 /// [slices]: ../../std/primitive.slice.html
3035 #[stable(feature = "rust1", since = "1.0.0")]
3036 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3037 inner: GenericSplitN<SplitMut<'a, T, P>>
3040 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3041 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3042 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3043 f.debug_struct("SplitNMut")
3044 .field("inner", &self.inner)
3049 /// An iterator over subslices separated by elements that match a
3050 /// predicate function, limited to a given number of splits, starting
3051 /// from the end of the slice.
3053 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3055 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3056 /// [slices]: ../../std/primitive.slice.html
3057 #[stable(feature = "rust1", since = "1.0.0")]
3058 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3059 inner: GenericSplitN<RSplitMut<'a, T, P>>
3062 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3063 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3064 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3065 f.debug_struct("RSplitNMut")
3066 .field("inner", &self.inner)
3071 macro_rules! forward_iterator {
3072 ($name:ident: $elem:ident, $iter_of:ty) => {
3073 #[stable(feature = "rust1", since = "1.0.0")]
3074 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3075 P: FnMut(&T) -> bool
3077 type Item = $iter_of;
3080 fn next(&mut self) -> Option<$iter_of> {
3085 fn size_hint(&self) -> (usize, Option<usize>) {
3086 self.inner.size_hint()
3090 #[stable(feature = "fused", since = "1.26.0")]
3091 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3092 where P: FnMut(&T) -> bool {}
3096 forward_iterator! { SplitN: T, &'a [T] }
3097 forward_iterator! { RSplitN: T, &'a [T] }
3098 forward_iterator! { SplitNMut: T, &'a mut [T] }
3099 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3101 /// An iterator over overlapping subslices of length `size`.
3103 /// This struct is created by the [`windows`] method on [slices].
3105 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3106 /// [slices]: ../../std/primitive.slice.html
3108 #[stable(feature = "rust1", since = "1.0.0")]
3109 pub struct Windows<'a, T:'a> {
3114 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3115 #[stable(feature = "rust1", since = "1.0.0")]
3116 impl<'a, T> Clone for Windows<'a, T> {
3117 fn clone(&self) -> Windows<'a, T> {
3125 #[stable(feature = "rust1", since = "1.0.0")]
3126 impl<'a, T> Iterator for Windows<'a, T> {
3127 type Item = &'a [T];
3130 fn next(&mut self) -> Option<&'a [T]> {
3131 if self.size > self.v.len() {
3134 let ret = Some(&self.v[..self.size]);
3135 self.v = &self.v[1..];
3141 fn size_hint(&self) -> (usize, Option<usize>) {
3142 if self.size > self.v.len() {
3145 let size = self.v.len() - self.size + 1;
3151 fn count(self) -> usize {
3156 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3157 let (end, overflow) = self.size.overflowing_add(n);
3158 if end > self.v.len() || overflow {
3162 let nth = &self.v[n..end];
3163 self.v = &self.v[n+1..];
3169 fn last(self) -> Option<Self::Item> {
3170 if self.size > self.v.len() {
3173 let start = self.v.len() - self.size;
3174 Some(&self.v[start..])
3179 #[stable(feature = "rust1", since = "1.0.0")]
3180 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3182 fn next_back(&mut self) -> Option<&'a [T]> {
3183 if self.size > self.v.len() {
3186 let ret = Some(&self.v[self.v.len()-self.size..]);
3187 self.v = &self.v[..self.v.len()-1];
3193 #[stable(feature = "rust1", since = "1.0.0")]
3194 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3196 #[stable(feature = "fused", since = "1.26.0")]
3197 impl<'a, T> FusedIterator for Windows<'a, T> {}
3200 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3201 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3202 from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
3204 fn may_have_side_effect() -> bool { false }
3207 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3210 /// When the slice len is not evenly divided by the chunk size, the last slice
3211 /// of the iteration will be the remainder.
3213 /// This struct is created by the [`chunks`] method on [slices].
3215 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3216 /// [slices]: ../../std/primitive.slice.html
3218 #[stable(feature = "rust1", since = "1.0.0")]
3219 pub struct Chunks<'a, T:'a> {
3224 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3225 #[stable(feature = "rust1", since = "1.0.0")]
3226 impl<'a, T> Clone for Chunks<'a, T> {
3227 fn clone(&self) -> Chunks<'a, T> {
3230 chunk_size: self.chunk_size,
3235 #[stable(feature = "rust1", since = "1.0.0")]
3236 impl<'a, T> Iterator for Chunks<'a, T> {
3237 type Item = &'a [T];
3240 fn next(&mut self) -> Option<&'a [T]> {
3241 if self.v.is_empty() {
3244 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3245 let (fst, snd) = self.v.split_at(chunksz);
3252 fn size_hint(&self) -> (usize, Option<usize>) {
3253 if self.v.is_empty() {
3256 let n = self.v.len() / self.chunk_size;
3257 let rem = self.v.len() % self.chunk_size;
3258 let n = if rem > 0 { n+1 } else { n };
3264 fn count(self) -> usize {
3269 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3270 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3271 if start >= self.v.len() || overflow {
3275 let end = match start.checked_add(self.chunk_size) {
3276 Some(sum) => cmp::min(self.v.len(), sum),
3277 None => self.v.len(),
3279 let nth = &self.v[start..end];
3280 self.v = &self.v[end..];
3286 fn last(self) -> Option<Self::Item> {
3287 if self.v.is_empty() {
3290 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3291 Some(&self.v[start..])
3296 #[stable(feature = "rust1", since = "1.0.0")]
3297 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3299 fn next_back(&mut self) -> Option<&'a [T]> {
3300 if self.v.is_empty() {
3303 let remainder = self.v.len() % self.chunk_size;
3304 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3305 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3312 #[stable(feature = "rust1", since = "1.0.0")]
3313 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3315 #[stable(feature = "fused", since = "1.26.0")]
3316 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3319 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3320 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3321 let start = i * self.chunk_size;
3322 let end = match start.checked_add(self.chunk_size) {
3323 None => self.v.len(),
3324 Some(end) => cmp::min(end, self.v.len()),
3326 from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
3328 fn may_have_side_effect() -> bool { false }
3331 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3332 /// elements at a time). When the slice len is not evenly divided by the chunk
3333 /// size, the last slice of the iteration will be the remainder.
3335 /// This struct is created by the [`chunks_mut`] method on [slices].
3337 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3338 /// [slices]: ../../std/primitive.slice.html
3340 #[stable(feature = "rust1", since = "1.0.0")]
3341 pub struct ChunksMut<'a, T:'a> {
3346 #[stable(feature = "rust1", since = "1.0.0")]
3347 impl<'a, T> Iterator for ChunksMut<'a, T> {
3348 type Item = &'a mut [T];
3351 fn next(&mut self) -> Option<&'a mut [T]> {
3352 if self.v.is_empty() {
3355 let sz = cmp::min(self.v.len(), self.chunk_size);
3356 let tmp = mem::replace(&mut self.v, &mut []);
3357 let (head, tail) = tmp.split_at_mut(sz);
3364 fn size_hint(&self) -> (usize, Option<usize>) {
3365 if self.v.is_empty() {
3368 let n = self.v.len() / self.chunk_size;
3369 let rem = self.v.len() % self.chunk_size;
3370 let n = if rem > 0 { n + 1 } else { n };
3376 fn count(self) -> usize {
3381 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3382 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3383 if start >= self.v.len() || overflow {
3387 let end = match start.checked_add(self.chunk_size) {
3388 Some(sum) => cmp::min(self.v.len(), sum),
3389 None => self.v.len(),
3391 let tmp = mem::replace(&mut self.v, &mut []);
3392 let (head, tail) = tmp.split_at_mut(end);
3393 let (_, nth) = head.split_at_mut(start);
3400 fn last(self) -> Option<Self::Item> {
3401 if self.v.is_empty() {
3404 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3405 Some(&mut self.v[start..])
3410 #[stable(feature = "rust1", since = "1.0.0")]
3411 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3413 fn next_back(&mut self) -> Option<&'a mut [T]> {
3414 if self.v.is_empty() {
3417 let remainder = self.v.len() % self.chunk_size;
3418 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3419 let tmp = mem::replace(&mut self.v, &mut []);
3420 let tmp_len = tmp.len();
3421 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3428 #[stable(feature = "rust1", since = "1.0.0")]
3429 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3431 #[stable(feature = "fused", since = "1.26.0")]
3432 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3435 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3436 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3437 let start = i * self.chunk_size;
3438 let end = match start.checked_add(self.chunk_size) {
3439 None => self.v.len(),
3440 Some(end) => cmp::min(end, self.v.len()),
3442 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
3444 fn may_have_side_effect() -> bool { false }
3447 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3450 /// When the slice len is not evenly divided by the chunk size, the last
3451 /// up to `chunk_size-1` elements will be omitted.
3453 /// This struct is created by the [`exact_chunks`] method on [slices].
3455 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3456 /// [slices]: ../../std/primitive.slice.html
3458 #[unstable(feature = "exact_chunks", issue = "47115")]
3459 pub struct ExactChunks<'a, T:'a> {
3464 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3465 #[unstable(feature = "exact_chunks", issue = "47115")]
3466 impl<'a, T> Clone for ExactChunks<'a, T> {
3467 fn clone(&self) -> ExactChunks<'a, T> {
3470 chunk_size: self.chunk_size,
3475 #[unstable(feature = "exact_chunks", issue = "47115")]
3476 impl<'a, T> Iterator for ExactChunks<'a, T> {
3477 type Item = &'a [T];
3480 fn next(&mut self) -> Option<&'a [T]> {
3481 if self.v.len() < self.chunk_size {
3484 let (fst, snd) = self.v.split_at(self.chunk_size);
3491 fn size_hint(&self) -> (usize, Option<usize>) {
3492 let n = self.v.len() / self.chunk_size;
3497 fn count(self) -> usize {
3502 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3503 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3504 if start >= self.v.len() || overflow {
3508 let (_, snd) = self.v.split_at(start);
3515 fn last(mut self) -> Option<Self::Item> {
3520 #[unstable(feature = "exact_chunks", issue = "47115")]
3521 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3523 fn next_back(&mut self) -> Option<&'a [T]> {
3524 if self.v.len() < self.chunk_size {
3527 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3534 #[unstable(feature = "exact_chunks", issue = "47115")]
3535 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
3536 fn is_empty(&self) -> bool {
3541 #[unstable(feature = "exact_chunks", issue = "47115")]
3542 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
3545 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
3546 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3547 let start = i * self.chunk_size;
3548 from_raw_parts(self.v.as_ptr().offset(start as isize), self.chunk_size)
3550 fn may_have_side_effect() -> bool { false }
3553 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3554 /// elements at a time). When the slice len is not evenly divided by the chunk
3555 /// size, the last up to `chunk_size-1` elements will be omitted.
3557 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
3559 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
3560 /// [slices]: ../../std/primitive.slice.html
3562 #[unstable(feature = "exact_chunks", issue = "47115")]
3563 pub struct ExactChunksMut<'a, T:'a> {
3568 #[unstable(feature = "exact_chunks", issue = "47115")]
3569 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
3570 type Item = &'a mut [T];
3573 fn next(&mut self) -> Option<&'a mut [T]> {
3574 if self.v.len() < self.chunk_size {
3577 let tmp = mem::replace(&mut self.v, &mut []);
3578 let (head, tail) = tmp.split_at_mut(self.chunk_size);
3585 fn size_hint(&self) -> (usize, Option<usize>) {
3586 let n = self.v.len() / self.chunk_size;
3591 fn count(self) -> usize {
3596 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3597 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3598 if start >= self.v.len() || overflow {
3602 let tmp = mem::replace(&mut self.v, &mut []);
3603 let (_, snd) = tmp.split_at_mut(start);
3610 fn last(mut self) -> Option<Self::Item> {
3615 #[unstable(feature = "exact_chunks", issue = "47115")]
3616 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
3618 fn next_back(&mut self) -> Option<&'a mut [T]> {
3619 if self.v.len() < self.chunk_size {
3622 let tmp = mem::replace(&mut self.v, &mut []);
3623 let tmp_len = tmp.len();
3624 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
3631 #[unstable(feature = "exact_chunks", issue = "47115")]
3632 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
3633 fn is_empty(&self) -> bool {
3638 #[unstable(feature = "exact_chunks", issue = "47115")]
3639 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
3642 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
3643 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3644 let start = i * self.chunk_size;
3645 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), self.chunk_size)
3647 fn may_have_side_effect() -> bool { false }
3654 /// Forms a slice from a pointer and a length.
3656 /// The `len` argument is the number of **elements**, not the number of bytes.
3660 /// This function is unsafe as there is no guarantee that the given pointer is
3661 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
3662 /// lifetime for the returned slice.
3664 /// `p` must be non-null, even for zero-length slices, because non-zero bits
3665 /// are required to distinguish between a zero-length slice within `Some()`
3666 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
3667 /// for zero-length slices, though.
3671 /// The lifetime for the returned slice is inferred from its usage. To
3672 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
3673 /// source lifetime is safe in the context, such as by providing a helper
3674 /// function taking the lifetime of a host value for the slice, or by explicit
3682 /// // manifest a slice out of thin air!
3683 /// let ptr = 0x1234 as *const usize;
3686 /// let slice = slice::from_raw_parts(ptr, amt);
3690 #[stable(feature = "rust1", since = "1.0.0")]
3691 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
3692 mem::transmute(Repr { data: p, len: len })
3695 /// Performs the same functionality as `from_raw_parts`, except that a mutable
3696 /// slice is returned.
3698 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
3699 /// as not being able to provide a non-aliasing guarantee of the returned
3700 /// mutable slice. `p` must be non-null even for zero-length slices as with
3701 /// `from_raw_parts`.
3703 #[stable(feature = "rust1", since = "1.0.0")]
3704 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
3705 mem::transmute(Repr { data: p, len: len })
3708 /// Converts a reference to T into a slice of length 1 (without copying).
3709 #[unstable(feature = "from_ref", issue = "45703")]
3710 pub fn from_ref<T>(s: &T) -> &[T] {
3712 from_raw_parts(s, 1)
3716 /// Converts a reference to T into a slice of length 1 (without copying).
3717 #[unstable(feature = "from_ref", issue = "45703")]
3718 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
3720 from_raw_parts_mut(s, 1)
3724 // This function is public only because there is no other way to unit test heapsort.
3725 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
3727 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
3728 where F: FnMut(&T, &T) -> bool
3730 sort::heapsort(v, &mut is_less);
3734 // Comparison traits
3738 /// Calls implementation provided memcmp.
3740 /// Interprets the data as u8.
3742 /// Returns 0 for equal, < 0 for less than and > 0 for greater
3744 // FIXME(#32610): Return type should be c_int
3745 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
3748 #[stable(feature = "rust1", since = "1.0.0")]
3749 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
3750 fn eq(&self, other: &[B]) -> bool {
3751 SlicePartialEq::equal(self, other)
3754 fn ne(&self, other: &[B]) -> bool {
3755 SlicePartialEq::not_equal(self, other)
3759 #[stable(feature = "rust1", since = "1.0.0")]
3760 impl<T: Eq> Eq for [T] {}
3762 /// Implements comparison of vectors lexicographically.
3763 #[stable(feature = "rust1", since = "1.0.0")]
3764 impl<T: Ord> Ord for [T] {
3765 fn cmp(&self, other: &[T]) -> Ordering {
3766 SliceOrd::compare(self, other)
3770 /// Implements comparison of vectors lexicographically.
3771 #[stable(feature = "rust1", since = "1.0.0")]
3772 impl<T: PartialOrd> PartialOrd for [T] {
3773 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
3774 SlicePartialOrd::partial_compare(self, other)
3779 // intermediate trait for specialization of slice's PartialEq
3780 trait SlicePartialEq<B> {
3781 fn equal(&self, other: &[B]) -> bool;
3783 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
3786 // Generic slice equality
3787 impl<A, B> SlicePartialEq<B> for [A]
3788 where A: PartialEq<B>
3790 default fn equal(&self, other: &[B]) -> bool {
3791 if self.len() != other.len() {
3795 for i in 0..self.len() {
3796 if !self[i].eq(&other[i]) {
3805 // Use memcmp for bytewise equality when the types allow
3806 impl<A> SlicePartialEq<A> for [A]
3807 where A: PartialEq<A> + BytewiseEquality
3809 fn equal(&self, other: &[A]) -> bool {
3810 if self.len() != other.len() {
3813 if self.as_ptr() == other.as_ptr() {
3817 let size = mem::size_of_val(self);
3818 memcmp(self.as_ptr() as *const u8,
3819 other.as_ptr() as *const u8, size) == 0
3825 // intermediate trait for specialization of slice's PartialOrd
3826 trait SlicePartialOrd<B> {
3827 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
3830 impl<A> SlicePartialOrd<A> for [A]
3833 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
3834 let l = cmp::min(self.len(), other.len());
3836 // Slice to the loop iteration range to enable bound check
3837 // elimination in the compiler
3838 let lhs = &self[..l];
3839 let rhs = &other[..l];
3842 match lhs[i].partial_cmp(&rhs[i]) {
3843 Some(Ordering::Equal) => (),
3844 non_eq => return non_eq,
3848 self.len().partial_cmp(&other.len())
3852 impl<A> SlicePartialOrd<A> for [A]
3855 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
3856 Some(SliceOrd::compare(self, other))
3861 // intermediate trait for specialization of slice's Ord
3863 fn compare(&self, other: &[B]) -> Ordering;
3866 impl<A> SliceOrd<A> for [A]
3869 default fn compare(&self, other: &[A]) -> Ordering {
3870 let l = cmp::min(self.len(), other.len());
3872 // Slice to the loop iteration range to enable bound check
3873 // elimination in the compiler
3874 let lhs = &self[..l];
3875 let rhs = &other[..l];
3878 match lhs[i].cmp(&rhs[i]) {
3879 Ordering::Equal => (),
3880 non_eq => return non_eq,
3884 self.len().cmp(&other.len())
3888 // memcmp compares a sequence of unsigned bytes lexicographically.
3889 // this matches the order we want for [u8], but no others (not even [i8]).
3890 impl SliceOrd<u8> for [u8] {
3892 fn compare(&self, other: &[u8]) -> Ordering {
3893 let order = unsafe {
3894 memcmp(self.as_ptr(), other.as_ptr(),
3895 cmp::min(self.len(), other.len()))
3898 self.len().cmp(&other.len())
3899 } else if order < 0 {
3908 /// Trait implemented for types that can be compared for equality using
3909 /// their bytewise representation
3910 trait BytewiseEquality { }
3912 macro_rules! impl_marker_for {
3913 ($traitname:ident, $($ty:ty)*) => {
3915 impl $traitname for $ty { }
3920 impl_marker_for!(BytewiseEquality,
3921 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
3924 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
3925 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
3926 &*self.ptr.offset(i as isize)
3928 fn may_have_side_effect() -> bool { false }
3932 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
3933 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
3934 &mut *self.ptr.offset(i as isize)
3936 fn may_have_side_effect() -> bool { false }
3939 trait SliceContains: Sized {
3940 fn slice_contains(&self, x: &[Self]) -> bool;
3943 impl<T> SliceContains for T where T: PartialEq {
3944 default fn slice_contains(&self, x: &[Self]) -> bool {
3945 x.iter().any(|y| *y == *self)
3949 impl SliceContains for u8 {
3950 fn slice_contains(&self, x: &[Self]) -> bool {
3951 memchr::memchr(*self, x).is_some()
3955 impl SliceContains for i8 {
3956 fn slice_contains(&self, x: &[Self]) -> bool {
3957 let byte = *self as u8;
3958 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
3959 memchr::memchr(byte, bytes).is_some()