1 // Copyright 2012-2014 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 `std::slice`.
15 #![stable(feature = "rust1", since = "1.0.0")]
17 // How this module is organized.
19 // The library infrastructure for slices is fairly messy. There's
20 // a lot of stuff defined here. Let's keep it clean.
22 // Since slices don't support inherent methods; all operations
23 // on them are defined on traits, which are then reexported from
24 // the prelude for convenience. So there are a lot of traits here.
26 // The layout of this file is thus:
28 // * Slice-specific 'extension' traits and their implementations. This
29 // is where most of the slice API resides.
30 // * Implementations of a few common traits with important slice ops.
31 // * Definitions of a bunch of iterators.
33 // * The `raw` and `bytes` submodules.
34 // * Boilerplate trait implementations.
37 use cmp::Ordering::{self, Less, Equal, Greater};
40 use intrinsics::assume;
42 use ops::{FnMut, self};
44 use option::Option::{None, Some};
46 use result::Result::{Ok, Err};
49 use marker::{Copy, Send, Sync, Sized, self};
50 use iter_private::TrustedRandomAccess;
62 /// Extension methods for slices.
63 #[unstable(feature = "core_slice_ext",
64 reason = "stable interface provided by `impl [T]` in later crates",
66 #[allow(missing_docs)] // documented elsewhere
70 #[stable(feature = "core", since = "1.6.0")]
71 fn split_at(&self, mid: usize) -> (&[Self::Item], &[Self::Item]);
72 #[stable(feature = "core", since = "1.6.0")]
73 fn iter(&self) -> Iter<Self::Item>;
74 #[stable(feature = "core", since = "1.6.0")]
75 fn split<P>(&self, pred: P) -> Split<Self::Item, P>
76 where P: FnMut(&Self::Item) -> bool;
77 #[stable(feature = "core", since = "1.6.0")]
78 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<Self::Item, P>
79 where P: FnMut(&Self::Item) -> bool;
80 #[stable(feature = "core", since = "1.6.0")]
81 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<Self::Item, P>
82 where P: FnMut(&Self::Item) -> bool;
83 #[stable(feature = "core", since = "1.6.0")]
84 fn windows(&self, size: usize) -> Windows<Self::Item>;
85 #[stable(feature = "core", since = "1.6.0")]
86 fn chunks(&self, size: usize) -> Chunks<Self::Item>;
87 #[stable(feature = "core", since = "1.6.0")]
88 fn get<I>(&self, index: I) -> Option<&I::Output>
89 where I: SliceIndex<Self::Item>;
90 #[stable(feature = "core", since = "1.6.0")]
91 fn first(&self) -> Option<&Self::Item>;
92 #[stable(feature = "core", since = "1.6.0")]
93 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
94 #[stable(feature = "core", since = "1.6.0")]
95 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
96 #[stable(feature = "core", since = "1.6.0")]
97 fn last(&self) -> Option<&Self::Item>;
98 #[stable(feature = "core", since = "1.6.0")]
99 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
100 where I: SliceIndex<Self::Item>;
101 #[stable(feature = "core", since = "1.6.0")]
102 fn as_ptr(&self) -> *const Self::Item;
103 #[stable(feature = "core", since = "1.6.0")]
104 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize>
105 where Self::Item: Borrow<Q>,
107 #[stable(feature = "core", since = "1.6.0")]
108 fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
109 where F: FnMut(&'a Self::Item) -> Ordering;
110 #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")]
111 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, f: F) -> Result<usize, usize>
112 where F: FnMut(&'a Self::Item) -> B,
115 #[stable(feature = "core", since = "1.6.0")]
116 fn len(&self) -> usize;
117 #[stable(feature = "core", since = "1.6.0")]
118 fn is_empty(&self) -> bool { self.len() == 0 }
119 #[stable(feature = "core", since = "1.6.0")]
120 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
121 where I: SliceIndex<Self::Item>;
122 #[stable(feature = "core", since = "1.6.0")]
123 fn iter_mut(&mut self) -> IterMut<Self::Item>;
124 #[stable(feature = "core", since = "1.6.0")]
125 fn first_mut(&mut self) -> Option<&mut Self::Item>;
126 #[stable(feature = "core", since = "1.6.0")]
127 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
128 #[stable(feature = "core", since = "1.6.0")]
129 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
130 #[stable(feature = "core", since = "1.6.0")]
131 fn last_mut(&mut self) -> Option<&mut Self::Item>;
132 #[stable(feature = "core", since = "1.6.0")]
133 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
134 where P: FnMut(&Self::Item) -> bool;
135 #[stable(feature = "core", since = "1.6.0")]
136 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
137 where P: FnMut(&Self::Item) -> bool;
138 #[stable(feature = "core", since = "1.6.0")]
139 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
140 where P: FnMut(&Self::Item) -> bool;
141 #[stable(feature = "core", since = "1.6.0")]
142 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
143 #[stable(feature = "core", since = "1.6.0")]
144 fn swap(&mut self, a: usize, b: usize);
145 #[stable(feature = "core", since = "1.6.0")]
146 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
147 #[stable(feature = "core", since = "1.6.0")]
148 fn reverse(&mut self);
149 #[stable(feature = "core", since = "1.6.0")]
150 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
151 where I: SliceIndex<Self::Item>;
152 #[stable(feature = "core", since = "1.6.0")]
153 fn as_mut_ptr(&mut self) -> *mut Self::Item;
155 #[stable(feature = "core", since = "1.6.0")]
156 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
158 #[stable(feature = "core", since = "1.6.0")]
159 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
161 #[stable(feature = "core", since = "1.6.0")]
162 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
164 #[stable(feature = "clone_from_slice", since = "1.7.0")]
165 fn clone_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Clone;
166 #[stable(feature = "copy_from_slice", since = "1.9.0")]
167 fn copy_from_slice(&mut self, src: &[Self::Item]) where Self::Item: Copy;
170 // Use macros to be generic over const/mut
171 macro_rules! slice_offset {
172 ($ptr:expr, $by:expr) => {{
174 if size_from_ptr(ptr) == 0 {
175 (ptr as *mut i8).wrapping_offset($by) as _
182 // make a &T from a *const T
183 macro_rules! make_ref {
186 if size_from_ptr(ptr) == 0 {
187 // Use a non-null pointer value
195 // make a &mut T from a *mut T
196 macro_rules! make_ref_mut {
199 if size_from_ptr(ptr) == 0 {
200 // Use a non-null pointer value
208 #[unstable(feature = "core_slice_ext",
209 reason = "stable interface provided by `impl [T]` in later crates",
211 impl<T> SliceExt for [T] {
215 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
216 (&self[..mid], &self[mid..])
220 fn iter(&self) -> Iter<T> {
222 let p = if mem::size_of::<T>() == 0 {
225 let p = self.as_ptr();
226 assume(!p.is_null());
232 end: slice_offset!(p, self.len() as isize),
233 _marker: marker::PhantomData
239 fn split<P>(&self, pred: P) -> Split<T, P> where P: FnMut(&T) -> bool {
248 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P> where
249 P: FnMut(&T) -> bool,
252 inner: GenericSplitN {
253 iter: self.split(pred),
261 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P> where
262 P: FnMut(&T) -> bool,
265 inner: GenericSplitN {
266 iter: self.split(pred),
274 fn windows(&self, size: usize) -> Windows<T> {
276 Windows { v: self, size: size }
280 fn chunks(&self, size: usize) -> Chunks<T> {
282 Chunks { v: self, size: size }
286 fn get<I>(&self, index: I) -> Option<&I::Output>
287 where I: SliceIndex<T>
293 fn first(&self) -> Option<&T> {
294 if self.is_empty() { None } else { Some(&self[0]) }
298 fn split_first(&self) -> Option<(&T, &[T])> {
299 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
303 fn split_last(&self) -> Option<(&T, &[T])> {
304 let len = self.len();
305 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
309 fn last(&self) -> Option<&T> {
310 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
314 unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
315 where I: SliceIndex<T>
317 index.get_unchecked(self)
321 fn as_ptr(&self) -> *const T {
322 self as *const [T] as *const T
325 fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
326 where F: FnMut(&'a T) -> Ordering
328 let mut base = 0usize;
332 let (head, tail) = s.split_at(s.len() >> 1);
338 base += head.len() + 1;
342 Equal => return Ok(base + head.len()),
348 fn len(&self) -> usize {
350 mem::transmute::<&[T], Repr<T>>(self).len
355 fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
356 where I: SliceIndex<T>
362 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
363 let len = self.len();
364 let ptr = self.as_mut_ptr();
369 (from_raw_parts_mut(ptr, mid),
370 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
375 fn iter_mut(&mut self) -> IterMut<T> {
377 let p = if mem::size_of::<T>() == 0 {
380 let p = self.as_mut_ptr();
381 assume(!p.is_null());
387 end: slice_offset!(p, self.len() as isize),
388 _marker: marker::PhantomData
394 fn last_mut(&mut self) -> Option<&mut T> {
395 let len = self.len();
396 if len == 0 { return None; }
397 Some(&mut self[len - 1])
401 fn first_mut(&mut self) -> Option<&mut T> {
402 if self.is_empty() { None } else { Some(&mut self[0]) }
406 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
407 if self.is_empty() { None } else {
408 let split = self.split_at_mut(1);
409 Some((&mut split.0[0], split.1))
414 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
415 let len = self.len();
416 if len == 0 { None } else {
417 let split = self.split_at_mut(len - 1);
418 Some((&mut split.1[0], split.0))
423 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P> where P: FnMut(&T) -> bool {
424 SplitMut { v: self, pred: pred, finished: false }
428 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P> where
432 inner: GenericSplitN {
433 iter: self.split_mut(pred),
441 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
442 P: FnMut(&T) -> bool,
445 inner: GenericSplitN {
446 iter: self.split_mut(pred),
454 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
455 assert!(chunk_size > 0);
456 ChunksMut { v: self, chunk_size: chunk_size }
460 fn swap(&mut self, a: usize, b: usize) {
462 // Can't take two mutable loans from one vector, so instead just cast
463 // them to their raw pointers to do the swap
464 let pa: *mut T = &mut self[a];
465 let pb: *mut T = &mut self[b];
470 fn reverse(&mut self) {
471 let mut i: usize = 0;
474 // Unsafe swap to avoid the bounds check in safe swap.
476 let pa: *mut T = self.get_unchecked_mut(i);
477 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
485 unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
486 where I: SliceIndex<T>
488 index.get_unchecked_mut(self)
492 fn as_mut_ptr(&mut self) -> *mut T {
493 self as *mut [T] as *mut T
497 fn contains(&self, x: &T) -> bool where T: PartialEq {
498 self.iter().any(|elt| *x == *elt)
502 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
503 let n = needle.len();
504 self.len() >= n && needle == &self[..n]
508 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
509 let (m, n) = (self.len(), needle.len());
510 m >= n && needle == &self[m-n..]
513 fn binary_search<Q: ?Sized>(&self, x: &Q) -> Result<usize, usize> where T: Borrow<Q>, Q: Ord {
514 self.binary_search_by(|p| p.borrow().cmp(x))
518 fn clone_from_slice(&mut self, src: &[T]) where T: Clone {
519 assert!(self.len() == src.len(),
520 "destination and source slices have different lengths");
521 // NOTE: We need to explicitly slice them to the same length
522 // for bounds checking to be elided, and the optimizer will
523 // generate memcpy for simple cases (for example T = u8).
524 let len = self.len();
525 let src = &src[..len];
527 self[i].clone_from(&src[i]);
532 fn copy_from_slice(&mut self, src: &[T]) where T: Copy {
533 assert!(self.len() == src.len(),
534 "destination and source slices have different lengths");
536 ptr::copy_nonoverlapping(
537 src.as_ptr(), self.as_mut_ptr(), self.len());
542 fn binary_search_by_key<'a, B, F, Q: ?Sized>(&'a self, b: &Q, mut f: F) -> Result<usize, usize>
543 where F: FnMut(&'a Self::Item) -> B,
547 self.binary_search_by(|k| f(k).borrow().cmp(b))
551 #[stable(feature = "rust1", since = "1.0.0")]
552 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
553 impl<T, I> ops::Index<I> for [T]
554 where I: SliceIndex<T>
556 type Output = I::Output;
559 fn index(&self, index: I) -> &I::Output {
564 #[stable(feature = "rust1", since = "1.0.0")]
565 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
566 impl<T, I> ops::IndexMut<I> for [T]
567 where I: SliceIndex<T>
570 fn index_mut(&mut self, index: I) -> &mut I::Output {
571 index.index_mut(self)
577 fn slice_index_len_fail(index: usize, len: usize) -> ! {
578 panic!("index {} out of range for slice of length {}", index, len);
583 fn slice_index_order_fail(index: usize, end: usize) -> ! {
584 panic!("slice index starts at {} but ends at {}", index, end);
587 /// A helper trait used for indexing operations.
588 #[unstable(feature = "slice_get_slice", issue = "35729")]
589 #[rustc_on_unimplemented = "slice indices are of type `usize` or ranges of `usize`"]
590 pub trait SliceIndex<T> {
591 /// The output type returned by methods.
594 /// Returns a shared reference to the output at this location, if in
596 fn get(self, slice: &[T]) -> Option<&Self::Output>;
598 /// Returns a mutable reference to the output at this location, if in
600 fn get_mut(self, slice: &mut [T]) -> Option<&mut Self::Output>;
602 /// Returns a shared reference to the output at this location, without
603 /// performing any bounds checking.
604 unsafe fn get_unchecked(self, slice: &[T]) -> &Self::Output;
606 /// Returns a mutable reference to the output at this location, without
607 /// performing any bounds checking.
608 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut Self::Output;
610 /// Returns a shared reference to the output at this location, panicking
611 /// if out of bounds.
612 fn index(self, slice: &[T]) -> &Self::Output;
614 /// Returns a mutable reference to the output at this location, panicking
615 /// if out of bounds.
616 fn index_mut(self, slice: &mut [T]) -> &mut Self::Output;
619 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
620 impl<T> SliceIndex<T> for usize {
624 fn get(self, slice: &[T]) -> Option<&T> {
625 if self < slice.len() {
627 Some(self.get_unchecked(slice))
635 fn get_mut(self, slice: &mut [T]) -> Option<&mut T> {
636 if self < slice.len() {
638 Some(self.get_unchecked_mut(slice))
646 unsafe fn get_unchecked(self, slice: &[T]) -> &T {
647 &*slice.as_ptr().offset(self as isize)
651 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T {
652 &mut *slice.as_mut_ptr().offset(self as isize)
656 fn index(self, slice: &[T]) -> &T {
657 // NB: use intrinsic indexing
662 fn index_mut(self, slice: &mut [T]) -> &mut T {
663 // NB: use intrinsic indexing
668 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
669 impl<T> SliceIndex<T> for ops::Range<usize> {
673 fn get(self, slice: &[T]) -> Option<&[T]> {
674 if self.start > self.end || self.end > slice.len() {
678 Some(self.get_unchecked(slice))
684 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
685 if self.start > self.end || self.end > slice.len() {
689 Some(self.get_unchecked_mut(slice))
695 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
696 from_raw_parts(slice.as_ptr().offset(self.start as isize), self.end - self.start)
700 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
701 from_raw_parts_mut(slice.as_mut_ptr().offset(self.start as isize), self.end - self.start)
705 fn index(self, slice: &[T]) -> &[T] {
706 if self.start > self.end {
707 slice_index_order_fail(self.start, self.end);
708 } else if self.end > slice.len() {
709 slice_index_len_fail(self.end, slice.len());
712 self.get_unchecked(slice)
717 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
718 if self.start > self.end {
719 slice_index_order_fail(self.start, self.end);
720 } else if self.end > slice.len() {
721 slice_index_len_fail(self.end, slice.len());
724 self.get_unchecked_mut(slice)
729 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
730 impl<T> SliceIndex<T> for ops::RangeTo<usize> {
734 fn get(self, slice: &[T]) -> Option<&[T]> {
735 (0..self.end).get(slice)
739 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
740 (0..self.end).get_mut(slice)
744 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
745 (0..self.end).get_unchecked(slice)
749 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
750 (0..self.end).get_unchecked_mut(slice)
754 fn index(self, slice: &[T]) -> &[T] {
755 (0..self.end).index(slice)
759 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
760 (0..self.end).index_mut(slice)
764 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
765 impl<T> SliceIndex<T> for ops::RangeFrom<usize> {
769 fn get(self, slice: &[T]) -> Option<&[T]> {
770 (self.start..slice.len()).get(slice)
774 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
775 (self.start..slice.len()).get_mut(slice)
779 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
780 (self.start..slice.len()).get_unchecked(slice)
784 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
785 (self.start..slice.len()).get_unchecked_mut(slice)
789 fn index(self, slice: &[T]) -> &[T] {
790 (self.start..slice.len()).index(slice)
794 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
795 (self.start..slice.len()).index_mut(slice)
799 #[stable(feature = "slice-get-slice-impls", since = "1.15.0")]
800 impl<T> SliceIndex<T> for ops::RangeFull {
804 fn get(self, slice: &[T]) -> Option<&[T]> {
809 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
814 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
819 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
824 fn index(self, slice: &[T]) -> &[T] {
829 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
835 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
836 impl<T> SliceIndex<T> for ops::RangeInclusive<usize> {
840 fn get(self, slice: &[T]) -> Option<&[T]> {
842 ops::RangeInclusive::Empty { .. } => Some(&[]),
843 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => None,
844 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get(slice),
849 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
851 ops::RangeInclusive::Empty { .. } => Some(&mut []),
852 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => None,
853 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get_mut(slice),
858 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
860 ops::RangeInclusive::Empty { .. } => &[],
861 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).get_unchecked(slice),
866 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
868 ops::RangeInclusive::Empty { .. } => &mut [],
869 ops::RangeInclusive::NonEmpty { start, end } => {
870 (start..end + 1).get_unchecked_mut(slice)
876 fn index(self, slice: &[T]) -> &[T] {
878 ops::RangeInclusive::Empty { .. } => &[],
879 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => {
880 panic!("attempted to index slice up to maximum usize");
882 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).index(slice),
887 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
889 ops::RangeInclusive::Empty { .. } => &mut [],
890 ops::RangeInclusive::NonEmpty { end, .. } if end == usize::max_value() => {
891 panic!("attempted to index slice up to maximum usize");
893 ops::RangeInclusive::NonEmpty { start, end } => (start..end + 1).index_mut(slice),
898 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
899 impl<T> SliceIndex<T> for ops::RangeToInclusive<usize> {
903 fn get(self, slice: &[T]) -> Option<&[T]> {
904 (0...self.end).get(slice)
908 fn get_mut(self, slice: &mut [T]) -> Option<&mut [T]> {
909 (0...self.end).get_mut(slice)
913 unsafe fn get_unchecked(self, slice: &[T]) -> &[T] {
914 (0...self.end).get_unchecked(slice)
918 unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] {
919 (0...self.end).get_unchecked_mut(slice)
923 fn index(self, slice: &[T]) -> &[T] {
924 (0...self.end).index(slice)
928 fn index_mut(self, slice: &mut [T]) -> &mut [T] {
929 (0...self.end).index_mut(slice)
933 ////////////////////////////////////////////////////////////////////////////////
935 ////////////////////////////////////////////////////////////////////////////////
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<'a, T> Default for &'a [T] {
939 /// Creates an empty slice.
940 fn default() -> &'a [T] { &[] }
943 #[stable(feature = "mut_slice_default", since = "1.5.0")]
944 impl<'a, T> Default for &'a mut [T] {
945 /// Creates a mutable empty slice.
946 fn default() -> &'a mut [T] { &mut [] }
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<'a, T> IntoIterator for &'a [T] {
956 type IntoIter = Iter<'a, T>;
958 fn into_iter(self) -> Iter<'a, T> {
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<'a, T> IntoIterator for &'a mut [T] {
965 type Item = &'a mut T;
966 type IntoIter = IterMut<'a, T>;
968 fn into_iter(self) -> IterMut<'a, T> {
974 fn size_from_ptr<T>(_: *const T) -> usize {
978 // The shared definition of the `Iter` and `IterMut` iterators
979 macro_rules! iterator {
980 (struct $name:ident -> $ptr:ty, $elem:ty, $mkref:ident) => {
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl<'a, T> Iterator for $name<'a, T> {
986 fn next(&mut self) -> Option<$elem> {
987 // could be implemented with slices, but this avoids bounds checks
989 if mem::size_of::<T>() != 0 {
990 assume(!self.ptr.is_null());
991 assume(!self.end.is_null());
993 if self.ptr == self.end {
996 Some($mkref!(self.ptr.post_inc()))
1002 fn size_hint(&self) -> (usize, Option<usize>) {
1003 let exact = ptrdistance(self.ptr, self.end);
1004 (exact, Some(exact))
1008 fn count(self) -> usize {
1013 fn nth(&mut self, n: usize) -> Option<$elem> {
1014 // Call helper method. Can't put the definition here because mut versus const.
1019 fn last(mut self) -> Option<$elem> {
1023 fn all<F>(&mut self, mut predicate: F) -> bool
1024 where F: FnMut(Self::Item) -> bool,
1026 self.search_while(true, move |elt| {
1028 SearchWhile::Continue
1030 SearchWhile::Done(false)
1035 fn any<F>(&mut self, mut predicate: F) -> bool
1036 where F: FnMut(Self::Item) -> bool,
1038 !self.all(move |elt| !predicate(elt))
1041 fn find<F>(&mut self, mut predicate: F) -> Option<Self::Item>
1042 where F: FnMut(&Self::Item) -> bool,
1044 self.search_while(None, move |elt| {
1045 if predicate(&elt) {
1046 SearchWhile::Done(Some(elt))
1048 SearchWhile::Continue
1053 fn position<F>(&mut self, mut predicate: F) -> Option<usize>
1054 where F: FnMut(Self::Item) -> bool,
1057 self.search_while(None, move |elt| {
1059 SearchWhile::Done(Some(index))
1062 SearchWhile::Continue
1067 fn rposition<F>(&mut self, mut predicate: F) -> Option<usize>
1068 where F: FnMut(Self::Item) -> bool,
1070 let mut index = self.len();
1071 self.rsearch_while(None, move |elt| {
1074 SearchWhile::Done(Some(index))
1076 SearchWhile::Continue
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
1085 fn next_back(&mut self) -> Option<$elem> {
1086 // could be implemented with slices, but this avoids bounds checks
1088 if mem::size_of::<T>() != 0 {
1089 assume(!self.ptr.is_null());
1090 assume(!self.end.is_null());
1092 if self.end == self.ptr {
1095 Some($mkref!(self.end.pre_dec()))
1101 // search_while is a generalization of the internal iteration methods.
1102 impl<'a, T> $name<'a, T> {
1103 // search through the iterator's element using the closure `g`.
1104 // if no element was found, return `default`.
1105 fn search_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1107 G: FnMut($elem) -> SearchWhile<Acc>
1109 // manual unrolling is needed when there are conditional exits from the loop
1111 while ptrdistance(self.ptr, self.end) >= 4 {
1112 search_while!(g($mkref!(self.ptr.post_inc())));
1113 search_while!(g($mkref!(self.ptr.post_inc())));
1114 search_while!(g($mkref!(self.ptr.post_inc())));
1115 search_while!(g($mkref!(self.ptr.post_inc())));
1117 while self.ptr != self.end {
1118 search_while!(g($mkref!(self.ptr.post_inc())));
1124 fn rsearch_while<Acc, G>(&mut self, default: Acc, mut g: G) -> Acc
1126 G: FnMut($elem) -> SearchWhile<Acc>
1129 while ptrdistance(self.ptr, self.end) >= 4 {
1130 search_while!(g($mkref!(self.end.pre_dec())));
1131 search_while!(g($mkref!(self.end.pre_dec())));
1132 search_while!(g($mkref!(self.end.pre_dec())));
1133 search_while!(g($mkref!(self.end.pre_dec())));
1135 while self.ptr != self.end {
1136 search_while!(g($mkref!(self.end.pre_dec())));
1145 macro_rules! make_slice {
1146 ($start: expr, $end: expr) => {{
1148 let diff = ($end as usize).wrapping_sub(start as usize);
1149 if size_from_ptr(start) == 0 {
1150 // use a non-null pointer value
1151 unsafe { from_raw_parts(1 as *const _, diff) }
1153 let len = diff / size_from_ptr(start);
1154 unsafe { from_raw_parts(start, len) }
1159 macro_rules! make_mut_slice {
1160 ($start: expr, $end: expr) => {{
1162 let diff = ($end as usize).wrapping_sub(start as usize);
1163 if size_from_ptr(start) == 0 {
1164 // use a non-null pointer value
1165 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
1167 let len = diff / size_from_ptr(start);
1168 unsafe { from_raw_parts_mut(start, len) }
1173 // An enum used for controlling the execution of `.search_while()`.
1174 enum SearchWhile<T> {
1175 // Continue searching
1177 // Fold is complete and will return this value
1181 // helper macro for search while's control flow
1182 macro_rules! search_while {
1185 SearchWhile::Continue => { }
1186 SearchWhile::Done(done) => return done,
1191 /// Immutable slice iterator
1193 /// This struct is created by the [`iter`] method on [slices].
1200 /// // First, we declare a type which has `iter` method to get the `Iter` struct (&[usize here]):
1201 /// let slice = &[1, 2, 3];
1203 /// // Then, we iterate over it:
1204 /// for element in slice.iter() {
1205 /// println!("{}", element);
1209 /// [`iter`]: ../../std/primitive.slice.html#method.iter
1210 /// [slices]: ../../std/primitive.slice.html
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 pub struct Iter<'a, T: 'a> {
1215 _marker: marker::PhantomData<&'a T>,
1218 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1219 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
1220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1221 f.debug_tuple("Iter")
1222 .field(&self.as_slice())
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1232 impl<'a, T> Iter<'a, T> {
1233 /// View the underlying data as a subslice of the original data.
1235 /// This has the same lifetime as the original slice, and so the
1236 /// iterator can continue to be used while this exists.
1243 /// // First, we declare a type which has the `iter` method to get the `Iter`
1244 /// // struct (&[usize here]):
1245 /// let slice = &[1, 2, 3];
1247 /// // Then, we get the iterator:
1248 /// let mut iter = slice.iter();
1249 /// // So if we print what `as_slice` method returns here, we have "[1, 2, 3]":
1250 /// println!("{:?}", iter.as_slice());
1252 /// // Next, we move to the second element of the slice:
1254 /// // Now `as_slice` returns "[2, 3]":
1255 /// println!("{:?}", iter.as_slice());
1257 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1258 pub fn as_slice(&self) -> &'a [T] {
1259 make_slice!(self.ptr, self.end)
1262 // Helper function for Iter::nth
1263 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
1264 match self.as_slice().get(n) {
1265 Some(elem_ref) => unsafe {
1266 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1270 self.ptr = self.end;
1277 iterator!{struct Iter -> *const T, &'a T, make_ref}
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<'a, T> ExactSizeIterator for Iter<'a, T> {
1281 fn is_empty(&self) -> bool {
1282 self.ptr == self.end
1286 #[unstable(feature = "fused", issue = "35602")]
1287 impl<'a, T> FusedIterator for Iter<'a, T> {}
1289 #[unstable(feature = "trusted_len", issue = "37572")]
1290 unsafe impl<'a, T> TrustedLen for Iter<'a, T> {}
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<'a, T> Clone for Iter<'a, T> {
1294 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
1297 #[stable(feature = "slice_iter_as_ref", since = "1.12.0")]
1298 impl<'a, T> AsRef<[T]> for Iter<'a, T> {
1299 fn as_ref(&self) -> &[T] {
1304 /// Mutable slice iterator.
1306 /// This struct is created by the [`iter_mut`] method on [slices].
1313 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1314 /// // struct (&[usize here]):
1315 /// let mut slice = &mut [1, 2, 3];
1317 /// // Then, we iterate over it and increment each element value:
1318 /// for element in slice.iter_mut() {
1322 /// // We now have "[2, 3, 4]":
1323 /// println!("{:?}", slice);
1326 /// [`iter_mut`]: ../../std/primitive.slice.html#method.iter_mut
1327 /// [slices]: ../../std/primitive.slice.html
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 pub struct IterMut<'a, T: 'a> {
1332 _marker: marker::PhantomData<&'a mut T>,
1335 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1336 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
1337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1338 f.debug_tuple("IterMut")
1339 .field(&make_slice!(self.ptr, self.end))
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1349 impl<'a, T> IterMut<'a, T> {
1350 /// View the underlying data as a subslice of the original data.
1352 /// To avoid creating `&mut` references that alias, this is forced
1353 /// to consume the iterator. Consider using the `Slice` and
1354 /// `SliceMut` implementations for obtaining slices with more
1355 /// restricted lifetimes that do not consume the iterator.
1362 /// // First, we declare a type which has `iter_mut` method to get the `IterMut`
1363 /// // struct (&[usize here]):
1364 /// let mut slice = &mut [1, 2, 3];
1367 /// // Then, we get the iterator:
1368 /// let mut iter = slice.iter_mut();
1369 /// // We move to next element:
1371 /// // So if we print what `into_slice` method returns here, we have "[2, 3]":
1372 /// println!("{:?}", iter.into_slice());
1375 /// // Now let's modify a value of the slice:
1377 /// // First we get back the iterator:
1378 /// let mut iter = slice.iter_mut();
1379 /// // We change the value of the first element of the slice returned by the `next` method:
1380 /// *iter.next().unwrap() += 1;
1382 /// // Now slice is "[2, 2, 3]":
1383 /// println!("{:?}", slice);
1385 #[stable(feature = "iter_to_slice", since = "1.4.0")]
1386 pub fn into_slice(self) -> &'a mut [T] {
1387 make_mut_slice!(self.ptr, self.end)
1390 // Helper function for IterMut::nth
1391 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
1392 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
1393 Some(elem_ref) => unsafe {
1394 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
1398 self.ptr = self.end;
1405 iterator!{struct IterMut -> *mut T, &'a mut T, make_ref_mut}
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {
1409 fn is_empty(&self) -> bool {
1410 self.ptr == self.end
1414 #[unstable(feature = "fused", issue = "35602")]
1415 impl<'a, T> FusedIterator for IterMut<'a, T> {}
1417 #[unstable(feature = "trusted_len", issue = "37572")]
1418 unsafe impl<'a, T> TrustedLen for IterMut<'a, T> {}
1421 // Return the number of elements of `T` from `start` to `end`.
1422 // Return the arithmetic difference if `T` is zero size.
1424 fn ptrdistance<T>(start: *const T, end: *const T) -> usize {
1425 let diff = (end as usize).wrapping_sub(start as usize);
1426 let size = mem::size_of::<T>();
1427 diff / (if size == 0 { 1 } else { size })
1430 // Extension methods for raw pointers, used by the iterators
1431 trait PointerExt : Copy {
1432 unsafe fn slice_offset(self, i: isize) -> Self;
1434 /// Increment self by 1, but return the old value
1436 unsafe fn post_inc(&mut self) -> Self {
1437 let current = *self;
1438 *self = self.slice_offset(1);
1442 /// Decrement self by 1, and return the new value
1444 unsafe fn pre_dec(&mut self) -> Self {
1445 *self = self.slice_offset(-1);
1450 impl<T> PointerExt for *const T {
1452 unsafe fn slice_offset(self, i: isize) -> Self {
1453 slice_offset!(self, i)
1457 impl<T> PointerExt for *mut T {
1459 unsafe fn slice_offset(self, i: isize) -> Self {
1460 slice_offset!(self, i)
1464 /// An internal abstraction over the splitting iterators, so that
1465 /// splitn, splitn_mut etc can be implemented once.
1467 trait SplitIter: DoubleEndedIterator {
1468 /// Mark the underlying iterator as complete, extracting the remaining
1469 /// portion of the slice.
1470 fn finish(&mut self) -> Option<Self::Item>;
1473 /// An iterator over subslices separated by elements that match a predicate
1476 /// This struct is created by the [`split`] method on [slices].
1478 /// [`split`]: ../../std/primitive.slice.html#method.split
1479 /// [slices]: ../../std/primitive.slice.html
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
1487 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1488 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for Split<'a, T, P> where P: FnMut(&T) -> bool {
1489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1490 f.debug_struct("Split")
1491 .field("v", &self.v)
1492 .field("finished", &self.finished)
1497 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
1500 fn clone(&self) -> Split<'a, T, P> {
1503 pred: self.pred.clone(),
1504 finished: self.finished,
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1511 type Item = &'a [T];
1514 fn next(&mut self) -> Option<&'a [T]> {
1515 if self.finished { return None; }
1517 match self.v.iter().position(|x| (self.pred)(x)) {
1518 None => self.finish(),
1520 let ret = Some(&self.v[..idx]);
1521 self.v = &self.v[idx + 1..];
1528 fn size_hint(&self) -> (usize, Option<usize>) {
1532 (1, Some(self.v.len() + 1))
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
1540 fn next_back(&mut self) -> Option<&'a [T]> {
1541 if self.finished { return None; }
1543 match self.v.iter().rposition(|x| (self.pred)(x)) {
1544 None => self.finish(),
1546 let ret = Some(&self.v[idx + 1..]);
1547 self.v = &self.v[..idx];
1554 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1556 fn finish(&mut self) -> Option<&'a [T]> {
1557 if self.finished { None } else { self.finished = true; Some(self.v) }
1561 #[unstable(feature = "fused", issue = "35602")]
1562 impl<'a, T, P> FusedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {}
1564 /// An iterator over the subslices of the vector which are separated
1565 /// by elements that match `pred`.
1567 /// This struct is created by the [`split_mut`] method on [slices].
1569 /// [`split_mut`]: ../../std/primitive.slice.html#method.split_mut
1570 /// [slices]: ../../std/primitive.slice.html
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1578 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1579 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1580 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1581 f.debug_struct("SplitMut")
1582 .field("v", &self.v)
1583 .field("finished", &self.finished)
1588 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1590 fn finish(&mut self) -> Option<&'a mut [T]> {
1594 self.finished = true;
1595 Some(mem::replace(&mut self.v, &mut []))
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1602 type Item = &'a mut [T];
1605 fn next(&mut self) -> Option<&'a mut [T]> {
1606 if self.finished { return None; }
1608 let idx_opt = { // work around borrowck limitations
1609 let pred = &mut self.pred;
1610 self.v.iter().position(|x| (*pred)(x))
1613 None => self.finish(),
1615 let tmp = mem::replace(&mut self.v, &mut []);
1616 let (head, tail) = tmp.split_at_mut(idx);
1617 self.v = &mut tail[1..];
1624 fn size_hint(&self) -> (usize, Option<usize>) {
1628 // if the predicate doesn't match anything, we yield one slice
1629 // if it matches every element, we yield len+1 empty slices.
1630 (1, Some(self.v.len() + 1))
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1637 P: FnMut(&T) -> bool,
1640 fn next_back(&mut self) -> Option<&'a mut [T]> {
1641 if self.finished { return None; }
1643 let idx_opt = { // work around borrowck limitations
1644 let pred = &mut self.pred;
1645 self.v.iter().rposition(|x| (*pred)(x))
1648 None => self.finish(),
1650 let tmp = mem::replace(&mut self.v, &mut []);
1651 let (head, tail) = tmp.split_at_mut(idx);
1653 Some(&mut tail[1..])
1659 #[unstable(feature = "fused", issue = "35602")]
1660 impl<'a, T, P> FusedIterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {}
1662 /// An private iterator over subslices separated by elements that
1663 /// match a predicate function, splitting at most a fixed number of
1666 struct GenericSplitN<I> {
1672 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1676 fn next(&mut self) -> Option<T> {
1679 1 => { self.count -= 1; self.iter.finish() }
1682 if self.invert {self.iter.next_back()} else {self.iter.next()}
1688 fn size_hint(&self) -> (usize, Option<usize>) {
1689 let (lower, upper_opt) = self.iter.size_hint();
1690 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1694 /// An iterator over subslices separated by elements that match a predicate
1695 /// function, limited to a given number of splits.
1697 /// This struct is created by the [`splitn`] method on [slices].
1699 /// [`splitn`]: ../../std/primitive.slice.html#method.splitn
1700 /// [slices]: ../../std/primitive.slice.html
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1703 inner: GenericSplitN<Split<'a, T, P>>
1706 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1707 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitN<'a, T, P> where P: FnMut(&T) -> bool {
1708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1709 f.debug_struct("SplitN")
1710 .field("inner", &self.inner)
1715 /// An iterator over subslices separated by elements that match a
1716 /// predicate function, limited to a given number of splits, starting
1717 /// from the end of the slice.
1719 /// This struct is created by the [`rsplitn`] method on [slices].
1721 /// [`rsplitn`]: ../../std/primitive.slice.html#method.rsplitn
1722 /// [slices]: ../../std/primitive.slice.html
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1725 inner: GenericSplitN<Split<'a, T, P>>
1728 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1729 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitN<'a, T, P> where P: FnMut(&T) -> bool {
1730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1731 f.debug_struct("RSplitN")
1732 .field("inner", &self.inner)
1737 /// An iterator over subslices separated by elements that match a predicate
1738 /// function, limited to a given number of splits.
1740 /// This struct is created by the [`splitn_mut`] method on [slices].
1742 /// [`splitn_mut`]: ../../std/primitive.slice.html#method.splitn_mut
1743 /// [slices]: ../../std/primitive.slice.html
1744 #[stable(feature = "rust1", since = "1.0.0")]
1745 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1746 inner: GenericSplitN<SplitMut<'a, T, P>>
1749 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1750 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for SplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1752 f.debug_struct("SplitNMut")
1753 .field("inner", &self.inner)
1758 /// An iterator over subslices separated by elements that match a
1759 /// predicate function, limited to a given number of splits, starting
1760 /// from the end of the slice.
1762 /// This struct is created by the [`rsplitn_mut`] method on [slices].
1764 /// [`rsplitn_mut`]: ../../std/primitive.slice.html#method.rsplitn_mut
1765 /// [slices]: ../../std/primitive.slice.html
1766 #[stable(feature = "rust1", since = "1.0.0")]
1767 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1768 inner: GenericSplitN<SplitMut<'a, T, P>>
1771 #[stable(feature = "core_impl_debug", since = "1.9.0")]
1772 impl<'a, T: 'a + fmt::Debug, P> fmt::Debug for RSplitNMut<'a, T, P> where P: FnMut(&T) -> bool {
1773 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1774 f.debug_struct("RSplitNMut")
1775 .field("inner", &self.inner)
1780 macro_rules! forward_iterator {
1781 ($name:ident: $elem:ident, $iter_of:ty) => {
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1784 P: FnMut(&T) -> bool
1786 type Item = $iter_of;
1789 fn next(&mut self) -> Option<$iter_of> {
1794 fn size_hint(&self) -> (usize, Option<usize>) {
1795 self.inner.size_hint()
1799 #[unstable(feature = "fused", issue = "35602")]
1800 impl<'a, $elem, P> FusedIterator for $name<'a, $elem, P>
1801 where P: FnMut(&T) -> bool {}
1805 forward_iterator! { SplitN: T, &'a [T] }
1806 forward_iterator! { RSplitN: T, &'a [T] }
1807 forward_iterator! { SplitNMut: T, &'a mut [T] }
1808 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1810 /// An iterator over overlapping subslices of length `size`.
1812 /// This struct is created by the [`windows`] method on [slices].
1814 /// [`windows`]: ../../std/primitive.slice.html#method.windows
1815 /// [slices]: ../../std/primitive.slice.html
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 pub struct Windows<'a, T:'a> {
1823 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 impl<'a, T> Clone for Windows<'a, T> {
1826 fn clone(&self) -> Windows<'a, T> {
1834 #[stable(feature = "rust1", since = "1.0.0")]
1835 impl<'a, T> Iterator for Windows<'a, T> {
1836 type Item = &'a [T];
1839 fn next(&mut self) -> Option<&'a [T]> {
1840 if self.size > self.v.len() {
1843 let ret = Some(&self.v[..self.size]);
1844 self.v = &self.v[1..];
1850 fn size_hint(&self) -> (usize, Option<usize>) {
1851 if self.size > self.v.len() {
1854 let size = self.v.len() - self.size + 1;
1860 fn count(self) -> usize {
1865 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1866 let (end, overflow) = self.size.overflowing_add(n);
1867 if end > self.v.len() || overflow {
1871 let nth = &self.v[n..end];
1872 self.v = &self.v[n+1..];
1878 fn last(self) -> Option<Self::Item> {
1879 if self.size > self.v.len() {
1882 let start = self.v.len() - self.size;
1883 Some(&self.v[start..])
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1891 fn next_back(&mut self) -> Option<&'a [T]> {
1892 if self.size > self.v.len() {
1895 let ret = Some(&self.v[self.v.len()-self.size..]);
1896 self.v = &self.v[..self.v.len()-1];
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1905 #[unstable(feature = "fused", issue = "35602")]
1906 impl<'a, T> FusedIterator for Windows<'a, T> {}
1908 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1911 /// When the slice len is not evenly divided by the chunk size, the last slice
1912 /// of the iteration will be the remainder.
1914 /// This struct is created by the [`chunks`] method on [slices].
1916 /// [`chunks`]: ../../std/primitive.slice.html#method.chunks
1917 /// [slices]: ../../std/primitive.slice.html
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 pub struct Chunks<'a, T:'a> {
1925 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<'a, T> Clone for Chunks<'a, T> {
1928 fn clone(&self) -> Chunks<'a, T> {
1936 #[stable(feature = "rust1", since = "1.0.0")]
1937 impl<'a, T> Iterator for Chunks<'a, T> {
1938 type Item = &'a [T];
1941 fn next(&mut self) -> Option<&'a [T]> {
1942 if self.v.is_empty() {
1945 let chunksz = cmp::min(self.v.len(), self.size);
1946 let (fst, snd) = self.v.split_at(chunksz);
1953 fn size_hint(&self) -> (usize, Option<usize>) {
1954 if self.v.is_empty() {
1957 let n = self.v.len() / self.size;
1958 let rem = self.v.len() % self.size;
1959 let n = if rem > 0 { n+1 } else { n };
1965 fn count(self) -> usize {
1970 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1971 let (start, overflow) = n.overflowing_mul(self.size);
1972 if start >= self.v.len() || overflow {
1976 let end = match start.checked_add(self.size) {
1977 Some(sum) => cmp::min(self.v.len(), sum),
1978 None => self.v.len(),
1980 let nth = &self.v[start..end];
1981 self.v = &self.v[end..];
1987 fn last(self) -> Option<Self::Item> {
1988 if self.v.is_empty() {
1991 let start = (self.v.len() - 1) / self.size * self.size;
1992 Some(&self.v[start..])
1997 #[stable(feature = "rust1", since = "1.0.0")]
1998 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
2000 fn next_back(&mut self) -> Option<&'a [T]> {
2001 if self.v.is_empty() {
2004 let remainder = self.v.len() % self.size;
2005 let chunksz = if remainder != 0 { remainder } else { self.size };
2006 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
2016 #[unstable(feature = "fused", issue = "35602")]
2017 impl<'a, T> FusedIterator for Chunks<'a, T> {}
2019 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
2020 /// elements at a time). When the slice len is not evenly divided by the chunk
2021 /// size, the last slice of the iteration will be the remainder.
2023 /// This struct is created by the [`chunks_mut`] method on [slices].
2025 /// [`chunks_mut`]: ../../std/primitive.slice.html#method.chunks_mut
2026 /// [slices]: ../../std/primitive.slice.html
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 pub struct ChunksMut<'a, T:'a> {
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 impl<'a, T> Iterator for ChunksMut<'a, T> {
2036 type Item = &'a mut [T];
2039 fn next(&mut self) -> Option<&'a mut [T]> {
2040 if self.v.is_empty() {
2043 let sz = cmp::min(self.v.len(), self.chunk_size);
2044 let tmp = mem::replace(&mut self.v, &mut []);
2045 let (head, tail) = tmp.split_at_mut(sz);
2052 fn size_hint(&self) -> (usize, Option<usize>) {
2053 if self.v.is_empty() {
2056 let n = self.v.len() / self.chunk_size;
2057 let rem = self.v.len() % self.chunk_size;
2058 let n = if rem > 0 { n + 1 } else { n };
2064 fn count(self) -> usize {
2069 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
2070 let (start, overflow) = n.overflowing_mul(self.chunk_size);
2071 if start >= self.v.len() || overflow {
2075 let end = match start.checked_add(self.chunk_size) {
2076 Some(sum) => cmp::min(self.v.len(), sum),
2077 None => self.v.len(),
2079 let tmp = mem::replace(&mut self.v, &mut []);
2080 let (head, tail) = tmp.split_at_mut(end);
2081 let (_, nth) = head.split_at_mut(start);
2088 fn last(self) -> Option<Self::Item> {
2089 if self.v.is_empty() {
2092 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
2093 Some(&mut self.v[start..])
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
2101 fn next_back(&mut self) -> Option<&'a mut [T]> {
2102 if self.v.is_empty() {
2105 let remainder = self.v.len() % self.chunk_size;
2106 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2107 let tmp = mem::replace(&mut self.v, &mut []);
2108 let tmp_len = tmp.len();
2109 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
2119 #[unstable(feature = "fused", issue = "35602")]
2120 impl<'a, T> FusedIterator for ChunksMut<'a, T> {}
2126 /// Forms a slice from a pointer and a length.
2128 /// The `len` argument is the number of **elements**, not the number of bytes.
2132 /// This function is unsafe as there is no guarantee that the given pointer is
2133 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
2134 /// lifetime for the returned slice.
2136 /// `p` must be non-null, even for zero-length slices.
2140 /// The lifetime for the returned slice is inferred from its usage. To
2141 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
2142 /// source lifetime is safe in the context, such as by providing a helper
2143 /// function taking the lifetime of a host value for the slice, or by explicit
2151 /// // manifest a slice out of thin air!
2152 /// let ptr = 0x1234 as *const usize;
2155 /// let slice = slice::from_raw_parts(ptr, amt);
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
2161 mem::transmute(Repr { data: p, len: len })
2164 /// Performs the same functionality as `from_raw_parts`, except that a mutable
2165 /// slice is returned.
2167 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
2168 /// as not being able to provide a non-aliasing guarantee of the returned
2171 #[stable(feature = "rust1", since = "1.0.0")]
2172 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
2173 mem::transmute(Repr { data: p, len: len })
2177 // Comparison traits
2181 /// Call implementation provided memcmp
2183 /// Interprets the data as u8.
2185 /// Return 0 for equal, < 0 for less than and > 0 for greater
2187 // FIXME(#32610): Return type should be c_int
2188 fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;
2191 #[stable(feature = "rust1", since = "1.0.0")]
2192 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
2193 fn eq(&self, other: &[B]) -> bool {
2194 SlicePartialEq::equal(self, other)
2197 fn ne(&self, other: &[B]) -> bool {
2198 SlicePartialEq::not_equal(self, other)
2202 #[stable(feature = "rust1", since = "1.0.0")]
2203 impl<T: Eq> Eq for [T] {}
2205 /// Implements comparison of vectors lexicographically.
2206 #[stable(feature = "rust1", since = "1.0.0")]
2207 impl<T: Ord> Ord for [T] {
2208 fn cmp(&self, other: &[T]) -> Ordering {
2209 SliceOrd::compare(self, other)
2213 /// Implements comparison of vectors lexicographically.
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 impl<T: PartialOrd> PartialOrd for [T] {
2216 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
2217 SlicePartialOrd::partial_compare(self, other)
2222 // intermediate trait for specialization of slice's PartialEq
2223 trait SlicePartialEq<B> {
2224 fn equal(&self, other: &[B]) -> bool;
2226 fn not_equal(&self, other: &[B]) -> bool { !self.equal(other) }
2229 // Generic slice equality
2230 impl<A, B> SlicePartialEq<B> for [A]
2231 where A: PartialEq<B>
2233 default fn equal(&self, other: &[B]) -> bool {
2234 if self.len() != other.len() {
2238 for i in 0..self.len() {
2239 if !self[i].eq(&other[i]) {
2248 // Use memcmp for bytewise equality when the types allow
2249 impl<A> SlicePartialEq<A> for [A]
2250 where A: PartialEq<A> + BytewiseEquality
2252 fn equal(&self, other: &[A]) -> bool {
2253 if self.len() != other.len() {
2256 if self.as_ptr() == other.as_ptr() {
2260 let size = mem::size_of_val(self);
2261 memcmp(self.as_ptr() as *const u8,
2262 other.as_ptr() as *const u8, size) == 0
2268 // intermediate trait for specialization of slice's PartialOrd
2269 trait SlicePartialOrd<B> {
2270 fn partial_compare(&self, other: &[B]) -> Option<Ordering>;
2273 impl<A> SlicePartialOrd<A> for [A]
2276 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2277 let l = cmp::min(self.len(), other.len());
2279 // Slice to the loop iteration range to enable bound check
2280 // elimination in the compiler
2281 let lhs = &self[..l];
2282 let rhs = &other[..l];
2285 match lhs[i].partial_cmp(&rhs[i]) {
2286 Some(Ordering::Equal) => (),
2287 non_eq => return non_eq,
2291 self.len().partial_cmp(&other.len())
2295 impl<A> SlicePartialOrd<A> for [A]
2298 default fn partial_compare(&self, other: &[A]) -> Option<Ordering> {
2299 Some(SliceOrd::compare(self, other))
2304 // intermediate trait for specialization of slice's Ord
2306 fn compare(&self, other: &[B]) -> Ordering;
2309 impl<A> SliceOrd<A> for [A]
2312 default fn compare(&self, other: &[A]) -> Ordering {
2313 let l = cmp::min(self.len(), other.len());
2315 // Slice to the loop iteration range to enable bound check
2316 // elimination in the compiler
2317 let lhs = &self[..l];
2318 let rhs = &other[..l];
2321 match lhs[i].cmp(&rhs[i]) {
2322 Ordering::Equal => (),
2323 non_eq => return non_eq,
2327 self.len().cmp(&other.len())
2331 // memcmp compares a sequence of unsigned bytes lexicographically.
2332 // this matches the order we want for [u8], but no others (not even [i8]).
2333 impl SliceOrd<u8> for [u8] {
2335 fn compare(&self, other: &[u8]) -> Ordering {
2336 let order = unsafe {
2337 memcmp(self.as_ptr(), other.as_ptr(),
2338 cmp::min(self.len(), other.len()))
2341 self.len().cmp(&other.len())
2342 } else if order < 0 {
2351 /// Trait implemented for types that can be compared for equality using
2352 /// their bytewise representation
2353 trait BytewiseEquality { }
2355 macro_rules! impl_marker_for {
2356 ($traitname:ident, $($ty:ty)*) => {
2358 impl $traitname for $ty { }
2363 impl_marker_for!(BytewiseEquality,
2364 u8 i8 u16 i16 u32 i32 u64 i64 usize isize char bool);
2367 unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> {
2368 unsafe fn get_unchecked(&mut self, i: usize) -> &'a T {
2369 &*self.ptr.offset(i as isize)
2371 fn may_have_side_effect() -> bool { false }
2375 unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> {
2376 unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T {
2377 &mut *self.ptr.offset(i as isize)
2379 fn may_have_side_effect() -> bool { false }