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, PartialEq, PartialOrd, Eq, Ord};
38 use cmp::Ordering::{Less, Equal, Greater};
41 use intrinsics::assume;
43 use ops::{FnMut, self, Index};
46 use option::Option::{None, Some};
48 use result::Result::{Ok, Err};
51 use marker::{Send, Sync, self};
52 use num::wrapping::OverflowingOps;
54 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
55 use raw::Slice as RawSlice;
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(&self, index: usize) -> Option<&Self::Item>;
89 #[stable(feature = "core", since = "1.6.0")]
90 fn first(&self) -> Option<&Self::Item>;
91 #[stable(feature = "core", since = "1.6.0")]
92 fn split_first(&self) -> Option<(&Self::Item, &[Self::Item])>;
93 #[stable(feature = "core", since = "1.6.0")]
94 fn split_last(&self) -> Option<(&Self::Item, &[Self::Item])>;
95 #[stable(feature = "core", since = "1.6.0")]
96 fn last(&self) -> Option<&Self::Item>;
97 #[stable(feature = "core", since = "1.6.0")]
98 unsafe fn get_unchecked(&self, index: usize) -> &Self::Item;
99 #[stable(feature = "core", since = "1.6.0")]
100 fn as_ptr(&self) -> *const Self::Item;
101 #[stable(feature = "core", since = "1.6.0")]
102 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize>
103 where Self::Item: Ord;
104 #[stable(feature = "core", since = "1.6.0")]
105 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
106 where F: FnMut(&Self::Item) -> Ordering;
107 #[stable(feature = "core", since = "1.6.0")]
108 fn len(&self) -> usize;
109 #[stable(feature = "core", since = "1.6.0")]
110 fn is_empty(&self) -> bool { self.len() == 0 }
111 #[stable(feature = "core", since = "1.6.0")]
112 fn get_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
113 #[stable(feature = "core", since = "1.6.0")]
114 fn iter_mut(&mut self) -> IterMut<Self::Item>;
115 #[stable(feature = "core", since = "1.6.0")]
116 fn first_mut(&mut self) -> Option<&mut Self::Item>;
117 #[stable(feature = "core", since = "1.6.0")]
118 fn split_first_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
119 #[stable(feature = "core", since = "1.6.0")]
120 fn split_last_mut(&mut self) -> Option<(&mut Self::Item, &mut [Self::Item])>;
121 #[stable(feature = "core", since = "1.6.0")]
122 fn last_mut(&mut self) -> Option<&mut Self::Item>;
123 #[stable(feature = "core", since = "1.6.0")]
124 fn split_mut<P>(&mut self, pred: P) -> SplitMut<Self::Item, P>
125 where P: FnMut(&Self::Item) -> bool;
126 #[stable(feature = "core", since = "1.6.0")]
127 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
128 where P: FnMut(&Self::Item) -> bool;
129 #[stable(feature = "core", since = "1.6.0")]
130 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
131 where P: FnMut(&Self::Item) -> bool;
132 #[stable(feature = "core", since = "1.6.0")]
133 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<Self::Item>;
134 #[stable(feature = "core", since = "1.6.0")]
135 fn swap(&mut self, a: usize, b: usize);
136 #[stable(feature = "core", since = "1.6.0")]
137 fn split_at_mut(&mut self, mid: usize) -> (&mut [Self::Item], &mut [Self::Item]);
138 #[stable(feature = "core", since = "1.6.0")]
139 fn reverse(&mut self);
140 #[stable(feature = "core", since = "1.6.0")]
141 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut Self::Item;
142 #[stable(feature = "core", since = "1.6.0")]
143 fn as_mut_ptr(&mut self) -> *mut Self::Item;
145 #[stable(feature = "core", since = "1.6.0")]
146 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
148 #[stable(feature = "core", since = "1.6.0")]
149 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
151 #[stable(feature = "core", since = "1.6.0")]
152 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
154 #[unstable(feature = "clone_from_slice", issue= "27750")]
155 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
158 // Use macros to be generic over const/mut
159 macro_rules! slice_offset {
160 ($ptr:expr, $by:expr) => {{
162 if size_from_ptr(ptr) == 0 {
163 ::intrinsics::arith_offset(ptr as *mut i8, $by) as *mut _
170 macro_rules! slice_ref {
173 if size_from_ptr(ptr) == 0 {
174 // Use a non-null pointer value
182 #[unstable(feature = "core_slice_ext",
183 reason = "stable interface provided by `impl [T]` in later crates",
185 impl<T> SliceExt for [T] {
189 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
190 (&self[..mid], &self[mid..])
194 fn iter(&self) -> Iter<T> {
196 let p = if mem::size_of::<T>() == 0 {
199 let p = self.as_ptr();
200 assume(!p.is_null());
206 end: slice_offset!(p, self.len() as isize),
207 _marker: marker::PhantomData
213 fn split<P>(&self, pred: P) -> Split<T, P> where P: FnMut(&T) -> bool {
222 fn splitn<P>(&self, n: usize, pred: P) -> SplitN<T, P> where
223 P: FnMut(&T) -> bool,
226 inner: GenericSplitN {
227 iter: self.split(pred),
235 fn rsplitn<P>(&self, n: usize, pred: P) -> RSplitN<T, P> where
236 P: FnMut(&T) -> bool,
239 inner: GenericSplitN {
240 iter: self.split(pred),
248 fn windows(&self, size: usize) -> Windows<T> {
250 Windows { v: self, size: size }
254 fn chunks(&self, size: usize) -> Chunks<T> {
256 Chunks { v: self, size: size }
260 fn get(&self, index: usize) -> Option<&T> {
261 if index < self.len() { Some(&self[index]) } else { None }
265 fn first(&self) -> Option<&T> {
266 if self.is_empty() { None } else { Some(&self[0]) }
270 fn split_first(&self) -> Option<(&T, &[T])> {
271 if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
275 fn split_last(&self) -> Option<(&T, &[T])> {
276 let len = self.len();
277 if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
281 fn last(&self) -> Option<&T> {
282 if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
286 unsafe fn get_unchecked(&self, index: usize) -> &T {
287 &*(self.repr().data.offset(index as isize))
291 fn as_ptr(&self) -> *const T {
295 fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
296 F: FnMut(&T) -> Ordering
298 let mut base : usize = 0;
299 let mut lim : usize = self.len();
302 let ix = base + (lim >> 1);
304 Equal => return Ok(ix),
317 fn len(&self) -> usize { self.repr().len }
320 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
321 if index < self.len() { Some(&mut self[index]) } else { None }
325 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
326 let len = self.len();
327 let ptr = self.as_mut_ptr();
332 (from_raw_parts_mut(ptr, mid),
333 from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
338 fn iter_mut(&mut self) -> IterMut<T> {
340 let p = if mem::size_of::<T>() == 0 {
343 let p = self.as_mut_ptr();
344 assume(!p.is_null());
350 end: slice_offset!(p, self.len() as isize),
351 _marker: marker::PhantomData
357 fn last_mut(&mut self) -> Option<&mut T> {
358 let len = self.len();
359 if len == 0 { return None; }
360 Some(&mut self[len - 1])
364 fn first_mut(&mut self) -> Option<&mut T> {
365 if self.is_empty() { None } else { Some(&mut self[0]) }
369 fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
370 if self.is_empty() { None } else {
371 let split = self.split_at_mut(1);
372 Some((&mut split.0[0], split.1))
377 fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
378 let len = self.len();
379 if len == 0 { None } else {
380 let split = self.split_at_mut(len - 1);
381 Some((&mut split.1[0], split.0))
386 fn split_mut<P>(&mut self, pred: P) -> SplitMut<T, P> where P: FnMut(&T) -> bool {
387 SplitMut { v: self, pred: pred, finished: false }
391 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<T, P> where
395 inner: GenericSplitN {
396 iter: self.split_mut(pred),
404 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<T, P> where
405 P: FnMut(&T) -> bool,
408 inner: GenericSplitN {
409 iter: self.split_mut(pred),
417 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
418 assert!(chunk_size > 0);
419 ChunksMut { v: self, chunk_size: chunk_size }
423 fn swap(&mut self, a: usize, b: usize) {
425 // Can't take two mutable loans from one vector, so instead just cast
426 // them to their raw pointers to do the swap
427 let pa: *mut T = &mut self[a];
428 let pb: *mut T = &mut self[b];
433 fn reverse(&mut self) {
434 let mut i: usize = 0;
437 // Unsafe swap to avoid the bounds check in safe swap.
439 let pa: *mut T = self.get_unchecked_mut(i);
440 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
448 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
449 &mut *(self.repr().data as *mut T).offset(index as isize)
453 fn as_mut_ptr(&mut self) -> *mut T {
454 self.repr().data as *mut T
458 fn contains(&self, x: &T) -> bool where T: PartialEq {
459 self.iter().any(|elt| *x == *elt)
463 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
464 let n = needle.len();
465 self.len() >= n && needle == &self[..n]
469 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
470 let (m, n) = (self.len(), needle.len());
471 m >= n && needle == &self[m-n..]
474 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
475 self.binary_search_by(|p| p.cmp(x))
479 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
480 let min = cmp::min(self.len(), src.len());
481 let dst = &mut self[.. min];
482 let src = &src[.. min];
484 dst[i].clone_from(&src[i]);
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl<T> ops::Index<usize> for [T] {
494 fn index(&self, index: usize) -> &T {
495 assert!(index < self.len());
496 unsafe { self.get_unchecked(index) }
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl<T> ops::IndexMut<usize> for [T] {
503 fn index_mut(&mut self, index: usize) -> &mut T {
504 assert!(index < self.len());
505 unsafe { self.get_unchecked_mut(index) }
511 fn slice_index_len_fail(index: usize, len: usize) -> ! {
512 panic!("index {} out of range for slice of length {}", index, len);
517 fn slice_index_order_fail(index: usize, end: usize) -> ! {
518 panic!("slice index starts at {} but ends at {}", index, end);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl<T> ops::Index<ops::Range<usize>> for [T] {
526 fn index(&self, index: ops::Range<usize>) -> &[T] {
527 if index.start > index.end {
528 slice_index_order_fail(index.start, index.end);
529 } else if index.end > self.len() {
530 slice_index_len_fail(index.end, self.len());
534 self.as_ptr().offset(index.start as isize),
535 index.end - index.start
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
545 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
546 self.index(ops::Range{ start: 0, end: index.end })
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
554 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
555 self.index(ops::Range{ start: index.start, end: self.len() })
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T> ops::Index<RangeFull> for [T] {
563 fn index(&self, _index: RangeFull) -> &[T] {
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
571 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
572 if index.start > index.end {
573 slice_index_order_fail(index.start, index.end);
574 } else if index.end > self.len() {
575 slice_index_len_fail(index.end, self.len());
579 self.as_mut_ptr().offset(index.start as isize),
580 index.end - index.start
585 #[stable(feature = "rust1", since = "1.0.0")]
586 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
588 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
589 self.index_mut(ops::Range{ start: 0, end: index.end })
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
595 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
596 let len = self.len();
597 self.index_mut(ops::Range{ start: index.start, end: len })
600 #[stable(feature = "rust1", since = "1.0.0")]
601 impl<T> ops::IndexMut<RangeFull> for [T] {
603 fn index_mut(&mut self, _index: RangeFull) -> &mut [T] {
609 ////////////////////////////////////////////////////////////////////////////////
611 ////////////////////////////////////////////////////////////////////////////////
613 #[stable(feature = "rust1", since = "1.0.0")]
614 impl<'a, T> Default for &'a [T] {
615 fn default() -> &'a [T] { &[] }
618 #[stable(feature = "mut_slice_default", since = "1.5.0")]
619 impl<'a, T> Default for &'a mut [T] {
620 fn default() -> &'a mut [T] { &mut [] }
627 #[stable(feature = "rust1", since = "1.0.0")]
628 impl<'a, T> IntoIterator for &'a [T] {
630 type IntoIter = Iter<'a, T>;
632 fn into_iter(self) -> Iter<'a, T> {
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<'a, T> IntoIterator for &'a mut [T] {
639 type Item = &'a mut T;
640 type IntoIter = IterMut<'a, T>;
642 fn into_iter(self) -> IterMut<'a, T> {
648 fn size_from_ptr<T>(_: *const T) -> usize {
652 // The shared definition of the `Iter` and `IterMut` iterators
653 macro_rules! iterator {
654 (struct $name:ident -> $ptr:ty, $elem:ty) => {
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl<'a, T> Iterator for $name<'a, T> {
660 fn next(&mut self) -> Option<$elem> {
661 // could be implemented with slices, but this avoids bounds checks
663 if mem::size_of::<T>() != 0 {
664 assume(!self.ptr.is_null());
665 assume(!self.end.is_null());
667 if self.ptr == self.end {
671 self.ptr = slice_offset!(self.ptr, 1);
672 Some(slice_ref!(old))
678 fn size_hint(&self) -> (usize, Option<usize>) {
679 let diff = (self.end as usize).wrapping_sub(self.ptr as usize);
680 let size = mem::size_of::<T>();
681 let exact = diff / (if size == 0 {1} else {size});
686 fn count(self) -> usize {
691 fn nth(&mut self, n: usize) -> Option<$elem> {
692 // Call helper method. Can't put the definition here because mut versus const.
697 fn last(mut self) -> Option<$elem> {
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
705 fn next_back(&mut self) -> Option<$elem> {
706 // could be implemented with slices, but this avoids bounds checks
708 if mem::size_of::<T>() != 0 {
709 assume(!self.ptr.is_null());
710 assume(!self.end.is_null());
712 if self.end == self.ptr {
715 self.end = slice_offset!(self.end, -1);
716 Some(slice_ref!(self.end))
724 macro_rules! make_slice {
725 ($start: expr, $end: expr) => {{
727 let diff = ($end as usize).wrapping_sub(start as usize);
728 if size_from_ptr(start) == 0 {
729 // use a non-null pointer value
730 unsafe { from_raw_parts(1 as *const _, diff) }
732 let len = diff / size_from_ptr(start);
733 unsafe { from_raw_parts(start, len) }
738 macro_rules! make_mut_slice {
739 ($start: expr, $end: expr) => {{
741 let diff = ($end as usize).wrapping_sub(start as usize);
742 if size_from_ptr(start) == 0 {
743 // use a non-null pointer value
744 unsafe { from_raw_parts_mut(1 as *mut _, diff) }
746 let len = diff / size_from_ptr(start);
747 unsafe { from_raw_parts_mut(start, len) }
752 /// Immutable slice iterator
753 #[stable(feature = "rust1", since = "1.0.0")]
754 pub struct Iter<'a, T: 'a> {
757 _marker: marker::PhantomData<&'a T>,
760 #[stable(feature = "rust1", since = "1.0.0")]
761 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
762 #[stable(feature = "rust1", since = "1.0.0")]
763 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
765 impl<'a, T> Iter<'a, T> {
766 /// View the underlying data as a subslice of the original data.
768 /// This has the same lifetime as the original slice, and so the
769 /// iterator can continue to be used while this exists.
770 #[stable(feature = "iter_to_slice", since = "1.4.0")]
771 pub fn as_slice(&self) -> &'a [T] {
772 make_slice!(self.ptr, self.end)
775 // Helper function for Iter::nth
776 fn iter_nth(&mut self, n: usize) -> Option<&'a T> {
777 match self.as_slice().get(n) {
778 Some(elem_ref) => unsafe {
779 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
790 iterator!{struct Iter -> *const T, &'a T}
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
795 #[stable(feature = "rust1", since = "1.0.0")]
796 impl<'a, T> Clone for Iter<'a, T> {
797 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
800 /// Mutable slice iterator.
801 #[stable(feature = "rust1", since = "1.0.0")]
802 pub struct IterMut<'a, T: 'a> {
805 _marker: marker::PhantomData<&'a mut T>,
808 #[stable(feature = "rust1", since = "1.0.0")]
809 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
810 #[stable(feature = "rust1", since = "1.0.0")]
811 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
813 impl<'a, T> IterMut<'a, T> {
814 /// View the underlying data as a subslice of the original data.
816 /// To avoid creating `&mut` references that alias, this is forced
817 /// to consume the iterator. Consider using the `Slice` and
818 /// `SliceMut` implementations for obtaining slices with more
819 /// restricted lifetimes that do not consume the iterator.
820 #[stable(feature = "iter_to_slice", since = "1.4.0")]
821 pub fn into_slice(self) -> &'a mut [T] {
822 make_mut_slice!(self.ptr, self.end)
825 // Helper function for IterMut::nth
826 fn iter_nth(&mut self, n: usize) -> Option<&'a mut T> {
827 match make_mut_slice!(self.ptr, self.end).get_mut(n) {
828 Some(elem_ref) => unsafe {
829 self.ptr = slice_offset!(self.ptr, (n as isize).wrapping_add(1));
840 iterator!{struct IterMut -> *mut T, &'a mut T}
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
845 /// An internal abstraction over the splitting iterators, so that
846 /// splitn, splitn_mut etc can be implemented once.
847 trait SplitIter: DoubleEndedIterator {
848 /// Mark the underlying iterator as complete, extracting the remaining
849 /// portion of the slice.
850 fn finish(&mut self) -> Option<Self::Item>;
853 /// An iterator over subslices separated by elements that match a predicate
855 #[stable(feature = "rust1", since = "1.0.0")]
856 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
862 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
865 fn clone(&self) -> Split<'a, T, P> {
868 pred: self.pred.clone(),
869 finished: self.finished,
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
879 fn next(&mut self) -> Option<&'a [T]> {
880 if self.finished { return None; }
882 match self.v.iter().position(|x| (self.pred)(x)) {
883 None => self.finish(),
885 let ret = Some(&self.v[..idx]);
886 self.v = &self.v[idx + 1..];
893 fn size_hint(&self) -> (usize, Option<usize>) {
897 (1, Some(self.v.len() + 1))
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
905 fn next_back(&mut self) -> Option<&'a [T]> {
906 if self.finished { return None; }
908 match self.v.iter().rposition(|x| (self.pred)(x)) {
909 None => self.finish(),
911 let ret = Some(&self.v[idx + 1..]);
912 self.v = &self.v[..idx];
919 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
921 fn finish(&mut self) -> Option<&'a [T]> {
922 if self.finished { None } else { self.finished = true; Some(self.v) }
926 /// An iterator over the subslices of the vector which are separated
927 /// by elements that match `pred`.
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
935 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
937 fn finish(&mut self) -> Option<&'a mut [T]> {
941 self.finished = true;
942 Some(mem::replace(&mut self.v, &mut []))
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
949 type Item = &'a mut [T];
952 fn next(&mut self) -> Option<&'a mut [T]> {
953 if self.finished { return None; }
955 let idx_opt = { // work around borrowck limitations
956 let pred = &mut self.pred;
957 self.v.iter().position(|x| (*pred)(x))
960 None => self.finish(),
962 let tmp = mem::replace(&mut self.v, &mut []);
963 let (head, tail) = tmp.split_at_mut(idx);
964 self.v = &mut tail[1..];
971 fn size_hint(&self) -> (usize, Option<usize>) {
975 // if the predicate doesn't match anything, we yield one slice
976 // if it matches every element, we yield len+1 empty slices.
977 (1, Some(self.v.len() + 1))
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
984 P: FnMut(&T) -> bool,
987 fn next_back(&mut self) -> Option<&'a mut [T]> {
988 if self.finished { return None; }
990 let idx_opt = { // work around borrowck limitations
991 let pred = &mut self.pred;
992 self.v.iter().rposition(|x| (*pred)(x))
995 None => self.finish(),
997 let tmp = mem::replace(&mut self.v, &mut []);
998 let (head, tail) = tmp.split_at_mut(idx);
1000 Some(&mut tail[1..])
1006 /// An private iterator over subslices separated by elements that
1007 /// match a predicate function, splitting at most a fixed number of
1009 struct GenericSplitN<I> {
1015 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1019 fn next(&mut self) -> Option<T> {
1022 1 => { self.count -= 1; self.iter.finish() }
1025 if self.invert {self.iter.next_back()} else {self.iter.next()}
1031 fn size_hint(&self) -> (usize, Option<usize>) {
1032 let (lower, upper_opt) = self.iter.size_hint();
1033 (lower, upper_opt.map(|upper| cmp::min(self.count, upper)))
1037 /// An iterator over subslices separated by elements that match a predicate
1038 /// function, limited to a given number of splits.
1039 #[stable(feature = "rust1", since = "1.0.0")]
1040 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1041 inner: GenericSplitN<Split<'a, T, P>>
1044 /// An iterator over subslices separated by elements that match a
1045 /// predicate function, limited to a given number of splits, starting
1046 /// from the end of the slice.
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1049 inner: GenericSplitN<Split<'a, T, P>>
1052 /// An iterator over subslices separated by elements that match a predicate
1053 /// function, limited to a given number of splits.
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1056 inner: GenericSplitN<SplitMut<'a, T, P>>
1059 /// An iterator over subslices separated by elements that match a
1060 /// predicate function, limited to a given number of splits, starting
1061 /// from the end of the slice.
1062 #[stable(feature = "rust1", since = "1.0.0")]
1063 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1064 inner: GenericSplitN<SplitMut<'a, T, P>>
1067 macro_rules! forward_iterator {
1068 ($name:ident: $elem:ident, $iter_of:ty) => {
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1071 P: FnMut(&T) -> bool
1073 type Item = $iter_of;
1076 fn next(&mut self) -> Option<$iter_of> {
1081 fn size_hint(&self) -> (usize, Option<usize>) {
1082 self.inner.size_hint()
1088 forward_iterator! { SplitN: T, &'a [T] }
1089 forward_iterator! { RSplitN: T, &'a [T] }
1090 forward_iterator! { SplitNMut: T, &'a mut [T] }
1091 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1093 /// An iterator over overlapping subslices of length `size`.
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 pub struct Windows<'a, T:'a> {
1100 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<'a, T> Clone for Windows<'a, T> {
1103 fn clone(&self) -> Windows<'a, T> {
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<'a, T> Iterator for Windows<'a, T> {
1113 type Item = &'a [T];
1116 fn next(&mut self) -> Option<&'a [T]> {
1117 if self.size > self.v.len() {
1120 let ret = Some(&self.v[..self.size]);
1121 self.v = &self.v[1..];
1127 fn size_hint(&self) -> (usize, Option<usize>) {
1128 if self.size > self.v.len() {
1131 let size = self.v.len() - self.size + 1;
1137 fn count(self) -> usize {
1142 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1143 let (end, overflow) = self.size.overflowing_add(n);
1144 if end > self.v.len() || overflow {
1148 let nth = &self.v[n..end];
1149 self.v = &self.v[n+1..];
1155 fn last(self) -> Option<Self::Item> {
1156 if self.size > self.v.len() {
1159 let start = self.v.len() - self.size;
1160 Some(&self.v[start..])
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1168 fn next_back(&mut self) -> Option<&'a [T]> {
1169 if self.size > self.v.len() {
1172 let ret = Some(&self.v[self.v.len()-self.size..]);
1173 self.v = &self.v[..self.v.len()-1];
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1182 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1185 /// When the slice len is not evenly divided by the chunk size, the last slice
1186 /// of the iteration will be the remainder.
1187 #[stable(feature = "rust1", since = "1.0.0")]
1188 pub struct Chunks<'a, T:'a> {
1193 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 impl<'a, T> Clone for Chunks<'a, T> {
1196 fn clone(&self) -> Chunks<'a, T> {
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl<'a, T> Iterator for Chunks<'a, T> {
1206 type Item = &'a [T];
1209 fn next(&mut self) -> Option<&'a [T]> {
1210 if self.v.is_empty() {
1213 let chunksz = cmp::min(self.v.len(), self.size);
1214 let (fst, snd) = self.v.split_at(chunksz);
1221 fn size_hint(&self) -> (usize, Option<usize>) {
1222 if self.v.is_empty() {
1225 let n = self.v.len() / self.size;
1226 let rem = self.v.len() % self.size;
1227 let n = if rem > 0 { n+1 } else { n };
1233 fn count(self) -> usize {
1238 fn nth(&mut self, n: usize) -> Option<Self::Item> {
1239 let (start, overflow) = n.overflowing_mul(self.size);
1240 if start >= self.v.len() || overflow {
1244 let end = match start.checked_add(self.size) {
1245 Some(sum) => cmp::min(self.v.len(), sum),
1246 None => self.v.len(),
1248 let nth = &self.v[start..end];
1249 self.v = &self.v[end..];
1255 fn last(self) -> Option<Self::Item> {
1256 if self.v.is_empty() {
1259 let start = (self.v.len() - 1) / self.size * self.size;
1260 Some(&self.v[start..])
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1268 fn next_back(&mut self) -> Option<&'a [T]> {
1269 if self.v.is_empty() {
1272 let remainder = self.v.len() % self.size;
1273 let chunksz = if remainder != 0 { remainder } else { self.size };
1274 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1284 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1285 /// elements at a time). When the slice len is not evenly divided by the chunk
1286 /// size, the last slice of the iteration will be the remainder.
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 pub struct ChunksMut<'a, T:'a> {
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<'a, T> Iterator for ChunksMut<'a, T> {
1295 type Item = &'a mut [T];
1298 fn next(&mut self) -> Option<&'a mut [T]> {
1299 if self.v.is_empty() {
1302 let sz = cmp::min(self.v.len(), self.chunk_size);
1303 let tmp = mem::replace(&mut self.v, &mut []);
1304 let (head, tail) = tmp.split_at_mut(sz);
1311 fn size_hint(&self) -> (usize, Option<usize>) {
1312 if self.v.is_empty() {
1315 let n = self.v.len() / self.chunk_size;
1316 let rem = self.v.len() % self.chunk_size;
1317 let n = if rem > 0 { n + 1 } else { n };
1323 fn count(self) -> usize {
1328 fn nth(&mut self, n: usize) -> Option<&'a mut [T]> {
1329 let (start, overflow) = n.overflowing_mul(self.chunk_size);
1330 if start >= self.v.len() || overflow {
1334 let end = match start.checked_add(self.chunk_size) {
1335 Some(sum) => cmp::min(self.v.len(), sum),
1336 None => self.v.len(),
1338 let tmp = mem::replace(&mut self.v, &mut []);
1339 let (head, tail) = tmp.split_at_mut(end);
1340 let (_, nth) = head.split_at_mut(start);
1347 fn last(self) -> Option<Self::Item> {
1348 if self.v.is_empty() {
1351 let start = (self.v.len() - 1) / self.chunk_size * self.chunk_size;
1352 Some(&mut self.v[start..])
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1360 fn next_back(&mut self) -> Option<&'a mut [T]> {
1361 if self.v.is_empty() {
1364 let remainder = self.v.len() % self.chunk_size;
1365 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1366 let tmp = mem::replace(&mut self.v, &mut []);
1367 let tmp_len = tmp.len();
1368 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1382 /// Forms a slice from a pointer and a length.
1384 /// The `len` argument is the number of **elements**, not the number of bytes.
1388 /// This function is unsafe as there is no guarantee that the given pointer is
1389 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1390 /// lifetime for the returned slice.
1392 /// `p` must be non-null, even for zero-length slices.
1396 /// The lifetime for the returned slice is inferred from its usage. To
1397 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1398 /// source lifetime is safe in the context, such as by providing a helper
1399 /// function taking the lifetime of a host value for the slice, or by explicit
1407 /// // manifest a slice out of thin air!
1408 /// let ptr = 0x1234 as *const usize;
1411 /// let slice = slice::from_raw_parts(ptr, amt);
1415 #[stable(feature = "rust1", since = "1.0.0")]
1416 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1417 mem::transmute(RawSlice { data: p, len: len })
1420 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1421 /// slice is returned.
1423 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1424 /// as not being able to provide a non-aliasing guarantee of the returned
1427 #[stable(feature = "rust1", since = "1.0.0")]
1428 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1429 mem::transmute(RawSlice { data: p, len: len })
1436 /// Operations on `[u8]`.
1437 #[unstable(feature = "slice_bytes", reason = "needs review",
1439 #[rustc_deprecated(reason = "unidiomatic functions not pulling their weight",
1441 #[allow(deprecated)]
1444 use slice::SliceExt;
1446 /// A trait for operations on mutable `[u8]`s.
1447 pub trait MutableByteVector {
1448 /// Sets all bytes of the receiver to the given value.
1449 fn set_memory(&mut self, value: u8);
1452 impl MutableByteVector for [u8] {
1454 fn set_memory(&mut self, value: u8) {
1455 unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1459 /// Copies data from `src` to `dst`
1461 /// Panics if the length of `dst` is less than the length of `src`.
1463 pub fn copy_memory(src: &[u8], dst: &mut [u8]) {
1464 let len_src = src.len();
1465 assert!(dst.len() >= len_src);
1466 // `dst` is unaliasable, so we know statically it doesn't overlap
1469 ptr::copy_nonoverlapping(src.as_ptr(),
1479 // Boilerplate traits
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1484 fn eq(&self, other: &[B]) -> bool {
1485 if self.len() != other.len() {
1489 for i in 0..self.len() {
1490 if !self[i].eq(&other[i]) {
1497 fn ne(&self, other: &[B]) -> bool {
1498 if self.len() != other.len() {
1502 for i in 0..self.len() {
1503 if self[i].ne(&other[i]) {
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<T: Eq> Eq for [T] {}
1515 #[stable(feature = "rust1", since = "1.0.0")]
1516 impl<T: Ord> Ord for [T] {
1517 fn cmp(&self, other: &[T]) -> Ordering {
1518 let l = cmp::min(self.len(), other.len());
1520 // Slice to the loop iteration range to enable bound check
1521 // elimination in the compiler
1522 let lhs = &self[..l];
1523 let rhs = &other[..l];
1526 match lhs[i].cmp(&rhs[i]) {
1527 Ordering::Equal => (),
1528 non_eq => return non_eq,
1532 self.len().cmp(&other.len())
1536 #[stable(feature = "rust1", since = "1.0.0")]
1537 impl<T: PartialOrd> PartialOrd for [T] {
1538 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1539 let l = cmp::min(self.len(), other.len());
1541 // Slice to the loop iteration range to enable bound check
1542 // elimination in the compiler
1543 let lhs = &self[..l];
1544 let rhs = &other[..l];
1547 match lhs[i].partial_cmp(&rhs[i]) {
1548 Some(Ordering::Equal) => (),
1549 non_eq => return non_eq,
1553 self.len().partial_cmp(&other.len())