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`.
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};
46 use ops::{FnMut, self, Index};
48 use option::Option::{None, Some};
50 use result::Result::{Ok, Err};
55 use marker::{Sized, 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 slice<'a>(&'a self, start: uint, end: uint) -> &'a [Self::Item];
71 fn slice_from<'a>(&'a self, start: uint) -> &'a [Self::Item];
72 fn slice_to<'a>(&'a self, end: uint) -> &'a [Self::Item];
73 fn split_at<'a>(&'a self, mid: uint) -> (&'a [Self::Item], &'a [Self::Item]);
74 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
75 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
76 where P: FnMut(&Self::Item) -> bool;
77 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, Self::Item, P>
78 where P: FnMut(&Self::Item) -> bool;
79 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, Self::Item, P>
80 where P: FnMut(&Self::Item) -> bool;
81 fn windows<'a>(&'a self, size: uint) -> Windows<'a, Self::Item>;
82 fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, Self::Item>;
83 fn get<'a>(&'a self, index: uint) -> Option<&'a Self::Item>;
84 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
85 fn tail<'a>(&'a self) -> &'a [Self::Item];
86 fn init<'a>(&'a self) -> &'a [Self::Item];
87 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
88 unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a Self::Item;
89 fn as_ptr(&self) -> *const Self::Item;
90 fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
91 F: FnMut(&Self::Item) -> Ordering;
92 fn len(&self) -> uint;
93 fn is_empty(&self) -> bool { self.len() == 0 }
94 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut Self::Item>;
95 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item];
96 fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [Self::Item];
97 fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [Self::Item];
98 fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [Self::Item];
99 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
100 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
101 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
102 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
103 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
104 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
105 where P: FnMut(&Self::Item) -> bool;
106 fn splitn_mut<P>(&mut self, n: uint, pred: P) -> SplitNMut<Self::Item, P>
107 where P: FnMut(&Self::Item) -> bool;
108 fn rsplitn_mut<P>(&mut self, n: uint, pred: P) -> RSplitNMut<Self::Item, P>
109 where P: FnMut(&Self::Item) -> bool;
110 fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, Self::Item>;
111 fn swap(&mut self, a: uint, b: uint);
112 fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
113 fn reverse(&mut self);
114 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut Self::Item;
115 fn as_mut_ptr(&mut self) -> *mut Self::Item;
117 fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
119 fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
121 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
123 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
125 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
127 fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
128 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
129 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
131 fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
135 impl<T> SliceExt for [T] {
139 fn slice(&self, start: uint, end: uint) -> &[T] {
140 assert!(start <= end);
141 assert!(end <= self.len());
144 data: self.as_ptr().offset(start as int),
151 fn slice_from(&self, start: uint) -> &[T] {
152 self.slice(start, self.len())
156 fn slice_to(&self, end: uint) -> &[T] {
161 fn split_at(&self, mid: uint) -> (&[T], &[T]) {
162 (&self[..mid], &self[mid..])
166 fn iter<'a>(&'a self) -> Iter<'a, T> {
168 let p = self.as_ptr();
169 if mem::size_of::<T>() == 0 {
171 end: (p as uint + self.len()) as *const T,
172 marker: marker::ContravariantLifetime::<'a>}
175 end: p.offset(self.len() as int),
176 marker: marker::ContravariantLifetime::<'a>}
182 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
191 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, T, P> where
192 P: FnMut(&T) -> bool,
195 inner: GenericSplitN {
196 iter: self.split(pred),
204 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, T, P> where
205 P: FnMut(&T) -> bool,
208 inner: GenericSplitN {
209 iter: self.split(pred),
217 fn windows(&self, size: uint) -> Windows<T> {
219 Windows { v: self, size: size }
223 fn chunks(&self, size: uint) -> Chunks<T> {
225 Chunks { v: self, size: size }
229 fn get(&self, index: uint) -> Option<&T> {
230 if index < self.len() { Some(&self[index]) } else { None }
234 fn first(&self) -> Option<&T> {
235 if self.len() == 0 { None } else { Some(&self[0]) }
239 fn tail(&self) -> &[T] { &self[1..] }
242 fn init(&self) -> &[T] {
243 &self[..self.len() - 1]
247 fn last(&self) -> Option<&T> {
248 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
252 unsafe fn get_unchecked(&self, index: uint) -> &T {
253 transmute(self.repr().data.offset(index as int))
257 fn as_ptr(&self) -> *const T {
262 fn binary_search_by<F>(&self, mut f: F) -> Result<uint, uint> where
263 F: FnMut(&T) -> Ordering
265 let mut base : uint = 0;
266 let mut lim : uint = self.len();
269 let ix = base + (lim >> 1);
271 Equal => return Ok(ix),
284 fn len(&self) -> uint { self.repr().len }
287 fn get_mut(&mut self, index: uint) -> Option<&mut T> {
288 if index < self.len() { Some(&mut self[index]) } else { None }
292 fn as_mut_slice(&mut self) -> &mut [T] { self }
294 fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T] {
295 ops::IndexMut::index_mut(self, &ops::Range { start: start, end: end } )
299 fn slice_from_mut(&mut self, start: uint) -> &mut [T] {
300 ops::IndexMut::index_mut(self, &ops::RangeFrom { start: start } )
304 fn slice_to_mut(&mut self, end: uint) -> &mut [T] {
305 ops::IndexMut::index_mut(self, &ops::RangeTo { end: end } )
309 fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
311 let self2: &mut [T] = mem::transmute_copy(&self);
313 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
314 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
319 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
321 let p = self.as_mut_ptr();
322 if mem::size_of::<T>() == 0 {
324 end: (p as uint + self.len()) as *mut T,
325 marker: marker::ContravariantLifetime::<'a>}
328 end: p.offset(self.len() as int),
329 marker: marker::ContravariantLifetime::<'a>}
335 fn last_mut(&mut self) -> Option<&mut T> {
336 let len = self.len();
337 if len == 0 { return None; }
338 Some(&mut self[len - 1])
342 fn first_mut(&mut self) -> Option<&mut T> {
343 if self.len() == 0 { None } else { Some(&mut self[0]) }
347 fn tail_mut(&mut self) -> &mut [T] {
348 self.slice_from_mut(1)
352 fn init_mut(&mut self) -> &mut [T] {
353 let len = self.len();
354 self.slice_to_mut(len-1)
358 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
359 SplitMut { v: self, pred: pred, finished: false }
363 fn splitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> SplitNMut<'a, T, P> where
367 inner: GenericSplitN {
368 iter: self.split_mut(pred),
376 fn rsplitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> RSplitNMut<'a, T, P> where
377 P: FnMut(&T) -> bool,
380 inner: GenericSplitN {
381 iter: self.split_mut(pred),
389 fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<T> {
390 assert!(chunk_size > 0);
391 ChunksMut { v: self, chunk_size: chunk_size }
394 fn swap(&mut self, a: uint, b: uint) {
396 // Can't take two mutable loans from one vector, so instead just cast
397 // them to their raw pointers to do the swap
398 let pa: *mut T = &mut self[a];
399 let pb: *mut T = &mut self[b];
404 fn reverse(&mut self) {
408 // Unsafe swap to avoid the bounds check in safe swap.
410 let pa: *mut T = self.get_unchecked_mut(i);
411 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
419 unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T {
420 transmute((self.repr().data as *mut T).offset(index as int))
424 fn as_mut_ptr(&mut self) -> *mut T {
425 self.repr().data as *mut T
429 fn position_elem(&self, x: &T) -> Option<uint> where T: PartialEq {
430 self.iter().position(|y| *x == *y)
434 fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
435 self.iter().rposition(|x| *x == *t)
439 fn contains(&self, x: &T) -> bool where T: PartialEq {
440 self.iter().any(|elt| *x == *elt)
444 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
445 let n = needle.len();
446 self.len() >= n && needle == &self[..n]
450 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
451 let (m, n) = (self.len(), needle.len());
452 m >= n && needle == &self[m-n..]
456 fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
457 self.binary_search_by(|p| p.cmp(x))
461 fn next_permutation(&mut self) -> bool where T: Ord {
462 // These cases only have 1 permutation each, so we can't do anything.
463 if self.len() < 2 { return false; }
465 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
466 let mut i = self.len() - 1;
467 while i > 0 && self[i-1] >= self[i] {
471 // If that is the entire vector, this is the last-ordered permutation.
476 // Step 2: Find the rightmost element larger than the pivot (i-1)
477 let mut j = self.len() - 1;
478 while j >= i && self[j] <= self[i-1] {
482 // Step 3: Swap that element with the pivot
485 // Step 4: Reverse the (previously) weakly decreasing part
486 self.slice_from_mut(i).reverse();
492 fn prev_permutation(&mut self) -> bool where T: Ord {
493 // These cases only have 1 permutation each, so we can't do anything.
494 if self.len() < 2 { return false; }
496 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
497 let mut i = self.len() - 1;
498 while i > 0 && self[i-1] <= self[i] {
502 // If that is the entire vector, this is the first-ordered permutation.
507 // Step 2: Reverse the weakly increasing part
508 self.slice_from_mut(i).reverse();
510 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
511 let mut j = self.len() - 1;
512 while j >= i && self[j-1] < self[i-1] {
516 // Step 4: Swap that element with the pivot
523 fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
524 let min = cmp::min(self.len(), src.len());
525 let dst = self.slice_to_mut(min);
526 let src = src.slice_to(min);
527 for i in range(0, min) {
528 dst[i].clone_from(&src[i]);
534 impl<T> ops::Index<uint> for [T] {
537 fn index(&self, &index: &uint) -> &T {
538 assert!(index < self.len());
540 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
544 impl<T> ops::IndexMut<uint> for [T] {
547 fn index_mut(&mut self, &index: &uint) -> &mut T {
548 assert!(index < self.len());
550 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
554 impl<T> ops::Index<ops::Range<uint>> for [T] {
557 fn index(&self, index: &ops::Range<uint>) -> &[T] {
558 assert!(index.start <= index.end);
559 assert!(index.end <= self.len());
562 data: self.as_ptr().offset(index.start as int),
563 len: index.end - index.start
568 impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
571 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
572 self.index(&ops::Range{ start: 0, end: index.end })
575 impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
578 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
579 self.index(&ops::Range{ start: index.start, end: self.len() })
582 impl<T> ops::Index<ops::FullRange> for [T] {
585 fn index(&self, _index: &ops::FullRange) -> &[T] {
590 impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
593 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
594 assert!(index.start <= index.end);
595 assert!(index.end <= self.len());
598 data: self.as_ptr().offset(index.start as int),
599 len: index.end - index.start
604 impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
607 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
608 self.index_mut(&ops::Range{ start: 0, end: index.end })
611 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
614 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
615 let len = self.len();
616 self.index_mut(&ops::Range{ start: index.start, end: len })
619 impl<T> ops::IndexMut<ops::FullRange> for [T] {
622 fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
628 ////////////////////////////////////////////////////////////////////////////////
630 ////////////////////////////////////////////////////////////////////////////////
632 /// Data that is viewable as a slice.
633 #[unstable = "will be replaced by slice syntax"]
634 pub trait AsSlice<T> {
635 /// Work with `self` as a slice.
636 fn as_slice<'a>(&'a self) -> &'a [T];
639 #[unstable = "trait is experimental"]
640 impl<T> AsSlice<T> for [T] {
642 fn as_slice<'a>(&'a self) -> &'a [T] { self }
645 #[unstable = "trait is experimental"]
646 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
648 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
651 #[unstable = "trait is experimental"]
652 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
654 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
658 impl<'a, T> Default for &'a [T] {
660 fn default() -> &'a [T] { &[] }
667 // The shared definition of the `Iter` and `IterMut` iterators
668 macro_rules! iterator {
669 (struct $name:ident -> $ptr:ty, $elem:ty) => {
671 impl<'a, T> Iterator for $name<'a, T> {
675 fn next(&mut self) -> Option<$elem> {
676 // could be implemented with slices, but this avoids bounds checks
678 if self.ptr == self.end {
681 if mem::size_of::<T>() == 0 {
682 // purposefully don't use 'ptr.offset' because for
683 // vectors with 0-size elements this would return the
685 self.ptr = transmute(self.ptr as uint + 1);
687 // Use a non-null pointer value
691 self.ptr = self.ptr.offset(1);
700 fn size_hint(&self) -> (uint, Option<uint>) {
701 let diff = (self.end as uint) - (self.ptr as uint);
702 let size = mem::size_of::<T>();
703 let exact = diff / (if size == 0 {1} else {size});
709 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
711 fn next_back(&mut self) -> Option<$elem> {
712 // could be implemented with slices, but this avoids bounds checks
714 if self.end == self.ptr {
717 if mem::size_of::<T>() == 0 {
718 // See above for why 'ptr.offset' isn't used
719 self.end = transmute(self.end as uint - 1);
721 // Use a non-null pointer value
724 self.end = self.end.offset(-1);
726 Some(transmute(self.end))
735 macro_rules! make_slice {
736 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
737 let diff = $end as uint - $start as uint;
738 let len = if mem::size_of::<T>() == 0 {
741 diff / mem::size_of::<$t>()
744 transmute::<_, $result>(RawSlice { data: $start as *const T, len: len })
749 /// Immutable slice iterator
751 pub struct Iter<'a, T: 'a> {
754 marker: marker::ContravariantLifetime<'a>
758 impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
761 fn index(&self, index: &ops::Range<uint>) -> &[T] {
762 self.as_slice().index(index)
767 impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
770 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
771 self.as_slice().index(index)
776 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
779 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
780 self.as_slice().index(index)
785 impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
788 fn index(&self, _index: &ops::FullRange) -> &[T] {
793 impl<'a, T> Iter<'a, T> {
794 /// View the underlying data as a subslice of the original data.
796 /// This has the same lifetime as the original slice, and so the
797 /// iterator can continue to be used while this exists.
799 pub fn as_slice(&self) -> &'a [T] {
800 make_slice!(T => &'a [T]: self.ptr, self.end)
804 impl<'a,T> Copy for Iter<'a,T> {}
806 iterator!{struct Iter -> *const T, &'a T}
809 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
812 impl<'a, T> Clone for Iter<'a, T> {
813 fn clone(&self) -> Iter<'a, T> { *self }
816 #[unstable = "trait is experimental"]
817 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
819 fn indexable(&self) -> uint {
820 let (exact, _) = self.size_hint();
825 fn idx(&mut self, index: uint) -> Option<&'a T> {
827 if index < self.indexable() {
828 if mem::size_of::<T>() == 0 {
829 // Use a non-null pointer value
832 Some(transmute(self.ptr.offset(index as int)))
841 /// Mutable slice iterator.
843 pub struct IterMut<'a, T: 'a> {
846 marker: marker::ContravariantLifetime<'a>,
851 impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
854 fn index(&self, index: &ops::Range<uint>) -> &[T] {
855 self.index(&ops::FullRange).index(index)
859 impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
862 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
863 self.index(&ops::FullRange).index(index)
867 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
870 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
871 self.index(&ops::FullRange).index(index)
875 impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> {
878 fn index(&self, _index: &ops::FullRange) -> &[T] {
879 make_slice!(T => &[T]: self.ptr, self.end)
884 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
887 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
888 self.index_mut(&ops::FullRange).index_mut(index)
892 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
895 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
896 self.index_mut(&ops::FullRange).index_mut(index)
900 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
903 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
904 self.index_mut(&ops::FullRange).index_mut(index)
908 impl<'a, T> ops::IndexMut<ops::FullRange> for IterMut<'a, T> {
911 fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
912 make_slice!(T => &mut [T]: self.ptr, self.end)
917 impl<'a, T> IterMut<'a, T> {
918 /// View the underlying data as a subslice of the original data.
920 /// To avoid creating `&mut` references that alias, this is forced
921 /// to consume the iterator. Consider using the `Slice` and
922 /// `SliceMut` implementations for obtaining slices with more
923 /// restricted lifetimes that do not consume the iterator.
925 pub fn into_slice(self) -> &'a mut [T] {
926 make_slice!(T => &'a mut [T]: self.ptr, self.end)
930 iterator!{struct IterMut -> *mut T, &'a mut T}
933 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
935 /// An internal abstraction over the splitting iterators, so that
936 /// splitn, splitn_mut etc can be implemented once.
937 trait SplitIter: DoubleEndedIterator {
938 /// Mark the underlying iterator as complete, extracting the remaining
939 /// portion of the slice.
940 fn finish(&mut self) -> Option<Self::Item>;
943 /// An iterator over subslices separated by elements that match a predicate
946 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
952 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
954 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
955 fn clone(&self) -> Split<'a, T, P> {
958 pred: self.pred.clone(),
959 finished: self.finished,
965 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
969 fn next(&mut self) -> Option<&'a [T]> {
970 if self.finished { return None; }
972 match self.v.iter().position(|x| (self.pred)(x)) {
973 None => self.finish(),
975 let ret = Some(&self.v[..idx]);
976 self.v = &self.v[idx + 1..];
983 fn size_hint(&self) -> (uint, Option<uint>) {
987 (1, Some(self.v.len() + 1))
993 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
995 fn next_back(&mut self) -> Option<&'a [T]> {
996 if self.finished { return None; }
998 match self.v.iter().rposition(|x| (self.pred)(x)) {
999 None => self.finish(),
1001 let ret = Some(&self.v[idx + 1..]);
1002 self.v = &self.v[..idx];
1009 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1011 fn finish(&mut self) -> Option<&'a [T]> {
1012 if self.finished { None } else { self.finished = true; Some(self.v) }
1016 /// An iterator over the subslices of the vector which are separated
1017 /// by elements that match `pred`.
1019 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1025 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1027 fn finish(&mut self) -> Option<&'a mut [T]> {
1031 self.finished = true;
1032 Some(mem::replace(&mut self.v, &mut []))
1038 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1039 type Item = &'a mut [T];
1042 fn next(&mut self) -> Option<&'a mut [T]> {
1043 if self.finished { return None; }
1045 let idx_opt = { // work around borrowck limitations
1046 let pred = &mut self.pred;
1047 self.v.iter().position(|x| (*pred)(x))
1050 None => self.finish(),
1052 let tmp = mem::replace(&mut self.v, &mut []);
1053 let (head, tail) = tmp.split_at_mut(idx);
1054 self.v = tail.slice_from_mut(1);
1061 fn size_hint(&self) -> (uint, Option<uint>) {
1065 // if the predicate doesn't match anything, we yield one slice
1066 // if it matches every element, we yield len+1 empty slices.
1067 (1, Some(self.v.len() + 1))
1073 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1074 P: FnMut(&T) -> bool,
1077 fn next_back(&mut self) -> Option<&'a mut [T]> {
1078 if self.finished { return None; }
1080 let idx_opt = { // work around borrowck limitations
1081 let pred = &mut self.pred;
1082 self.v.iter().rposition(|x| (*pred)(x))
1085 None => self.finish(),
1087 let tmp = mem::replace(&mut self.v, &mut []);
1088 let (head, tail) = tmp.split_at_mut(idx);
1090 Some(tail.slice_from_mut(1))
1096 /// An private iterator over subslices separated by elements that
1097 /// match a predicate function, splitting at most a fixed number of
1099 struct GenericSplitN<I> {
1105 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1109 fn next(&mut self) -> Option<T> {
1110 if self.count == 0 {
1114 if self.invert { self.iter.next_back() } else { self.iter.next() }
1119 fn size_hint(&self) -> (uint, Option<uint>) {
1120 let (lower, upper_opt) = self.iter.size_hint();
1121 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1125 /// An iterator over subslices separated by elements that match a predicate
1126 /// function, limited to a given number of splits.
1128 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1129 inner: GenericSplitN<Split<'a, T, P>>
1132 /// An iterator over subslices separated by elements that match a
1133 /// predicate function, limited to a given number of splits, starting
1134 /// from the end of the slice.
1136 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1137 inner: GenericSplitN<Split<'a, T, P>>
1140 /// An iterator over subslices separated by elements that match a predicate
1141 /// function, limited to a given number of splits.
1143 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1144 inner: GenericSplitN<SplitMut<'a, T, P>>
1147 /// An iterator over subslices separated by elements that match a
1148 /// predicate function, limited to a given number of splits, starting
1149 /// from the end of the slice.
1151 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1152 inner: GenericSplitN<SplitMut<'a, T, P>>
1155 macro_rules! forward_iterator {
1156 ($name:ident: $elem:ident, $iter_of:ty) => {
1158 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1159 P: FnMut(&T) -> bool
1161 type Item = $iter_of;
1164 fn next(&mut self) -> Option<$iter_of> {
1169 fn size_hint(&self) -> (uint, Option<uint>) {
1170 self.inner.size_hint()
1176 forward_iterator! { SplitN: T, &'a [T] }
1177 forward_iterator! { RSplitN: T, &'a [T] }
1178 forward_iterator! { SplitNMut: T, &'a mut [T] }
1179 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1181 /// An iterator over overlapping subslices of length `size`.
1184 pub struct Windows<'a, T:'a> {
1190 impl<'a, T> Iterator for Windows<'a, T> {
1191 type Item = &'a [T];
1194 fn next(&mut self) -> Option<&'a [T]> {
1195 if self.size > self.v.len() {
1198 let ret = Some(&self.v[..self.size]);
1199 self.v = &self.v[1..];
1205 fn size_hint(&self) -> (uint, Option<uint>) {
1206 if self.size > self.v.len() {
1209 let x = self.v.len() - self.size;
1210 (x.saturating_add(1), x.checked_add(1u))
1215 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1218 /// When the slice len is not evenly divided by the chunk size, the last slice
1219 /// of the iteration will be the remainder.
1222 pub struct Chunks<'a, T:'a> {
1228 impl<'a, T> Iterator for Chunks<'a, T> {
1229 type Item = &'a [T];
1232 fn next(&mut self) -> Option<&'a [T]> {
1233 if self.v.len() == 0 {
1236 let chunksz = cmp::min(self.v.len(), self.size);
1237 let (fst, snd) = self.v.split_at(chunksz);
1244 fn size_hint(&self) -> (uint, Option<uint>) {
1245 if self.v.len() == 0 {
1248 let n = self.v.len() / self.size;
1249 let rem = self.v.len() % self.size;
1250 let n = if rem > 0 { n+1 } else { n };
1257 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1259 fn next_back(&mut self) -> Option<&'a [T]> {
1260 if self.v.len() == 0 {
1263 let remainder = self.v.len() % self.size;
1264 let chunksz = if remainder != 0 { remainder } else { self.size };
1265 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1272 #[unstable = "trait is experimental"]
1273 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1275 fn indexable(&self) -> uint {
1276 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1280 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1281 if index < self.indexable() {
1282 let lo = index * self.size;
1283 let mut hi = lo + self.size;
1284 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1286 Some(&self.v[lo..hi])
1293 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1294 /// elements at a time). When the slice len is not evenly divided by the chunk
1295 /// size, the last slice of the iteration will be the remainder.
1297 pub struct ChunksMut<'a, T:'a> {
1303 impl<'a, T> Iterator for ChunksMut<'a, T> {
1304 type Item = &'a mut [T];
1307 fn next(&mut self) -> Option<&'a mut [T]> {
1308 if self.v.len() == 0 {
1311 let sz = cmp::min(self.v.len(), self.chunk_size);
1312 let tmp = mem::replace(&mut self.v, &mut []);
1313 let (head, tail) = tmp.split_at_mut(sz);
1320 fn size_hint(&self) -> (uint, Option<uint>) {
1321 if self.v.len() == 0 {
1324 let n = self.v.len() / self.chunk_size;
1325 let rem = self.v.len() % self.chunk_size;
1326 let n = if rem > 0 { n + 1 } else { n };
1333 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1335 fn next_back(&mut self) -> Option<&'a mut [T]> {
1336 if self.v.len() == 0 {
1339 let remainder = self.v.len() % self.chunk_size;
1340 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1341 let tmp = mem::replace(&mut self.v, &mut []);
1342 let tmp_len = tmp.len();
1343 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1355 /// Converts a pointer to A into a slice of length 1 (without copying).
1357 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1359 transmute(RawSlice { data: s, len: 1 })
1363 /// Converts a pointer to A into a slice of length 1 (without copying).
1365 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1367 let ptr: *const A = transmute(s);
1368 transmute(RawSlice { data: ptr, len: 1 })
1372 /// Forms a slice from a pointer and a length.
1374 /// The pointer given is actually a reference to the base of the slice. This
1375 /// reference is used to give a concrete lifetime to tie the returned slice to.
1376 /// Typically this should indicate that the slice is valid for as long as the
1377 /// pointer itself is valid.
1379 /// The `len` argument is the number of **elements**, not the number of bytes.
1381 /// This function is unsafe as there is no guarantee that the given pointer is
1382 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1383 /// lifetime for the returned slice.
1390 /// // manifest a slice out of thin air!
1391 /// let ptr = 0x1234 as *const uint;
1394 /// let slice = slice::from_raw_buf(&ptr, amt);
1398 #[unstable = "should be renamed to from_raw_parts"]
1399 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1400 transmute(RawSlice { data: *p, len: len })
1403 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1404 /// slice is returned.
1406 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1407 /// not being able to provide a non-aliasing guarantee of the returned mutable
1410 #[unstable = "should be renamed to from_raw_parts_mut"]
1411 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1412 transmute(RawSlice { data: *p as *const T, len: len })
1419 /// Operations on `[u8]`.
1420 #[unstable = "needs review"]
1423 use slice::SliceExt;
1425 /// A trait for operations on mutable `[u8]`s.
1426 pub trait MutableByteVector {
1427 /// Sets all bytes of the receiver to the given value.
1428 fn set_memory(&mut self, value: u8);
1431 impl MutableByteVector for [u8] {
1434 fn set_memory(&mut self, value: u8) {
1435 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1439 /// Copies data from `src` to `dst`
1441 /// Panics if the length of `dst` is less than the length of `src`.
1443 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1444 let len_src = src.len();
1445 assert!(dst.len() >= len_src);
1446 // `dst` is unaliasable, so we know statically it doesn't overlap
1449 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1459 // Boilerplate traits
1463 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1464 fn eq(&self, other: &[B]) -> bool {
1465 self.len() == other.len() &&
1466 order::eq(self.iter(), other.iter())
1468 fn ne(&self, other: &[B]) -> bool {
1469 self.len() != other.len() ||
1470 order::ne(self.iter(), other.iter())
1475 impl<T: Eq> Eq for [T] {}
1478 impl<T: Ord> Ord for [T] {
1479 fn cmp(&self, other: &[T]) -> Ordering {
1480 order::cmp(self.iter(), other.iter())
1485 impl<T: PartialOrd> PartialOrd for [T] {
1487 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1488 order::partial_cmp(self.iter(), other.iter())
1491 fn lt(&self, other: &[T]) -> bool {
1492 order::lt(self.iter(), other.iter())
1495 fn le(&self, other: &[T]) -> bool {
1496 order::le(self.iter(), other.iter())
1499 fn ge(&self, other: &[T]) -> bool {
1500 order::ge(self.iter(), other.iter())
1503 fn gt(&self, other: &[T]) -> bool {
1504 order::gt(self.iter(), other.iter())
1508 /// Extension methods for slices containing integers.
1510 pub trait IntSliceExt<U, S> {
1511 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1512 fn as_unsigned<'a>(&'a self) -> &'a [U];
1513 /// Converts the slice to an immutable slice of signed integers with the same width.
1514 fn as_signed<'a>(&'a self) -> &'a [S];
1516 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1517 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1518 /// Converts the slice to a mutable slice of signed integers with the same width.
1519 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1522 macro_rules! impl_int_slice {
1523 ($u:ty, $s:ty, $t:ty) => {
1525 impl IntSliceExt<$u, $s> for [$t] {
1527 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1529 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1531 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1533 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1538 macro_rules! impl_int_slices {
1540 impl_int_slice! { $u, $s, $u }
1541 impl_int_slice! { $u, $s, $s }
1545 impl_int_slices! { u8, i8 }
1546 impl_int_slices! { u16, i16 }
1547 impl_int_slices! { u32, i32 }
1548 impl_int_slices! { u64, i64 }
1549 impl_int_slices! { uint, int }