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 }
354 fn swap(&mut self, a: usize, b: usize) {
356 // Can't take two mutable loans from one vector, so instead just cast
357 // them to their raw pointers to do the swap
358 let pa: *mut T = &mut self[a];
359 let pb: *mut T = &mut self[b];
364 fn reverse(&mut self) {
365 let mut i: usize = 0;
368 // Unsafe swap to avoid the bounds check in safe swap.
370 let pa: *mut T = self.get_unchecked_mut(i);
371 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
379 unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
380 transmute((self.repr().data as *mut T).offset(index as isize))
384 fn as_mut_ptr(&mut self) -> *mut T {
385 self.repr().data as *mut T
389 fn position_elem(&self, x: &T) -> Option<usize> where T: PartialEq {
390 self.iter().position(|y| *x == *y)
394 fn rposition_elem(&self, t: &T) -> Option<usize> where T: PartialEq {
395 self.iter().rposition(|x| *x == *t)
399 fn contains(&self, x: &T) -> bool where T: PartialEq {
400 self.iter().any(|elt| *x == *elt)
404 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
405 let n = needle.len();
406 self.len() >= n && needle == &self[..n]
410 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
411 let (m, n) = (self.len(), needle.len());
412 m >= n && needle == &self[m-n..]
415 #[unstable(feature = "core")]
416 fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
417 self.binary_search_by(|p| p.cmp(x))
420 #[unstable(feature = "core")]
421 fn next_permutation(&mut self) -> bool where T: Ord {
422 // These cases only have 1 permutation each, so we can't do anything.
423 if self.len() < 2 { return false; }
425 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
426 let mut i = self.len() - 1;
427 while i > 0 && self[i-1] >= self[i] {
431 // If that is the entire vector, this is the last-ordered permutation.
436 // Step 2: Find the rightmost element larger than the pivot (i-1)
437 let mut j = self.len() - 1;
438 while j >= i && self[j] <= self[i-1] {
442 // Step 3: Swap that element with the pivot
445 // Step 4: Reverse the (previously) weakly decreasing part
451 #[unstable(feature = "core")]
452 fn prev_permutation(&mut self) -> bool where T: Ord {
453 // These cases only have 1 permutation each, so we can't do anything.
454 if self.len() < 2 { return false; }
456 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
457 let mut i = self.len() - 1;
458 while i > 0 && self[i-1] <= self[i] {
462 // If that is the entire vector, this is the first-ordered permutation.
467 // Step 2: Reverse the weakly increasing part
470 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
471 let mut j = self.len() - 1;
472 while j >= i && self[j-1] < self[i-1] {
476 // Step 4: Swap that element with the pivot
483 fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone {
484 let min = cmp::min(self.len(), src.len());
485 let dst = &mut self[.. min];
486 let src = &src[.. min];
488 dst[i].clone_from(&src[i]);
494 #[stable(feature = "rust1", since = "1.0.0")]
495 impl<T> ops::Index<usize> for [T] {
498 fn index(&self, &index: &usize) -> &T {
499 assert!(index < self.len());
501 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl<T> ops::IndexMut<usize> for [T] {
507 fn index_mut(&mut self, &index: &usize) -> &mut T {
508 assert!(index < self.len());
510 unsafe { mem::transmute(self.repr().data.offset(index as isize)) }
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T> ops::Index<ops::Range<usize>> for [T] {
518 fn index(&self, index: &ops::Range<usize>) -> &[T] {
519 assert!(index.start <= index.end);
520 assert!(index.end <= self.len());
523 data: self.as_ptr().offset(index.start as isize),
524 len: index.end - index.start
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<T> ops::Index<ops::RangeTo<usize>> for [T] {
533 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
534 self.index(&ops::Range{ start: 0, end: index.end })
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T> ops::Index<ops::RangeFrom<usize>> for [T] {
541 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
542 self.index(&ops::Range{ start: index.start, end: self.len() })
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T> ops::Index<RangeFull> for [T] {
549 fn index(&self, _index: &RangeFull) -> &[T] {
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl<T> ops::IndexMut<ops::Range<usize>> for [T] {
557 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
558 assert!(index.start <= index.end);
559 assert!(index.end <= self.len());
562 data: self.as_ptr().offset(index.start as isize),
563 len: index.end - index.start
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl<T> ops::IndexMut<ops::RangeTo<usize>> for [T] {
571 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
572 self.index_mut(&ops::Range{ start: 0, end: index.end })
575 #[stable(feature = "rust1", since = "1.0.0")]
576 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for [T] {
578 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
579 let len = self.len();
580 self.index_mut(&ops::Range{ start: index.start, end: len })
583 #[stable(feature = "rust1", since = "1.0.0")]
584 impl<T> ops::IndexMut<RangeFull> for [T] {
586 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
592 ////////////////////////////////////////////////////////////////////////////////
594 ////////////////////////////////////////////////////////////////////////////////
596 /// Data that is viewable as a slice.
597 #[unstable(feature = "core",
598 reason = "will be replaced by slice syntax")]
599 pub trait AsSlice<T> {
600 /// Work with `self` as a slice.
601 fn as_slice<'a>(&'a self) -> &'a [T];
604 #[unstable(feature = "core", reason = "trait is experimental")]
605 impl<T> AsSlice<T> for [T] {
607 fn as_slice<'a>(&'a self) -> &'a [T] { self }
610 #[unstable(feature = "core", reason = "trait is experimental")]
611 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
613 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
616 #[unstable(feature = "core", reason = "trait is experimental")]
617 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
619 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
622 #[stable(feature = "rust1", since = "1.0.0")]
623 impl<'a, T> Default for &'a [T] {
624 #[stable(feature = "rust1", since = "1.0.0")]
625 fn default() -> &'a [T] { &[] }
632 #[stable(feature = "rust1", since = "1.0.0")]
633 impl<'a, T> IntoIterator for &'a [T] {
635 type IntoIter = Iter<'a, T>;
637 fn into_iter(self) -> Iter<'a, T> {
642 #[stable(feature = "rust1", since = "1.0.0")]
643 impl<'a, T> IntoIterator for &'a mut [T] {
644 type Item = &'a mut T;
645 type IntoIter = IterMut<'a, T>;
647 fn into_iter(self) -> IterMut<'a, T> {
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 ::intrinsics::assume(!self.ptr.is_null());
664 ::intrinsics::assume(!self.end.is_null());
665 if self.ptr == self.end {
668 if mem::size_of::<T>() == 0 {
669 // purposefully don't use 'ptr.offset' because for
670 // vectors with 0-size elements this would return the
672 self.ptr = transmute(self.ptr as usize + 1);
674 // Use a non-null pointer value
675 Some(&mut *(1 as *mut _))
678 self.ptr = self.ptr.offset(1);
687 fn size_hint(&self) -> (usize, Option<usize>) {
688 let diff = (self.end as usize) - (self.ptr as usize);
689 let size = mem::size_of::<T>();
690 let exact = diff / (if size == 0 {1} else {size});
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
698 fn next_back(&mut self) -> Option<$elem> {
699 // could be implemented with slices, but this avoids bounds checks
701 ::intrinsics::assume(!self.ptr.is_null());
702 ::intrinsics::assume(!self.end.is_null());
703 if self.end == self.ptr {
706 if mem::size_of::<T>() == 0 {
707 // See above for why 'ptr.offset' isn't used
708 self.end = transmute(self.end as usize - 1);
710 // Use a non-null pointer value
711 Some(&mut *(1 as *mut _))
713 self.end = self.end.offset(-1);
715 Some(transmute(self.end))
724 macro_rules! make_slice {
725 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
726 let diff = $end as usize - $start as usize;
727 let len = if mem::size_of::<T>() == 0 {
730 diff / mem::size_of::<$t>()
733 transmute::<_, $result>(RawSlice { data: $start, len: len })
738 /// Immutable slice iterator
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub struct Iter<'a, T: 'a> {
743 _marker: marker::PhantomData<&'a T>,
746 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
747 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
749 #[unstable(feature = "core")]
750 impl<'a, T> ops::Index<ops::Range<usize>> for Iter<'a, T> {
753 fn index(&self, index: &ops::Range<usize>) -> &[T] {
754 self.as_slice().index(index)
758 #[unstable(feature = "core")]
759 impl<'a, T> ops::Index<ops::RangeTo<usize>> for Iter<'a, T> {
762 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
763 self.as_slice().index(index)
767 #[unstable(feature = "core")]
768 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for Iter<'a, T> {
771 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
772 self.as_slice().index(index)
776 #[unstable(feature = "core")]
777 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
780 fn index(&self, _index: &RangeFull) -> &[T] {
785 impl<'a, T> Iter<'a, T> {
786 /// View the underlying data as a subslice of the original data.
788 /// This has the same lifetime as the original slice, and so the
789 /// iterator can continue to be used while this exists.
790 #[unstable(feature = "core")]
791 pub fn as_slice(&self) -> &'a [T] {
792 make_slice!(T => &'a [T]: self.ptr, self.end)
796 iterator!{struct Iter -> *const T, &'a T}
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
801 #[stable(feature = "rust1", since = "1.0.0")]
802 impl<'a, T> Clone for Iter<'a, T> {
803 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, _marker: self._marker } }
806 #[unstable(feature = "core", reason = "trait is experimental")]
807 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
809 fn indexable(&self) -> usize {
810 let (exact, _) = self.size_hint();
815 fn idx(&mut self, index: usize) -> Option<&'a T> {
817 if index < self.indexable() {
818 if mem::size_of::<T>() == 0 {
819 // Use a non-null pointer value
820 Some(&mut *(1 as *mut _))
822 Some(transmute(self.ptr.offset(index as isize)))
831 /// Mutable slice iterator.
832 #[stable(feature = "rust1", since = "1.0.0")]
833 pub struct IterMut<'a, T: 'a> {
836 _marker: marker::PhantomData<&'a mut T>,
839 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
840 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
842 #[unstable(feature = "core")]
843 impl<'a, T> ops::Index<ops::Range<usize>> for IterMut<'a, T> {
846 fn index(&self, index: &ops::Range<usize>) -> &[T] {
847 self.index(&RangeFull).index(index)
850 #[unstable(feature = "core")]
851 impl<'a, T> ops::Index<ops::RangeTo<usize>> for IterMut<'a, T> {
854 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
855 self.index(&RangeFull).index(index)
858 #[unstable(feature = "core")]
859 impl<'a, T> ops::Index<ops::RangeFrom<usize>> for IterMut<'a, T> {
862 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
863 self.index(&RangeFull).index(index)
866 #[unstable(feature = "core")]
867 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
870 fn index(&self, _index: &RangeFull) -> &[T] {
871 make_slice!(T => &[T]: self.ptr, self.end)
875 #[unstable(feature = "core")]
876 impl<'a, T> ops::IndexMut<ops::Range<usize>> for IterMut<'a, T> {
878 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
879 self.index_mut(&RangeFull).index_mut(index)
882 #[unstable(feature = "core")]
883 impl<'a, T> ops::IndexMut<ops::RangeTo<usize>> for IterMut<'a, T> {
885 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
886 self.index_mut(&RangeFull).index_mut(index)
889 #[unstable(feature = "core")]
890 impl<'a, T> ops::IndexMut<ops::RangeFrom<usize>> for IterMut<'a, T> {
892 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
893 self.index_mut(&RangeFull).index_mut(index)
896 #[unstable(feature = "core")]
897 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
899 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
900 make_slice!(T => &mut [T]: self.ptr, self.end)
905 impl<'a, T> IterMut<'a, T> {
906 /// View the underlying data as a subslice of the original data.
908 /// To avoid creating `&mut` references that alias, this is forced
909 /// to consume the iterator. Consider using the `Slice` and
910 /// `SliceMut` implementations for obtaining slices with more
911 /// restricted lifetimes that do not consume the iterator.
912 #[unstable(feature = "core")]
913 pub fn into_slice(self) -> &'a mut [T] {
914 make_slice!(T => &'a mut [T]: self.ptr, self.end)
918 iterator!{struct IterMut -> *mut T, &'a mut T}
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
923 /// An internal abstraction over the splitting iterators, so that
924 /// splitn, splitn_mut etc can be implemented once.
925 trait SplitIter: DoubleEndedIterator {
926 /// Mark the underlying iterator as complete, extracting the remaining
927 /// portion of the slice.
928 fn finish(&mut self) -> Option<Self::Item>;
931 /// An iterator over subslices separated by elements that match a predicate
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
940 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
941 #[stable(feature = "rust1", since = "1.0.0")]
942 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
943 fn clone(&self) -> Split<'a, T, P> {
946 pred: self.pred.clone(),
947 finished: self.finished,
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
957 fn next(&mut self) -> Option<&'a [T]> {
958 if self.finished { return None; }
960 match self.v.iter().position(|x| (self.pred)(x)) {
961 None => self.finish(),
963 let ret = Some(&self.v[..idx]);
964 self.v = &self.v[idx + 1..];
971 fn size_hint(&self) -> (usize, Option<usize>) {
975 (1, Some(self.v.len() + 1))
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
983 fn next_back(&mut self) -> Option<&'a [T]> {
984 if self.finished { return None; }
986 match self.v.iter().rposition(|x| (self.pred)(x)) {
987 None => self.finish(),
989 let ret = Some(&self.v[idx + 1..]);
990 self.v = &self.v[..idx];
997 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
999 fn finish(&mut self) -> Option<&'a [T]> {
1000 if self.finished { None } else { self.finished = true; Some(self.v) }
1004 /// An iterator over the subslices of the vector which are separated
1005 /// by elements that match `pred`.
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1013 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1015 fn finish(&mut self) -> Option<&'a mut [T]> {
1019 self.finished = true;
1020 Some(mem::replace(&mut self.v, &mut []))
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1027 type Item = &'a mut [T];
1030 fn next(&mut self) -> Option<&'a mut [T]> {
1031 if self.finished { return None; }
1033 let idx_opt = { // work around borrowck limitations
1034 let pred = &mut self.pred;
1035 self.v.iter().position(|x| (*pred)(x))
1038 None => self.finish(),
1040 let tmp = mem::replace(&mut self.v, &mut []);
1041 let (head, tail) = tmp.split_at_mut(idx);
1042 self.v = &mut tail[1..];
1049 fn size_hint(&self) -> (usize, Option<usize>) {
1053 // if the predicate doesn't match anything, we yield one slice
1054 // if it matches every element, we yield len+1 empty slices.
1055 (1, Some(self.v.len() + 1))
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1062 P: FnMut(&T) -> bool,
1065 fn next_back(&mut self) -> Option<&'a mut [T]> {
1066 if self.finished { return None; }
1068 let idx_opt = { // work around borrowck limitations
1069 let pred = &mut self.pred;
1070 self.v.iter().rposition(|x| (*pred)(x))
1073 None => self.finish(),
1075 let tmp = mem::replace(&mut self.v, &mut []);
1076 let (head, tail) = tmp.split_at_mut(idx);
1078 Some(&mut tail[1..])
1084 /// An private iterator over subslices separated by elements that
1085 /// match a predicate function, splitting at most a fixed number of
1087 struct GenericSplitN<I> {
1093 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1097 fn next(&mut self) -> Option<T> {
1098 if self.count == 0 {
1102 if self.invert { self.iter.next_back() } else { self.iter.next() }
1107 fn size_hint(&self) -> (usize, Option<usize>) {
1108 let (lower, upper_opt) = self.iter.size_hint();
1109 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1113 /// An iterator over subslices separated by elements that match a predicate
1114 /// function, limited to a given number of splits.
1115 #[stable(feature = "rust1", since = "1.0.0")]
1116 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1117 inner: GenericSplitN<Split<'a, T, P>>
1120 /// An iterator over subslices separated by elements that match a
1121 /// predicate function, limited to a given number of splits, starting
1122 /// from the end of the slice.
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1125 inner: GenericSplitN<Split<'a, T, P>>
1128 /// An iterator over subslices separated by elements that match a predicate
1129 /// function, limited to a given number of splits.
1130 #[stable(feature = "rust1", since = "1.0.0")]
1131 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1132 inner: GenericSplitN<SplitMut<'a, T, P>>
1135 /// An iterator over subslices separated by elements that match a
1136 /// predicate function, limited to a given number of splits, starting
1137 /// from the end of the slice.
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1140 inner: GenericSplitN<SplitMut<'a, T, P>>
1143 macro_rules! forward_iterator {
1144 ($name:ident: $elem:ident, $iter_of:ty) => {
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1147 P: FnMut(&T) -> bool
1149 type Item = $iter_of;
1152 fn next(&mut self) -> Option<$iter_of> {
1157 fn size_hint(&self) -> (usize, Option<usize>) {
1158 self.inner.size_hint()
1164 forward_iterator! { SplitN: T, &'a [T] }
1165 forward_iterator! { RSplitN: T, &'a [T] }
1166 forward_iterator! { SplitNMut: T, &'a mut [T] }
1167 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1169 /// An iterator over overlapping subslices of length `size`.
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 pub struct Windows<'a, T:'a> {
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 impl<'a, T> Iterator for Windows<'a, T> {
1179 type Item = &'a [T];
1182 fn next(&mut self) -> Option<&'a [T]> {
1183 if self.size > self.v.len() {
1186 let ret = Some(&self.v[..self.size]);
1187 self.v = &self.v[1..];
1193 fn size_hint(&self) -> (usize, Option<usize>) {
1194 if self.size > self.v.len() {
1197 let size = self.v.len() - self.size + 1;
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 impl<'a, T> DoubleEndedIterator for Windows<'a, T> {
1206 fn next_back(&mut self) -> Option<&'a [T]> {
1207 if self.size > self.v.len() {
1210 let ret = Some(&self.v[self.v.len()-self.size..]);
1211 self.v = &self.v[..self.v.len()-1];
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 impl<'a, T> ExactSizeIterator for Windows<'a, T> {}
1220 #[unstable(feature = "core", reason = "trait is experimental")]
1221 impl<'a, T> RandomAccessIterator for Windows<'a, T> {
1223 fn indexable(&self) -> usize {
1228 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1229 if index + self.size > self.v.len() {
1232 Some(&self.v[index .. index+self.size])
1237 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1240 /// When the slice len is not evenly divided by the chunk size, the last slice
1241 /// of the iteration will be the remainder.
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 pub struct Chunks<'a, T:'a> {
1249 #[stable(feature = "rust1", since = "1.0.0")]
1250 impl<'a, T> Iterator for Chunks<'a, T> {
1251 type Item = &'a [T];
1254 fn next(&mut self) -> Option<&'a [T]> {
1255 if self.v.len() == 0 {
1258 let chunksz = cmp::min(self.v.len(), self.size);
1259 let (fst, snd) = self.v.split_at(chunksz);
1266 fn size_hint(&self) -> (usize, Option<usize>) {
1267 if self.v.len() == 0 {
1270 let n = self.v.len() / self.size;
1271 let rem = self.v.len() % self.size;
1272 let n = if rem > 0 { n+1 } else { n };
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1281 fn next_back(&mut self) -> Option<&'a [T]> {
1282 if self.v.len() == 0 {
1285 let remainder = self.v.len() % self.size;
1286 let chunksz = if remainder != 0 { remainder } else { self.size };
1287 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1297 #[unstable(feature = "core", reason = "trait is experimental")]
1298 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1300 fn indexable(&self) -> usize {
1301 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1305 fn idx(&mut self, index: usize) -> Option<&'a [T]> {
1306 if index < self.indexable() {
1307 let lo = index * self.size;
1308 let mut hi = lo + self.size;
1309 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1311 Some(&self.v[lo..hi])
1318 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1319 /// elements at a time). When the slice len is not evenly divided by the chunk
1320 /// size, the last slice of the iteration will be the remainder.
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 pub struct ChunksMut<'a, T:'a> {
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<'a, T> Iterator for ChunksMut<'a, T> {
1329 type Item = &'a mut [T];
1332 fn next(&mut self) -> Option<&'a mut [T]> {
1333 if self.v.len() == 0 {
1336 let sz = cmp::min(self.v.len(), self.chunk_size);
1337 let tmp = mem::replace(&mut self.v, &mut []);
1338 let (head, tail) = tmp.split_at_mut(sz);
1345 fn size_hint(&self) -> (usize, Option<usize>) {
1346 if self.v.len() == 0 {
1349 let n = self.v.len() / self.chunk_size;
1350 let rem = self.v.len() % self.chunk_size;
1351 let n = if rem > 0 { n + 1 } else { n };
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.len() == 0 {
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 /// Converts a pointer to A into a slice of length 1 (without copying).
1383 #[unstable(feature = "core")]
1384 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1386 transmute(RawSlice { data: s, len: 1 })
1390 /// Converts a pointer to A into a slice of length 1 (without copying).
1391 #[unstable(feature = "core")]
1392 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1394 let ptr: *const A = transmute(s);
1395 transmute(RawSlice { data: ptr, len: 1 })
1399 /// Forms a slice from a pointer and a length.
1401 /// The `len` argument is the number of **elements**, not the number of bytes.
1403 /// This function is unsafe as there is no guarantee that the given pointer is
1404 /// valid for `len` elements, nor whether the lifetime inferred is a suitable
1405 /// lifetime for the returned slice.
1409 /// The lifetime for the returned slice is inferred from its usage. To
1410 /// prevent accidental misuse, it's suggested to tie the lifetime to whichever
1411 /// source lifetime is safe in the context, such as by providing a helper
1412 /// function taking the lifetime of a host value for the slice, or by explicit
1420 /// // manifest a slice out of thin air!
1421 /// let ptr = 0x1234 as *const usize;
1424 /// let slice = slice::from_raw_parts(ptr, amt);
1428 #[unstable(feature = "core")]
1429 pub unsafe fn from_raw_parts<'a, T>(p: *const T, len: usize) -> &'a [T] {
1430 transmute(RawSlice { data: p, len: len })
1433 /// Performs the same functionality as `from_raw_parts`, except that a mutable
1434 /// slice is returned.
1436 /// This function is unsafe for the same reasons as `from_raw_parts`, as well
1437 /// as not being able to provide a non-aliasing guarantee of the returned
1440 #[unstable(feature = "core")]
1441 pub unsafe fn from_raw_parts_mut<'a, T>(p: *mut T, len: usize) -> &'a mut [T] {
1442 transmute(RawSlice { data: p, len: len })
1445 /// Forms a slice from a pointer and a length.
1447 /// The pointer given is actually a reference to the base of the slice. This
1448 /// reference is used to give a concrete lifetime to tie the returned slice to.
1449 /// Typically this should indicate that the slice is valid for as long as the
1450 /// pointer itself is valid.
1452 /// The `len` argument is the number of **elements**, not the number of bytes.
1454 /// This function is unsafe as there is no guarantee that the given pointer is
1455 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1456 /// lifetime for the returned slice.
1463 /// // manifest a slice out of thin air!
1464 /// let ptr = 0x1234 as *const usize;
1467 /// let slice = slice::from_raw_buf(&ptr, amt);
1471 #[unstable(feature = "core")]
1472 #[deprecated(since = "1.0.0",
1473 reason = "use from_raw_parts")]
1474 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: usize) -> &'a [T] {
1475 transmute(RawSlice { data: *p, len: len })
1478 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1479 /// slice is returned.
1481 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1482 /// not being able to provide a non-aliasing guarantee of the returned mutable
1485 #[unstable(feature = "core")]
1486 #[deprecated(since = "1.0.0",
1487 reason = "use from_raw_parts_mut")]
1488 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: usize) -> &'a mut [T] {
1489 transmute(RawSlice { data: *p, len: len })
1496 /// Operations on `[u8]`.
1497 #[unstable(feature = "core", reason = "needs review")]
1500 use slice::SliceExt;
1502 /// A trait for operations on mutable `[u8]`s.
1503 pub trait MutableByteVector {
1504 /// Sets all bytes of the receiver to the given value.
1505 fn set_memory(&mut self, value: u8);
1508 impl MutableByteVector for [u8] {
1510 fn set_memory(&mut self, value: u8) {
1511 unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()) };
1515 /// Copies data from `src` to `dst`
1517 /// Panics if the length of `dst` is less than the length of `src`.
1519 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1520 let len_src = src.len();
1521 assert!(dst.len() >= len_src);
1522 // `dst` is unaliasable, so we know statically it doesn't overlap
1525 ptr::copy_nonoverlapping(dst.as_mut_ptr(),
1535 // Boilerplate traits
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1540 fn eq(&self, other: &[B]) -> bool {
1541 self.len() == other.len() &&
1542 order::eq(self.iter(), other.iter())
1544 fn ne(&self, other: &[B]) -> bool {
1545 self.len() != other.len() ||
1546 order::ne(self.iter(), other.iter())
1550 #[stable(feature = "rust1", since = "1.0.0")]
1551 impl<T: Eq> Eq for [T] {}
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<T: Ord> Ord for [T] {
1555 fn cmp(&self, other: &[T]) -> Ordering {
1556 order::cmp(self.iter(), other.iter())
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<T: PartialOrd> PartialOrd for [T] {
1563 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1564 order::partial_cmp(self.iter(), other.iter())
1567 fn lt(&self, other: &[T]) -> bool {
1568 order::lt(self.iter(), other.iter())
1571 fn le(&self, other: &[T]) -> bool {
1572 order::le(self.iter(), other.iter())
1575 fn ge(&self, other: &[T]) -> bool {
1576 order::ge(self.iter(), other.iter())
1579 fn gt(&self, other: &[T]) -> bool {
1580 order::gt(self.iter(), other.iter())
1584 /// Extension methods for slices containing integers.
1585 #[unstable(feature = "core")]
1586 pub trait IntSliceExt<U, S> {
1587 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1588 fn as_unsigned<'a>(&'a self) -> &'a [U];
1589 /// Converts the slice to an immutable slice of signed integers with the same width.
1590 fn as_signed<'a>(&'a self) -> &'a [S];
1592 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1593 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1594 /// Converts the slice to a mutable slice of signed integers with the same width.
1595 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1598 macro_rules! impl_int_slice {
1599 ($u:ty, $s:ty, $t:ty) => {
1600 #[unstable(feature = "core")]
1601 impl IntSliceExt<$u, $s> for [$t] {
1603 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1605 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1607 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1609 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1614 macro_rules! impl_int_slices {
1616 impl_int_slice! { $u, $s, $u }
1617 impl_int_slice! { $u, $s, $s }
1621 impl_int_slices! { u8, i8 }
1622 impl_int_slices! { u16, i16 }
1623 impl_int_slices! { u32, i32 }
1624 impl_int_slices! { u64, i64 }
1625 impl_int_slices! { usize, isize }