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")]
16 #![doc(primitive = "slice")]
18 // How this module is organized.
20 // The library infrastructure for slices is fairly messy. There's
21 // a lot of stuff defined here. Let's keep it clean.
23 // Since slices don't support inherent methods; all operations
24 // on them are defined on traits, which are then reexported from
25 // the prelude for convenience. So there are a lot of traits here.
27 // The layout of this file is thus:
29 // * Slice-specific 'extension' traits and their implementations. This
30 // is where most of the slice API resides.
31 // * Implementations of a few common traits with important slice ops.
32 // * Definitions of a bunch of iterators.
34 // * The `raw` and `bytes` submodules.
35 // * Boilerplate trait implementations.
39 use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord};
40 use cmp::Ordering::{Less, Equal, Greater};
44 use ops::{FnMut, self, Index};
47 use option::Option::{None, Some};
49 use result::Result::{Ok, Err};
54 use marker::{Sized, self};
56 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
57 use raw::Slice as RawSlice;
64 /// Extension methods for slices.
65 #[allow(missing_docs)] // docs in libcollections
69 fn split_at<'a>(&'a self, mid: usize) -> (&'a [Self::Item], &'a [Self::Item]);
70 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
71 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
72 where P: FnMut(&Self::Item) -> bool;
73 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, Self::Item, P>
74 where P: FnMut(&Self::Item) -> bool;
75 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, Self::Item, P>
76 where P: FnMut(&Self::Item) -> bool;
77 fn windows<'a>(&'a self, size: usize) -> Windows<'a, Self::Item>;
78 fn chunks<'a>(&'a self, size: usize) -> Chunks<'a, Self::Item>;
79 fn get<'a>(&'a self, index: usize) -> Option<&'a Self::Item>;
80 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
81 fn tail<'a>(&'a self) -> &'a [Self::Item];
82 fn init<'a>(&'a self) -> &'a [Self::Item];
83 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
84 unsafe fn get_unchecked<'a>(&'a self, index: usize) -> &'a Self::Item;
85 fn as_ptr(&self) -> *const Self::Item;
86 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
87 F: FnMut(&Self::Item) -> Ordering;
88 fn len(&self) -> usize;
89 fn is_empty(&self) -> bool { self.len() == 0 }
90 fn get_mut<'a>(&'a mut self, index: usize) -> Option<&'a mut Self::Item>;
91 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item];
92 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
93 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
94 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
95 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
96 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
97 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
98 where P: FnMut(&Self::Item) -> bool;
99 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
100 where P: FnMut(&Self::Item) -> bool;
101 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
102 where P: FnMut(&Self::Item) -> bool;
103 fn chunks_mut<'a>(&'a mut self, chunk_size: usize) -> ChunksMut<'a, Self::Item>;
104 fn swap(&mut self, a: usize, b: usize);
105 fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
106 fn reverse(&mut self);
107 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Item;
108 fn as_mut_ptr(&mut self) -> *mut Self::Item;
110 fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
112 fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
114 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
116 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
118 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
120 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
121 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
122 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
124 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
127 #[unstable(feature = "core")]
128 impl<T> SliceExt for [T] {
132 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
133 (&self[..mid], &self[mid..])
137 fn iter<'a>(&'a self) -> Iter<'a, T> {
139 let p = self.as_ptr();
140 if mem::size_of::<T>() == 0 {
142 end: (p as usize + self.len()) as *const T,
143 marker: marker::ContravariantLifetime::<'a>}
146 end: p.offset(self.len() as isize),
147 marker: marker::ContravariantLifetime::<'a>}
153 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
162 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, T, P> where
163 P: FnMut(&T) -> bool,
166 inner: GenericSplitN {
167 iter: self.split(pred),
175 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, T, P> where
176 P: FnMut(&T) -> bool,
179 inner: GenericSplitN {
180 iter: self.split(pred),
188 fn windows(&self, size: usize) -> Windows<T> {
190 Windows { v: self, size: size }
194 fn chunks(&self, size: usize) -> Chunks<T> {
196 Chunks { v: self, size: size }
200 fn get(&self, index: usize) -> Option<&T> {
201 if index < self.len() { Some(&self[index]) } else { None }
205 fn first(&self) -> Option<&T> {
206 if self.len() == 0 { None } else { Some(&self[0]) }
210 fn tail(&self) -> &[T] { &self[1..] }
213 fn init(&self) -> &[T] {
214 &self[..self.len() - 1]
218 fn last(&self) -> Option<&T> {
219 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
223 unsafe fn get_unchecked(&self, index: usize) -> &T {
224 transmute(self.repr().data.offset(index as isize))
228 fn as_ptr(&self) -> *const T {
232 #[unstable(feature = "core")]
233 fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
234 F: FnMut(&T) -> Ordering
236 let mut base : usize = 0;
237 let mut lim : usize = self.len();
240 let ix = base + (lim >> 1);
242 Equal => return Ok(ix),
255 fn len(&self) -> usize { self.repr().len }
258 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
259 if index < self.len() { Some(&mut self[index]) } else { None }
263 fn as_mut_slice(&mut self) -> &mut [T] { self }
266 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
268 let self2: &mut [T] = mem::transmute_copy(&self);
270 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
271 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
276 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
278 let p = self.as_mut_ptr();
279 if mem::size_of::<T>() == 0 {
281 end: (p as usize + self.len()) as *mut T,
282 marker: marker::ContravariantLifetime::<'a>}
285 end: p.offset(self.len() as isize),
286 marker: marker::ContravariantLifetime::<'a>}
292 fn last_mut(&mut self) -> Option<&mut T> {
293 let len = self.len();
294 if len == 0 { return None; }
295 Some(&mut self[len - 1])
299 fn first_mut(&mut self) -> Option<&mut T> {
300 if self.len() == 0 { None } else { Some(&mut self[0]) }
304 fn tail_mut(&mut self) -> &mut [T] {
309 fn init_mut(&mut self) -> &mut [T] {
310 let len = self.len();
311 &mut self[.. (len - 1)]
315 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
316 SplitMut { v: self, pred: pred, finished: false }
320 fn splitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> SplitNMut<'a, T, P> where
324 inner: GenericSplitN {
325 iter: self.split_mut(pred),
333 fn rsplitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> RSplitNMut<'a, T, P> where
334 P: FnMut(&T) -> bool,
337 inner: GenericSplitN {
338 iter: self.split_mut(pred),
346 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
347 assert!(chunk_size > 0);
348 ChunksMut { v: self, chunk_size: chunk_size }
351 fn swap(&mut self, a: usize, b: usize) {
353 // Can't take two mutable loans from one vector, so instead just cast
354 // them to their raw pointers to do the swap
355 let pa: *mut T = &mut self[a];
356 let pb: *mut T = &mut self[b];
361 fn reverse(&mut self) {
362 let mut i: usize = 0;
365 // Unsafe swap to avoid the bounds check in safe swap.
367 let pa: *mut T = self.get_unchecked_mut(i);
368 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
376 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
377 transmute((self.repr().data as *mut T).offset(index as isize))
381 fn as_mut_ptr(&mut self) -> *mut T {
382 self.repr().data as *mut T
386 fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
387 self.iter().position(|y| *x == *y)
391 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
392 self.iter().rposition(|x| *x == *t)
396 fn contains(&self, x: &T) -> bool where T: PartialEq {
397 self.iter().any(|elt| *x == *elt)
401 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
402 let n = needle.len();
403 self.len() >= n && needle == &self[..n]
407 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
408 let (m, n) = (self.len(), needle.len());
409 m >= n && needle == &self[m-n..]
412 #[unstable(feature = "core")]
413 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
414 self.binary_search_by(|p| p.cmp(x))
417 #[unstable(feature = "core")]
418 fn next_permutation(&mut self) -> bool where T: Ord {
419 // These cases only have 1 permutation each, so we can't do anything.
420 if self.len() < 2 { return false; }
422 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
423 let mut i = self.len() - 1;
424 while i > 0 && self[i-1] >= self[i] {
428 // If that is the entire vector, this is the last-ordered permutation.
433 // Step 2: Find the rightmost element larger than the pivot (i-1)
434 let mut j = self.len() - 1;
435 while j >= i && self[j] <= self[i-1] {
439 // Step 3: Swap that element with the pivot
442 // Step 4: Reverse the (previously) weakly decreasing part
448 #[unstable(feature = "core")]
449 fn prev_permutation(&mut self) -> bool where T: Ord {
450 // These cases only have 1 permutation each, so we can't do anything.
451 if self.len() < 2 { return false; }
453 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
454 let mut i = self.len() - 1;
455 while i > 0 && self[i-1] <= self[i] {
459 // If that is the entire vector, this is the first-ordered permutation.
464 // Step 2: Reverse the weakly increasing part
467 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
468 let mut j = self.len() - 1;
469 while j >= i && self[j-1] < self[i-1] {
473 // Step 4: Swap that element with the pivot
480 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
481 let min = cmp::min(self.len(), src.len());
482 let dst = &mut self[.. min];
483 let src = &src[.. min];
485 dst[i].clone_from(&src[i]);
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl<T> ops::Index<usize> for [T] {
495 fn index(&self, &index: &usize) -> &T {
496 assert!(index < self.len());
498 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
502 #[stable(feature = "rust1", since = "1.0.0")]
503 impl<T> ops::IndexMut<usize> for [T] {
504 fn index_mut(&mut self, &index: &usize) -> &mut T {
505 assert!(index < self.len());
507 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
511 #[stable(feature = "rust1", since = "1.0.0")]
512 impl<T> ops::Index<ops::Range<usize>> for [T] {
515 fn index(&self, index: &ops::Range<usize>) -> &[T] {
516 assert!(index.start <= index.end);
517 assert!(index.end <= self.len());
520 data: self.as_ptr().offset(index.start as isize),
521 len: index.end - index.start
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
530 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
531 self.index(&ops::Range{ start: 0, end: index.end })
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
538 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
539 self.index(&ops::Range{ start: index.start, end: self.len() })
542 #[stable(feature = "rust1", since = "1.0.0")]
543 impl<T> ops::Index<RangeFull> for [T] {
546 fn index(&self, _index: &RangeFull) -> &[T] {
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
554 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
555 assert!(index.start <= index.end);
556 assert!(index.end <= self.len());
559 data: self.as_ptr().offset(index.start as isize),
560 len: index.end - index.start
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
568 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
569 self.index_mut(&ops::Range{ start: 0, end: index.end })
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
575 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
576 let len = self.len();
577 self.index_mut(&ops::Range{ start: index.start, end: len })
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl<T> ops::IndexMut<RangeFull> for [T] {
583 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
589 ////////////////////////////////////////////////////////////////////////////////
591 ////////////////////////////////////////////////////////////////////////////////
593 /// Data that is viewable as a slice.
594 #[unstable(feature = "core",
595 reason = "will be replaced by slice syntax")]
596 pub trait AsSlice<T> {
597 /// Work with `self` as a slice.
598 fn as_slice<'a>(&'a self) -> &'a [T];
601 #[unstable(feature = "core", reason = "trait is experimental")]
602 impl<T> AsSlice<T> for [T] {
604 fn as_slice<'a>(&'a self) -> &'a [T] { self }
607 #[unstable(feature = "core", reason = "trait is experimental")]
608 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
610 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
613 #[unstable(feature = "core", reason = "trait is experimental")]
614 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
616 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl<'a, T> Default for &'a [T] {
621 #[stable(feature = "rust1", since = "1.0.0")]
622 fn default() -> &'a [T] { &[] }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a, T> IntoIterator for &'a [T] {
632 type IntoIter = Iter<'a, T>;
634 fn into_iter(self) -> Iter<'a, T> {
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<'a, T> IntoIterator for &'a mut [T] {
641 type Item = &'a mut T;
642 type IntoIter = IterMut<'a, T>;
644 fn into_iter(self) -> IterMut<'a, T> {
649 // The shared definition of the `Iter` and `IterMut` iterators
650 macro_rules! iterator {
651 (struct $name:ident -> $ptr:ty, $elem:ty) => {
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl<'a, T> Iterator for $name<'a, T> {
657 fn next(&mut self) -> Option<$elem> {
658 // could be implemented with slices, but this avoids bounds checks
660 if self.ptr == self.end {
663 if mem::size_of::<T>() == 0 {
664 // purposefully don't use 'ptr.offset' because for
665 // vectors with 0-size elements this would return the
667 self.ptr = transmute(self.ptr as usize + 1);
669 // Use a non-null pointer value
670 Some(&mut *(1 as *mut _))
673 self.ptr = self.ptr.offset(1);
682 fn size_hint(&self) -> (usize, Option<usize>) {
683 let diff = (self.end as usize) - (self.ptr as usize);
684 let size = mem::size_of::<T>();
685 let exact = diff / (if size == 0 {1} else {size});
690 #[stable(feature = "rust1", since = "1.0.0")]
691 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
693 fn next_back(&mut self) -> Option<$elem> {
694 // could be implemented with slices, but this avoids bounds checks
696 if self.end == self.ptr {
699 if mem::size_of::<T>() == 0 {
700 // See above for why 'ptr.offset' isn't used
701 self.end = transmute(self.end as usize - 1);
703 // Use a non-null pointer value
704 Some(&mut *(1 as *mut _))
706 self.end = self.end.offset(-1);
708 Some(transmute(self.end))
717 macro_rules! make_slice {
718 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
719 let diff = $end as usize - $start as usize;
720 let len = if mem::size_of::<T>() == 0 {
723 diff / mem::size_of::<$t>()
726 transmute::<_, $result>(RawSlice { data: $start, len: len })
731 /// Immutable slice iterator
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub struct Iter<'a, T: 'a> {
736 marker: marker::ContravariantLifetime<'a>
739 #[unstable(feature = "core")]
740 impl<'a, T> ops::Index<ops::Range<usize>> for Iter<'a, T> {
743 fn index(&self, index: &ops::Range<usize>) -> &[T] {
744 self.as_slice().index(index)
748 #[unstable(feature = "core")]
749 impl<'a, T> ops::Index<ops::RangeTo<usize>> for Iter<'a, T> {
752 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
753 self.as_slice().index(index)
757 #[unstable(feature = "core")]
758 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for Iter<'a, T> {
761 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
762 self.as_slice().index(index)
766 #[unstable(feature = "core")]
767 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
770 fn index(&self, _index: &RangeFull) -> &[T] {
775 impl<'a, T> Iter<'a, T> {
776 /// View the underlying data as a subslice of the original data.
778 /// This has the same lifetime as the original slice, and so the
779 /// iterator can continue to be used while this exists.
780 #[unstable(feature = "core")]
781 pub fn as_slice(&self) -> &'a [T] {
782 make_slice!(T => &'a [T]: self.ptr, self.end)
786 iterator!{struct Iter -> *const T, &'a T}
788 #[stable(feature = "rust1", since = "1.0.0")]
789 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<'a, T> Clone for Iter<'a, T> {
793 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, marker: self.marker } }
796 #[unstable(feature = "core", reason = "trait is experimental")]
797 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
799 fn indexable(&self) -> usize {
800 let (exact, _) = self.size_hint();
805 fn idx(&mut self, index: usize) -> Option<&'a T> {
807 if index < self.indexable() {
808 if mem::size_of::<T>() == 0 {
809 // Use a non-null pointer value
810 Some(&mut *(1 as *mut _))
812 Some(transmute(self.ptr.offset(index as isize)))
821 /// Mutable slice iterator.
822 #[stable(feature = "rust1", since = "1.0.0")]
823 pub struct IterMut<'a, T: 'a> {
826 marker: marker::ContravariantLifetime<'a>,
830 #[unstable(feature = "core")]
831 impl<'a, T> ops::Index<ops::Range<usize>> for IterMut<'a, T> {
834 fn index(&self, index: &ops::Range<usize>) -> &[T] {
835 self.index(&RangeFull).index(index)
838 #[unstable(feature = "core")]
839 impl<'a, T> ops::Index<ops::RangeTo<usize>> for IterMut<'a, T> {
842 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
843 self.index(&RangeFull).index(index)
846 #[unstable(feature = "core")]
847 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for IterMut<'a, T> {
850 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
851 self.index(&RangeFull).index(index)
854 #[unstable(feature = "core")]
855 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
858 fn index(&self, _index: &RangeFull) -> &[T] {
859 make_slice!(T => &[T]: self.ptr, self.end)
863 #[unstable(feature = "core")]
864 impl<'a, T> ops::IndexMut<ops::Range<usize>> for IterMut<'a, T> {
866 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
867 self.index_mut(&RangeFull).index_mut(index)
870 #[unstable(feature = "core")]
871 impl<'a, T> ops::IndexMut<ops::RangeTo<usize>> for IterMut<'a, T> {
873 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
874 self.index_mut(&RangeFull).index_mut(index)
877 #[unstable(feature = "core")]
878 impl<'a, T> ops::IndexMut<ops::RangeFrom<usize>> for IterMut<'a, T> {
880 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
881 self.index_mut(&RangeFull).index_mut(index)
884 #[unstable(feature = "core")]
885 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
887 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
888 make_slice!(T => &mut [T]: self.ptr, self.end)
893 impl<'a, T> IterMut<'a, T> {
894 /// View the underlying data as a subslice of the original data.
896 /// To avoid creating `&mut` references that alias, this is forced
897 /// to consume the iterator. Consider using the `Slice` and
898 /// `SliceMut` implementations for obtaining slices with more
899 /// restricted lifetimes that do not consume the iterator.
900 #[unstable(feature = "core")]
901 pub fn into_slice(self) -> &'a mut [T] {
902 make_slice!(T => &'a mut [T]: self.ptr, self.end)
906 iterator!{struct IterMut -> *mut T, &'a mut T}
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
911 /// An internal abstraction over the splitting iterators, so that
912 /// splitn, splitn_mut etc can be implemented once.
913 trait SplitIter: DoubleEndedIterator {
914 /// Mark the underlying iterator as complete, extracting the remaining
915 /// portion of the slice.
916 fn finish(&mut self) -> Option<Self::Item>;
919 /// An iterator over subslices separated by elements that match a predicate
921 #[stable(feature = "rust1", since = "1.0.0")]
922 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
928 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
929 #[stable(feature = "rust1", since = "1.0.0")]
930 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
931 fn clone(&self) -> Split<'a, T, P> {
934 pred: self.pred.clone(),
935 finished: self.finished,
940 #[stable(feature = "rust1", since = "1.0.0")]
941 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
945 fn next(&mut self) -> Option<&'a [T]> {
946 if self.finished { return None; }
948 match self.v.iter().position(|x| (self.pred)(x)) {
949 None => self.finish(),
951 let ret = Some(&self.v[..idx]);
952 self.v = &self.v[idx + 1..];
959 fn size_hint(&self) -> (usize, Option<usize>) {
963 (1, Some(self.v.len() + 1))
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
971 fn next_back(&mut self) -> Option<&'a [T]> {
972 if self.finished { return None; }
974 match self.v.iter().rposition(|x| (self.pred)(x)) {
975 None => self.finish(),
977 let ret = Some(&self.v[idx + 1..]);
978 self.v = &self.v[..idx];
985 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
987 fn finish(&mut self) -> Option<&'a [T]> {
988 if self.finished { None } else { self.finished = true; Some(self.v) }
992 /// An iterator over the subslices of the vector which are separated
993 /// by elements that match `pred`.
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1001 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1003 fn finish(&mut self) -> Option<&'a mut [T]> {
1007 self.finished = true;
1008 Some(mem::replace(&mut self.v, &mut []))
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1015 type Item = &'a mut [T];
1018 fn next(&mut self) -> Option<&'a mut [T]> {
1019 if self.finished { return None; }
1021 let idx_opt = { // work around borrowck limitations
1022 let pred = &mut self.pred;
1023 self.v.iter().position(|x| (*pred)(x))
1026 None => self.finish(),
1028 let tmp = mem::replace(&mut self.v, &mut []);
1029 let (head, tail) = tmp.split_at_mut(idx);
1030 self.v = &mut tail[1..];
1037 fn size_hint(&self) -> (usize, Option<usize>) {
1041 // if the predicate doesn't match anything, we yield one slice
1042 // if it matches every element, we yield len+1 empty slices.
1043 (1, Some(self.v.len() + 1))
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1050 P: FnMut(&T) -> bool,
1053 fn next_back(&mut self) -> Option<&'a mut [T]> {
1054 if self.finished { return None; }
1056 let idx_opt = { // work around borrowck limitations
1057 let pred = &mut self.pred;
1058 self.v.iter().rposition(|x| (*pred)(x))
1061 None => self.finish(),
1063 let tmp = mem::replace(&mut self.v, &mut []);
1064 let (head, tail) = tmp.split_at_mut(idx);
1066 Some(&mut tail[1..])
1072 /// An private iterator over subslices separated by elements that
1073 /// match a predicate function, splitting at most a fixed number of
1075 struct GenericSplitN<I> {
1081 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1085 fn next(&mut self) -> Option<T> {
1086 if self.count == 0 {
1090 if self.invert { self.iter.next_back() } else { self.iter.next() }
1095 fn size_hint(&self) -> (usize, Option<usize>) {
1096 let (lower, upper_opt) = self.iter.size_hint();
1097 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1101 /// An iterator over subslices separated by elements that match a predicate
1102 /// function, limited to a given number of splits.
1103 #[stable(feature = "rust1", since = "1.0.0")]
1104 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1105 inner: GenericSplitN<Split<'a, T, P>>
1108 /// An iterator over subslices separated by elements that match a
1109 /// predicate function, limited to a given number of splits, starting
1110 /// from the end of the slice.
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1113 inner: GenericSplitN<Split<'a, T, P>>
1116 /// An iterator over subslices separated by elements that match a predicate
1117 /// function, limited to a given number of splits.
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1120 inner: GenericSplitN<SplitMut<'a, T, P>>
1123 /// An iterator over subslices separated by elements that match a
1124 /// predicate function, limited to a given number of splits, starting
1125 /// from the end of the slice.
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1128 inner: GenericSplitN<SplitMut<'a, T, P>>
1131 macro_rules! forward_iterator {
1132 ($name:ident: $elem:ident, $iter_of:ty) => {
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1135 P: FnMut(&T) -> bool
1137 type Item = $iter_of;
1140 fn next(&mut self) -> Option<$iter_of> {
1145 fn size_hint(&self) -> (usize, Option<usize>) {
1146 self.inner.size_hint()
1152 forward_iterator! { SplitN: T, &'a [T] }
1153 forward_iterator! { RSplitN: T, &'a [T] }
1154 forward_iterator! { SplitNMut: T, &'a mut [T] }
1155 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1157 /// An iterator over overlapping subslices of length `size`.
1159 #[stable(feature = "rust1", since = "1.0.0")]
1160 pub struct Windows<'a, T:'a> {
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 impl<'a, T> Iterator for Windows<'a, T> {
1167 type Item = &'a [T];
1170 fn next(&mut self) -> Option<&'a [T]> {
1171 if self.size > self.v.len() {
1174 let ret = Some(&self.v[..self.size]);
1175 self.v = &self.v[1..];
1181 fn size_hint(&self) -> (usize, Option<usize>) {
1182 if self.size > self.v.len() {
1185 let size = self.v.len() - self.size + 1;
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1194 fn next_back(&mut self) -> Option<&'a [T]> {
1195 if self.size > self.v.len() {
1198 let ret = Some(&self.v[self.v.len()-self.size..]);
1199 self.v = &self.v[..self.v.len()-1];
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1208 #[unstable(feature = "core", reason = "trait is experimental")]
1209 impl<'a, T> RandomAccessIterator for Windows<'a, T> {
1211 fn indexable(&self) -> usize {
1216 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1217 if index + self.size > self.v.len() {
1220 Some(&self.v[index .. index+self.size])
1225 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1228 /// When the slice len is not evenly divided by the chunk size, the last slice
1229 /// of the iteration will be the remainder.
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 pub struct Chunks<'a, T:'a> {
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<'a, T> Iterator for Chunks<'a, T> {
1239 type Item = &'a [T];
1242 fn next(&mut self) -> Option<&'a [T]> {
1243 if self.v.len() == 0 {
1246 let chunksz = cmp::min(self.v.len(), self.size);
1247 let (fst, snd) = self.v.split_at(chunksz);
1254 fn size_hint(&self) -> (usize, Option<usize>) {
1255 if self.v.len() == 0 {
1258 let n = self.v.len() / self.size;
1259 let rem = self.v.len() % self.size;
1260 let n = if rem > 0 { n+1 } else { n };
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1269 fn next_back(&mut self) -> Option<&'a [T]> {
1270 if self.v.len() == 0 {
1273 let remainder = self.v.len() % self.size;
1274 let chunksz = if remainder != 0 { remainder } else { self.size };
1275 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1285 #[unstable(feature = "core", reason = "trait is experimental")]
1286 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1288 fn indexable(&self) -> usize {
1289 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1293 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1294 if index < self.indexable() {
1295 let lo = index * self.size;
1296 let mut hi = lo + self.size;
1297 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1299 Some(&self.v[lo..hi])
1306 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1307 /// elements at a time). When the slice len is not evenly divided by the chunk
1308 /// size, the last slice of the iteration will be the remainder.
1309 #[stable(feature = "rust1", since = "1.0.0")]
1310 pub struct ChunksMut<'a, T:'a> {
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<'a, T> Iterator for ChunksMut<'a, T> {
1317 type Item = &'a mut [T];
1320 fn next(&mut self) -> Option<&'a mut [T]> {
1321 if self.v.len() == 0 {
1324 let sz = cmp::min(self.v.len(), self.chunk_size);
1325 let tmp = mem::replace(&mut self.v, &mut []);
1326 let (head, tail) = tmp.split_at_mut(sz);
1333 fn size_hint(&self) -> (usize, Option<usize>) {
1334 if self.v.len() == 0 {
1337 let n = self.v.len() / self.chunk_size;
1338 let rem = self.v.len() % self.chunk_size;
1339 let n = if rem > 0 { n + 1 } else { n };
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1348 fn next_back(&mut self) -> Option<&'a mut [T]> {
1349 if self.v.len() == 0 {
1352 let remainder = self.v.len() % self.chunk_size;
1353 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1354 let tmp = mem::replace(&mut self.v, &mut []);
1355 let tmp_len = tmp.len();
1356 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1370 /// Converts a pointer to A into a slice of length 1 (without copying).
1371 #[unstable(feature = "core")]
1372 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1374 transmute(RawSlice { data: s, len: 1 })
1378 /// Converts a pointer to A into a slice of length 1 (without copying).
1379 #[unstable(feature = "core")]
1380 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1382 let ptr: *const A = transmute(s);
1383 transmute(RawSlice { data: ptr, len: 1 })
1387 /// Forms a slice from a pointer and a length.
1389 /// The `len` argument is the number of **elements**, not the number of bytes.
1391 /// This function is unsafe as there is no guarantee that the given pointer is
1392 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1393 /// lifetime for the returned slice.
1397 /// The lifetime for the returned slice is inferred from its usage. To
1398 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1399 /// source lifetime is safe in the context, such as by providing a helper
1400 /// function taking the lifetime of a host value for the slice, or by explicit
1408 /// // manifest a slice out of thin air!
1409 /// let ptr = 0x1234 as *const usize;
1412 /// let slice = slice::from_raw_parts(ptr, amt);
1416 #[unstable(feature = "core")]
1417 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1418 transmute(RawSlice { data: p, len: len })
1421 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1422 /// slice is returned.
1424 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1425 /// as not being able to provide a non-aliasing guarantee of the returned
1428 #[unstable(feature = "core")]
1429 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1430 transmute(RawSlice { data: p, len: len })
1433 /// Forms a slice from a pointer and a length.
1435 /// The pointer given is actually a reference to the base of the slice. This
1436 /// reference is used to give a concrete lifetime to tie the returned slice to.
1437 /// Typically this should indicate that the slice is valid for as long as the
1438 /// pointer itself is valid.
1440 /// The `len` argument is the number of **elements**, not the number of bytes.
1442 /// This function is unsafe as there is no guarantee that the given pointer is
1443 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1444 /// lifetime for the returned slice.
1451 /// // manifest a slice out of thin air!
1452 /// let ptr = 0x1234 as *const usize;
1455 /// let slice = slice::from_raw_buf(&ptr, amt);
1459 #[unstable(feature = "core")]
1460 #[deprecated(since = "1.0.0",
1461 reason = "use from_raw_parts")]
1462 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: usize) -> &'a [T] {
1463 transmute(RawSlice { data: *p, len: len })
1466 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1467 /// slice is returned.
1469 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1470 /// not being able to provide a non-aliasing guarantee of the returned mutable
1473 #[unstable(feature = "core")]
1474 #[deprecated(since = "1.0.0",
1475 reason = "use from_raw_parts_mut")]
1476 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: usize) -> &'a mut [T] {
1477 transmute(RawSlice { data: *p, len: len })
1484 /// Operations on `[u8]`.
1485 #[unstable(feature = "core", reason = "needs review")]
1488 use slice::SliceExt;
1490 /// A trait for operations on mutable `[u8]`s.
1491 pub trait MutableByteVector {
1492 /// Sets all bytes of the receiver to the given value.
1493 fn set_memory(&mut self, value: u8);
1496 impl MutableByteVector for [u8] {
1498 fn set_memory(&mut self, value: u8) {
1499 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1503 /// Copies data from `src` to `dst`
1505 /// Panics if the length of `dst` is less than the length of `src`.
1507 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1508 let len_src = src.len();
1509 assert!(dst.len() >= len_src);
1510 // `dst` is unaliasable, so we know statically it doesn't overlap
1513 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1523 // Boilerplate traits
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1528 fn eq(&self, other: &[B]) -> bool {
1529 self.len() == other.len() &&
1530 order::eq(self.iter(), other.iter())
1532 fn ne(&self, other: &[B]) -> bool {
1533 self.len() != other.len() ||
1534 order::ne(self.iter(), other.iter())
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl<T: Eq> Eq for [T] {}
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl<T: Ord> Ord for [T] {
1543 fn cmp(&self, other: &[T]) -> Ordering {
1544 order::cmp(self.iter(), other.iter())
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<T: PartialOrd> PartialOrd for [T] {
1551 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1552 order::partial_cmp(self.iter(), other.iter())
1555 fn lt(&self, other: &[T]) -> bool {
1556 order::lt(self.iter(), other.iter())
1559 fn le(&self, other: &[T]) -> bool {
1560 order::le(self.iter(), other.iter())
1563 fn ge(&self, other: &[T]) -> bool {
1564 order::ge(self.iter(), other.iter())
1567 fn gt(&self, other: &[T]) -> bool {
1568 order::gt(self.iter(), other.iter())
1572 /// Extension methods for slices containing integers.
1573 #[unstable(feature = "core")]
1574 pub trait IntSliceExt<U, S> {
1575 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1576 fn as_unsigned<'a>(&'a self) -> &'a [U];
1577 /// Converts the slice to an immutable slice of signed integers with the same width.
1578 fn as_signed<'a>(&'a self) -> &'a [S];
1580 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1581 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1582 /// Converts the slice to a mutable slice of signed integers with the same width.
1583 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1586 macro_rules! impl_int_slice {
1587 ($u:ty, $s:ty, $t:ty) => {
1588 #[unstable(feature = "core")]
1589 impl IntSliceExt<$u, $s> for [$t] {
1591 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1593 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1595 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1597 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1602 macro_rules! impl_int_slices {
1604 impl_int_slice! { $u, $s, $u }
1605 impl_int_slice! { $u, $s, $s }
1609 impl_int_slices! { u8, i8 }
1610 impl_int_slices! { u16, i16 }
1611 impl_int_slices! { u32, i32 }
1612 impl_int_slices! { u64, i64 }
1613 impl_int_slices! { usize, isize }