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());
1700 /// Function to calculate lenghts of the middle and trailing slice for `align_to{,_mut}`.
1702 fn align_to_offsets<U>(&self) -> (usize, usize) {
1703 // What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
1704 // lowest number of `T`s. And how many `T`s we need for each such "multiple".
1706 // Consider for example T=u8 U=u16. Then we can put 1 U in 2 Ts. Simple. Now, consider
1707 // for example a case where size_of::<T> = 16, size_of::<U> = 24. We can put 2 Us in
1708 // place of every 3 Ts in the `rest` slice. A bit more complicated.
1710 // Formula to calculate this is:
1712 // Us = lcm(size_of::<T>, size_of::<U>) / size_of::<U>
1713 // Ts = lcm(size_of::<T>, size_of::<U>) / size_of::<T>
1715 // Expanded and simplified:
1717 // Us = size_of::<T> / gcd(size_of::<T>, size_of::<U>)
1718 // Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
1720 // Luckily since all this is constant-evaluated... performance here matters not!
1722 fn gcd(a: usize, b: usize) -> usize {
1723 // iterative stein’s algorithm
1724 // We should still make this `const fn` (and revert to recursive algorithm if we do)
1725 // because relying on llvm to consteval all this is… well, it makes me
1726 let (ctz_a, mut ctz_b) = unsafe {
1727 if a == 0 { return b; }
1728 if b == 0 { return a; }
1729 (::intrinsics::cttz_nonzero(a), ::intrinsics::cttz_nonzero(b))
1731 let k = ctz_a.min(ctz_b);
1732 let mut a = a >> ctz_a;
1735 // remove all factors of 2 from b
1738 ::mem::swap(&mut a, &mut b);
1745 ctz_b = ::intrinsics::cttz_nonzero(b);
1750 let gcd: usize = gcd(::mem::size_of::<T>(), ::mem::size_of::<U>());
1751 let ts: usize = ::mem::size_of::<U>() / gcd;
1752 let us: usize = ::mem::size_of::<T>() / gcd;
1754 // Armed with this knowledge, we can find how many `U`s we can fit!
1755 let us_len = self.len() / ts * us;
1756 // And how many `T`s will be in the trailing slice!
1757 let ts_len = self.len() % ts;
1758 return (us_len, ts_len);
1761 /// Transmute the slice to a slice of another type, ensuring aligment of the types is
1764 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1765 /// slice of a new type, and the suffix slice. The middle slice will have the greatest length
1766 /// possible for a given type and input slice.
1768 /// This method has no purpose when either input element `T` or output element `U` are
1769 /// zero-sized and will return the original slice without splitting anything.
1773 /// This method is essentially a `transmute` with respect to the elements in the returned
1774 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1781 /// # #![feature(slice_align_to)]
1783 /// let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1784 /// let (prefix, shorts, suffix) = bytes.align_to::<u16>();
1785 /// // less_efficient_algorithm_for_bytes(prefix);
1786 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1787 /// // less_efficient_algorithm_for_bytes(suffix);
1790 #[unstable(feature = "slice_align_to", issue = "44488")]
1792 pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T]) {
1793 // Note that most of this function will be constant-evaluated,
1794 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1795 // handle ZSTs specially, which is – don't handle them at all.
1796 return (self, &[], &[]);
1799 // First, find at what point do we split between the first and 2nd slice. Easy with
1800 // ptr.align_offset.
1801 let ptr = self.as_ptr();
1802 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1803 if offset > self.len() {
1804 return (self, &[], &[]);
1806 let (left, rest) = self.split_at(offset);
1807 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1809 from_raw_parts(rest.as_ptr() as *const U, us_len),
1810 from_raw_parts(rest.as_ptr().offset((rest.len() - ts_len) as isize), ts_len))
1814 /// Transmute the slice to a slice of another type, ensuring aligment of the types is
1817 /// This method splits the slice into three distinct slices: prefix, correctly aligned middle
1818 /// slice of a new type, and the suffix slice. The middle slice will have the greatest length
1819 /// possible for a given type and input slice.
1821 /// This method has no purpose when either input element `T` or output element `U` are
1822 /// zero-sized and will return the original slice without splitting anything.
1826 /// This method is essentially a `transmute` with respect to the elements in the returned
1827 /// middle slice, so all the usual caveats pertaining to `transmute::<T, U>` also apply here.
1834 /// # #![feature(slice_align_to)]
1836 /// let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
1837 /// let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
1838 /// // less_efficient_algorithm_for_bytes(prefix);
1839 /// // more_efficient_algorithm_for_aligned_shorts(shorts);
1840 /// // less_efficient_algorithm_for_bytes(suffix);
1843 #[unstable(feature = "slice_align_to", issue = "44488")]
1845 pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T]) {
1846 // Note that most of this function will be constant-evaluated,
1847 if ::mem::size_of::<U>() == 0 || ::mem::size_of::<T>() == 0 {
1848 // handle ZSTs specially, which is – don't handle them at all.
1849 return (self, &mut [], &mut []);
1852 // First, find at what point do we split between the first and 2nd slice. Easy with
1853 // ptr.align_offset.
1854 let ptr = self.as_ptr();
1855 let offset = ::ptr::align_offset(ptr, ::mem::align_of::<U>());
1856 if offset > self.len() {
1857 return (self, &mut [], &mut []);
1859 let (left, rest) = self.split_at_mut(offset);
1860 let (us_len, ts_len) = rest.align_to_offsets::<U>();
1861 let mut_ptr = rest.as_mut_ptr();
1863 from_raw_parts_mut(mut_ptr as *mut U, us_len),
1864 from_raw_parts_mut(mut_ptr.offset((rest.len() - ts_len) as isize), ts_len))
1869 #[lang = "slice_u8"]
1872 /// Checks if all bytes in this slice are within the ASCII range.
1873 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1875 pub fn is_ascii(&self) -> bool {
1876 self.iter().all(|b| b.is_ascii())
1879 /// Checks that two slices are an ASCII case-insensitive match.
1881 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
1882 /// but without allocating and copying temporaries.
1883 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1885 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
1886 self.len() == other.len() &&
1887 self.iter().zip(other).all(|(a, b)| {
1888 a.eq_ignore_ascii_case(b)
1892 /// Converts this slice to its ASCII upper case equivalent in-place.
1894 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
1895 /// but non-ASCII letters are unchanged.
1897 /// To return a new uppercased value without modifying the existing one, use
1898 /// [`to_ascii_uppercase`].
1900 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
1901 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1903 pub fn make_ascii_uppercase(&mut self) {
1905 byte.make_ascii_uppercase();
1909 /// Converts this slice to its ASCII lower case equivalent in-place.
1911 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
1912 /// but non-ASCII letters are unchanged.
1914 /// To return a new lowercased value without modifying the existing one, use
1915 /// [`to_ascii_lowercase`].
1917 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
1918 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
1920 pub fn make_ascii_lowercase(&mut self) {
1922 byte.make_ascii_lowercase();
1928 #[stable(feature = "rust1", since = "1.0.0")]
1929 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1930 impl<T, I> ops::Index<I> for [T]
1931 where I: SliceIndex<[T]>
1933 type Output = I::Output;
1936 fn index(&self, index: I) -> &I::Output {
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1943 impl<T, I> ops::IndexMut<I> for [T]
1944 where I: SliceIndex<[T]>
1947 fn index_mut(&mut self, index: I) -> &mut I::Output {
1948 index.index_mut(self)
1954 fn slice_index_len_fail(index: usize, len: usize) -> ! {
1955 panic!("index {} out of range for slice of length {}", index, len);
1960 fn slice_index_order_fail(index: usize, end: usize) -> ! {
1961 panic!("slice index starts at {} but ends at {}", index, end);
1966 fn slice_index_overflow_fail() -> ! {
1967 panic!("attempted to index slice up to maximum usize");
1970 /// A helper trait used for indexing operations.
1971 #[unstable(feature = "slice_get_slice", issue = "35729")]
1972 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
1973 pub trait SliceIndex<T: ?Sized> {
1974 /// The output type returned by methods.
1975 type Output: ?Sized;
1977 /// Returns a shared reference to the output at this location, if in
1979 fn get(self, slice: &T) -> Option<&Self::Output>;
1981 /// Returns a mutable reference to the output at this location, if in
1983 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
1985 /// Returns a shared reference to the output at this location, without
1986 /// performing any bounds checking.
1987 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
1989 /// Returns a mutable reference to the output at this location, without
1990 /// performing any bounds checking.
1991 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
1993 /// Returns a shared reference to the output at this location, panicking
1994 /// if out of bounds.
1995 fn index(self, slice: &T) -> &Self::Output;
1997 /// Returns a mutable reference to the output at this location, panicking
1998 /// if out of bounds.
1999 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2002 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2003 impl<T> SliceIndex<[T]> for usize {
2007 fn get(self, slice: &[T]) -> Option<&T> {
2008 if self < slice.len() {
2010 Some(self.get_unchecked(slice))
2018 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2019 if self < slice.len() {
2021 Some(self.get_unchecked_mut(slice))
2029 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2030 &*slice.as_ptr().offset(self as isize)
2034 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2035 &mut *slice.as_mut_ptr().offset(self as isize)
2039 fn index(self, slice: &[T]) -> &T {
2040 // NB: use intrinsic indexing
2045 fn index_mut(self, slice: &mut [T]) -> &mut T {
2046 // NB: use intrinsic indexing
2051 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2052 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2056 fn get(self, slice: &[T]) -> Option<&[T]> {
2057 if self.start > self.end || self.end > slice.len() {
2061 Some(self.get_unchecked(slice))
2067 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2068 if self.start > self.end || self.end > slice.len() {
2072 Some(self.get_unchecked_mut(slice))
2078 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2079 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
2083 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2084 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
2088 fn index(self, slice: &[T]) -> &[T] {
2089 if self.start > self.end {
2090 slice_index_order_fail(self.start, self.end);
2091 } else if self.end > slice.len() {
2092 slice_index_len_fail(self.end, slice.len());
2095 self.get_unchecked(slice)
2100 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2101 if self.start > self.end {
2102 slice_index_order_fail(self.start, self.end);
2103 } else if self.end > slice.len() {
2104 slice_index_len_fail(self.end, slice.len());
2107 self.get_unchecked_mut(slice)
2112 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2113 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2117 fn get(self, slice: &[T]) -> Option<&[T]> {
2118 (0..self.end).get(slice)
2122 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2123 (0..self.end).get_mut(slice)
2127 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2128 (0..self.end).get_unchecked(slice)
2132 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2133 (0..self.end).get_unchecked_mut(slice)
2137 fn index(self, slice: &[T]) -> &[T] {
2138 (0..self.end).index(slice)
2142 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2143 (0..self.end).index_mut(slice)
2147 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2148 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2152 fn get(self, slice: &[T]) -> Option<&[T]> {
2153 (self.start..slice.len()).get(slice)
2157 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2158 (self.start..slice.len()).get_mut(slice)
2162 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2163 (self.start..slice.len()).get_unchecked(slice)
2167 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2168 (self.start..slice.len()).get_unchecked_mut(slice)
2172 fn index(self, slice: &[T]) -> &[T] {
2173 (self.start..slice.len()).index(slice)
2177 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2178 (self.start..slice.len()).index_mut(slice)
2182 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2183 impl<T> SliceIndex<[T]> for ops::RangeFull {
2187 fn get(self, slice: &[T]) -> Option<&[T]> {
2192 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2197 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2202 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2207 fn index(self, slice: &[T]) -> &[T] {
2212 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2218 #[stable(feature = "inclusive_range", since = "1.26.0")]
2219 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2223 fn get(self, slice: &[T]) -> Option<&[T]> {
2224 if self.end == usize::max_value() { None }
2225 else { (self.start..self.end + 1).get(slice) }
2229 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2230 if self.end == usize::max_value() { None }
2231 else { (self.start..self.end + 1).get_mut(slice) }
2235 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2236 (self.start..self.end + 1).get_unchecked(slice)
2240 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2241 (self.start..self.end + 1).get_unchecked_mut(slice)
2245 fn index(self, slice: &[T]) -> &[T] {
2246 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2247 (self.start..self.end + 1).index(slice)
2251 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2252 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2253 (self.start..self.end + 1).index_mut(slice)
2257 #[stable(feature = "inclusive_range", since = "1.26.0")]
2258 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2262 fn get(self, slice: &[T]) -> Option<&[T]> {
2263 (0..=self.end).get(slice)
2267 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2268 (0..=self.end).get_mut(slice)
2272 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2273 (0..=self.end).get_unchecked(slice)
2277 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2278 (0..=self.end).get_unchecked_mut(slice)
2282 fn index(self, slice: &[T]) -> &[T] {
2283 (0..=self.end).index(slice)
2287 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2288 (0..=self.end).index_mut(slice)
2292 ////////////////////////////////////////////////////////////////////////////////
2294 ////////////////////////////////////////////////////////////////////////////////
2296 #[stable(feature = "rust1", since = "1.0.0")]
2297 impl<'a, T> Default for &'a [T] {
2298 /// Creates an empty slice.
2299 fn default() -> &'a [T] { &[] }
2302 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2303 impl<'a, T> Default for &'a mut [T] {
2304 /// Creates a mutable empty slice.
2305 fn default() -> &'a mut [T] { &mut [] }
2312 #[stable(feature = "rust1", since = "1.0.0")]
2313 impl<'a, T> IntoIterator for &'a [T] {
2315 type IntoIter = Iter<'a, T>;
2317 fn into_iter(self) -> Iter<'a, T> {
2322 #[stable(feature = "rust1", since = "1.0.0")]
2323 impl<'a, T> IntoIterator for &'a mut [T] {
2324 type Item = &'a mut T;
2325 type IntoIter = IterMut<'a, T>;
2327 fn into_iter(self) -> IterMut<'a, T> {
2333 fn size_from_ptr<T>(_: *const T) -> usize {
2337 // The shared definition of the `Iter` and `IterMut` iterators
2338 macro_rules! iterator {
2339 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 impl<'a, T> Iterator for $name<'a, T> {
2345 fn next(&mut self) -> Option<$elem> {
2346 // could be implemented with slices, but this avoids bounds checks
2348 if mem::size_of::<T>() != 0 {
2349 assume(!self.ptr.is_null());
2350 assume(!self.end.is_null());
2352 if self.ptr == self.end {
2355 Some($mkref!(self.ptr.post_inc()))
2361 fn size_hint(&self) -> (usize, Option<usize>) {
2362 let exact = unsafe { ptrdistance(self.ptr, self.end) };
2363 (exact, Some(exact))
2367 fn count(self) -> usize {
2372 fn nth(&mut self, n: usize) -> Option<$elem> {
2373 // Call helper method. Can't put the definition here because mut versus const.
2378 fn last(mut self) -> Option<$elem> {
2383 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2384 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2386 // manual unrolling is needed when there are conditional exits from the loop
2387 let mut accum = init;
2389 while ptrdistance(self.ptr, self.end) >= 4 {
2390 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2391 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2392 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2393 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2395 while self.ptr != self.end {
2396 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2403 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2404 where Fold: FnMut(Acc, Self::Item) -> Acc,
2406 // Let LLVM unroll this, rather than using the default
2407 // impl that would force the manual unrolling above
2408 let mut accum = init;
2409 while let Some(x) = self.next() {
2410 accum = f(accum, x);
2416 #[rustc_inherit_overflow_checks]
2417 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2419 P: FnMut(Self::Item) -> bool,
2421 // The addition might panic on overflow
2422 // Use the len of the slice to hint optimizer to remove result index bounds check.
2423 let n = make_slice!(self.ptr, self.end).len();
2424 self.try_fold(0, move |i, x| {
2425 if predicate(x) { Err(i) }
2429 unsafe { assume(i < n) };
2435 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2436 P: FnMut(Self::Item) -> bool,
2437 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2439 // No need for an overflow check here, because `ExactSizeIterator`
2440 // implies that the number of elements fits into a `usize`.
2441 // Use the len of the slice to hint optimizer to remove result index bounds check.
2442 let n = make_slice!(self.ptr, self.end).len();
2443 self.try_rfold(n, move |i, x| {
2445 if predicate(x) { Err(i) }
2449 unsafe { assume(i < n) };
2455 #[stable(feature = "rust1", since = "1.0.0")]
2456 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2458 fn next_back(&mut self) -> Option<$elem> {
2459 // could be implemented with slices, but this avoids bounds checks
2461 if mem::size_of::<T>() != 0 {
2462 assume(!self.ptr.is_null());
2463 assume(!self.end.is_null());
2465 if self.end == self.ptr {
2468 Some($mkref!(self.end.pre_dec()))
2474 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2475 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2477 // manual unrolling is needed when there are conditional exits from the loop
2478 let mut accum = init;
2480 while ptrdistance(self.ptr, self.end) >= 4 {
2481 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2482 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2483 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2484 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2486 while self.ptr != self.end {
2487 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2494 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2495 where Fold: FnMut(Acc, Self::Item) -> Acc,
2497 // Let LLVM unroll this, rather than using the default
2498 // impl that would force the manual unrolling above
2499 let mut accum = init;
2500 while let Some(x) = self.next_back() {
2501 accum = f(accum, x);
2509 macro_rules! make_slice {
2510 ($start: expr, $end: expr) => {{
2512 let diff = ($end as usize).wrapping_sub(start as usize);
2513 if size_from_ptr(start) == 0 {
2514 // use a non-null pointer value
2515 unsafe { from_raw_parts(1 as *const _, diff) }
2517 let len = diff / size_from_ptr(start);
2518 unsafe { from_raw_parts(start, len) }
2523 macro_rules! make_mut_slice {
2524 ($start: expr, $end: expr) => {{
2526 let diff = ($end as usize).wrapping_sub(start as usize);
2527 if size_from_ptr(start) == 0 {
2528 // use a non-null pointer value
2529 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
2531 let len = diff / size_from_ptr(start);
2532 unsafe { from_raw_parts_mut(start, len) }
2537 /// Immutable slice iterator
2539 /// This struct is created by the [`iter`] method on [slices].
2546 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2547 /// let slice = &[1, 2, 3];
2549 /// // Then, we iterate over it:
2550 /// for element in slice.iter() {
2551 /// println!("{}", element);
2555 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2556 /// [slices]: ../../std/primitive.slice.html
2557 #[stable(feature = "rust1", since = "1.0.0")]
2558 pub struct Iter<'a, T: 'a> {
2561 _marker: marker::PhantomData<&'a T>,
2564 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2565 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2567 f.debug_tuple("Iter")
2568 .field(&self.as_slice())
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2575 #[stable(feature = "rust1", since = "1.0.0")]
2576 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2578 impl<'a, T> Iter<'a, T> {
2579 /// View the underlying data as a subslice of the original data.
2581 /// This has the same lifetime as the original slice, and so the
2582 /// iterator can continue to be used while this exists.
2589 /// // First, we declare a type which has the `iter` method to get the `Iter`
2590 /// // struct (&[usize here]):
2591 /// let slice = &[1, 2, 3];
2593 /// // Then, we get the iterator:
2594 /// let mut iter = slice.iter();
2595 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2596 /// println!("{:?}", iter.as_slice());
2598 /// // Next, we move to the second element of the slice:
2600 /// // Now `as_slice` returns "[2, 3]":
2601 /// println!("{:?}", iter.as_slice());
2603 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2604 pub fn as_slice(&self) -> &'a [T] {
2605 make_slice!(self.ptr, self.end)
2608 // Helper function for Iter::nth
2609 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
2610 match self.as_slice().get(n) {
2611 Some(elem_ref) => unsafe {
2612 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2616 self.ptr = self.end;
2623 iterator!{struct Iter -> *const T, &'a T, make_ref}
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2627 fn is_empty(&self) -> bool {
2628 self.ptr == self.end
2632 #[stable(feature = "fused", since = "1.26.0")]
2633 impl<'a, T> FusedIterator for Iter<'a, T> {}
2635 #[unstable(feature = "trusted_len", issue = "37572")]
2636 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
2638 #[stable(feature = "rust1", since = "1.0.0")]
2639 impl<'a, T> Clone for Iter<'a, T> {
2640 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2643 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2644 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2645 fn as_ref(&self) -> &[T] {
2650 /// Mutable slice iterator.
2652 /// This struct is created by the [`iter_mut`] method on [slices].
2659 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2660 /// // struct (&[usize here]):
2661 /// let mut slice = &mut [1, 2, 3];
2663 /// // Then, we iterate over it and increment each element value:
2664 /// for element in slice.iter_mut() {
2668 /// // We now have "[2, 3, 4]":
2669 /// println!("{:?}", slice);
2672 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2673 /// [slices]: ../../std/primitive.slice.html
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 pub struct IterMut<'a, T: 'a> {
2678 _marker: marker::PhantomData<&'a mut T>,
2681 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2682 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2684 f.debug_tuple("IterMut")
2685 .field(&make_slice!(self.ptr, self.end))
2690 #[stable(feature = "rust1", since = "1.0.0")]
2691 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2692 #[stable(feature = "rust1", since = "1.0.0")]
2693 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2695 impl<'a, T> IterMut<'a, T> {
2696 /// View the underlying data as a subslice of the original data.
2698 /// To avoid creating `&mut` references that alias, this is forced
2699 /// to consume the iterator. Consider using the `Slice` and
2700 /// `SliceMut` implementations for obtaining slices with more
2701 /// restricted lifetimes that do not consume the iterator.
2708 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2709 /// // struct (&[usize here]):
2710 /// let mut slice = &mut [1, 2, 3];
2713 /// // Then, we get the iterator:
2714 /// let mut iter = slice.iter_mut();
2715 /// // We move to next element:
2717 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
2718 /// println!("{:?}", iter.into_slice());
2721 /// // Now let's modify a value of the slice:
2723 /// // First we get back the iterator:
2724 /// let mut iter = slice.iter_mut();
2725 /// // We change the value of the first element of the slice returned by the `next` method:
2726 /// *iter.next().unwrap() += 1;
2728 /// // Now slice is "[2, 2, 3]":
2729 /// println!("{:?}", slice);
2731 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2732 pub fn into_slice(self) -> &'a mut [T] {
2733 make_mut_slice!(self.ptr, self.end)
2736 // Helper function for IterMut::nth
2737 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
2738 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
2739 Some(elem_ref) => unsafe {
2740 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2744 self.ptr = self.end;
2751 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
2753 #[stable(feature = "rust1", since = "1.0.0")]
2754 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
2755 fn is_empty(&self) -> bool {
2756 self.ptr == self.end
2760 #[stable(feature = "fused", since = "1.26.0")]
2761 impl<'a, T> FusedIterator for IterMut<'a, T> {}
2763 #[unstable(feature = "trusted_len", issue = "37572")]
2764 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
2767 // Return the number of elements of `T` from `start` to `end`.
2768 // Return the arithmetic difference if `T` is zero size.
2770 unsafe fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
2771 if mem::size_of::<T>() == 0 {
2772 (end as usize).wrapping_sub(start as usize)
2774 end.offset_from(start) as usize
2778 // Extension methods for raw pointers, used by the iterators
2779 trait PointerExt : Copy {
2780 unsafe fn slice_offset(self, i: isize) -> Self;
2782 /// Increments `self` by 1, but returns the old value.
2784 unsafe fn post_inc(&mut self) -> Self {
2785 let current = *self;
2786 *self = self.slice_offset(1);
2790 /// Decrements `self` by 1, and returns the new value.
2792 unsafe fn pre_dec(&mut self) -> Self {
2793 *self = self.slice_offset(-1);
2798 impl<T> PointerExt for *const T {
2800 unsafe fn slice_offset(self, i: isize) -> Self {
2801 slice_offset!(self, i)
2805 impl<T> PointerExt for *mut T {
2807 unsafe fn slice_offset(self, i: isize) -> Self {
2808 slice_offset!(self, i)
2812 /// An internal abstraction over the splitting iterators, so that
2813 /// splitn, splitn_mut etc can be implemented once.
2815 trait SplitIter: DoubleEndedIterator {
2816 /// Marks the underlying iterator as complete, extracting the remaining
2817 /// portion of the slice.
2818 fn finish(&mut self) -> Option<Self::Item>;
2821 /// An iterator over subslices separated by elements that match a predicate
2824 /// This struct is created by the [`split`] method on [slices].
2826 /// [`split`]: ../../std/primitive.slice.html#method.split
2827 /// [slices]: ../../std/primitive.slice.html
2828 #[stable(feature = "rust1", since = "1.0.0")]
2829 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
2835 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2836 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
2837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2838 f.debug_struct("Split")
2839 .field("v", &self.v)
2840 .field("finished", &self.finished)
2845 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
2846 #[stable(feature = "rust1", since = "1.0.0")]
2847 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
2848 fn clone(&self) -> Split<'a, T, P> {
2851 pred: self.pred.clone(),
2852 finished: self.finished,
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2859 type Item = &'a [T];
2862 fn next(&mut self) -> Option<&'a [T]> {
2863 if self.finished { return None; }
2865 match self.v.iter().position(|x| (self.pred)(x)) {
2866 None => self.finish(),
2868 let ret = Some(&self.v[..idx]);
2869 self.v = &self.v[idx + 1..];
2876 fn size_hint(&self) -> (usize, Option<usize>) {
2880 (1, Some(self.v.len() + 1))
2885 #[stable(feature = "rust1", since = "1.0.0")]
2886 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
2888 fn next_back(&mut self) -> Option<&'a [T]> {
2889 if self.finished { return None; }
2891 match self.v.iter().rposition(|x| (self.pred)(x)) {
2892 None => self.finish(),
2894 let ret = Some(&self.v[idx + 1..]);
2895 self.v = &self.v[..idx];
2902 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
2904 fn finish(&mut self) -> Option<&'a [T]> {
2905 if self.finished { None } else { self.finished = true; Some(self.v) }
2909 #[stable(feature = "fused", since = "1.26.0")]
2910 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
2912 /// An iterator over the subslices of the vector which are separated
2913 /// by elements that match `pred`.
2915 /// This struct is created by the [`split_mut`] method on [slices].
2917 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
2918 /// [slices]: ../../std/primitive.slice.html
2919 #[stable(feature = "rust1", since = "1.0.0")]
2920 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
2926 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2927 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2928 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2929 f.debug_struct("SplitMut")
2930 .field("v", &self.v)
2931 .field("finished", &self.finished)
2936 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2938 fn finish(&mut self) -> Option<&'a mut [T]> {
2942 self.finished = true;
2943 Some(mem::replace(&mut self.v, &mut []))
2948 #[stable(feature = "rust1", since = "1.0.0")]
2949 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
2950 type Item = &'a mut [T];
2953 fn next(&mut self) -> Option<&'a mut [T]> {
2954 if self.finished { return None; }
2956 let idx_opt = { // work around borrowck limitations
2957 let pred = &mut self.pred;
2958 self.v.iter().position(|x| (*pred)(x))
2961 None => self.finish(),
2963 let tmp = mem::replace(&mut self.v, &mut []);
2964 let (head, tail) = tmp.split_at_mut(idx);
2965 self.v = &mut tail[1..];
2972 fn size_hint(&self) -> (usize, Option<usize>) {
2976 // if the predicate doesn't match anything, we yield one slice
2977 // if it matches every element, we yield len+1 empty slices.
2978 (1, Some(self.v.len() + 1))
2983 #[stable(feature = "rust1", since = "1.0.0")]
2984 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
2985 P: FnMut(&T) -> bool,
2988 fn next_back(&mut self) -> Option<&'a mut [T]> {
2989 if self.finished { return None; }
2991 let idx_opt = { // work around borrowck limitations
2992 let pred = &mut self.pred;
2993 self.v.iter().rposition(|x| (*pred)(x))
2996 None => self.finish(),
2998 let tmp = mem::replace(&mut self.v, &mut []);
2999 let (head, tail) = tmp.split_at_mut(idx);
3001 Some(&mut tail[1..])
3007 #[stable(feature = "fused", since = "1.26.0")]
3008 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3010 /// An iterator over subslices separated by elements that match a predicate
3011 /// function, starting from the end of the slice.
3013 /// This struct is created by the [`rsplit`] method on [slices].
3015 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3016 /// [slices]: ../../std/primitive.slice.html
3017 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3018 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3019 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3020 inner: Split<'a, T, P>
3023 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3024 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3025 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3026 f.debug_struct("RSplit")
3027 .field("v", &self.inner.v)
3028 .field("finished", &self.inner.finished)
3033 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3034 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3035 type Item = &'a [T];
3038 fn next(&mut self) -> Option<&'a [T]> {
3039 self.inner.next_back()
3043 fn size_hint(&self) -> (usize, Option<usize>) {
3044 self.inner.size_hint()
3048 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3049 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3051 fn next_back(&mut self) -> Option<&'a [T]> {
3056 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3057 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3059 fn finish(&mut self) -> Option<&'a [T]> {
3064 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3065 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
3067 /// An iterator over the subslices of the vector which are separated
3068 /// by elements that match `pred`, starting from the end of the slice.
3070 /// This struct is created by the [`rsplit_mut`] method on [slices].
3072 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3073 /// [slices]: ../../std/primitive.slice.html
3074 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3075 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3076 inner: SplitMut<'a, T, P>
3079 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3080 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3081 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3082 f.debug_struct("RSplitMut")
3083 .field("v", &self.inner.v)
3084 .field("finished", &self.inner.finished)
3089 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3090 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3092 fn finish(&mut self) -> Option<&'a mut [T]> {
3097 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3098 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3099 type Item = &'a mut [T];
3102 fn next(&mut self) -> Option<&'a mut [T]> {
3103 self.inner.next_back()
3107 fn size_hint(&self) -> (usize, Option<usize>) {
3108 self.inner.size_hint()
3112 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3113 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3114 P: FnMut(&T) -> bool,
3117 fn next_back(&mut self) -> Option<&'a mut [T]> {
3122 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3123 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3125 /// An private iterator over subslices separated by elements that
3126 /// match a predicate function, splitting at most a fixed number of
3129 struct GenericSplitN<I> {
3134 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3138 fn next(&mut self) -> Option<T> {
3141 1 => { self.count -= 1; self.iter.finish() }
3142 _ => { self.count -= 1; self.iter.next() }
3147 fn size_hint(&self) -> (usize, Option<usize>) {
3148 let (lower, upper_opt) = self.iter.size_hint();
3149 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3153 /// An iterator over subslices separated by elements that match a predicate
3154 /// function, limited to a given number of splits.
3156 /// This struct is created by the [`splitn`] method on [slices].
3158 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3159 /// [slices]: ../../std/primitive.slice.html
3160 #[stable(feature = "rust1", since = "1.0.0")]
3161 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3162 inner: GenericSplitN<Split<'a, T, P>>
3165 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3166 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
3167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3168 f.debug_struct("SplitN")
3169 .field("inner", &self.inner)
3174 /// An iterator over subslices separated by elements that match a
3175 /// predicate function, limited to a given number of splits, starting
3176 /// from the end of the slice.
3178 /// This struct is created by the [`rsplitn`] method on [slices].
3180 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3181 /// [slices]: ../../std/primitive.slice.html
3182 #[stable(feature = "rust1", since = "1.0.0")]
3183 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3184 inner: GenericSplitN<RSplit<'a, T, P>>
3187 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3188 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3190 f.debug_struct("RSplitN")
3191 .field("inner", &self.inner)
3196 /// An iterator over subslices separated by elements that match a predicate
3197 /// function, limited to a given number of splits.
3199 /// This struct is created by the [`splitn_mut`] method on [slices].
3201 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3202 /// [slices]: ../../std/primitive.slice.html
3203 #[stable(feature = "rust1", since = "1.0.0")]
3204 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3205 inner: GenericSplitN<SplitMut<'a, T, P>>
3208 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3209 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3211 f.debug_struct("SplitNMut")
3212 .field("inner", &self.inner)
3217 /// An iterator over subslices separated by elements that match a
3218 /// predicate function, limited to a given number of splits, starting
3219 /// from the end of the slice.
3221 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3223 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3224 /// [slices]: ../../std/primitive.slice.html
3225 #[stable(feature = "rust1", since = "1.0.0")]
3226 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3227 inner: GenericSplitN<RSplitMut<'a, T, P>>
3230 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3231 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3233 f.debug_struct("RSplitNMut")
3234 .field("inner", &self.inner)
3239 macro_rules! forward_iterator {
3240 ($name:ident: $elem:ident, $iter_of:ty) => {
3241 #[stable(feature = "rust1", since = "1.0.0")]
3242 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3243 P: FnMut(&T) -> bool
3245 type Item = $iter_of;
3248 fn next(&mut self) -> Option<$iter_of> {
3253 fn size_hint(&self) -> (usize, Option<usize>) {
3254 self.inner.size_hint()
3258 #[stable(feature = "fused", since = "1.26.0")]
3259 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3260 where P: FnMut(&T) -> bool {}
3264 forward_iterator! { SplitN: T, &'a [T] }
3265 forward_iterator! { RSplitN: T, &'a [T] }
3266 forward_iterator! { SplitNMut: T, &'a mut [T] }
3267 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3269 /// An iterator over overlapping subslices of length `size`.
3271 /// This struct is created by the [`windows`] method on [slices].
3273 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3274 /// [slices]: ../../std/primitive.slice.html
3276 #[stable(feature = "rust1", since = "1.0.0")]
3277 pub struct Windows<'a, T:'a> {
3282 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3283 #[stable(feature = "rust1", since = "1.0.0")]
3284 impl<'a, T> Clone for Windows<'a, T> {
3285 fn clone(&self) -> Windows<'a, T> {
3293 #[stable(feature = "rust1", since = "1.0.0")]
3294 impl<'a, T> Iterator for Windows<'a, T> {
3295 type Item = &'a [T];
3298 fn next(&mut self) -> Option<&'a [T]> {
3299 if self.size > self.v.len() {
3302 let ret = Some(&self.v[..self.size]);
3303 self.v = &self.v[1..];
3309 fn size_hint(&self) -> (usize, Option<usize>) {
3310 if self.size > self.v.len() {
3313 let size = self.v.len() - self.size + 1;
3319 fn count(self) -> usize {
3324 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3325 let (end, overflow) = self.size.overflowing_add(n);
3326 if end > self.v.len() || overflow {
3330 let nth = &self.v[n..end];
3331 self.v = &self.v[n+1..];
3337 fn last(self) -> Option<Self::Item> {
3338 if self.size > self.v.len() {
3341 let start = self.v.len() - self.size;
3342 Some(&self.v[start..])
3347 #[stable(feature = "rust1", since = "1.0.0")]
3348 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3350 fn next_back(&mut self) -> Option<&'a [T]> {
3351 if self.size > self.v.len() {
3354 let ret = Some(&self.v[self.v.len()-self.size..]);
3355 self.v = &self.v[..self.v.len()-1];
3361 #[stable(feature = "rust1", since = "1.0.0")]
3362 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3364 #[stable(feature = "fused", since = "1.26.0")]
3365 impl<'a, T> FusedIterator for Windows<'a, T> {}
3368 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3369 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3370 from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
3372 fn may_have_side_effect() -> bool { false }
3375 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3378 /// When the slice len is not evenly divided by the chunk size, the last slice
3379 /// of the iteration will be the remainder.
3381 /// This struct is created by the [`chunks`] method on [slices].
3383 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3384 /// [slices]: ../../std/primitive.slice.html
3386 #[stable(feature = "rust1", since = "1.0.0")]
3387 pub struct Chunks<'a, T:'a> {
3392 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3393 #[stable(feature = "rust1", since = "1.0.0")]
3394 impl<'a, T> Clone for Chunks<'a, T> {
3395 fn clone(&self) -> Chunks<'a, T> {
3398 chunk_size: self.chunk_size,
3403 #[stable(feature = "rust1", since = "1.0.0")]
3404 impl<'a, T> Iterator for Chunks<'a, T> {
3405 type Item = &'a [T];
3408 fn next(&mut self) -> Option<&'a [T]> {
3409 if self.v.is_empty() {
3412 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3413 let (fst, snd) = self.v.split_at(chunksz);
3420 fn size_hint(&self) -> (usize, Option<usize>) {
3421 if self.v.is_empty() {
3424 let n = self.v.len() / self.chunk_size;
3425 let rem = self.v.len() % self.chunk_size;
3426 let n = if rem > 0 { n+1 } else { n };
3432 fn count(self) -> usize {
3437 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3438 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3439 if start >= self.v.len() || overflow {
3443 let end = match start.checked_add(self.chunk_size) {
3444 Some(sum) => cmp::min(self.v.len(), sum),
3445 None => self.v.len(),
3447 let nth = &self.v[start..end];
3448 self.v = &self.v[end..];
3454 fn last(self) -> Option<Self::Item> {
3455 if self.v.is_empty() {
3458 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3459 Some(&self.v[start..])
3464 #[stable(feature = "rust1", since = "1.0.0")]
3465 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3467 fn next_back(&mut self) -> Option<&'a [T]> {
3468 if self.v.is_empty() {
3471 let remainder = self.v.len() % self.chunk_size;
3472 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3473 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3480 #[stable(feature = "rust1", since = "1.0.0")]
3481 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3483 #[stable(feature = "fused", since = "1.26.0")]
3484 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3487 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3488 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3489 let start = i * self.chunk_size;
3490 let end = match start.checked_add(self.chunk_size) {
3491 None => self.v.len(),
3492 Some(end) => cmp::min(end, self.v.len()),
3494 from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
3496 fn may_have_side_effect() -> bool { false }
3499 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3500 /// elements at a time). When the slice len is not evenly divided by the chunk
3501 /// size, the last slice of the iteration will be the remainder.
3503 /// This struct is created by the [`chunks_mut`] method on [slices].
3505 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3506 /// [slices]: ../../std/primitive.slice.html
3508 #[stable(feature = "rust1", since = "1.0.0")]
3509 pub struct ChunksMut<'a, T:'a> {
3514 #[stable(feature = "rust1", since = "1.0.0")]
3515 impl<'a, T> Iterator for ChunksMut<'a, T> {
3516 type Item = &'a mut [T];
3519 fn next(&mut self) -> Option<&'a mut [T]> {
3520 if self.v.is_empty() {
3523 let sz = cmp::min(self.v.len(), self.chunk_size);
3524 let tmp = mem::replace(&mut self.v, &mut []);
3525 let (head, tail) = tmp.split_at_mut(sz);
3532 fn size_hint(&self) -> (usize, Option<usize>) {
3533 if self.v.is_empty() {
3536 let n = self.v.len() / self.chunk_size;
3537 let rem = self.v.len() % self.chunk_size;
3538 let n = if rem > 0 { n + 1 } else { n };
3544 fn count(self) -> usize {
3549 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3550 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3551 if start >= self.v.len() || overflow {
3555 let end = match start.checked_add(self.chunk_size) {
3556 Some(sum) => cmp::min(self.v.len(), sum),
3557 None => self.v.len(),
3559 let tmp = mem::replace(&mut self.v, &mut []);
3560 let (head, tail) = tmp.split_at_mut(end);
3561 let (_, nth) = head.split_at_mut(start);
3568 fn last(self) -> Option<Self::Item> {
3569 if self.v.is_empty() {
3572 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3573 Some(&mut self.v[start..])
3578 #[stable(feature = "rust1", since = "1.0.0")]
3579 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3581 fn next_back(&mut self) -> Option<&'a mut [T]> {
3582 if self.v.is_empty() {
3585 let remainder = self.v.len() % self.chunk_size;
3586 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3587 let tmp = mem::replace(&mut self.v, &mut []);
3588 let tmp_len = tmp.len();
3589 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3596 #[stable(feature = "rust1", since = "1.0.0")]
3597 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3599 #[stable(feature = "fused", since = "1.26.0")]
3600 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3603 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3604 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3605 let start = i * self.chunk_size;
3606 let end = match start.checked_add(self.chunk_size) {
3607 None => self.v.len(),
3608 Some(end) => cmp::min(end, self.v.len()),
3610 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
3612 fn may_have_side_effect() -> bool { false }
3615 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3618 /// When the slice len is not evenly divided by the chunk size, the last
3619 /// up to `chunk_size-1` elements will be omitted.
3621 /// This struct is created by the [`exact_chunks`] method on [slices].
3623 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3624 /// [slices]: ../../std/primitive.slice.html
3626 #[unstable(feature = "exact_chunks", issue = "47115")]
3627 pub struct ExactChunks<'a, T:'a> {
3632 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3633 #[unstable(feature = "exact_chunks", issue = "47115")]
3634 impl<'a, T> Clone for ExactChunks<'a, T> {
3635 fn clone(&self) -> ExactChunks<'a, T> {
3638 chunk_size: self.chunk_size,
3643 #[unstable(feature = "exact_chunks", issue = "47115")]
3644 impl<'a, T> Iterator for ExactChunks<'a, T> {
3645 type Item = &'a [T];
3648 fn next(&mut self) -> Option<&'a [T]> {
3649 if self.v.len() < self.chunk_size {
3652 let (fst, snd) = self.v.split_at(self.chunk_size);
3659 fn size_hint(&self) -> (usize, Option<usize>) {
3660 let n = self.v.len() / self.chunk_size;
3665 fn count(self) -> usize {
3670 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3671 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3672 if start >= self.v.len() || overflow {
3676 let (_, snd) = self.v.split_at(start);
3683 fn last(mut self) -> Option<Self::Item> {
3688 #[unstable(feature = "exact_chunks", issue = "47115")]
3689 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3691 fn next_back(&mut self) -> Option<&'a [T]> {
3692 if self.v.len() < self.chunk_size {
3695 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
3702 #[unstable(feature = "exact_chunks", issue = "47115")]
3703 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
3704 fn is_empty(&self) -> bool {
3709 #[unstable(feature = "exact_chunks", issue = "47115")]
3710 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
3713 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
3714 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3715 let start = i * self.chunk_size;
3716 from_raw_parts(self.v.as_ptr().offset(start as isize), self.chunk_size)
3718 fn may_have_side_effect() -> bool { false }
3721 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3722 /// elements at a time). When the slice len is not evenly divided by the chunk
3723 /// size, the last up to `chunk_size-1` elements will be omitted.
3725 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
3727 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
3728 /// [slices]: ../../std/primitive.slice.html
3730 #[unstable(feature = "exact_chunks", issue = "47115")]
3731 pub struct ExactChunksMut<'a, T:'a> {
3736 #[unstable(feature = "exact_chunks", issue = "47115")]
3737 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
3738 type Item = &'a mut [T];
3741 fn next(&mut self) -> Option<&'a mut [T]> {
3742 if self.v.len() < self.chunk_size {
3745 let tmp = mem::replace(&mut self.v, &mut []);
3746 let (head, tail) = tmp.split_at_mut(self.chunk_size);
3753 fn size_hint(&self) -> (usize, Option<usize>) {
3754 let n = self.v.len() / self.chunk_size;
3759 fn count(self) -> usize {
3764 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3765 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3766 if start >= self.v.len() || overflow {
3770 let tmp = mem::replace(&mut self.v, &mut []);
3771 let (_, snd) = tmp.split_at_mut(start);
3778 fn last(mut self) -> Option<Self::Item> {
3783 #[unstable(feature = "exact_chunks", issue = "47115")]
3784 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
3786 fn next_back(&mut self) -> Option<&'a mut [T]> {
3787 if self.v.len() < self.chunk_size {
3790 let tmp = mem::replace(&mut self.v, &mut []);
3791 let tmp_len = tmp.len();
3792 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
3799 #[unstable(feature = "exact_chunks", issue = "47115")]
3800 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
3801 fn is_empty(&self) -> bool {
3806 #[unstable(feature = "exact_chunks", issue = "47115")]
3807 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
3810 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
3811 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3812 let start = i * self.chunk_size;
3813 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), self.chunk_size)
3815 fn may_have_side_effect() -> bool { false }
3822 /// Forms a slice from a pointer and a length.
3824 /// The `len` argument is the number of **elements**, not the number of bytes.
3828 /// This function is unsafe as there is no guarantee that the given pointer is
3829 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
3830 /// lifetime for the returned slice.
3832 /// `p` must be non-null, even for zero-length slices, because non-zero bits
3833 /// are required to distinguish between a zero-length slice within `Some()`
3834 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
3835 /// for zero-length slices, though.
3839 /// The lifetime for the returned slice is inferred from its usage. To
3840 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
3841 /// source lifetime is safe in the context, such as by providing a helper
3842 /// function taking the lifetime of a host value for the slice, or by explicit
3850 /// // manifest a slice out of thin air!
3851 /// let ptr = 0x1234 as *const usize;
3854 /// let slice = slice::from_raw_parts(ptr, amt);
3858 #[stable(feature = "rust1", since = "1.0.0")]
3859 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
3860 mem::transmute(Repr { data: p, len: len })
3863 /// Performs the same functionality as `from_raw_parts`, except that a mutable
3864 /// slice is returned.
3866 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
3867 /// as not being able to provide a non-aliasing guarantee of the returned
3868 /// mutable slice. `p` must be non-null even for zero-length slices as with
3869 /// `from_raw_parts`.
3871 #[stable(feature = "rust1", since = "1.0.0")]
3872 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
3873 mem::transmute(Repr { data: p, len: len })
3876 /// Converts a reference to T into a slice of length 1 (without copying).
3877 #[unstable(feature = "from_ref", issue = "45703")]
3878 pub fn from_ref<T>(s: &T) -> &[T] {
3880 from_raw_parts(s, 1)
3884 /// Converts a reference to T into a slice of length 1 (without copying).
3885 #[unstable(feature = "from_ref", issue = "45703")]
3886 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
3888 from_raw_parts_mut(s, 1)
3892 // This function is public only because there is no other way to unit test heapsort.
3893 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
3895 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
3896 where F: FnMut(&T, &T) -> bool
3898 sort::heapsort(v, &mut is_less);
3902 // Comparison traits
3906 /// Calls implementation provided memcmp.
3908 /// Interprets the data as u8.
3910 /// Returns 0 for equal, < 0 for less than and > 0 for greater
3912 // FIXME(#32610): Return type should be c_int
3913 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
3916 #[stable(feature = "rust1", since = "1.0.0")]
3917 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
3918 fn eq(&self, other: &[B]) -> bool {
3919 SlicePartialEq::equal(self, other)
3922 fn ne(&self, other: &[B]) -> bool {
3923 SlicePartialEq::not_equal(self, other)
3927 #[stable(feature = "rust1", since = "1.0.0")]
3928 impl<T: Eq> Eq for [T] {}
3930 /// Implements comparison of vectors lexicographically.
3931 #[stable(feature = "rust1", since = "1.0.0")]
3932 impl<T: Ord> Ord for [T] {
3933 fn cmp(&self, other: &[T]) -> Ordering {
3934 SliceOrd::compare(self, other)
3938 /// Implements comparison of vectors lexicographically.
3939 #[stable(feature = "rust1", since = "1.0.0")]
3940 impl<T: PartialOrd> PartialOrd for [T] {
3941 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
3942 SlicePartialOrd::partial_compare(self, other)
3947 // intermediate trait for specialization of slice's PartialEq
3948 trait SlicePartialEq<B> {
3949 fn equal(&self, other: &[B]) -> bool;
3951 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
3954 // Generic slice equality
3955 impl<A, B> SlicePartialEq<B> for [A]
3956 where A: PartialEq<B>
3958 default fn equal(&self, other: &[B]) -> bool {
3959 if self.len() != other.len() {
3963 for i in 0..self.len() {
3964 if !self[i].eq(&other[i]) {
3973 // Use memcmp for bytewise equality when the types allow
3974 impl<A> SlicePartialEq<A> for [A]
3975 where A: PartialEq<A> + BytewiseEquality
3977 fn equal(&self, other: &[A]) -> bool {
3978 if self.len() != other.len() {
3981 if self.as_ptr() == other.as_ptr() {
3985 let size = mem::size_of_val(self);
3986 memcmp(self.as_ptr() as *const u8,
3987 other.as_ptr() as *const u8, size) == 0
3993 // intermediate trait for specialization of slice's PartialOrd
3994 trait SlicePartialOrd<B> {
3995 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
3998 impl<A> SlicePartialOrd<A> for [A]
4001 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4002 let l = cmp::min(self.len(), other.len());
4004 // Slice to the loop iteration range to enable bound check
4005 // elimination in the compiler
4006 let lhs = &self[..l];
4007 let rhs = &other[..l];
4010 match lhs[i].partial_cmp(&rhs[i]) {
4011 Some(Ordering::Equal) => (),
4012 non_eq => return non_eq,
4016 self.len().partial_cmp(&other.len())
4020 impl<A> SlicePartialOrd<A> for [A]
4023 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4024 Some(SliceOrd::compare(self, other))
4029 // intermediate trait for specialization of slice's Ord
4031 fn compare(&self, other: &[B]) -> Ordering;
4034 impl<A> SliceOrd<A> for [A]
4037 default fn compare(&self, other: &[A]) -> Ordering {
4038 let l = cmp::min(self.len(), other.len());
4040 // Slice to the loop iteration range to enable bound check
4041 // elimination in the compiler
4042 let lhs = &self[..l];
4043 let rhs = &other[..l];
4046 match lhs[i].cmp(&rhs[i]) {
4047 Ordering::Equal => (),
4048 non_eq => return non_eq,
4052 self.len().cmp(&other.len())
4056 // memcmp compares a sequence of unsigned bytes lexicographically.
4057 // this matches the order we want for [u8], but no others (not even [i8]).
4058 impl SliceOrd<u8> for [u8] {
4060 fn compare(&self, other: &[u8]) -> Ordering {
4061 let order = unsafe {
4062 memcmp(self.as_ptr(), other.as_ptr(),
4063 cmp::min(self.len(), other.len()))
4066 self.len().cmp(&other.len())
4067 } else if order < 0 {
4076 /// Trait implemented for types that can be compared for equality using
4077 /// their bytewise representation
4078 trait BytewiseEquality { }
4080 macro_rules! impl_marker_for {
4081 ($traitname:ident, $($ty:ty)*) => {
4083 impl $traitname for $ty { }
4088 impl_marker_for!(BytewiseEquality,
4089 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4092 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4093 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4094 &*self.ptr.offset(i as isize)
4096 fn may_have_side_effect() -> bool { false }
4100 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4101 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4102 &mut *self.ptr.offset(i as isize)
4104 fn may_have_side_effect() -> bool { false }
4107 trait SliceContains: Sized {
4108 fn slice_contains(&self, x: &[Self]) -> bool;
4111 impl<T> SliceContains for T where T: PartialEq {
4112 default fn slice_contains(&self, x: &[Self]) -> bool {
4113 x.iter().any(|y| *y == *self)
4117 impl SliceContains for u8 {
4118 fn slice_contains(&self, x: &[Self]) -> bool {
4119 memchr::memchr(*self, x).is_some()
4123 impl SliceContains for i8 {
4124 fn slice_contains(&self, x: &[Self]) -> bool {
4125 let byte = *self as u8;
4126 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4127 memchr::memchr(byte, bytes).is_some()