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};
43 use intrinsics::assume;
45 use ops::{FnMut, self, Index};
48 use option::Option::{None, Some};
50 use result::Result::{Ok, Err};
55 use marker::{Send, Sized, Sync, self};
57 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
58 use raw::Slice as RawSlice;
65 /// Extension methods for slices.
66 #[allow(missing_docs)] // docs in libcollections
70 fn split_at<'a>(&'a self, mid: usize) -> (&'a [Self::Item], &'a [Self::Item]);
71 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
72 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
73 where P: FnMut(&Self::Item) -> bool;
74 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, Self::Item, P>
75 where P: FnMut(&Self::Item) -> bool;
76 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, Self::Item, P>
77 where P: FnMut(&Self::Item) -> bool;
78 fn windows<'a>(&'a self, size: usize) -> Windows<'a, Self::Item>;
79 fn chunks<'a>(&'a self, size: usize) -> Chunks<'a, Self::Item>;
80 fn get<'a>(&'a self, index: usize) -> Option<&'a Self::Item>;
81 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
82 fn tail<'a>(&'a self) -> &'a [Self::Item];
83 fn init<'a>(&'a self) -> &'a [Self::Item];
84 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
85 unsafe fn get_unchecked<'a>(&'a self, index: usize) -> &'a Self::Item;
86 fn as_ptr(&self) -> *const Self::Item;
87 fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where
88 F: FnMut(&Self::Item) -> Ordering;
89 fn len(&self) -> usize;
90 fn is_empty(&self) -> bool { self.len() == 0 }
91 fn get_mut<'a>(&'a mut self, index: usize) -> Option<&'a mut Self::Item>;
92 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item];
93 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
94 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
95 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
96 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
97 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
98 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
99 where P: FnMut(&Self::Item) -> bool;
100 fn splitn_mut<P>(&mut self, n: usize, pred: P) -> SplitNMut<Self::Item, P>
101 where P: FnMut(&Self::Item) -> bool;
102 fn rsplitn_mut<P>(&mut self, n: usize, pred: P) -> RSplitNMut<Self::Item, P>
103 where P: FnMut(&Self::Item) -> bool;
104 fn chunks_mut<'a>(&'a mut self, chunk_size: usize) -> ChunksMut<'a, Self::Item>;
105 fn swap(&mut self, a: usize, b: usize);
106 fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
107 fn reverse(&mut self);
108 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Item;
109 fn as_mut_ptr(&mut self) -> *mut Self::Item;
111 fn position_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
113 fn rposition_elem(&self, t: &Self::Item) -> Option<usize> where Self::Item: PartialEq;
115 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
117 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
119 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
121 fn binary_search(&self, x: &Self::Item) -> Result<usize, usize> where Self::Item: Ord;
122 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
123 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
125 fn clone_from_slice(&mut self, &[Self::Item]) -> usize where Self::Item: Clone;
128 #[unstable(feature = "core")]
129 impl<T> SliceExt for [T] {
133 fn split_at(&self, mid: usize) -> (&[T], &[T]) {
134 (&self[..mid], &self[mid..])
138 fn iter<'a>(&'a self) -> Iter<'a, T> {
140 let p = self.as_ptr();
141 assume(!p.is_null());
142 if mem::size_of::<T>() == 0 {
144 end: (p as usize + self.len()) as *const T,
145 _marker: marker::PhantomData}
148 end: p.offset(self.len() as isize),
149 _marker: marker::PhantomData}
155 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
164 fn splitn<'a, P>(&'a self, n: usize, pred: P) -> SplitN<'a, T, P> where
165 P: FnMut(&T) -> bool,
168 inner: GenericSplitN {
169 iter: self.split(pred),
177 fn rsplitn<'a, P>(&'a self, n: usize, pred: P) -> RSplitN<'a, T, P> where
178 P: FnMut(&T) -> bool,
181 inner: GenericSplitN {
182 iter: self.split(pred),
190 fn windows(&self, size: usize) -> Windows<T> {
192 Windows { v: self, size: size }
196 fn chunks(&self, size: usize) -> Chunks<T> {
198 Chunks { v: self, size: size }
202 fn get(&self, index: usize) -> Option<&T> {
203 if index < self.len() { Some(&self[index]) } else { None }
207 fn first(&self) -> Option<&T> {
208 if self.len() == 0 { None } else { Some(&self[0]) }
212 fn tail(&self) -> &[T] { &self[1..] }
215 fn init(&self) -> &[T] {
216 &self[..self.len() - 1]
220 fn last(&self) -> Option<&T> {
221 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
225 unsafe fn get_unchecked(&self, index: usize) -> &T {
226 transmute(self.repr().data.offset(index as isize))
230 fn as_ptr(&self) -> *const T {
234 #[unstable(feature = "core")]
235 fn binary_search_by<F>(&self, mut f: F) -> Result<usize, usize> where
236 F: FnMut(&T) -> Ordering
238 let mut base : usize = 0;
239 let mut lim : usize = self.len();
242 let ix = base + (lim >> 1);
244 Equal => return Ok(ix),
257 fn len(&self) -> usize { self.repr().len }
260 fn get_mut(&mut self, index: usize) -> Option<&mut T> {
261 if index < self.len() { Some(&mut self[index]) } else { None }
265 fn as_mut_slice(&mut self) -> &mut [T] { self }
268 fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) {
270 let self2: &mut [T] = mem::transmute_copy(&self);
272 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
273 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
278 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
280 let p = self.as_mut_ptr();
281 assume(!p.is_null());
282 if mem::size_of::<T>() == 0 {
284 end: (p as usize + self.len()) as *mut T,
285 _marker: marker::PhantomData}
288 end: p.offset(self.len() as isize),
289 _marker: marker::PhantomData}
295 fn last_mut(&mut self) -> Option<&mut T> {
296 let len = self.len();
297 if len == 0 { return None; }
298 Some(&mut self[len - 1])
302 fn first_mut(&mut self) -> Option<&mut T> {
303 if self.len() == 0 { None } else { Some(&mut self[0]) }
307 fn tail_mut(&mut self) -> &mut [T] {
312 fn init_mut(&mut self) -> &mut [T] {
313 let len = self.len();
314 &mut self[.. (len - 1)]
318 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
319 SplitMut { v: self, pred: pred, finished: false }
323 fn splitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> SplitNMut<'a, T, P> where
327 inner: GenericSplitN {
328 iter: self.split_mut(pred),
336 fn rsplitn_mut<'a, P>(&'a mut self, n: usize, pred: P) -> RSplitNMut<'a, T, P> where
337 P: FnMut(&T) -> bool,
340 inner: GenericSplitN {
341 iter: self.split_mut(pred),
349 fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T> {
350 assert!(chunk_size > 0);
351 ChunksMut { v: self, chunk_size: chunk_size }
355 fn swap(&mut self, a: usize, b: usize) {
357 // Can't take two mutable loans from one vector, so instead just cast
358 // them to their raw pointers to do the swap
359 let pa: *mut T = &mut self[a];
360 let pb: *mut T = &mut self[b];
365 fn reverse(&mut self) {
366 let mut i: usize = 0;
369 // Unsafe swap to avoid the bounds check in safe swap.
371 let pa: *mut T = self.get_unchecked_mut(i);
372 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
380 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
381 transmute((self.repr().data as *mut T).offset(index as isize))
385 fn as_mut_ptr(&mut self) -> *mut T {
386 self.repr().data as *mut T
390 fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
391 self.iter().position(|y| *x == *y)
395 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
396 self.iter().rposition(|x| *x == *t)
400 fn contains(&self, x: &T) -> bool where T: PartialEq {
401 self.iter().any(|elt| *x == *elt)
405 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
406 let n = needle.len();
407 self.len() >= n && needle == &self[..n]
411 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
412 let (m, n) = (self.len(), needle.len());
413 m >= n && needle == &self[m-n..]
416 #[unstable(feature = "core")]
417 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
418 self.binary_search_by(|p| p.cmp(x))
421 #[unstable(feature = "core")]
422 fn next_permutation(&mut self) -> bool where T: Ord {
423 // These cases only have 1 permutation each, so we can't do anything.
424 if self.len() < 2 { return false; }
426 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
427 let mut i = self.len() - 1;
428 while i > 0 && self[i-1] >= self[i] {
432 // If that is the entire vector, this is the last-ordered permutation.
437 // Step 2: Find the rightmost element larger than the pivot (i-1)
438 let mut j = self.len() - 1;
439 while j >= i && self[j] <= self[i-1] {
443 // Step 3: Swap that element with the pivot
446 // Step 4: Reverse the (previously) weakly decreasing part
452 #[unstable(feature = "core")]
453 fn prev_permutation(&mut self) -> bool where T: Ord {
454 // These cases only have 1 permutation each, so we can't do anything.
455 if self.len() < 2 { return false; }
457 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
458 let mut i = self.len() - 1;
459 while i > 0 && self[i-1] <= self[i] {
463 // If that is the entire vector, this is the first-ordered permutation.
468 // Step 2: Reverse the weakly increasing part
471 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
472 let mut j = self.len() - 1;
473 while j >= i && self[j-1] < self[i-1] {
477 // Step 4: Swap that element with the pivot
484 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
485 let min = cmp::min(self.len(), src.len());
486 let dst = &mut self[.. min];
487 let src = &src[.. min];
489 dst[i].clone_from(&src[i]);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl<T> ops::Index<usize> for [T] {
499 fn index(&self, &index: &usize) -> &T {
500 assert!(index < self.len());
502 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl<T> ops::IndexMut<usize> for [T] {
508 fn index_mut(&mut self, &index: &usize) -> &mut T {
509 assert!(index < self.len());
511 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<T> ops::Index<ops::Range<usize>> for [T] {
519 fn index(&self, index: &ops::Range<usize>) -> &[T] {
520 assert!(index.start <= index.end);
521 assert!(index.end <= self.len());
524 data: self.as_ptr().offset(index.start as isize),
525 len: index.end - index.start
530 #[stable(feature = "rust1", since = "1.0.0")]
531 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
534 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
535 self.index(&ops::Range{ start: 0, end: index.end })
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
542 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
543 self.index(&ops::Range{ start: index.start, end: self.len() })
546 #[stable(feature = "rust1", since = "1.0.0")]
547 impl<T> ops::Index<RangeFull> for [T] {
550 fn index(&self, _index: &RangeFull) -> &[T] {
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
558 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
559 assert!(index.start <= index.end);
560 assert!(index.end <= self.len());
563 data: self.as_ptr().offset(index.start as isize),
564 len: index.end - index.start
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
572 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
573 self.index_mut(&ops::Range{ start: 0, end: index.end })
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
579 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
580 let len = self.len();
581 self.index_mut(&ops::Range{ start: index.start, end: len })
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl<T> ops::IndexMut<RangeFull> for [T] {
587 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
593 ////////////////////////////////////////////////////////////////////////////////
595 ////////////////////////////////////////////////////////////////////////////////
597 /// Data that is viewable as a slice.
598 #[unstable(feature = "core",
599 reason = "will be replaced by slice syntax")]
600 pub trait AsSlice<T> {
601 /// Work with `self` as a slice.
602 fn as_slice<'a>(&'a self) -> &'a [T];
605 #[unstable(feature = "core", reason = "trait is experimental")]
606 impl<T> AsSlice<T> for [T] {
608 fn as_slice<'a>(&'a self) -> &'a [T] { self }
611 #[unstable(feature = "core", reason = "trait is experimental")]
612 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
614 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
617 #[unstable(feature = "core", reason = "trait is experimental")]
618 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
620 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl<'a, T> Default for &'a [T] {
625 #[stable(feature = "rust1", since = "1.0.0")]
626 fn default() -> &'a [T] { &[] }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<'a, T> IntoIterator for &'a [T] {
636 type IntoIter = Iter<'a, T>;
638 fn into_iter(self) -> Iter<'a, T> {
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<'a, T> IntoIterator for &'a mut [T] {
645 type Item = &'a mut T;
646 type IntoIter = IterMut<'a, T>;
648 fn into_iter(self) -> IterMut<'a, T> {
653 // The shared definition of the `Iter` and `IterMut` iterators
654 macro_rules! iterator {
655 (struct $name:ident -> $ptr:ty, $elem:ty) => {
656 #[stable(feature = "rust1", since = "1.0.0")]
657 impl<'a, T> Iterator for $name<'a, T> {
661 fn next(&mut self) -> Option<$elem> {
662 // could be implemented with slices, but this avoids bounds checks
664 ::intrinsics::assume(!self.ptr.is_null());
665 ::intrinsics::assume(!self.end.is_null());
666 if self.ptr == self.end {
669 if mem::size_of::<T>() == 0 {
670 // purposefully don't use 'ptr.offset' because for
671 // vectors with 0-size elements this would return the
673 self.ptr = transmute(self.ptr as usize + 1);
675 // Use a non-null pointer value
676 Some(&mut *(1 as *mut _))
679 self.ptr = self.ptr.offset(1);
688 fn size_hint(&self) -> (usize, Option<usize>) {
689 let diff = (self.end as usize) - (self.ptr as usize);
690 let size = mem::size_of::<T>();
691 let exact = diff / (if size == 0 {1} else {size});
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
699 fn next_back(&mut self) -> Option<$elem> {
700 // could be implemented with slices, but this avoids bounds checks
702 ::intrinsics::assume(!self.ptr.is_null());
703 ::intrinsics::assume(!self.end.is_null());
704 if self.end == self.ptr {
707 if mem::size_of::<T>() == 0 {
708 // See above for why 'ptr.offset' isn't used
709 self.end = transmute(self.end as usize - 1);
711 // Use a non-null pointer value
712 Some(&mut *(1 as *mut _))
714 self.end = self.end.offset(-1);
716 Some(transmute(self.end))
725 macro_rules! make_slice {
726 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
727 let diff = $end as usize - $start as usize;
728 let len = if mem::size_of::<T>() == 0 {
731 diff / mem::size_of::<$t>()
734 transmute::<_, $result>(RawSlice { data: $start, len: len })
739 /// Immutable slice iterator
740 #[stable(feature = "rust1", since = "1.0.0")]
741 pub struct Iter<'a, T: 'a> {
744 _marker: marker::PhantomData<&'a T>,
747 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
748 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
750 #[unstable(feature = "core")]
751 impl<'a, T> ops::Index<ops::Range<usize>> for Iter<'a, T> {
754 fn index(&self, index: &ops::Range<usize>) -> &[T] {
755 self.as_slice().index(index)
759 #[unstable(feature = "core")]
760 impl<'a, T> ops::Index<ops::RangeTo<usize>> for Iter<'a, T> {
763 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
764 self.as_slice().index(index)
768 #[unstable(feature = "core")]
769 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for Iter<'a, T> {
772 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
773 self.as_slice().index(index)
777 #[unstable(feature = "core")]
778 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
781 fn index(&self, _index: &RangeFull) -> &[T] {
786 impl<'a, T> Iter<'a, T> {
787 /// View the underlying data as a subslice of the original data.
789 /// This has the same lifetime as the original slice, and so the
790 /// iterator can continue to be used while this exists.
791 #[unstable(feature = "core")]
792 pub fn as_slice(&self) -> &'a [T] {
793 make_slice!(T => &'a [T]: self.ptr, self.end)
797 iterator!{struct Iter -> *const T, &'a T}
799 #[stable(feature = "rust1", since = "1.0.0")]
800 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl<'a, T> Clone for Iter<'a, T> {
804 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
807 #[unstable(feature = "core", reason = "trait is experimental")]
808 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
810 fn indexable(&self) -> usize {
811 let (exact, _) = self.size_hint();
816 fn idx(&mut self, index: usize) -> Option<&'a T> {
818 if index < self.indexable() {
819 if mem::size_of::<T>() == 0 {
820 // Use a non-null pointer value
821 Some(&mut *(1 as *mut _))
823 Some(transmute(self.ptr.offset(index as isize)))
832 /// Mutable slice iterator.
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub struct IterMut<'a, T: 'a> {
837 _marker: marker::PhantomData<&'a mut T>,
840 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
841 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
843 #[unstable(feature = "core")]
844 impl<'a, T> ops::Index<ops::Range<usize>> for IterMut<'a, T> {
847 fn index(&self, index: &ops::Range<usize>) -> &[T] {
848 self.index(&RangeFull).index(index)
851 #[unstable(feature = "core")]
852 impl<'a, T> ops::Index<ops::RangeTo<usize>> for IterMut<'a, T> {
855 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
856 self.index(&RangeFull).index(index)
859 #[unstable(feature = "core")]
860 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for IterMut<'a, T> {
863 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
864 self.index(&RangeFull).index(index)
867 #[unstable(feature = "core")]
868 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
871 fn index(&self, _index: &RangeFull) -> &[T] {
872 make_slice!(T => &[T]: self.ptr, self.end)
876 #[unstable(feature = "core")]
877 impl<'a, T> ops::IndexMut<ops::Range<usize>> for IterMut<'a, T> {
879 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
880 self.index_mut(&RangeFull).index_mut(index)
883 #[unstable(feature = "core")]
884 impl<'a, T> ops::IndexMut<ops::RangeTo<usize>> for IterMut<'a, T> {
886 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
887 self.index_mut(&RangeFull).index_mut(index)
890 #[unstable(feature = "core")]
891 impl<'a, T> ops::IndexMut<ops::RangeFrom<usize>> for IterMut<'a, T> {
893 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
894 self.index_mut(&RangeFull).index_mut(index)
897 #[unstable(feature = "core")]
898 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
900 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
901 make_slice!(T => &mut [T]: self.ptr, self.end)
906 impl<'a, T> IterMut<'a, T> {
907 /// View the underlying data as a subslice of the original data.
909 /// To avoid creating `&mut` references that alias, this is forced
910 /// to consume the iterator. Consider using the `Slice` and
911 /// `SliceMut` implementations for obtaining slices with more
912 /// restricted lifetimes that do not consume the iterator.
913 #[unstable(feature = "core")]
914 pub fn into_slice(self) -> &'a mut [T] {
915 make_slice!(T => &'a mut [T]: self.ptr, self.end)
919 iterator!{struct IterMut -> *mut T, &'a mut T}
921 #[stable(feature = "rust1", since = "1.0.0")]
922 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
924 /// An internal abstraction over the splitting iterators, so that
925 /// splitn, splitn_mut etc can be implemented once.
926 trait SplitIter: DoubleEndedIterator {
927 /// Mark the underlying iterator as complete, extracting the remaining
928 /// portion of the slice.
929 fn finish(&mut self) -> Option<Self::Item>;
932 /// An iterator over subslices separated by elements that match a predicate
934 #[stable(feature = "rust1", since = "1.0.0")]
935 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
941 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
944 fn clone(&self) -> Split<'a, T, P> {
947 pred: self.pred.clone(),
948 finished: self.finished,
953 #[stable(feature = "rust1", since = "1.0.0")]
954 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
958 fn next(&mut self) -> Option<&'a [T]> {
959 if self.finished { return None; }
961 match self.v.iter().position(|x| (self.pred)(x)) {
962 None => self.finish(),
964 let ret = Some(&self.v[..idx]);
965 self.v = &self.v[idx + 1..];
972 fn size_hint(&self) -> (usize, Option<usize>) {
976 (1, Some(self.v.len() + 1))
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
984 fn next_back(&mut self) -> Option<&'a [T]> {
985 if self.finished { return None; }
987 match self.v.iter().rposition(|x| (self.pred)(x)) {
988 None => self.finish(),
990 let ret = Some(&self.v[idx + 1..]);
991 self.v = &self.v[..idx];
998 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1000 fn finish(&mut self) -> Option<&'a [T]> {
1001 if self.finished { None } else { self.finished = true; Some(self.v) }
1005 /// An iterator over the subslices of the vector which are separated
1006 /// by elements that match `pred`.
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1014 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1016 fn finish(&mut self) -> Option<&'a mut [T]> {
1020 self.finished = true;
1021 Some(mem::replace(&mut self.v, &mut []))
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1028 type Item = &'a mut [T];
1031 fn next(&mut self) -> Option<&'a mut [T]> {
1032 if self.finished { return None; }
1034 let idx_opt = { // work around borrowck limitations
1035 let pred = &mut self.pred;
1036 self.v.iter().position(|x| (*pred)(x))
1039 None => self.finish(),
1041 let tmp = mem::replace(&mut self.v, &mut []);
1042 let (head, tail) = tmp.split_at_mut(idx);
1043 self.v = &mut tail[1..];
1050 fn size_hint(&self) -> (usize, Option<usize>) {
1054 // if the predicate doesn't match anything, we yield one slice
1055 // if it matches every element, we yield len+1 empty slices.
1056 (1, Some(self.v.len() + 1))
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1063 P: FnMut(&T) -> bool,
1066 fn next_back(&mut self) -> Option<&'a mut [T]> {
1067 if self.finished { return None; }
1069 let idx_opt = { // work around borrowck limitations
1070 let pred = &mut self.pred;
1071 self.v.iter().rposition(|x| (*pred)(x))
1074 None => self.finish(),
1076 let tmp = mem::replace(&mut self.v, &mut []);
1077 let (head, tail) = tmp.split_at_mut(idx);
1079 Some(&mut tail[1..])
1085 /// An private iterator over subslices separated by elements that
1086 /// match a predicate function, splitting at most a fixed number of
1088 struct GenericSplitN<I> {
1094 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1098 fn next(&mut self) -> Option<T> {
1099 if self.count == 0 {
1103 if self.invert { self.iter.next_back() } else { self.iter.next() }
1108 fn size_hint(&self) -> (usize, Option<usize>) {
1109 let (lower, upper_opt) = self.iter.size_hint();
1110 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1114 /// An iterator over subslices separated by elements that match a predicate
1115 /// function, limited to a given number of splits.
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1118 inner: GenericSplitN<Split<'a, T, P>>
1121 /// An iterator over subslices separated by elements that match a
1122 /// predicate function, limited to a given number of splits, starting
1123 /// from the end of the slice.
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1126 inner: GenericSplitN<Split<'a, T, P>>
1129 /// An iterator over subslices separated by elements that match a predicate
1130 /// function, limited to a given number of splits.
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1133 inner: GenericSplitN<SplitMut<'a, T, P>>
1136 /// An iterator over subslices separated by elements that match a
1137 /// predicate function, limited to a given number of splits, starting
1138 /// from the end of the slice.
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1141 inner: GenericSplitN<SplitMut<'a, T, P>>
1144 macro_rules! forward_iterator {
1145 ($name:ident: $elem:ident, $iter_of:ty) => {
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1148 P: FnMut(&T) -> bool
1150 type Item = $iter_of;
1153 fn next(&mut self) -> Option<$iter_of> {
1158 fn size_hint(&self) -> (usize, Option<usize>) {
1159 self.inner.size_hint()
1165 forward_iterator! { SplitN: T, &'a [T] }
1166 forward_iterator! { RSplitN: T, &'a [T] }
1167 forward_iterator! { SplitNMut: T, &'a mut [T] }
1168 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1170 /// An iterator over overlapping subslices of length `size`.
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub struct Windows<'a, T:'a> {
1177 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<'a, T> Clone for Windows<'a, T> {
1180 fn clone(&self) -> Windows<'a, T> {
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 impl<'a, T> Iterator for Windows<'a, T> {
1190 type Item = &'a [T];
1193 fn next(&mut self) -> Option<&'a [T]> {
1194 if self.size > self.v.len() {
1197 let ret = Some(&self.v[..self.size]);
1198 self.v = &self.v[1..];
1204 fn size_hint(&self) -> (usize, Option<usize>) {
1205 if self.size > self.v.len() {
1208 let size = self.v.len() - self.size + 1;
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1217 fn next_back(&mut self) -> Option<&'a [T]> {
1218 if self.size > self.v.len() {
1221 let ret = Some(&self.v[self.v.len()-self.size..]);
1222 self.v = &self.v[..self.v.len()-1];
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1231 #[unstable(feature = "core", reason = "trait is experimental")]
1232 impl<'a, T> RandomAccessIterator for Windows<'a, T> {
1234 fn indexable(&self) -> usize {
1239 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1240 if index + self.size > self.v.len() {
1243 Some(&self.v[index .. index+self.size])
1248 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1251 /// When the slice len is not evenly divided by the chunk size, the last slice
1252 /// of the iteration will be the remainder.
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 pub struct Chunks<'a, T:'a> {
1259 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl<'a, T> Clone for Chunks<'a, T> {
1262 fn clone(&self) -> Chunks<'a, T> {
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 impl<'a, T> Iterator for Chunks<'a, T> {
1272 type Item = &'a [T];
1275 fn next(&mut self) -> Option<&'a [T]> {
1276 if self.v.len() == 0 {
1279 let chunksz = cmp::min(self.v.len(), self.size);
1280 let (fst, snd) = self.v.split_at(chunksz);
1287 fn size_hint(&self) -> (usize, Option<usize>) {
1288 if self.v.len() == 0 {
1291 let n = self.v.len() / self.size;
1292 let rem = self.v.len() % self.size;
1293 let n = if rem > 0 { n+1 } else { n };
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1302 fn next_back(&mut self) -> Option<&'a [T]> {
1303 if self.v.len() == 0 {
1306 let remainder = self.v.len() % self.size;
1307 let chunksz = if remainder != 0 { remainder } else { self.size };
1308 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1318 #[unstable(feature = "core", reason = "trait is experimental")]
1319 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1321 fn indexable(&self) -> usize {
1322 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1326 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1327 if index < self.indexable() {
1328 let lo = index * self.size;
1329 let mut hi = lo + self.size;
1330 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1332 Some(&self.v[lo..hi])
1339 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1340 /// elements at a time). When the slice len is not evenly divided by the chunk
1341 /// size, the last slice of the iteration will be the remainder.
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 pub struct ChunksMut<'a, T:'a> {
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<'a, T> Iterator for ChunksMut<'a, T> {
1350 type Item = &'a mut [T];
1353 fn next(&mut self) -> Option<&'a mut [T]> {
1354 if self.v.len() == 0 {
1357 let sz = cmp::min(self.v.len(), self.chunk_size);
1358 let tmp = mem::replace(&mut self.v, &mut []);
1359 let (head, tail) = tmp.split_at_mut(sz);
1366 fn size_hint(&self) -> (usize, Option<usize>) {
1367 if self.v.len() == 0 {
1370 let n = self.v.len() / self.chunk_size;
1371 let rem = self.v.len() % self.chunk_size;
1372 let n = if rem > 0 { n + 1 } else { n };
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1381 fn next_back(&mut self) -> Option<&'a mut [T]> {
1382 if self.v.len() == 0 {
1385 let remainder = self.v.len() % self.chunk_size;
1386 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1387 let tmp = mem::replace(&mut self.v, &mut []);
1388 let tmp_len = tmp.len();
1389 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1396 #[stable(feature = "rust1", since = "1.0.0")]
1397 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1403 /// Converts a pointer to A into a slice of length 1 (without copying).
1404 #[unstable(feature = "core")]
1405 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1407 transmute(RawSlice { data: s, len: 1 })
1411 /// Converts a pointer to A into a slice of length 1 (without copying).
1412 #[unstable(feature = "core")]
1413 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1415 let ptr: *const A = transmute(s);
1416 transmute(RawSlice { data: ptr, len: 1 })
1420 /// Forms a slice from a pointer and a length.
1422 /// The `len` argument is the number of **elements**, not the number of bytes.
1424 /// This function is unsafe as there is no guarantee that the given pointer is
1425 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1426 /// lifetime for the returned slice.
1430 /// The lifetime for the returned slice is inferred from its usage. To
1431 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1432 /// source lifetime is safe in the context, such as by providing a helper
1433 /// function taking the lifetime of a host value for the slice, or by explicit
1441 /// // manifest a slice out of thin air!
1442 /// let ptr = 0x1234 as *const usize;
1445 /// let slice = slice::from_raw_parts(ptr, amt);
1449 #[unstable(feature = "core")]
1450 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1451 transmute(RawSlice { data: p, len: len })
1454 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1455 /// slice is returned.
1457 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1458 /// as not being able to provide a non-aliasing guarantee of the returned
1461 #[unstable(feature = "core")]
1462 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1463 transmute(RawSlice { data: p, len: len })
1466 /// Forms a slice from a pointer and a length.
1468 /// The pointer given is actually a reference to the base of the slice. This
1469 /// reference is used to give a concrete lifetime to tie the returned slice to.
1470 /// Typically this should indicate that the slice is valid for as long as the
1471 /// pointer itself is valid.
1473 /// The `len` argument is the number of **elements**, not the number of bytes.
1475 /// This function is unsafe as there is no guarantee that the given pointer is
1476 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1477 /// lifetime for the returned slice.
1484 /// // manifest a slice out of thin air!
1485 /// let ptr = 0x1234 as *const usize;
1488 /// let slice = slice::from_raw_buf(&ptr, amt);
1492 #[unstable(feature = "core")]
1493 #[deprecated(since = "1.0.0",
1494 reason = "use from_raw_parts")]
1495 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: usize) -> &'a [T] {
1496 transmute(RawSlice { data: *p, len: len })
1499 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1500 /// slice is returned.
1502 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1503 /// not being able to provide a non-aliasing guarantee of the returned mutable
1506 #[unstable(feature = "core")]
1507 #[deprecated(since = "1.0.0",
1508 reason = "use from_raw_parts_mut")]
1509 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: usize) -> &'a mut [T] {
1510 transmute(RawSlice { data: *p, len: len })
1517 /// Operations on `[u8]`.
1518 #[unstable(feature = "core", reason = "needs review")]
1521 use slice::SliceExt;
1523 /// A trait for operations on mutable `[u8]`s.
1524 pub trait MutableByteVector {
1525 /// Sets all bytes of the receiver to the given value.
1526 fn set_memory(&mut self, value: u8);
1529 impl MutableByteVector for [u8] {
1531 fn set_memory(&mut self, value: u8) {
1532 unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1536 /// Copies data from `src` to `dst`
1538 /// Panics if the length of `dst` is less than the length of `src`.
1540 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1541 let len_src = src.len();
1542 assert!(dst.len() >= len_src);
1543 // `dst` is unaliasable, so we know statically it doesn't overlap
1546 ptr::copy_nonoverlapping(dst.as_mut_ptr(),
1556 // Boilerplate traits
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1561 fn eq(&self, other: &[B]) -> bool {
1562 self.len() == other.len() &&
1563 order::eq(self.iter(), other.iter())
1565 fn ne(&self, other: &[B]) -> bool {
1566 self.len() != other.len() ||
1567 order::ne(self.iter(), other.iter())
1571 #[stable(feature = "rust1", since = "1.0.0")]
1572 impl<T: Eq> Eq for [T] {}
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<T: Ord> Ord for [T] {
1576 fn cmp(&self, other: &[T]) -> Ordering {
1577 order::cmp(self.iter(), other.iter())
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<T: PartialOrd> PartialOrd for [T] {
1584 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1585 order::partial_cmp(self.iter(), other.iter())
1588 fn lt(&self, other: &[T]) -> bool {
1589 order::lt(self.iter(), other.iter())
1592 fn le(&self, other: &[T]) -> bool {
1593 order::le(self.iter(), other.iter())
1596 fn ge(&self, other: &[T]) -> bool {
1597 order::ge(self.iter(), other.iter())
1600 fn gt(&self, other: &[T]) -> bool {
1601 order::gt(self.iter(), other.iter())
1605 /// Extension methods for slices containing integers.
1606 #[unstable(feature = "core")]
1607 pub trait IntSliceExt<U, S> {
1608 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1609 fn as_unsigned<'a>(&'a self) -> &'a [U];
1610 /// Converts the slice to an immutable slice of signed integers with the same width.
1611 fn as_signed<'a>(&'a self) -> &'a [S];
1613 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1614 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1615 /// Converts the slice to a mutable slice of signed integers with the same width.
1616 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1619 macro_rules! impl_int_slice {
1620 ($u:ty, $s:ty, $t:ty) => {
1621 #[unstable(feature = "core")]
1622 impl IntSliceExt<$u, $s> for [$t] {
1624 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1626 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1628 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1630 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1635 macro_rules! impl_int_slices {
1637 impl_int_slice! { $u, $s, $u }
1638 impl_int_slice! { $u, $s, $s }
1642 impl_int_slices! { u8, i8 }
1643 impl_int_slices! { u16, i16 }
1644 impl_int_slices! { u32, i32 }
1645 impl_int_slices! { u64, i64 }
1646 impl_int_slices! { usize, isize }