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
73 /// Extension methods for slices.
74 #[unstable(feature = "core_slice_ext",
75 reason = "stable interface provided by `impl [T]` in later crates",
77 #[allow(missing_docs)] // documented elsewhere
82 #[stable(feature = "core", since = "1.6.0")]
83 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
85 #[stable(feature = "core", since = "1.6.0")]
86 fn iter(&self) -> Iter<Self::Item>;
88 #[stable(feature = "core", since = "1.6.0")]
89 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
90 where P: FnMut(&Self::Item) -> bool;
92 #[stable(feature = "slice_rsplit", since = "1.27.0")]
93 fn rsplit<P>(&self, pred: P) -> RSplit<Self::Item, P>
94 where P: FnMut(&Self::Item) -> bool;
96 #[stable(feature = "core", since = "1.6.0")]
97 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
98 where P: FnMut(&Self::Item) -> bool;
100 #[stable(feature = "core", since = "1.6.0")]
101 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
102 where P: FnMut(&Self::Item) -> bool;
104 #[stable(feature = "core", since = "1.6.0")]
105 fn windows(&self, size: usize) -> Windows<Self::Item>;
107 #[stable(feature = "core", since = "1.6.0")]
108 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
110 #[unstable(feature = "exact_chunks", issue = "47115")]
111 fn exact_chunks(&self, size: usize) -> ExactChunks<Self::Item>;
113 #[stable(feature = "core", since = "1.6.0")]
114 fn get<I>(&self, index: I) -> Option<&I::Output>
115 where I: SliceIndex<Self>;
116 #[stable(feature = "core", since = "1.6.0")]
117 fn first(&self) -> Option<&Self::Item>;
119 #[stable(feature = "core", since = "1.6.0")]
120 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
122 #[stable(feature = "core", since = "1.6.0")]
123 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
125 #[stable(feature = "core", since = "1.6.0")]
126 fn last(&self) -> Option<&Self::Item>;
128 #[stable(feature = "core", since = "1.6.0")]
129 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
130 where I: SliceIndex<Self>;
131 #[stable(feature = "core", since = "1.6.0")]
132 fn as_ptr(&self) -> *const Self::Item;
134 #[stable(feature = "core", since = "1.6.0")]
135 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
136 where Self::Item: Ord;
138 #[stable(feature = "core", since = "1.6.0")]
139 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
140 where F: FnMut(&'a Self::Item) -> Ordering;
142 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
143 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
144 where F: FnMut(&'a Self::Item) -> B,
147 #[stable(feature = "core", since = "1.6.0")]
148 fn len(&self) -> usize;
150 #[stable(feature = "core", since = "1.6.0")]
151 fn is_empty(&self) -> bool { self.len() == 0 }
153 #[stable(feature = "core", since = "1.6.0")]
154 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
155 where I: SliceIndex<Self>;
156 #[stable(feature = "core", since = "1.6.0")]
157 fn iter_mut(&mut self) -> IterMut<Self::Item>;
159 #[stable(feature = "core", since = "1.6.0")]
160 fn first_mut(&mut self) -> Option<&mut Self::Item>;
162 #[stable(feature = "core", since = "1.6.0")]
163 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
165 #[stable(feature = "core", since = "1.6.0")]
166 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
168 #[stable(feature = "core", since = "1.6.0")]
169 fn last_mut(&mut self) -> Option<&mut Self::Item>;
171 #[stable(feature = "core", since = "1.6.0")]
172 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
173 where P: FnMut(&Self::Item) -> bool;
175 #[stable(feature = "slice_rsplit", since = "1.27.0")]
176 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<Self::Item, P>
177 where P: FnMut(&Self::Item) -> bool;
179 #[stable(feature = "core", since = "1.6.0")]
180 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
181 where P: FnMut(&Self::Item) -> bool;
183 #[stable(feature = "core", since = "1.6.0")]
184 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
185 where P: FnMut(&Self::Item) -> bool;
187 #[stable(feature = "core", since = "1.6.0")]
188 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
190 #[unstable(feature = "exact_chunks", issue = "47115")]
191 fn exact_chunks_mut(&mut self, size: usize) -> ExactChunksMut<Self::Item>;
193 #[stable(feature = "core", since = "1.6.0")]
194 fn swap(&mut self, a: usize, b: usize);
196 #[stable(feature = "core", since = "1.6.0")]
197 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
199 #[stable(feature = "core", since = "1.6.0")]
200 fn reverse(&mut self);
202 #[stable(feature = "core", since = "1.6.0")]
203 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
204 where I: SliceIndex<Self>;
205 #[stable(feature = "core", since = "1.6.0")]
206 fn as_mut_ptr(&mut self) -> *mut Self::Item;
208 #[stable(feature = "core", since = "1.6.0")]
209 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
211 #[stable(feature = "core", since = "1.6.0")]
212 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
214 #[stable(feature = "core", since = "1.6.0")]
215 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
217 #[stable(feature = "slice_rotate", since = "1.26.0")]
218 fn rotate_left(&mut self, mid: usize);
220 #[stable(feature = "slice_rotate", since = "1.26.0")]
221 fn rotate_right(&mut self, k: usize);
223 #[stable(feature = "clone_from_slice", since = "1.7.0")]
224 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
226 #[stable(feature = "copy_from_slice", since = "1.9.0")]
227 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
229 #[stable(feature = "swap_with_slice", since = "1.27.0")]
230 fn swap_with_slice(&mut self, src: &mut [Self::Item]);
232 #[stable(feature = "sort_unstable", since = "1.20.0")]
233 fn sort_unstable(&mut self)
234 where Self::Item: Ord;
236 #[stable(feature = "sort_unstable", since = "1.20.0")]
237 fn sort_unstable_by<F>(&mut self, compare: F)
238 where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
240 #[stable(feature = "sort_unstable", since = "1.20.0")]
241 fn sort_unstable_by_key<B, F>(&mut self, f: F)
242 where F: FnMut(&Self::Item) -> B,
246 // Use macros to be generic over const/mut
247 macro_rules! slice_offset {
248 ($ptr:expr, $by:expr) => {{
250 if size_from_ptr(ptr) == 0 {
251 (ptr as *mut i8).wrapping_offset($by) as _
258 // make a &T from a *const T
259 macro_rules! make_ref {
262 if size_from_ptr(ptr) == 0 {
263 // Use a non-null pointer value
271 // make a &mut T from a *mut T
272 macro_rules! make_ref_mut {
275 if size_from_ptr(ptr) == 0 {
276 // Use a non-null pointer value
284 #[unstable(feature = "core_slice_ext",
285 reason = "stable interface provided by `impl [T]` in later crates",
287 impl<T> SliceExt for [T] {
291 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
292 (&self[..mid], &self[mid..])
296 fn iter(&self) -> Iter<T> {
298 let p = if mem::size_of::<T>() == 0 {
301 let p = self.as_ptr();
302 assume(!p.is_null());
308 end: slice_offset!(p, self.len() as isize),
309 _marker: marker::PhantomData
315 fn split<P>(&self, pred: P) -> Split<T, P>
316 where P: FnMut(&T) -> bool
326 fn rsplit<P>(&self, pred: P) -> RSplit<T, P>
327 where P: FnMut(&T) -> bool
329 RSplit { inner: self.split(pred) }
333 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P>
334 where P: FnMut(&T) -> bool
337 inner: GenericSplitN {
338 iter: self.split(pred),
345 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P>
346 where P: FnMut(&T) -> bool
349 inner: GenericSplitN {
350 iter: self.rsplit(pred),
357 fn windows(&self, size: usize) -> Windows<T> {
359 Windows { v: self, size: size }
363 fn chunks(&self, chunk_size: usize) -> Chunks<T> {
364 assert!(chunk_size != 0);
365 Chunks { v: self, chunk_size: chunk_size }
369 fn exact_chunks(&self, chunk_size: usize) -> ExactChunks<T> {
370 assert!(chunk_size != 0);
371 let rem = self.len() % chunk_size;
372 let len = self.len() - rem;
373 ExactChunks { v: &self[..len], chunk_size: chunk_size}
377 fn get<I>(&self, index: I) -> Option<&I::Output>
378 where I: SliceIndex<[T]>
384 fn first(&self) -> Option<&T> {
385 if self.is_empty() { None } else { Some(&self[0]) }
389 fn split_first(&self) -> Option<(&T, &[T])> {
390 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
394 fn split_last(&self) -> Option<(&T, &[T])> {
395 let len = self.len();
396 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
400 fn last(&self) -> Option<&T> {
401 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
405 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
406 where I: SliceIndex<[T]>
408 index.get_unchecked(self)
412 fn as_ptr(&self) -> *const T {
413 self as *const [T] as *const T
416 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
417 where F: FnMut(&'a T) -> Ordering
420 let mut size = s.len();
424 let mut base = 0usize;
427 let mid = base + half;
428 // mid is always in [0, size), that means mid is >= 0 and < size.
429 // mid >= 0: by definition
430 // mid < size: mid = size / 2 + size / 4 + size / 8 ...
431 let cmp = f(unsafe { s.get_unchecked(mid) });
432 base = if cmp == Greater { base } else { mid };
435 // base is always in [0, size) because base <= mid.
436 let cmp = f(unsafe { s.get_unchecked(base) });
437 if cmp == Equal { Ok(base) } else { Err(base + (cmp == Less) as usize) }
441 fn len(&self) -> usize {
443 mem::transmute::<&[T], Repr<T>>(self).len
448 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
449 where I: SliceIndex<[T]>
455 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
456 let len = self.len();
457 let ptr = self.as_mut_ptr();
462 (from_raw_parts_mut(ptr, mid),
463 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
468 fn iter_mut(&mut self) -> IterMut<T> {
470 let p = if mem::size_of::<T>() == 0 {
473 let p = self.as_mut_ptr();
474 assume(!p.is_null());
480 end: slice_offset!(p, self.len() as isize),
481 _marker: marker::PhantomData
487 fn last_mut(&mut self) -> Option<&mut T> {
488 let len = self.len();
489 if len == 0 { return None; }
490 Some(&mut self[len - 1])
494 fn first_mut(&mut self) -> Option<&mut T> {
495 if self.is_empty() { None } else { Some(&mut self[0]) }
499 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
500 if self.is_empty() { None } else {
501 let split = self.split_at_mut(1);
502 Some((&mut split.0[0], split.1))
507 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
508 let len = self.len();
509 if len == 0 { None } else {
510 let split = self.split_at_mut(len - 1);
511 Some((&mut split.1[0], split.0))
516 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P>
517 where P: FnMut(&T) -> bool
519 SplitMut { v: self, pred: pred, finished: false }
523 fn rsplit_mut<P>(&mut self, pred: P) -> RSplitMut<T, P>
524 where P: FnMut(&T) -> bool
526 RSplitMut { inner: self.split_mut(pred) }
530 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P>
531 where P: FnMut(&T) -> bool
534 inner: GenericSplitN {
535 iter: self.split_mut(pred),
542 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
543 P: FnMut(&T) -> bool,
546 inner: GenericSplitN {
547 iter: self.rsplit_mut(pred),
554 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
555 assert!(chunk_size != 0);
556 ChunksMut { v: self, chunk_size: chunk_size }
560 fn exact_chunks_mut(&mut self, chunk_size: usize) -> ExactChunksMut<T> {
561 assert!(chunk_size != 0);
562 let rem = self.len() % chunk_size;
563 let len = self.len() - rem;
564 ExactChunksMut { v: &mut self[..len], chunk_size: chunk_size}
568 fn swap(&mut self, a: usize, b: usize) {
570 // Can't take two mutable loans from one vector, so instead just cast
571 // them to their raw pointers to do the swap
572 let pa: *mut T = &mut self[a];
573 let pb: *mut T = &mut self[b];
578 fn reverse(&mut self) {
579 let mut i: usize = 0;
582 // For very small types, all the individual reads in the normal
583 // path perform poorly. We can do better, given efficient unaligned
584 // load/store, by loading a larger chunk and reversing a register.
586 // Ideally LLVM would do this for us, as it knows better than we do
587 // whether unaligned reads are efficient (since that changes between
588 // different ARM versions, for example) and what the best chunk size
589 // would be. Unfortunately, as of LLVM 4.0 (2017-05) it only unrolls
590 // the loop, so we need to do this ourselves. (Hypothesis: reverse
591 // is troublesome because the sides can be aligned differently --
592 // will be, when the length is odd -- so there's no way of emitting
593 // pre- and postludes to use fully-aligned SIMD in the middle.)
596 cfg!(any(target_arch = "x86", target_arch = "x86_64"));
598 if fast_unaligned && mem::size_of::<T>() == 1 {
599 // Use the llvm.bswap intrinsic to reverse u8s in a usize
600 let chunk = mem::size_of::<usize>();
601 while i + chunk - 1 < ln / 2 {
603 let pa: *mut T = self.get_unchecked_mut(i);
604 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
605 let va = ptr::read_unaligned(pa as *mut usize);
606 let vb = ptr::read_unaligned(pb as *mut usize);
607 ptr::write_unaligned(pa as *mut usize, vb.swap_bytes());
608 ptr::write_unaligned(pb as *mut usize, va.swap_bytes());
614 if fast_unaligned && mem::size_of::<T>() == 2 {
615 // Use rotate-by-16 to reverse u16s in a u32
616 let chunk = mem::size_of::<u32>() / 2;
617 while i + chunk - 1 < ln / 2 {
619 let pa: *mut T = self.get_unchecked_mut(i);
620 let pb: *mut T = self.get_unchecked_mut(ln - i - chunk);
621 let va = ptr::read_unaligned(pa as *mut u32);
622 let vb = ptr::read_unaligned(pb as *mut u32);
623 ptr::write_unaligned(pa as *mut u32, vb.rotate_left(16));
624 ptr::write_unaligned(pb as *mut u32, va.rotate_left(16));
631 // Unsafe swap to avoid the bounds check in safe swap.
633 let pa: *mut T = self.get_unchecked_mut(i);
634 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
642 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
643 where I: SliceIndex<[T]>
645 index.get_unchecked_mut(self)
649 fn as_mut_ptr(&mut self) -> *mut T {
650 self as *mut [T] as *mut T
654 fn contains(&self, x: &T) -> bool where T: PartialEq {
655 x.slice_contains(self)
659 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
660 let n = needle.len();
661 self.len() >= n && needle == &self[..n]
665 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
666 let (m, n) = (self.len(), needle.len());
667 m >= n && needle == &self[m-n..]
670 fn binary_search(&self, x: &T) -> Result<usize, usize>
673 self.binary_search_by(|p| p.cmp(x))
676 fn rotate_left(&mut self, mid: usize) {
677 assert!(mid <= self.len());
678 let k = self.len() - mid;
681 let p = self.as_mut_ptr();
682 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
686 fn rotate_right(&mut self, k: usize) {
687 assert!(k <= self.len());
688 let mid = self.len() - k;
691 let p = self.as_mut_ptr();
692 rotate::ptr_rotate(mid, p.offset(mid as isize), k);
697 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
698 assert!(self.len() == src.len(),
699 "destination and source slices have different lengths");
700 // NOTE: We need to explicitly slice them to the same length
701 // for bounds checking to be elided, and the optimizer will
702 // generate memcpy for simple cases (for example T = u8).
703 let len = self.len();
704 let src = &src[..len];
706 self[i].clone_from(&src[i]);
711 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
712 assert!(self.len() == src.len(),
713 "destination and source slices have different lengths");
715 ptr::copy_nonoverlapping(
716 src.as_ptr(), self.as_mut_ptr(), self.len());
721 fn swap_with_slice(&mut self, src: &mut [T]) {
722 assert!(self.len() == src.len(),
723 "destination and source slices have different lengths");
725 ptr::swap_nonoverlapping(
726 self.as_mut_ptr(), src.as_mut_ptr(), self.len());
731 fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
732 where F: FnMut(&'a Self::Item) -> B,
735 self.binary_search_by(|k| f(k).cmp(b))
739 fn sort_unstable(&mut self)
740 where Self::Item: Ord
742 sort::quicksort(self, |a, b| a.lt(b));
746 fn sort_unstable_by<F>(&mut self, mut compare: F)
747 where F: FnMut(&Self::Item, &Self::Item) -> Ordering
749 sort::quicksort(self, |a, b| compare(a, b) == Ordering::Less);
753 fn sort_unstable_by_key<B, F>(&mut self, mut f: F)
754 where F: FnMut(&Self::Item) -> B,
757 sort::quicksort(self, |a, b| f(a).lt(&f(b)));
761 // FIXME: remove (inline) this macro and the SliceExt trait
762 // when updating to a bootstrap compiler that has the new lang items.
763 #[cfg_attr(stage0, macro_export)]
764 #[unstable(feature = "core_slice_ext", issue = "32110")]
765 macro_rules! slice_core_methods { () => {
766 /// Returns the number of elements in the slice.
771 /// let a = [1, 2, 3];
772 /// assert_eq!(a.len(), 3);
774 #[stable(feature = "rust1", since = "1.0.0")]
776 pub fn len(&self) -> usize {
780 /// Returns `true` if the slice has a length of 0.
785 /// let a = [1, 2, 3];
786 /// assert!(!a.is_empty());
788 #[stable(feature = "rust1", since = "1.0.0")]
790 pub fn is_empty(&self) -> bool {
791 SliceExt::is_empty(self)
794 /// Returns the first element of the slice, or `None` if it is empty.
799 /// let v = [10, 40, 30];
800 /// assert_eq!(Some(&10), v.first());
802 /// let w: &[i32] = &[];
803 /// assert_eq!(None, w.first());
805 #[stable(feature = "rust1", since = "1.0.0")]
807 pub fn first(&self) -> Option<&T> {
808 SliceExt::first(self)
811 /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
816 /// let x = &mut [0, 1, 2];
818 /// if let Some(first) = x.first_mut() {
821 /// assert_eq!(x, &[5, 1, 2]);
823 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn first_mut(&mut self) -> Option<&mut T> {
826 SliceExt::first_mut(self)
829 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
834 /// let x = &[0, 1, 2];
836 /// if let Some((first, elements)) = x.split_first() {
837 /// assert_eq!(first, &0);
838 /// assert_eq!(elements, &[1, 2]);
841 #[stable(feature = "slice_splits", since = "1.5.0")]
843 pub fn split_first(&self) -> Option<(&T, &[T])> {
844 SliceExt::split_first(self)
847 /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
852 /// let x = &mut [0, 1, 2];
854 /// if let Some((first, elements)) = x.split_first_mut() {
859 /// assert_eq!(x, &[3, 4, 5]);
861 #[stable(feature = "slice_splits", since = "1.5.0")]
863 pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
864 SliceExt::split_first_mut(self)
867 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
872 /// let x = &[0, 1, 2];
874 /// if let Some((last, elements)) = x.split_last() {
875 /// assert_eq!(last, &2);
876 /// assert_eq!(elements, &[0, 1]);
879 #[stable(feature = "slice_splits", since = "1.5.0")]
881 pub fn split_last(&self) -> Option<(&T, &[T])> {
882 SliceExt::split_last(self)
885 /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty.
890 /// let x = &mut [0, 1, 2];
892 /// if let Some((last, elements)) = x.split_last_mut() {
897 /// assert_eq!(x, &[4, 5, 3]);
899 #[stable(feature = "slice_splits", since = "1.5.0")]
901 pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
902 SliceExt::split_last_mut(self)
905 /// Returns the last element of the slice, or `None` if it is empty.
910 /// let v = [10, 40, 30];
911 /// assert_eq!(Some(&30), v.last());
913 /// let w: &[i32] = &[];
914 /// assert_eq!(None, w.last());
916 #[stable(feature = "rust1", since = "1.0.0")]
918 pub fn last(&self) -> Option<&T> {
922 /// Returns a mutable pointer to the last item in the slice.
927 /// let x = &mut [0, 1, 2];
929 /// if let Some(last) = x.last_mut() {
932 /// assert_eq!(x, &[0, 1, 10]);
934 #[stable(feature = "rust1", since = "1.0.0")]
936 pub fn last_mut(&mut self) -> Option<&mut T> {
937 SliceExt::last_mut(self)
940 /// Returns a reference to an element or subslice depending on the type of
943 /// - If given a position, returns a reference to the element at that
944 /// position or `None` if out of bounds.
945 /// - If given a range, returns the subslice corresponding to that range,
946 /// or `None` if out of bounds.
951 /// let v = [10, 40, 30];
952 /// assert_eq!(Some(&40), v.get(1));
953 /// assert_eq!(Some(&[10, 40][..]), v.get(0..2));
954 /// assert_eq!(None, v.get(3));
955 /// assert_eq!(None, v.get(0..4));
957 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn get<I>(&self, index: I) -> Option<&I::Output>
960 where I: SliceIndex<Self>
962 SliceExt::get(self, index)
965 /// Returns a mutable reference to an element or subslice depending on the
966 /// type of index (see [`get`]) or `None` if the index is out of bounds.
968 /// [`get`]: #method.get
973 /// let x = &mut [0, 1, 2];
975 /// if let Some(elem) = x.get_mut(1) {
978 /// assert_eq!(x, &[0, 42, 2]);
980 #[stable(feature = "rust1", since = "1.0.0")]
982 pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
983 where I: SliceIndex<Self>
985 SliceExt::get_mut(self, index)
988 /// Returns a reference to an element or subslice, without doing bounds
991 /// This is generally not recommended, use with caution! For a safe
992 /// alternative see [`get`].
994 /// [`get`]: #method.get
999 /// let x = &[1, 2, 4];
1002 /// assert_eq!(x.get_unchecked(1), &2);
1005 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
1008 where I: SliceIndex<Self>
1010 SliceExt::get_unchecked(self, index)
1013 /// Returns a mutable reference to an element or subslice, without doing
1014 /// bounds checking.
1016 /// This is generally not recommended, use with caution! For a safe
1017 /// alternative see [`get_mut`].
1019 /// [`get_mut`]: #method.get_mut
1024 /// let x = &mut [1, 2, 4];
1027 /// let elem = x.get_unchecked_mut(1);
1030 /// assert_eq!(x, &[1, 13, 4]);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1034 pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
1035 where I: SliceIndex<Self>
1037 SliceExt::get_unchecked_mut(self, index)
1040 /// Returns a raw pointer to the slice's buffer.
1042 /// The caller must ensure that the slice outlives the pointer this
1043 /// function returns, or else it will end up pointing to garbage.
1045 /// Modifying the container referenced by this slice may cause its buffer
1046 /// to be reallocated, which would also make any pointers to it invalid.
1051 /// let x = &[1, 2, 4];
1052 /// let x_ptr = x.as_ptr();
1055 /// for i in 0..x.len() {
1056 /// assert_eq!(x.get_unchecked(i), &*x_ptr.offset(i as isize));
1060 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub fn as_ptr(&self) -> *const T {
1063 SliceExt::as_ptr(self)
1066 /// Returns an unsafe mutable pointer to the slice's buffer.
1068 /// The caller must ensure that the slice outlives the pointer this
1069 /// function returns, or else it will end up pointing to garbage.
1071 /// Modifying the container referenced by this slice may cause its buffer
1072 /// to be reallocated, which would also make any pointers to it invalid.
1077 /// let x = &mut [1, 2, 4];
1078 /// let x_ptr = x.as_mut_ptr();
1081 /// for i in 0..x.len() {
1082 /// *x_ptr.offset(i as isize) += 2;
1085 /// assert_eq!(x, &[3, 4, 6]);
1087 #[stable(feature = "rust1", since = "1.0.0")]
1089 pub fn as_mut_ptr(&mut self) -> *mut T {
1090 SliceExt::as_mut_ptr(self)
1093 /// Swaps two elements in the slice.
1097 /// * a - The index of the first element
1098 /// * b - The index of the second element
1102 /// Panics if `a` or `b` are out of bounds.
1107 /// let mut v = ["a", "b", "c", "d"];
1109 /// assert!(v == ["a", "d", "c", "b"]);
1111 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn swap(&mut self, a: usize, b: usize) {
1114 SliceExt::swap(self, a, b)
1117 /// Reverses the order of elements in the slice, in place.
1122 /// let mut v = [1, 2, 3];
1124 /// assert!(v == [3, 2, 1]);
1126 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn reverse(&mut self) {
1129 SliceExt::reverse(self)
1132 /// Returns an iterator over the slice.
1137 /// let x = &[1, 2, 4];
1138 /// let mut iterator = x.iter();
1140 /// assert_eq!(iterator.next(), Some(&1));
1141 /// assert_eq!(iterator.next(), Some(&2));
1142 /// assert_eq!(iterator.next(), Some(&4));
1143 /// assert_eq!(iterator.next(), None);
1145 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn iter(&self) -> Iter<T> {
1148 SliceExt::iter(self)
1151 /// Returns an iterator that allows modifying each value.
1156 /// let x = &mut [1, 2, 4];
1157 /// for elem in x.iter_mut() {
1160 /// assert_eq!(x, &[3, 4, 6]);
1162 #[stable(feature = "rust1", since = "1.0.0")]
1164 pub fn iter_mut(&mut self) -> IterMut<T> {
1165 SliceExt::iter_mut(self)
1168 /// Returns an iterator over all contiguous windows of length
1169 /// `size`. The windows overlap. If the slice is shorter than
1170 /// `size`, the iterator returns no values.
1174 /// Panics if `size` is 0.
1179 /// let slice = ['r', 'u', 's', 't'];
1180 /// let mut iter = slice.windows(2);
1181 /// assert_eq!(iter.next().unwrap(), &['r', 'u']);
1182 /// assert_eq!(iter.next().unwrap(), &['u', 's']);
1183 /// assert_eq!(iter.next().unwrap(), &['s', 't']);
1184 /// assert!(iter.next().is_none());
1187 /// If the slice is shorter than `size`:
1190 /// let slice = ['f', 'o', 'o'];
1191 /// let mut iter = slice.windows(4);
1192 /// assert!(iter.next().is_none());
1194 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn windows(&self, size: usize) -> Windows<T> {
1197 SliceExt::windows(self, size)
1200 /// Returns an iterator over `chunk_size` elements of the slice at a
1201 /// time. The chunks are slices and do not overlap. If `chunk_size` does
1202 /// not divide the length of the slice, then the last chunk will
1203 /// not have length `chunk_size`.
1205 /// See [`exact_chunks`] for a variant of this iterator that returns chunks
1206 /// of always exactly `chunk_size` elements.
1210 /// Panics if `chunk_size` is 0.
1215 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1216 /// let mut iter = slice.chunks(2);
1217 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1218 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1219 /// assert_eq!(iter.next().unwrap(), &['m']);
1220 /// assert!(iter.next().is_none());
1223 /// [`exact_chunks`]: #method.exact_chunks
1224 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn chunks(&self, chunk_size: usize) -> Chunks<T> {
1227 SliceExt::chunks(self, chunk_size)
1230 /// Returns an iterator over `chunk_size` elements of the slice at a
1231 /// time. The chunks are slices and do not overlap. If `chunk_size` does
1232 /// not divide the length of the slice, then the last up to `chunk_size-1`
1233 /// elements will be omitted.
1235 /// Due to each chunk having exactly `chunk_size` elements, the compiler
1236 /// can often optimize the resulting code better than in the case of
1241 /// Panics if `chunk_size` is 0.
1246 /// #![feature(exact_chunks)]
1248 /// let slice = ['l', 'o', 'r', 'e', 'm'];
1249 /// let mut iter = slice.exact_chunks(2);
1250 /// assert_eq!(iter.next().unwrap(), &['l', 'o']);
1251 /// assert_eq!(iter.next().unwrap(), &['r', 'e']);
1252 /// assert!(iter.next().is_none());
1255 /// [`chunks`]: #method.chunks
1256 #[unstable(feature = "exact_chunks", issue = "47115")]
1258 pub fn exact_chunks(&self, chunk_size: usize) -> ExactChunks<T> {
1259 SliceExt::exact_chunks(self, chunk_size)
1262 /// Returns an iterator over `chunk_size` elements of the slice at a time.
1263 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
1264 /// not divide the length of the slice, then the last chunk will not
1265 /// have length `chunk_size`.
1267 /// See [`exact_chunks_mut`] for a variant of this iterator that returns chunks
1268 /// of always exactly `chunk_size` elements.
1272 /// Panics if `chunk_size` is 0.
1277 /// let v = &mut [0, 0, 0, 0, 0];
1278 /// let mut count = 1;
1280 /// for chunk in v.chunks_mut(2) {
1281 /// for elem in chunk.iter_mut() {
1286 /// assert_eq!(v, &[1, 1, 2, 2, 3]);
1289 /// [`exact_chunks_mut`]: #method.exact_chunks_mut
1290 #[stable(feature = "rust1", since = "1.0.0")]
1292 pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
1293 SliceExt::chunks_mut(self, chunk_size)
1296 /// Returns an iterator over `chunk_size` elements of the slice at a time.
1297 /// The chunks are mutable slices, and do not overlap. If `chunk_size` does
1298 /// not divide the length of the slice, then the last up to `chunk_size-1`
1299 /// elements will be omitted.
1302 /// Due to each chunk having exactly `chunk_size` elements, the compiler
1303 /// can often optimize the resulting code better than in the case of
1308 /// Panics if `chunk_size` is 0.
1313 /// #![feature(exact_chunks)]
1315 /// let v = &mut [0, 0, 0, 0, 0];
1316 /// let mut count = 1;
1318 /// for chunk in v.exact_chunks_mut(2) {
1319 /// for elem in chunk.iter_mut() {
1324 /// assert_eq!(v, &[1, 1, 2, 2, 0]);
1327 /// [`chunks_mut`]: #method.chunks_mut
1328 #[unstable(feature = "exact_chunks", issue = "47115")]
1330 pub fn exact_chunks_mut(&mut self, chunk_size: usize) -> ExactChunksMut<T> {
1331 SliceExt::exact_chunks_mut(self, chunk_size)
1334 /// Divides one slice into two at an index.
1336 /// The first will contain all indices from `[0, mid)` (excluding
1337 /// the index `mid` itself) and the second will contain all
1338 /// indices from `[mid, len)` (excluding the index `len` itself).
1342 /// Panics if `mid > len`.
1347 /// let v = [1, 2, 3, 4, 5, 6];
1350 /// let (left, right) = v.split_at(0);
1351 /// assert!(left == []);
1352 /// assert!(right == [1, 2, 3, 4, 5, 6]);
1356 /// let (left, right) = v.split_at(2);
1357 /// assert!(left == [1, 2]);
1358 /// assert!(right == [3, 4, 5, 6]);
1362 /// let (left, right) = v.split_at(6);
1363 /// assert!(left == [1, 2, 3, 4, 5, 6]);
1364 /// assert!(right == []);
1367 #[stable(feature = "rust1", since = "1.0.0")]
1369 pub fn split_at(&self, mid: usize) -> (&[T], &[T]) {
1370 SliceExt::split_at(self, mid)
1373 /// Divides one mutable slice into two at an index.
1375 /// The first will contain all indices from `[0, mid)` (excluding
1376 /// the index `mid` itself) and the second will contain all
1377 /// indices from `[mid, len)` (excluding the index `len` itself).
1381 /// Panics if `mid > len`.
1386 /// let mut v = [1, 0, 3, 0, 5, 6];
1387 /// // scoped to restrict the lifetime of the borrows
1389 /// let (left, right) = v.split_at_mut(2);
1390 /// assert!(left == [1, 0]);
1391 /// assert!(right == [3, 0, 5, 6]);
1395 /// assert!(v == [1, 2, 3, 4, 5, 6]);
1397 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
1400 SliceExt::split_at_mut(self, mid)
1403 /// Returns an iterator over subslices separated by elements that match
1404 /// `pred`. The matched element is not contained in the subslices.
1409 /// let slice = [10, 40, 33, 20];
1410 /// let mut iter = slice.split(|num| num % 3 == 0);
1412 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1413 /// assert_eq!(iter.next().unwrap(), &[20]);
1414 /// assert!(iter.next().is_none());
1417 /// If the first element is matched, an empty slice will be the first item
1418 /// returned by the iterator. Similarly, if the last element in the slice
1419 /// is matched, an empty slice will be the last item returned by the
1423 /// let slice = [10, 40, 33];
1424 /// let mut iter = slice.split(|num| num % 3 == 0);
1426 /// assert_eq!(iter.next().unwrap(), &[10, 40]);
1427 /// assert_eq!(iter.next().unwrap(), &[]);
1428 /// assert!(iter.next().is_none());
1431 /// If two matched elements are directly adjacent, an empty slice will be
1432 /// present between them:
1435 /// let slice = [10, 6, 33, 20];
1436 /// let mut iter = slice.split(|num| num % 3 == 0);
1438 /// assert_eq!(iter.next().unwrap(), &[10]);
1439 /// assert_eq!(iter.next().unwrap(), &[]);
1440 /// assert_eq!(iter.next().unwrap(), &[20]);
1441 /// assert!(iter.next().is_none());
1443 #[stable(feature = "rust1", since = "1.0.0")]
1445 pub fn split<F>(&self, pred: F) -> Split<T, F>
1446 where F: FnMut(&T) -> bool
1448 SliceExt::split(self, pred)
1451 /// Returns an iterator over mutable subslices separated by elements that
1452 /// match `pred`. The matched element is not contained in the subslices.
1457 /// let mut v = [10, 40, 30, 20, 60, 50];
1459 /// for group in v.split_mut(|num| *num % 3 == 0) {
1462 /// assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1464 #[stable(feature = "rust1", since = "1.0.0")]
1466 pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
1467 where F: FnMut(&T) -> bool
1469 SliceExt::split_mut(self, pred)
1472 /// Returns an iterator over subslices separated by elements that match
1473 /// `pred`, starting at the end of the slice and working backwards.
1474 /// The matched element is not contained in the subslices.
1479 /// let slice = [11, 22, 33, 0, 44, 55];
1480 /// let mut iter = slice.rsplit(|num| *num == 0);
1482 /// assert_eq!(iter.next().unwrap(), &[44, 55]);
1483 /// assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
1484 /// assert_eq!(iter.next(), None);
1487 /// As with `split()`, if the first or last element is matched, an empty
1488 /// slice will be the first (or last) item returned by the iterator.
1491 /// let v = &[0, 1, 1, 2, 3, 5, 8];
1492 /// let mut it = v.rsplit(|n| *n % 2 == 0);
1493 /// assert_eq!(it.next().unwrap(), &[]);
1494 /// assert_eq!(it.next().unwrap(), &[3, 5]);
1495 /// assert_eq!(it.next().unwrap(), &[1, 1]);
1496 /// assert_eq!(it.next().unwrap(), &[]);
1497 /// assert_eq!(it.next(), None);
1499 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1501 pub fn rsplit<F>(&self, pred: F) -> RSplit<T, F>
1502 where F: FnMut(&T) -> bool
1504 SliceExt::rsplit(self, pred)
1507 /// Returns an iterator over mutable subslices separated by elements that
1508 /// match `pred`, starting at the end of the slice and working
1509 /// backwards. The matched element is not contained in the subslices.
1514 /// let mut v = [100, 400, 300, 200, 600, 500];
1516 /// let mut count = 0;
1517 /// for group in v.rsplit_mut(|num| *num % 3 == 0) {
1519 /// group[0] = count;
1521 /// assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1524 #[stable(feature = "slice_rsplit", since = "1.27.0")]
1526 pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<T, F>
1527 where F: FnMut(&T) -> bool
1529 SliceExt::rsplit_mut(self, pred)
1532 /// Returns an iterator over subslices separated by elements that match
1533 /// `pred`, limited to returning at most `n` items. The matched element is
1534 /// not contained in the subslices.
1536 /// The last element returned, if any, will contain the remainder of the
1541 /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`,
1542 /// `[20, 60, 50]`):
1545 /// let v = [10, 40, 30, 20, 60, 50];
1547 /// for group in v.splitn(2, |num| *num % 3 == 0) {
1548 /// println!("{:?}", group);
1551 #[stable(feature = "rust1", since = "1.0.0")]
1553 pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
1554 where F: FnMut(&T) -> bool
1556 SliceExt::splitn(self, n, pred)
1559 /// Returns an iterator over subslices separated by elements that match
1560 /// `pred`, limited to returning at most `n` items. The matched element is
1561 /// not contained in the subslices.
1563 /// The last element returned, if any, will contain the remainder of the
1569 /// let mut v = [10, 40, 30, 20, 60, 50];
1571 /// for group in v.splitn_mut(2, |num| *num % 3 == 0) {
1574 /// assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1576 #[stable(feature = "rust1", since = "1.0.0")]
1578 pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
1579 where F: FnMut(&T) -> bool
1581 SliceExt::splitn_mut(self, n, pred)
1584 /// Returns an iterator over subslices separated by elements that match
1585 /// `pred` limited to returning at most `n` items. This starts at the end of
1586 /// the slice and works backwards. The matched element is not contained in
1589 /// The last element returned, if any, will contain the remainder of the
1594 /// Print the slice split once, starting from the end, by numbers divisible
1595 /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`):
1598 /// let v = [10, 40, 30, 20, 60, 50];
1600 /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
1601 /// println!("{:?}", group);
1604 #[stable(feature = "rust1", since = "1.0.0")]
1606 pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
1607 where F: FnMut(&T) -> bool
1609 SliceExt::rsplitn(self, n, pred)
1612 /// Returns an iterator over subslices separated by elements that match
1613 /// `pred` limited to returning at most `n` items. This starts at the end of
1614 /// the slice and works backwards. The matched element is not contained in
1617 /// The last element returned, if any, will contain the remainder of the
1623 /// let mut s = [10, 40, 30, 20, 60, 50];
1625 /// for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
1628 /// assert_eq!(s, [1, 40, 30, 20, 60, 1]);
1630 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
1633 where F: FnMut(&T) -> bool
1635 SliceExt::rsplitn_mut(self, n, pred)
1638 /// Returns `true` if the slice contains an element with the given value.
1643 /// let v = [10, 40, 30];
1644 /// assert!(v.contains(&30));
1645 /// assert!(!v.contains(&50));
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 pub fn contains(&self, x: &T) -> bool
1651 SliceExt::contains(self, x)
1654 /// Returns `true` if `needle` is a prefix of the slice.
1659 /// let v = [10, 40, 30];
1660 /// assert!(v.starts_with(&[10]));
1661 /// assert!(v.starts_with(&[10, 40]));
1662 /// assert!(!v.starts_with(&[50]));
1663 /// assert!(!v.starts_with(&[10, 50]));
1666 /// Always returns `true` if `needle` is an empty slice:
1669 /// let v = &[10, 40, 30];
1670 /// assert!(v.starts_with(&[]));
1671 /// let v: &[u8] = &[];
1672 /// assert!(v.starts_with(&[]));
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 pub fn starts_with(&self, needle: &[T]) -> bool
1678 SliceExt::starts_with(self, needle)
1681 /// Returns `true` if `needle` is a suffix of the slice.
1686 /// let v = [10, 40, 30];
1687 /// assert!(v.ends_with(&[30]));
1688 /// assert!(v.ends_with(&[40, 30]));
1689 /// assert!(!v.ends_with(&[50]));
1690 /// assert!(!v.ends_with(&[50, 30]));
1693 /// Always returns `true` if `needle` is an empty slice:
1696 /// let v = &[10, 40, 30];
1697 /// assert!(v.ends_with(&[]));
1698 /// let v: &[u8] = &[];
1699 /// assert!(v.ends_with(&[]));
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub fn ends_with(&self, needle: &[T]) -> bool
1705 SliceExt::ends_with(self, needle)
1708 /// Binary searches this sorted slice for a given element.
1710 /// If the value is found then `Ok` is returned, containing the
1711 /// index of the matching element; if the value is not found then
1712 /// `Err` is returned, containing the index where a matching
1713 /// element could be inserted while maintaining sorted order.
1717 /// Looks up a series of four elements. The first is found, with a
1718 /// uniquely determined position; the second and third are not
1719 /// found; the fourth could match any position in `[1, 4]`.
1722 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1724 /// assert_eq!(s.binary_search(&13), Ok(9));
1725 /// assert_eq!(s.binary_search(&4), Err(7));
1726 /// assert_eq!(s.binary_search(&100), Err(13));
1727 /// let r = s.binary_search(&1);
1728 /// assert!(match r { Ok(1...4) => true, _ => false, });
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
1734 SliceExt::binary_search(self, x)
1737 /// Binary searches this sorted slice with a comparator function.
1739 /// The comparator function should implement an order consistent
1740 /// with the sort order of the underlying slice, returning an
1741 /// order code that indicates whether its argument is `Less`,
1742 /// `Equal` or `Greater` the desired target.
1744 /// If a matching value is found then returns `Ok`, containing
1745 /// the index for the matched element; if no match is found then
1746 /// `Err` is returned, containing the index where a matching
1747 /// element could be inserted while maintaining sorted order.
1751 /// Looks up a series of four elements. The first is found, with a
1752 /// uniquely determined position; the second and third are not
1753 /// found; the fourth could match any position in `[1, 4]`.
1756 /// let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
1759 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
1761 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
1763 /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
1765 /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
1766 /// assert!(match r { Ok(1...4) => true, _ => false, });
1768 #[stable(feature = "rust1", since = "1.0.0")]
1770 pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
1771 where F: FnMut(&'a T) -> Ordering
1773 SliceExt::binary_search_by(self, f)
1776 /// Binary searches this sorted slice with a key extraction function.
1778 /// Assumes that the slice is sorted by the key, for instance with
1779 /// [`sort_by_key`] using the same key extraction function.
1781 /// If a matching value is found then returns `Ok`, containing the
1782 /// index for the matched element; if no match is found then `Err`
1783 /// is returned, containing the index where a matching element could
1784 /// be inserted while maintaining sorted order.
1786 /// [`sort_by_key`]: #method.sort_by_key
1790 /// Looks up a series of four elements in a slice of pairs sorted by
1791 /// their second elements. The first is found, with a uniquely
1792 /// determined position; the second and third are not found; the
1793 /// fourth could match any position in `[1, 4]`.
1796 /// let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
1797 /// (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
1798 /// (1, 21), (2, 34), (4, 55)];
1800 /// assert_eq!(s.binary_search_by_key(&13, |&(a,b)| b), Ok(9));
1801 /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7));
1802 /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13));
1803 /// let r = s.binary_search_by_key(&1, |&(a,b)| b);
1804 /// assert!(match r { Ok(1...4) => true, _ => false, });
1806 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
1808 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, f: F) -> Result<usize, usize>
1809 where F: FnMut(&'a T) -> B,
1812 SliceExt::binary_search_by_key(self, b, f)
1815 /// Sorts the slice, but may not preserve the order of equal elements.
1817 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1818 /// and `O(n log n)` worst-case.
1820 /// # Current implementation
1822 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1823 /// which combines the fast average case of randomized quicksort with the fast worst case of
1824 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1825 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1826 /// deterministic behavior.
1828 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1829 /// slice consists of several concatenated sorted sequences.
1834 /// let mut v = [-5, 4, 1, -3, 2];
1836 /// v.sort_unstable();
1837 /// assert!(v == [-5, -3, 1, 2, 4]);
1840 /// [pdqsort]: https://github.com/orlp/pdqsort
1841 #[stable(feature = "sort_unstable", since = "1.20.0")]
1843 pub fn sort_unstable(&mut self)
1846 SliceExt::sort_unstable(self);
1849 /// Sorts the slice with a comparator function, but may not preserve the order of equal
1852 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1853 /// and `O(n log n)` worst-case.
1855 /// # Current implementation
1857 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1858 /// which combines the fast average case of randomized quicksort with the fast worst case of
1859 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1860 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1861 /// deterministic behavior.
1863 /// It is typically faster than stable sorting, except in a few special cases, e.g. when the
1864 /// slice consists of several concatenated sorted sequences.
1869 /// let mut v = [5, 4, 1, 3, 2];
1870 /// v.sort_unstable_by(|a, b| a.cmp(b));
1871 /// assert!(v == [1, 2, 3, 4, 5]);
1873 /// // reverse sorting
1874 /// v.sort_unstable_by(|a, b| b.cmp(a));
1875 /// assert!(v == [5, 4, 3, 2, 1]);
1878 /// [pdqsort]: https://github.com/orlp/pdqsort
1879 #[stable(feature = "sort_unstable", since = "1.20.0")]
1881 pub fn sort_unstable_by<F>(&mut self, compare: F)
1882 where F: FnMut(&T, &T) -> Ordering
1884 SliceExt::sort_unstable_by(self, compare);
1887 /// Sorts the slice with a key extraction function, but may not preserve the order of equal
1890 /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate),
1891 /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`.
1893 /// # Current implementation
1895 /// The current algorithm is based on [pattern-defeating quicksort][pdqsort] by Orson Peters,
1896 /// which combines the fast average case of randomized quicksort with the fast worst case of
1897 /// heapsort, while achieving linear time on slices with certain patterns. It uses some
1898 /// randomization to avoid degenerate cases, but with a fixed seed to always provide
1899 /// deterministic behavior.
1904 /// let mut v = [-5i32, 4, 1, -3, 2];
1906 /// v.sort_unstable_by_key(|k| k.abs());
1907 /// assert!(v == [1, 2, -3, 4, -5]);
1910 /// [pdqsort]: https://github.com/orlp/pdqsort
1911 #[stable(feature = "sort_unstable", since = "1.20.0")]
1913 pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
1914 where F: FnMut(&T) -> K, K: Ord
1916 SliceExt::sort_unstable_by_key(self, f);
1919 /// Rotates the slice in-place such that the first `mid` elements of the
1920 /// slice move to the end while the last `self.len() - mid` elements move to
1921 /// the front. After calling `rotate_left`, the element previously at index
1922 /// `mid` will become the first element in the slice.
1926 /// This function will panic if `mid` is greater than the length of the
1927 /// slice. Note that `mid == self.len()` does _not_ panic and is a no-op
1932 /// Takes linear (in `self.len()`) time.
1937 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1938 /// a.rotate_left(2);
1939 /// assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
1942 /// Rotating a subslice:
1945 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1946 /// a[1..5].rotate_left(1);
1947 /// assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1949 #[stable(feature = "slice_rotate", since = "1.26.0")]
1950 pub fn rotate_left(&mut self, mid: usize) {
1951 SliceExt::rotate_left(self, mid);
1954 /// Rotates the slice in-place such that the first `self.len() - k`
1955 /// elements of the slice move to the end while the last `k` elements move
1956 /// to the front. After calling `rotate_right`, the element previously at
1957 /// index `self.len() - k` will become the first element in the slice.
1961 /// This function will panic if `k` is greater than the length of the
1962 /// slice. Note that `k == self.len()` does _not_ panic and is a no-op
1967 /// Takes linear (in `self.len()`) time.
1972 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1973 /// a.rotate_right(2);
1974 /// assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
1977 /// Rotate a subslice:
1980 /// let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
1981 /// a[1..5].rotate_right(1);
1982 /// assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1984 #[stable(feature = "slice_rotate", since = "1.26.0")]
1985 pub fn rotate_right(&mut self, k: usize) {
1986 SliceExt::rotate_right(self, k);
1989 /// Copies the elements from `src` into `self`.
1991 /// The length of `src` must be the same as `self`.
1993 /// If `src` implements `Copy`, it can be more performant to use
1994 /// [`copy_from_slice`].
1998 /// This function will panic if the two slices have different lengths.
2002 /// Cloning two elements from a slice into another:
2005 /// let src = [1, 2, 3, 4];
2006 /// let mut dst = [0, 0];
2008 /// dst.clone_from_slice(&src[2..]);
2010 /// assert_eq!(src, [1, 2, 3, 4]);
2011 /// assert_eq!(dst, [3, 4]);
2014 /// Rust enforces that there can only be one mutable reference with no
2015 /// immutable references to a particular piece of data in a particular
2016 /// scope. Because of this, attempting to use `clone_from_slice` on a
2017 /// single slice will result in a compile failure:
2020 /// let mut slice = [1, 2, 3, 4, 5];
2022 /// slice[..2].clone_from_slice(&slice[3..]); // compile fail!
2025 /// To work around this, we can use [`split_at_mut`] to create two distinct
2026 /// sub-slices from a slice:
2029 /// let mut slice = [1, 2, 3, 4, 5];
2032 /// let (left, right) = slice.split_at_mut(2);
2033 /// left.clone_from_slice(&right[1..]);
2036 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2039 /// [`copy_from_slice`]: #method.copy_from_slice
2040 /// [`split_at_mut`]: #method.split_at_mut
2041 #[stable(feature = "clone_from_slice", since = "1.7.0")]
2042 pub fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
2043 SliceExt::clone_from_slice(self, src)
2046 /// Copies all elements from `src` into `self`, using a memcpy.
2048 /// The length of `src` must be the same as `self`.
2050 /// If `src` does not implement `Copy`, use [`clone_from_slice`].
2054 /// This function will panic if the two slices have different lengths.
2058 /// Copying two elements from a slice into another:
2061 /// let src = [1, 2, 3, 4];
2062 /// let mut dst = [0, 0];
2064 /// dst.copy_from_slice(&src[2..]);
2066 /// assert_eq!(src, [1, 2, 3, 4]);
2067 /// assert_eq!(dst, [3, 4]);
2070 /// Rust enforces that there can only be one mutable reference with no
2071 /// immutable references to a particular piece of data in a particular
2072 /// scope. Because of this, attempting to use `copy_from_slice` on a
2073 /// single slice will result in a compile failure:
2076 /// let mut slice = [1, 2, 3, 4, 5];
2078 /// slice[..2].copy_from_slice(&slice[3..]); // compile fail!
2081 /// To work around this, we can use [`split_at_mut`] to create two distinct
2082 /// sub-slices from a slice:
2085 /// let mut slice = [1, 2, 3, 4, 5];
2088 /// let (left, right) = slice.split_at_mut(2);
2089 /// left.copy_from_slice(&right[1..]);
2092 /// assert_eq!(slice, [4, 5, 3, 4, 5]);
2095 /// [`clone_from_slice`]: #method.clone_from_slice
2096 /// [`split_at_mut`]: #method.split_at_mut
2097 #[stable(feature = "copy_from_slice", since = "1.9.0")]
2098 pub fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
2099 SliceExt::copy_from_slice(self, src)
2102 /// Swaps all elements in `self` with those in `other`.
2104 /// The length of `other` must be the same as `self`.
2108 /// This function will panic if the two slices have different lengths.
2112 /// Swapping two elements across slices:
2115 /// let mut slice1 = [0, 0];
2116 /// let mut slice2 = [1, 2, 3, 4];
2118 /// slice1.swap_with_slice(&mut slice2[2..]);
2120 /// assert_eq!(slice1, [3, 4]);
2121 /// assert_eq!(slice2, [1, 2, 0, 0]);
2124 /// Rust enforces that there can only be one mutable reference to a
2125 /// particular piece of data in a particular scope. Because of this,
2126 /// attempting to use `swap_with_slice` on a single slice will result in
2127 /// a compile failure:
2130 /// let mut slice = [1, 2, 3, 4, 5];
2131 /// slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
2134 /// To work around this, we can use [`split_at_mut`] to create two distinct
2135 /// mutable sub-slices from a slice:
2138 /// let mut slice = [1, 2, 3, 4, 5];
2141 /// let (left, right) = slice.split_at_mut(2);
2142 /// left.swap_with_slice(&mut right[1..]);
2145 /// assert_eq!(slice, [4, 5, 3, 1, 2]);
2148 /// [`split_at_mut`]: #method.split_at_mut
2149 #[stable(feature = "swap_with_slice", since = "1.27.0")]
2150 pub fn swap_with_slice(&mut self, other: &mut [T]) {
2151 SliceExt::swap_with_slice(self, other)
2159 slice_core_methods!();
2162 // FIXME: remove (inline) this macro
2163 // when updating to a bootstrap compiler that has the new lang items.
2164 #[cfg_attr(stage0, macro_export)]
2165 #[unstable(feature = "core_slice_ext", issue = "32110")]
2166 macro_rules! slice_u8_core_methods { () => {
2167 /// Checks if all bytes in this slice are within the ASCII range.
2168 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2170 pub fn is_ascii(&self) -> bool {
2171 self.iter().all(|b| b.is_ascii())
2174 /// Checks that two slices are an ASCII case-insensitive match.
2176 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2177 /// but without allocating and copying temporaries.
2178 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2180 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
2181 self.len() == other.len() &&
2182 self.iter().zip(other).all(|(a, b)| {
2183 a.eq_ignore_ascii_case(b)
2187 /// Converts this slice to its ASCII upper case equivalent in-place.
2189 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2190 /// but non-ASCII letters are unchanged.
2192 /// To return a new uppercased value without modifying the existing one, use
2193 /// [`to_ascii_uppercase`].
2195 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2196 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2198 pub fn make_ascii_uppercase(&mut self) {
2200 byte.make_ascii_uppercase();
2204 /// Converts this slice to its ASCII lower case equivalent in-place.
2206 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2207 /// but non-ASCII letters are unchanged.
2209 /// To return a new lowercased value without modifying the existing one, use
2210 /// [`to_ascii_lowercase`].
2212 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2213 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2215 pub fn make_ascii_lowercase(&mut self) {
2217 byte.make_ascii_lowercase();
2222 #[lang = "slice_u8"]
2226 slice_u8_core_methods!();
2229 #[stable(feature = "rust1", since = "1.0.0")]
2230 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2231 impl<T, I> ops::Index<I> for [T]
2232 where I: SliceIndex<[T]>
2234 type Output = I::Output;
2237 fn index(&self, index: I) -> &I::Output {
2242 #[stable(feature = "rust1", since = "1.0.0")]
2243 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2244 impl<T, I> ops::IndexMut<I> for [T]
2245 where I: SliceIndex<[T]>
2248 fn index_mut(&mut self, index: I) -> &mut I::Output {
2249 index.index_mut(self)
2255 fn slice_index_len_fail(index: usize, len: usize) -> ! {
2256 panic!("index {} out of range for slice of length {}", index, len);
2261 fn slice_index_order_fail(index: usize, end: usize) -> ! {
2262 panic!("slice index starts at {} but ends at {}", index, end);
2267 fn slice_index_overflow_fail() -> ! {
2268 panic!("attempted to index slice up to maximum usize");
2271 /// A helper trait used for indexing operations.
2272 #[unstable(feature = "slice_get_slice", issue = "35729")]
2273 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
2274 pub trait SliceIndex<T: ?Sized> {
2275 /// The output type returned by methods.
2276 type Output: ?Sized;
2278 /// Returns a shared reference to the output at this location, if in
2280 fn get(self, slice: &T) -> Option<&Self::Output>;
2282 /// Returns a mutable reference to the output at this location, if in
2284 fn get_mut(self, slice: &mut T) -> Option<&mut Self::Output>;
2286 /// Returns a shared reference to the output at this location, without
2287 /// performing any bounds checking.
2288 unsafe fn get_unchecked(self, slice: &T) -> &Self::Output;
2290 /// Returns a mutable reference to the output at this location, without
2291 /// performing any bounds checking.
2292 unsafe fn get_unchecked_mut(self, slice: &mut T) -> &mut Self::Output;
2294 /// Returns a shared reference to the output at this location, panicking
2295 /// if out of bounds.
2296 fn index(self, slice: &T) -> &Self::Output;
2298 /// Returns a mutable reference to the output at this location, panicking
2299 /// if out of bounds.
2300 fn index_mut(self, slice: &mut T) -> &mut Self::Output;
2303 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2304 impl<T> SliceIndex<[T]> for usize {
2308 fn get(self, slice: &[T]) -> Option<&T> {
2309 if self < slice.len() {
2311 Some(self.get_unchecked(slice))
2319 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
2320 if self < slice.len() {
2322 Some(self.get_unchecked_mut(slice))
2330 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
2331 &*slice.as_ptr().offset(self as isize)
2335 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
2336 &mut *slice.as_mut_ptr().offset(self as isize)
2340 fn index(self, slice: &[T]) -> &T {
2341 // NB: use intrinsic indexing
2346 fn index_mut(self, slice: &mut [T]) -> &mut T {
2347 // NB: use intrinsic indexing
2352 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2353 impl<T> SliceIndex<[T]> for ops::Range<usize> {
2357 fn get(self, slice: &[T]) -> Option<&[T]> {
2358 if self.start > self.end || self.end > slice.len() {
2362 Some(self.get_unchecked(slice))
2368 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2369 if self.start > self.end || self.end > slice.len() {
2373 Some(self.get_unchecked_mut(slice))
2379 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2380 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
2384 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2385 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
2389 fn index(self, slice: &[T]) -> &[T] {
2390 if self.start > self.end {
2391 slice_index_order_fail(self.start, self.end);
2392 } else if self.end > slice.len() {
2393 slice_index_len_fail(self.end, slice.len());
2396 self.get_unchecked(slice)
2401 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2402 if self.start > self.end {
2403 slice_index_order_fail(self.start, self.end);
2404 } else if self.end > slice.len() {
2405 slice_index_len_fail(self.end, slice.len());
2408 self.get_unchecked_mut(slice)
2413 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2414 impl<T> SliceIndex<[T]> for ops::RangeTo<usize> {
2418 fn get(self, slice: &[T]) -> Option<&[T]> {
2419 (0..self.end).get(slice)
2423 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2424 (0..self.end).get_mut(slice)
2428 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2429 (0..self.end).get_unchecked(slice)
2433 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2434 (0..self.end).get_unchecked_mut(slice)
2438 fn index(self, slice: &[T]) -> &[T] {
2439 (0..self.end).index(slice)
2443 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2444 (0..self.end).index_mut(slice)
2448 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2449 impl<T> SliceIndex<[T]> for ops::RangeFrom<usize> {
2453 fn get(self, slice: &[T]) -> Option<&[T]> {
2454 (self.start..slice.len()).get(slice)
2458 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2459 (self.start..slice.len()).get_mut(slice)
2463 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2464 (self.start..slice.len()).get_unchecked(slice)
2468 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2469 (self.start..slice.len()).get_unchecked_mut(slice)
2473 fn index(self, slice: &[T]) -> &[T] {
2474 (self.start..slice.len()).index(slice)
2478 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2479 (self.start..slice.len()).index_mut(slice)
2483 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
2484 impl<T> SliceIndex<[T]> for ops::RangeFull {
2488 fn get(self, slice: &[T]) -> Option<&[T]> {
2493 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2498 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2503 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2508 fn index(self, slice: &[T]) -> &[T] {
2513 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2519 #[stable(feature = "inclusive_range", since = "1.26.0")]
2520 impl<T> SliceIndex<[T]> for ops::RangeInclusive<usize> {
2524 fn get(self, slice: &[T]) -> Option<&[T]> {
2525 if self.end == usize::max_value() { None }
2526 else { (self.start..self.end + 1).get(slice) }
2530 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2531 if self.end == usize::max_value() { None }
2532 else { (self.start..self.end + 1).get_mut(slice) }
2536 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2537 (self.start..self.end + 1).get_unchecked(slice)
2541 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2542 (self.start..self.end + 1).get_unchecked_mut(slice)
2546 fn index(self, slice: &[T]) -> &[T] {
2547 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2548 (self.start..self.end + 1).index(slice)
2552 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2553 if self.end == usize::max_value() { slice_index_overflow_fail(); }
2554 (self.start..self.end + 1).index_mut(slice)
2558 #[stable(feature = "inclusive_range", since = "1.26.0")]
2559 impl<T> SliceIndex<[T]> for ops::RangeToInclusive<usize> {
2563 fn get(self, slice: &[T]) -> Option<&[T]> {
2564 (0..=self.end).get(slice)
2568 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
2569 (0..=self.end).get_mut(slice)
2573 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
2574 (0..=self.end).get_unchecked(slice)
2578 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
2579 (0..=self.end).get_unchecked_mut(slice)
2583 fn index(self, slice: &[T]) -> &[T] {
2584 (0..=self.end).index(slice)
2588 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
2589 (0..=self.end).index_mut(slice)
2593 ////////////////////////////////////////////////////////////////////////////////
2595 ////////////////////////////////////////////////////////////////////////////////
2597 #[stable(feature = "rust1", since = "1.0.0")]
2598 impl<'a, T> Default for &'a [T] {
2599 /// Creates an empty slice.
2600 fn default() -> &'a [T] { &[] }
2603 #[stable(feature = "mut_slice_default", since = "1.5.0")]
2604 impl<'a, T> Default for &'a mut [T] {
2605 /// Creates a mutable empty slice.
2606 fn default() -> &'a mut [T] { &mut [] }
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl<'a, T> IntoIterator for &'a [T] {
2616 type IntoIter = Iter<'a, T>;
2618 fn into_iter(self) -> Iter<'a, T> {
2623 #[stable(feature = "rust1", since = "1.0.0")]
2624 impl<'a, T> IntoIterator for &'a mut [T] {
2625 type Item = &'a mut T;
2626 type IntoIter = IterMut<'a, T>;
2628 fn into_iter(self) -> IterMut<'a, T> {
2634 fn size_from_ptr<T>(_: *const T) -> usize {
2638 // The shared definition of the `Iter` and `IterMut` iterators
2639 macro_rules! iterator {
2640 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
2641 #[stable(feature = "rust1", since = "1.0.0")]
2642 impl<'a, T> Iterator for $name<'a, T> {
2646 fn next(&mut self) -> Option<$elem> {
2647 // could be implemented with slices, but this avoids bounds checks
2649 if mem::size_of::<T>() != 0 {
2650 assume(!self.ptr.is_null());
2651 assume(!self.end.is_null());
2653 if self.ptr == self.end {
2656 Some($mkref!(self.ptr.post_inc()))
2662 fn size_hint(&self) -> (usize, Option<usize>) {
2663 let exact = unsafe { ptrdistance(self.ptr, self.end) };
2664 (exact, Some(exact))
2668 fn count(self) -> usize {
2673 fn nth(&mut self, n: usize) -> Option<$elem> {
2674 // Call helper method. Can't put the definition here because mut versus const.
2679 fn last(mut self) -> Option<$elem> {
2684 fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2685 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2687 // manual unrolling is needed when there are conditional exits from the loop
2688 let mut accum = init;
2690 while ptrdistance(self.ptr, self.end) >= 4 {
2691 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2692 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2693 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2694 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2696 while self.ptr != self.end {
2697 accum = f(accum, $mkref!(self.ptr.post_inc()))?;
2704 fn fold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2705 where Fold: FnMut(Acc, Self::Item) -> Acc,
2707 // Let LLVM unroll this, rather than using the default
2708 // impl that would force the manual unrolling above
2709 let mut accum = init;
2710 while let Some(x) = self.next() {
2711 accum = f(accum, x);
2717 #[rustc_inherit_overflow_checks]
2718 fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
2720 P: FnMut(Self::Item) -> bool,
2722 // The addition might panic on overflow
2723 // Use the len of the slice to hint optimizer to remove result index bounds check.
2724 let n = make_slice!(self.ptr, self.end).len();
2725 self.try_fold(0, move |i, x| {
2726 if predicate(x) { Err(i) }
2730 unsafe { assume(i < n) };
2736 fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
2737 P: FnMut(Self::Item) -> bool,
2738 Self: Sized + ExactSizeIterator + DoubleEndedIterator
2740 // No need for an overflow check here, because `ExactSizeIterator`
2741 // implies that the number of elements fits into a `usize`.
2742 // Use the len of the slice to hint optimizer to remove result index bounds check.
2743 let n = make_slice!(self.ptr, self.end).len();
2744 self.try_rfold(n, move |i, x| {
2746 if predicate(x) { Err(i) }
2750 unsafe { assume(i < n) };
2756 #[stable(feature = "rust1", since = "1.0.0")]
2757 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
2759 fn next_back(&mut self) -> Option<$elem> {
2760 // could be implemented with slices, but this avoids bounds checks
2762 if mem::size_of::<T>() != 0 {
2763 assume(!self.ptr.is_null());
2764 assume(!self.end.is_null());
2766 if self.end == self.ptr {
2769 Some($mkref!(self.end.pre_dec()))
2775 fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R where
2776 Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
2778 // manual unrolling is needed when there are conditional exits from the loop
2779 let mut accum = init;
2781 while ptrdistance(self.ptr, self.end) >= 4 {
2782 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2783 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2784 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2785 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2787 while self.ptr != self.end {
2788 accum = f(accum, $mkref!(self.end.pre_dec()))?;
2795 fn rfold<Acc, Fold>(mut self, init: Acc, mut f: Fold) -> Acc
2796 where Fold: FnMut(Acc, Self::Item) -> Acc,
2798 // Let LLVM unroll this, rather than using the default
2799 // impl that would force the manual unrolling above
2800 let mut accum = init;
2801 while let Some(x) = self.next_back() {
2802 accum = f(accum, x);
2810 macro_rules! make_slice {
2811 ($start: expr, $end: expr) => {{
2813 let diff = ($end as usize).wrapping_sub(start as usize);
2814 if size_from_ptr(start) == 0 {
2815 // use a non-null pointer value
2816 unsafe { from_raw_parts(1 as *const _, diff) }
2818 let len = diff / size_from_ptr(start);
2819 unsafe { from_raw_parts(start, len) }
2824 macro_rules! make_mut_slice {
2825 ($start: expr, $end: expr) => {{
2827 let diff = ($end as usize).wrapping_sub(start as usize);
2828 if size_from_ptr(start) == 0 {
2829 // use a non-null pointer value
2830 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
2832 let len = diff / size_from_ptr(start);
2833 unsafe { from_raw_parts_mut(start, len) }
2838 /// Immutable slice iterator
2840 /// This struct is created by the [`iter`] method on [slices].
2847 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
2848 /// let slice = &[1, 2, 3];
2850 /// // Then, we iterate over it:
2851 /// for element in slice.iter() {
2852 /// println!("{}", element);
2856 /// [`iter`]: ../../std/primitive.slice.html#method.iter
2857 /// [slices]: ../../std/primitive.slice.html
2858 #[stable(feature = "rust1", since = "1.0.0")]
2859 pub struct Iter<'a, T: 'a> {
2862 _marker: marker::PhantomData<&'a T>,
2865 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2866 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
2867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2868 f.debug_tuple("Iter")
2869 .field(&self.as_slice())
2874 #[stable(feature = "rust1", since = "1.0.0")]
2875 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2876 #[stable(feature = "rust1", since = "1.0.0")]
2877 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2879 impl<'a, T> Iter<'a, T> {
2880 /// View the underlying data as a subslice of the original data.
2882 /// This has the same lifetime as the original slice, and so the
2883 /// iterator can continue to be used while this exists.
2890 /// // First, we declare a type which has the `iter` method to get the `Iter`
2891 /// // struct (&[usize here]):
2892 /// let slice = &[1, 2, 3];
2894 /// // Then, we get the iterator:
2895 /// let mut iter = slice.iter();
2896 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
2897 /// println!("{:?}", iter.as_slice());
2899 /// // Next, we move to the second element of the slice:
2901 /// // Now `as_slice` returns "[2, 3]":
2902 /// println!("{:?}", iter.as_slice());
2904 #[stable(feature = "iter_to_slice", since = "1.4.0")]
2905 pub fn as_slice(&self) -> &'a [T] {
2906 make_slice!(self.ptr, self.end)
2909 // Helper function for Iter::nth
2910 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
2911 match self.as_slice().get(n) {
2912 Some(elem_ref) => unsafe {
2913 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
2917 self.ptr = self.end;
2924 iterator!{struct Iter -> *const T, &'a T, make_ref}
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
2928 fn is_empty(&self) -> bool {
2929 self.ptr == self.end
2933 #[stable(feature = "fused", since = "1.26.0")]
2934 impl<'a, T> FusedIterator for Iter<'a, T> {}
2936 #[unstable(feature = "trusted_len", issue = "37572")]
2937 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
2939 #[stable(feature = "rust1", since = "1.0.0")]
2940 impl<'a, T> Clone for Iter<'a, T> {
2941 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
2944 #[stable(feature = "slice_iter_as_ref", since = "1.13.0")]
2945 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
2946 fn as_ref(&self) -> &[T] {
2951 /// Mutable slice iterator.
2953 /// This struct is created by the [`iter_mut`] method on [slices].
2960 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
2961 /// // struct (&[usize here]):
2962 /// let mut slice = &mut [1, 2, 3];
2964 /// // Then, we iterate over it and increment each element value:
2965 /// for element in slice.iter_mut() {
2969 /// // We now have "[2, 3, 4]":
2970 /// println!("{:?}", slice);
2973 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
2974 /// [slices]: ../../std/primitive.slice.html
2975 #[stable(feature = "rust1", since = "1.0.0")]
2976 pub struct IterMut<'a, T: 'a> {
2979 _marker: marker::PhantomData<&'a mut T>,
2982 #[stable(feature = "core_impl_debug", since = "1.9.0")]
2983 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
2984 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2985 f.debug_tuple("IterMut")
2986 .field(&make_slice!(self.ptr, self.end))
2991 #[stable(feature = "rust1", since = "1.0.0")]
2992 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2993 #[stable(feature = "rust1", since = "1.0.0")]
2994 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2996 impl<'a, T> IterMut<'a, T> {
2997 /// View the underlying data as a subslice of the original data.
2999 /// To avoid creating `&mut` references that alias, this is forced
3000 /// to consume the iterator. Consider using the `Slice` and
3001 /// `SliceMut` implementations for obtaining slices with more
3002 /// restricted lifetimes that do not consume the iterator.
3009 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
3010 /// // struct (&[usize here]):
3011 /// let mut slice = &mut [1, 2, 3];
3014 /// // Then, we get the iterator:
3015 /// let mut iter = slice.iter_mut();
3016 /// // We move to next element:
3018 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
3019 /// println!("{:?}", iter.into_slice());
3022 /// // Now let's modify a value of the slice:
3024 /// // First we get back the iterator:
3025 /// let mut iter = slice.iter_mut();
3026 /// // We change the value of the first element of the slice returned by the `next` method:
3027 /// *iter.next().unwrap() += 1;
3029 /// // Now slice is "[2, 2, 3]":
3030 /// println!("{:?}", slice);
3032 #[stable(feature = "iter_to_slice", since = "1.4.0")]
3033 pub fn into_slice(self) -> &'a mut [T] {
3034 make_mut_slice!(self.ptr, self.end)
3037 // Helper function for IterMut::nth
3038 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
3039 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
3040 Some(elem_ref) => unsafe {
3041 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
3045 self.ptr = self.end;
3052 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
3054 #[stable(feature = "rust1", since = "1.0.0")]
3055 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
3056 fn is_empty(&self) -> bool {
3057 self.ptr == self.end
3061 #[stable(feature = "fused", since = "1.26.0")]
3062 impl<'a, T> FusedIterator for IterMut<'a, T> {}
3064 #[unstable(feature = "trusted_len", issue = "37572")]
3065 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
3068 // Return the number of elements of `T` from `start` to `end`.
3069 // Return the arithmetic difference if `T` is zero size.
3071 unsafe fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
3072 if mem::size_of::<T>() == 0 {
3073 (end as usize).wrapping_sub(start as usize)
3075 end.offset_from(start) as usize
3079 // Extension methods for raw pointers, used by the iterators
3080 trait PointerExt : Copy {
3081 unsafe fn slice_offset(self, i: isize) -> Self;
3083 /// Increments `self` by 1, but returns the old value.
3085 unsafe fn post_inc(&mut self) -> Self {
3086 let current = *self;
3087 *self = self.slice_offset(1);
3091 /// Decrements `self` by 1, and returns the new value.
3093 unsafe fn pre_dec(&mut self) -> Self {
3094 *self = self.slice_offset(-1);
3099 impl<T> PointerExt for *const T {
3101 unsafe fn slice_offset(self, i: isize) -> Self {
3102 slice_offset!(self, i)
3106 impl<T> PointerExt for *mut T {
3108 unsafe fn slice_offset(self, i: isize) -> Self {
3109 slice_offset!(self, i)
3113 /// An internal abstraction over the splitting iterators, so that
3114 /// splitn, splitn_mut etc can be implemented once.
3116 trait SplitIter: DoubleEndedIterator {
3117 /// Marks the underlying iterator as complete, extracting the remaining
3118 /// portion of the slice.
3119 fn finish(&mut self) -> Option<Self::Item>;
3122 /// An iterator over subslices separated by elements that match a predicate
3125 /// This struct is created by the [`split`] method on [slices].
3127 /// [`split`]: ../../std/primitive.slice.html#method.split
3128 /// [slices]: ../../std/primitive.slice.html
3129 #[stable(feature = "rust1", since = "1.0.0")]
3130 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
3136 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3137 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
3138 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3139 f.debug_struct("Split")
3140 .field("v", &self.v)
3141 .field("finished", &self.finished)
3146 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3147 #[stable(feature = "rust1", since = "1.0.0")]
3148 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
3149 fn clone(&self) -> Split<'a, T, P> {
3152 pred: self.pred.clone(),
3153 finished: self.finished,
3158 #[stable(feature = "rust1", since = "1.0.0")]
3159 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3160 type Item = &'a [T];
3163 fn next(&mut self) -> Option<&'a [T]> {
3164 if self.finished { return None; }
3166 match self.v.iter().position(|x| (self.pred)(x)) {
3167 None => self.finish(),
3169 let ret = Some(&self.v[..idx]);
3170 self.v = &self.v[idx + 1..];
3177 fn size_hint(&self) -> (usize, Option<usize>) {
3181 (1, Some(self.v.len() + 1))
3186 #[stable(feature = "rust1", since = "1.0.0")]
3187 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
3189 fn next_back(&mut self) -> Option<&'a [T]> {
3190 if self.finished { return None; }
3192 match self.v.iter().rposition(|x| (self.pred)(x)) {
3193 None => self.finish(),
3195 let ret = Some(&self.v[idx + 1..]);
3196 self.v = &self.v[..idx];
3203 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
3205 fn finish(&mut self) -> Option<&'a [T]> {
3206 if self.finished { None } else { self.finished = true; Some(self.v) }
3210 #[stable(feature = "fused", since = "1.26.0")]
3211 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
3213 /// An iterator over the subslices of the vector which are separated
3214 /// by elements that match `pred`.
3216 /// This struct is created by the [`split_mut`] method on [slices].
3218 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
3219 /// [slices]: ../../std/primitive.slice.html
3220 #[stable(feature = "rust1", since = "1.0.0")]
3221 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3227 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3228 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3229 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3230 f.debug_struct("SplitMut")
3231 .field("v", &self.v)
3232 .field("finished", &self.finished)
3237 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3239 fn finish(&mut self) -> Option<&'a mut [T]> {
3243 self.finished = true;
3244 Some(mem::replace(&mut self.v, &mut []))
3249 #[stable(feature = "rust1", since = "1.0.0")]
3250 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3251 type Item = &'a mut [T];
3254 fn next(&mut self) -> Option<&'a mut [T]> {
3255 if self.finished { return None; }
3257 let idx_opt = { // work around borrowck limitations
3258 let pred = &mut self.pred;
3259 self.v.iter().position(|x| (*pred)(x))
3262 None => self.finish(),
3264 let tmp = mem::replace(&mut self.v, &mut []);
3265 let (head, tail) = tmp.split_at_mut(idx);
3266 self.v = &mut tail[1..];
3273 fn size_hint(&self) -> (usize, Option<usize>) {
3277 // if the predicate doesn't match anything, we yield one slice
3278 // if it matches every element, we yield len+1 empty slices.
3279 (1, Some(self.v.len() + 1))
3284 #[stable(feature = "rust1", since = "1.0.0")]
3285 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
3286 P: FnMut(&T) -> bool,
3289 fn next_back(&mut self) -> Option<&'a mut [T]> {
3290 if self.finished { return None; }
3292 let idx_opt = { // work around borrowck limitations
3293 let pred = &mut self.pred;
3294 self.v.iter().rposition(|x| (*pred)(x))
3297 None => self.finish(),
3299 let tmp = mem::replace(&mut self.v, &mut []);
3300 let (head, tail) = tmp.split_at_mut(idx);
3302 Some(&mut tail[1..])
3308 #[stable(feature = "fused", since = "1.26.0")]
3309 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3311 /// An iterator over subslices separated by elements that match a predicate
3312 /// function, starting from the end of the slice.
3314 /// This struct is created by the [`rsplit`] method on [slices].
3316 /// [`rsplit`]: ../../std/primitive.slice.html#method.rsplit
3317 /// [slices]: ../../std/primitive.slice.html
3318 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3319 #[derive(Clone)] // Is this correct, or does it incorrectly require `T: Clone`?
3320 pub struct RSplit<'a, T:'a, P> where P: FnMut(&T) -> bool {
3321 inner: Split<'a, T, P>
3324 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3325 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3327 f.debug_struct("RSplit")
3328 .field("v", &self.inner.v)
3329 .field("finished", &self.inner.finished)
3334 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3335 impl<'a, T, P> Iterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3336 type Item = &'a [T];
3339 fn next(&mut self) -> Option<&'a [T]> {
3340 self.inner.next_back()
3344 fn size_hint(&self) -> (usize, Option<usize>) {
3345 self.inner.size_hint()
3349 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3350 impl<'a, T, P> DoubleEndedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3352 fn next_back(&mut self) -> Option<&'a [T]> {
3357 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3358 impl<'a, T, P> SplitIter for RSplit<'a, T, P> where P: FnMut(&T) -> bool {
3360 fn finish(&mut self) -> Option<&'a [T]> {
3365 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3366 impl<'a, T, P> FusedIterator for RSplit<'a, T, P> where P: FnMut(&T) -> bool {}
3368 /// An iterator over the subslices of the vector which are separated
3369 /// by elements that match `pred`, starting from the end of the slice.
3371 /// This struct is created by the [`rsplit_mut`] method on [slices].
3373 /// [`rsplit_mut`]: ../../std/primitive.slice.html#method.rsplit_mut
3374 /// [slices]: ../../std/primitive.slice.html
3375 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3376 pub struct RSplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
3377 inner: SplitMut<'a, T, P>
3380 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3381 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3383 f.debug_struct("RSplitMut")
3384 .field("v", &self.inner.v)
3385 .field("finished", &self.inner.finished)
3390 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3391 impl<'a, T, P> SplitIter for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3393 fn finish(&mut self) -> Option<&'a mut [T]> {
3398 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3399 impl<'a, T, P> Iterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {
3400 type Item = &'a mut [T];
3403 fn next(&mut self) -> Option<&'a mut [T]> {
3404 self.inner.next_back()
3408 fn size_hint(&self) -> (usize, Option<usize>) {
3409 self.inner.size_hint()
3413 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3414 impl<'a, T, P> DoubleEndedIterator for RSplitMut<'a, T, P> where
3415 P: FnMut(&T) -> bool,
3418 fn next_back(&mut self) -> Option<&'a mut [T]> {
3423 #[stable(feature = "slice_rsplit", since = "1.27.0")]
3424 impl<'a, T, P> FusedIterator for RSplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
3426 /// An private iterator over subslices separated by elements that
3427 /// match a predicate function, splitting at most a fixed number of
3430 struct GenericSplitN<I> {
3435 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
3439 fn next(&mut self) -> Option<T> {
3442 1 => { self.count -= 1; self.iter.finish() }
3443 _ => { self.count -= 1; self.iter.next() }
3448 fn size_hint(&self) -> (usize, Option<usize>) {
3449 let (lower, upper_opt) = self.iter.size_hint();
3450 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
3454 /// An iterator over subslices separated by elements that match a predicate
3455 /// function, limited to a given number of splits.
3457 /// This struct is created by the [`splitn`] method on [slices].
3459 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
3460 /// [slices]: ../../std/primitive.slice.html
3461 #[stable(feature = "rust1", since = "1.0.0")]
3462 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3463 inner: GenericSplitN<Split<'a, T, P>>
3466 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3467 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
3468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3469 f.debug_struct("SplitN")
3470 .field("inner", &self.inner)
3475 /// An iterator over subslices separated by elements that match a
3476 /// predicate function, limited to a given number of splits, starting
3477 /// from the end of the slice.
3479 /// This struct is created by the [`rsplitn`] method on [slices].
3481 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
3482 /// [slices]: ../../std/primitive.slice.html
3483 #[stable(feature = "rust1", since = "1.0.0")]
3484 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3485 inner: GenericSplitN<RSplit<'a, T, P>>
3488 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3489 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
3490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3491 f.debug_struct("RSplitN")
3492 .field("inner", &self.inner)
3497 /// An iterator over subslices separated by elements that match a predicate
3498 /// function, limited to a given number of splits.
3500 /// This struct is created by the [`splitn_mut`] method on [slices].
3502 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
3503 /// [slices]: ../../std/primitive.slice.html
3504 #[stable(feature = "rust1", since = "1.0.0")]
3505 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3506 inner: GenericSplitN<SplitMut<'a, T, P>>
3509 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3510 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3512 f.debug_struct("SplitNMut")
3513 .field("inner", &self.inner)
3518 /// An iterator over subslices separated by elements that match a
3519 /// predicate function, limited to a given number of splits, starting
3520 /// from the end of the slice.
3522 /// This struct is created by the [`rsplitn_mut`] method on [slices].
3524 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
3525 /// [slices]: ../../std/primitive.slice.html
3526 #[stable(feature = "rust1", since = "1.0.0")]
3527 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
3528 inner: GenericSplitN<RSplitMut<'a, T, P>>
3531 #[stable(feature = "core_impl_debug", since = "1.9.0")]
3532 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
3533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3534 f.debug_struct("RSplitNMut")
3535 .field("inner", &self.inner)
3540 macro_rules! forward_iterator {
3541 ($name:ident: $elem:ident, $iter_of:ty) => {
3542 #[stable(feature = "rust1", since = "1.0.0")]
3543 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
3544 P: FnMut(&T) -> bool
3546 type Item = $iter_of;
3549 fn next(&mut self) -> Option<$iter_of> {
3554 fn size_hint(&self) -> (usize, Option<usize>) {
3555 self.inner.size_hint()
3559 #[stable(feature = "fused", since = "1.26.0")]
3560 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
3561 where P: FnMut(&T) -> bool {}
3565 forward_iterator! { SplitN: T, &'a [T] }
3566 forward_iterator! { RSplitN: T, &'a [T] }
3567 forward_iterator! { SplitNMut: T, &'a mut [T] }
3568 forward_iterator! { RSplitNMut: T, &'a mut [T] }
3570 /// An iterator over overlapping subslices of length `size`.
3572 /// This struct is created by the [`windows`] method on [slices].
3574 /// [`windows`]: ../../std/primitive.slice.html#method.windows
3575 /// [slices]: ../../std/primitive.slice.html
3577 #[stable(feature = "rust1", since = "1.0.0")]
3578 pub struct Windows<'a, T:'a> {
3583 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3584 #[stable(feature = "rust1", since = "1.0.0")]
3585 impl<'a, T> Clone for Windows<'a, T> {
3586 fn clone(&self) -> Windows<'a, T> {
3594 #[stable(feature = "rust1", since = "1.0.0")]
3595 impl<'a, T> Iterator for Windows<'a, T> {
3596 type Item = &'a [T];
3599 fn next(&mut self) -> Option<&'a [T]> {
3600 if self.size > self.v.len() {
3603 let ret = Some(&self.v[..self.size]);
3604 self.v = &self.v[1..];
3610 fn size_hint(&self) -> (usize, Option<usize>) {
3611 if self.size > self.v.len() {
3614 let size = self.v.len() - self.size + 1;
3620 fn count(self) -> usize {
3625 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3626 let (end, overflow) = self.size.overflowing_add(n);
3627 if end > self.v.len() || overflow {
3631 let nth = &self.v[n..end];
3632 self.v = &self.v[n+1..];
3638 fn last(self) -> Option<Self::Item> {
3639 if self.size > self.v.len() {
3642 let start = self.v.len() - self.size;
3643 Some(&self.v[start..])
3648 #[stable(feature = "rust1", since = "1.0.0")]
3649 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
3651 fn next_back(&mut self) -> Option<&'a [T]> {
3652 if self.size > self.v.len() {
3655 let ret = Some(&self.v[self.v.len()-self.size..]);
3656 self.v = &self.v[..self.v.len()-1];
3662 #[stable(feature = "rust1", since = "1.0.0")]
3663 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
3665 #[stable(feature = "fused", since = "1.26.0")]
3666 impl<'a, T> FusedIterator for Windows<'a, T> {}
3669 unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> {
3670 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3671 from_raw_parts(self.v.as_ptr().offset(i as isize), self.size)
3673 fn may_have_side_effect() -> bool { false }
3676 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3679 /// When the slice len is not evenly divided by the chunk size, the last slice
3680 /// of the iteration will be the remainder.
3682 /// This struct is created by the [`chunks`] method on [slices].
3684 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
3685 /// [slices]: ../../std/primitive.slice.html
3687 #[stable(feature = "rust1", since = "1.0.0")]
3688 pub struct Chunks<'a, T:'a> {
3693 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3694 #[stable(feature = "rust1", since = "1.0.0")]
3695 impl<'a, T> Clone for Chunks<'a, T> {
3696 fn clone(&self) -> Chunks<'a, T> {
3699 chunk_size: self.chunk_size,
3704 #[stable(feature = "rust1", since = "1.0.0")]
3705 impl<'a, T> Iterator for Chunks<'a, T> {
3706 type Item = &'a [T];
3709 fn next(&mut self) -> Option<&'a [T]> {
3710 if self.v.is_empty() {
3713 let chunksz = cmp::min(self.v.len(), self.chunk_size);
3714 let (fst, snd) = self.v.split_at(chunksz);
3721 fn size_hint(&self) -> (usize, Option<usize>) {
3722 if self.v.is_empty() {
3725 let n = self.v.len() / self.chunk_size;
3726 let rem = self.v.len() % self.chunk_size;
3727 let n = if rem > 0 { n+1 } else { n };
3733 fn count(self) -> usize {
3738 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3739 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3740 if start >= self.v.len() || overflow {
3744 let end = match start.checked_add(self.chunk_size) {
3745 Some(sum) => cmp::min(self.v.len(), sum),
3746 None => self.v.len(),
3748 let nth = &self.v[start..end];
3749 self.v = &self.v[end..];
3755 fn last(self) -> Option<Self::Item> {
3756 if self.v.is_empty() {
3759 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3760 Some(&self.v[start..])
3765 #[stable(feature = "rust1", since = "1.0.0")]
3766 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
3768 fn next_back(&mut self) -> Option<&'a [T]> {
3769 if self.v.is_empty() {
3772 let remainder = self.v.len() % self.chunk_size;
3773 let chunksz = if remainder != 0 { remainder } else { self.chunk_size };
3774 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
3781 #[stable(feature = "rust1", since = "1.0.0")]
3782 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
3784 #[stable(feature = "fused", since = "1.26.0")]
3785 impl<'a, T> FusedIterator for Chunks<'a, T> {}
3788 unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> {
3789 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
3790 let start = i * self.chunk_size;
3791 let end = match start.checked_add(self.chunk_size) {
3792 None => self.v.len(),
3793 Some(end) => cmp::min(end, self.v.len()),
3795 from_raw_parts(self.v.as_ptr().offset(start as isize), end - start)
3797 fn may_have_side_effect() -> bool { false }
3800 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
3801 /// elements at a time). When the slice len is not evenly divided by the chunk
3802 /// size, the last slice of the iteration will be the remainder.
3804 /// This struct is created by the [`chunks_mut`] method on [slices].
3806 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
3807 /// [slices]: ../../std/primitive.slice.html
3809 #[stable(feature = "rust1", since = "1.0.0")]
3810 pub struct ChunksMut<'a, T:'a> {
3815 #[stable(feature = "rust1", since = "1.0.0")]
3816 impl<'a, T> Iterator for ChunksMut<'a, T> {
3817 type Item = &'a mut [T];
3820 fn next(&mut self) -> Option<&'a mut [T]> {
3821 if self.v.is_empty() {
3824 let sz = cmp::min(self.v.len(), self.chunk_size);
3825 let tmp = mem::replace(&mut self.v, &mut []);
3826 let (head, tail) = tmp.split_at_mut(sz);
3833 fn size_hint(&self) -> (usize, Option<usize>) {
3834 if self.v.is_empty() {
3837 let n = self.v.len() / self.chunk_size;
3838 let rem = self.v.len() % self.chunk_size;
3839 let n = if rem > 0 { n + 1 } else { n };
3845 fn count(self) -> usize {
3850 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
3851 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3852 if start >= self.v.len() || overflow {
3856 let end = match start.checked_add(self.chunk_size) {
3857 Some(sum) => cmp::min(self.v.len(), sum),
3858 None => self.v.len(),
3860 let tmp = mem::replace(&mut self.v, &mut []);
3861 let (head, tail) = tmp.split_at_mut(end);
3862 let (_, nth) = head.split_at_mut(start);
3869 fn last(self) -> Option<Self::Item> {
3870 if self.v.is_empty() {
3873 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
3874 Some(&mut self.v[start..])
3879 #[stable(feature = "rust1", since = "1.0.0")]
3880 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
3882 fn next_back(&mut self) -> Option<&'a mut [T]> {
3883 if self.v.is_empty() {
3886 let remainder = self.v.len() % self.chunk_size;
3887 let sz = if remainder != 0 { remainder } else { self.chunk_size };
3888 let tmp = mem::replace(&mut self.v, &mut []);
3889 let tmp_len = tmp.len();
3890 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
3897 #[stable(feature = "rust1", since = "1.0.0")]
3898 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
3900 #[stable(feature = "fused", since = "1.26.0")]
3901 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
3904 unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> {
3905 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
3906 let start = i * self.chunk_size;
3907 let end = match start.checked_add(self.chunk_size) {
3908 None => self.v.len(),
3909 Some(end) => cmp::min(end, self.v.len()),
3911 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), end - start)
3913 fn may_have_side_effect() -> bool { false }
3916 /// An iterator over a slice in (non-overlapping) chunks (`chunk_size` elements at a
3919 /// When the slice len is not evenly divided by the chunk size, the last
3920 /// up to `chunk_size-1` elements will be omitted.
3922 /// This struct is created by the [`exact_chunks`] method on [slices].
3924 /// [`exact_chunks`]: ../../std/primitive.slice.html#method.exact_chunks
3925 /// [slices]: ../../std/primitive.slice.html
3927 #[unstable(feature = "exact_chunks", issue = "47115")]
3928 pub struct ExactChunks<'a, T:'a> {
3933 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
3934 #[unstable(feature = "exact_chunks", issue = "47115")]
3935 impl<'a, T> Clone for ExactChunks<'a, T> {
3936 fn clone(&self) -> ExactChunks<'a, T> {
3939 chunk_size: self.chunk_size,
3944 #[unstable(feature = "exact_chunks", issue = "47115")]
3945 impl<'a, T> Iterator for ExactChunks<'a, T> {
3946 type Item = &'a [T];
3949 fn next(&mut self) -> Option<&'a [T]> {
3950 if self.v.len() < self.chunk_size {
3953 let (fst, snd) = self.v.split_at(self.chunk_size);
3960 fn size_hint(&self) -> (usize, Option<usize>) {
3961 let n = self.v.len() / self.chunk_size;
3966 fn count(self) -> usize {
3971 fn nth(&mut self, n: usize) -> Option<Self::Item> {
3972 let (start, overflow) = n.overflowing_mul(self.chunk_size);
3973 if start >= self.v.len() || overflow {
3977 let (_, snd) = self.v.split_at(start);
3984 fn last(mut self) -> Option<Self::Item> {
3989 #[unstable(feature = "exact_chunks", issue = "47115")]
3990 impl<'a, T> DoubleEndedIterator for ExactChunks<'a, T> {
3992 fn next_back(&mut self) -> Option<&'a [T]> {
3993 if self.v.len() < self.chunk_size {
3996 let (fst, snd) = self.v.split_at(self.v.len() - self.chunk_size);
4003 #[unstable(feature = "exact_chunks", issue = "47115")]
4004 impl<'a, T> ExactSizeIterator for ExactChunks<'a, T> {
4005 fn is_empty(&self) -> bool {
4010 #[unstable(feature = "exact_chunks", issue = "47115")]
4011 impl<'a, T> FusedIterator for ExactChunks<'a, T> {}
4014 unsafe impl<'a, T> TrustedRandomAccess for ExactChunks<'a, T> {
4015 unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] {
4016 let start = i * self.chunk_size;
4017 from_raw_parts(self.v.as_ptr().offset(start as isize), self.chunk_size)
4019 fn may_have_side_effect() -> bool { false }
4022 /// An iterator over a slice in (non-overlapping) mutable chunks (`chunk_size`
4023 /// elements at a time). When the slice len is not evenly divided by the chunk
4024 /// size, the last up to `chunk_size-1` elements will be omitted.
4026 /// This struct is created by the [`exact_chunks_mut`] method on [slices].
4028 /// [`exact_chunks_mut`]: ../../std/primitive.slice.html#method.exact_chunks_mut
4029 /// [slices]: ../../std/primitive.slice.html
4031 #[unstable(feature = "exact_chunks", issue = "47115")]
4032 pub struct ExactChunksMut<'a, T:'a> {
4037 #[unstable(feature = "exact_chunks", issue = "47115")]
4038 impl<'a, T> Iterator for ExactChunksMut<'a, T> {
4039 type Item = &'a mut [T];
4042 fn next(&mut self) -> Option<&'a mut [T]> {
4043 if self.v.len() < self.chunk_size {
4046 let tmp = mem::replace(&mut self.v, &mut []);
4047 let (head, tail) = tmp.split_at_mut(self.chunk_size);
4054 fn size_hint(&self) -> (usize, Option<usize>) {
4055 let n = self.v.len() / self.chunk_size;
4060 fn count(self) -> usize {
4065 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
4066 let (start, overflow) = n.overflowing_mul(self.chunk_size);
4067 if start >= self.v.len() || overflow {
4071 let tmp = mem::replace(&mut self.v, &mut []);
4072 let (_, snd) = tmp.split_at_mut(start);
4079 fn last(mut self) -> Option<Self::Item> {
4084 #[unstable(feature = "exact_chunks", issue = "47115")]
4085 impl<'a, T> DoubleEndedIterator for ExactChunksMut<'a, T> {
4087 fn next_back(&mut self) -> Option<&'a mut [T]> {
4088 if self.v.len() < self.chunk_size {
4091 let tmp = mem::replace(&mut self.v, &mut []);
4092 let tmp_len = tmp.len();
4093 let (head, tail) = tmp.split_at_mut(tmp_len - self.chunk_size);
4100 #[unstable(feature = "exact_chunks", issue = "47115")]
4101 impl<'a, T> ExactSizeIterator for ExactChunksMut<'a, T> {
4102 fn is_empty(&self) -> bool {
4107 #[unstable(feature = "exact_chunks", issue = "47115")]
4108 impl<'a, T> FusedIterator for ExactChunksMut<'a, T> {}
4111 unsafe impl<'a, T> TrustedRandomAccess for ExactChunksMut<'a, T> {
4112 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] {
4113 let start = i * self.chunk_size;
4114 from_raw_parts_mut(self.v.as_mut_ptr().offset(start as isize), self.chunk_size)
4116 fn may_have_side_effect() -> bool { false }
4123 /// Forms a slice from a pointer and a length.
4125 /// The `len` argument is the number of **elements**, not the number of bytes.
4129 /// This function is unsafe as there is no guarantee that the given pointer is
4130 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
4131 /// lifetime for the returned slice.
4133 /// `p` must be non-null, even for zero-length slices, because non-zero bits
4134 /// are required to distinguish between a zero-length slice within `Some()`
4135 /// from `None`. `p` can be a bogus non-dereferencable pointer, such as `0x1`,
4136 /// for zero-length slices, though.
4140 /// The lifetime for the returned slice is inferred from its usage. To
4141 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
4142 /// source lifetime is safe in the context, such as by providing a helper
4143 /// function taking the lifetime of a host value for the slice, or by explicit
4151 /// // manifest a slice out of thin air!
4152 /// let ptr = 0x1234 as *const usize;
4155 /// let slice = slice::from_raw_parts(ptr, amt);
4159 #[stable(feature = "rust1", since = "1.0.0")]
4160 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
4161 mem::transmute(Repr { data: p, len: len })
4164 /// Performs the same functionality as `from_raw_parts`, except that a mutable
4165 /// slice is returned.
4167 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
4168 /// as not being able to provide a non-aliasing guarantee of the returned
4169 /// mutable slice. `p` must be non-null even for zero-length slices as with
4170 /// `from_raw_parts`.
4172 #[stable(feature = "rust1", since = "1.0.0")]
4173 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
4174 mem::transmute(Repr { data: p, len: len })
4177 /// Converts a reference to T into a slice of length 1 (without copying).
4178 #[unstable(feature = "from_ref", issue = "45703")]
4179 pub fn from_ref<T>(s: &T) -> &[T] {
4181 from_raw_parts(s, 1)
4185 /// Converts a reference to T into a slice of length 1 (without copying).
4186 #[unstable(feature = "from_ref", issue = "45703")]
4187 pub fn from_ref_mut<T>(s: &mut T) -> &mut [T] {
4189 from_raw_parts_mut(s, 1)
4193 // This function is public only because there is no other way to unit test heapsort.
4194 #[unstable(feature = "sort_internals", reason = "internal to sort module", issue = "0")]
4196 pub fn heapsort<T, F>(v: &mut [T], mut is_less: F)
4197 where F: FnMut(&T, &T) -> bool
4199 sort::heapsort(v, &mut is_less);
4203 // Comparison traits
4207 /// Calls implementation provided memcmp.
4209 /// Interprets the data as u8.
4211 /// Returns 0 for equal, < 0 for less than and > 0 for greater
4213 // FIXME(#32610): Return type should be c_int
4214 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
4217 #[stable(feature = "rust1", since = "1.0.0")]
4218 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
4219 fn eq(&self, other: &[B]) -> bool {
4220 SlicePartialEq::equal(self, other)
4223 fn ne(&self, other: &[B]) -> bool {
4224 SlicePartialEq::not_equal(self, other)
4228 #[stable(feature = "rust1", since = "1.0.0")]
4229 impl<T: Eq> Eq for [T] {}
4231 /// Implements comparison of vectors lexicographically.
4232 #[stable(feature = "rust1", since = "1.0.0")]
4233 impl<T: Ord> Ord for [T] {
4234 fn cmp(&self, other: &[T]) -> Ordering {
4235 SliceOrd::compare(self, other)
4239 /// Implements comparison of vectors lexicographically.
4240 #[stable(feature = "rust1", since = "1.0.0")]
4241 impl<T: PartialOrd> PartialOrd for [T] {
4242 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
4243 SlicePartialOrd::partial_compare(self, other)
4248 // intermediate trait for specialization of slice's PartialEq
4249 trait SlicePartialEq<B> {
4250 fn equal(&self, other: &[B]) -> bool;
4252 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
4255 // Generic slice equality
4256 impl<A, B> SlicePartialEq<B> for [A]
4257 where A: PartialEq<B>
4259 default fn equal(&self, other: &[B]) -> bool {
4260 if self.len() != other.len() {
4264 for i in 0..self.len() {
4265 if !self[i].eq(&other[i]) {
4274 // Use memcmp for bytewise equality when the types allow
4275 impl<A> SlicePartialEq<A> for [A]
4276 where A: PartialEq<A> + BytewiseEquality
4278 fn equal(&self, other: &[A]) -> bool {
4279 if self.len() != other.len() {
4282 if self.as_ptr() == other.as_ptr() {
4286 let size = mem::size_of_val(self);
4287 memcmp(self.as_ptr() as *const u8,
4288 other.as_ptr() as *const u8, size) == 0
4294 // intermediate trait for specialization of slice's PartialOrd
4295 trait SlicePartialOrd<B> {
4296 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
4299 impl<A> SlicePartialOrd<A> for [A]
4302 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4303 let l = cmp::min(self.len(), other.len());
4305 // Slice to the loop iteration range to enable bound check
4306 // elimination in the compiler
4307 let lhs = &self[..l];
4308 let rhs = &other[..l];
4311 match lhs[i].partial_cmp(&rhs[i]) {
4312 Some(Ordering::Equal) => (),
4313 non_eq => return non_eq,
4317 self.len().partial_cmp(&other.len())
4321 impl<A> SlicePartialOrd<A> for [A]
4324 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
4325 Some(SliceOrd::compare(self, other))
4330 // intermediate trait for specialization of slice's Ord
4332 fn compare(&self, other: &[B]) -> Ordering;
4335 impl<A> SliceOrd<A> for [A]
4338 default fn compare(&self, other: &[A]) -> Ordering {
4339 let l = cmp::min(self.len(), other.len());
4341 // Slice to the loop iteration range to enable bound check
4342 // elimination in the compiler
4343 let lhs = &self[..l];
4344 let rhs = &other[..l];
4347 match lhs[i].cmp(&rhs[i]) {
4348 Ordering::Equal => (),
4349 non_eq => return non_eq,
4353 self.len().cmp(&other.len())
4357 // memcmp compares a sequence of unsigned bytes lexicographically.
4358 // this matches the order we want for [u8], but no others (not even [i8]).
4359 impl SliceOrd<u8> for [u8] {
4361 fn compare(&self, other: &[u8]) -> Ordering {
4362 let order = unsafe {
4363 memcmp(self.as_ptr(), other.as_ptr(),
4364 cmp::min(self.len(), other.len()))
4367 self.len().cmp(&other.len())
4368 } else if order < 0 {
4377 /// Trait implemented for types that can be compared for equality using
4378 /// their bytewise representation
4379 trait BytewiseEquality { }
4381 macro_rules! impl_marker_for {
4382 ($traitname:ident, $($ty:ty)*) => {
4384 impl $traitname for $ty { }
4389 impl_marker_for!(BytewiseEquality,
4390 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
4393 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
4394 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
4395 &*self.ptr.offset(i as isize)
4397 fn may_have_side_effect() -> bool { false }
4401 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
4402 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
4403 &mut *self.ptr.offset(i as isize)
4405 fn may_have_side_effect() -> bool { false }
4408 trait SliceContains: Sized {
4409 fn slice_contains(&self, x: &[Self]) -> bool;
4412 impl<T> SliceContains for T where T: PartialEq {
4413 default fn slice_contains(&self, x: &[Self]) -> bool {
4414 x.iter().any(|y| *y == *self)
4418 impl SliceContains for u8 {
4419 fn slice_contains(&self, x: &[Self]) -> bool {
4420 memchr::memchr(*self, x).is_some()
4424 impl SliceContains for i8 {
4425 fn slice_contains(&self, x: &[Self]) -> bool {
4426 let byte = *self as u8;
4427 let bytes: &[u8] = unsafe { from_raw_parts(x.as_ptr() as *const u8, x.len()) };
4428 memchr::memchr(byte, bytes).is_some()