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};
46 use ops::{FnMut, self, Index};
48 use ops::FullRange as RangeFull;
52 use option::Option::{None, Some};
54 use result::Result::{Ok, Err};
59 use marker::{Sized, self};
61 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
62 use raw::Slice as RawSlice;
69 /// Extension methods for slices.
70 #[allow(missing_docs)] // docs in libcollections
74 fn split_at<'a>(&'a self, mid: uint) -> (&'a [Self::Item], &'a [Self::Item]);
75 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
76 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
77 where P: FnMut(&Self::Item) -> bool;
78 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, Self::Item, P>
79 where P: FnMut(&Self::Item) -> bool;
80 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, Self::Item, P>
81 where P: FnMut(&Self::Item) -> bool;
82 fn windows<'a>(&'a self, size: uint) -> Windows<'a, Self::Item>;
83 fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, Self::Item>;
84 fn get<'a>(&'a self, index: uint) -> Option<&'a Self::Item>;
85 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
86 fn tail<'a>(&'a self) -> &'a [Self::Item];
87 fn init<'a>(&'a self) -> &'a [Self::Item];
88 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
89 unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a Self::Item;
90 fn as_ptr(&self) -> *const Self::Item;
91 fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
92 F: FnMut(&Self::Item) -> Ordering;
93 fn len(&self) -> uint;
94 fn is_empty(&self) -> bool { self.len() == 0 }
95 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut Self::Item>;
96 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item];
97 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
98 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
99 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
100 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
101 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
102 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
103 where P: FnMut(&Self::Item) -> bool;
104 fn splitn_mut<P>(&mut self, n: uint, pred: P) -> SplitNMut<Self::Item, P>
105 where P: FnMut(&Self::Item) -> bool;
106 fn rsplitn_mut<P>(&mut self, n: uint, pred: P) -> RSplitNMut<Self::Item, P>
107 where P: FnMut(&Self::Item) -> bool;
108 fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, Self::Item>;
109 fn swap(&mut self, a: uint, b: uint);
110 fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
111 fn reverse(&mut self);
112 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut Self::Item;
113 fn as_mut_ptr(&mut self) -> *mut Self::Item;
115 fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
117 fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
119 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
121 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
123 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
125 fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
126 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
127 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
129 fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
132 #[unstable(feature = "core")]
133 impl<T> SliceExt for [T] {
137 fn split_at(&self, mid: uint) -> (&[T], &[T]) {
138 (&self[..mid], &self[mid..])
142 fn iter<'a>(&'a self) -> Iter<'a, T> {
144 let p = self.as_ptr();
145 if mem::size_of::<T>() == 0 {
147 end: (p as uint + self.len()) as *const T,
148 marker: marker::ContravariantLifetime::<'a>}
151 end: p.offset(self.len() as int),
152 marker: marker::ContravariantLifetime::<'a>}
158 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
167 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, T, P> where
168 P: FnMut(&T) -> bool,
171 inner: GenericSplitN {
172 iter: self.split(pred),
180 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, T, P> where
181 P: FnMut(&T) -> bool,
184 inner: GenericSplitN {
185 iter: self.split(pred),
193 fn windows(&self, size: uint) -> Windows<T> {
195 Windows { v: self, size: size }
199 fn chunks(&self, size: uint) -> Chunks<T> {
201 Chunks { v: self, size: size }
205 fn get(&self, index: uint) -> Option<&T> {
206 if index < self.len() { Some(&self[index]) } else { None }
210 fn first(&self) -> Option<&T> {
211 if self.len() == 0 { None } else { Some(&self[0]) }
215 fn tail(&self) -> &[T] { &self[1..] }
218 fn init(&self) -> &[T] {
219 &self[..self.len() - 1]
223 fn last(&self) -> Option<&T> {
224 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
228 unsafe fn get_unchecked(&self, index: uint) -> &T {
229 transmute(self.repr().data.offset(index as int))
233 fn as_ptr(&self) -> *const T {
237 #[unstable(feature = "core")]
238 fn binary_search_by<F>(&self, mut f: F) -> Result<uint, uint> where
239 F: FnMut(&T) -> Ordering
241 let mut base : uint = 0;
242 let mut lim : uint = self.len();
245 let ix = base + (lim >> 1);
247 Equal => return Ok(ix),
260 fn len(&self) -> uint { self.repr().len }
263 fn get_mut(&mut self, index: uint) -> Option<&mut T> {
264 if index < self.len() { Some(&mut self[index]) } else { None }
268 fn as_mut_slice(&mut self) -> &mut [T] { self }
271 fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
273 let self2: &mut [T] = mem::transmute_copy(&self);
275 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
276 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
281 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
283 let p = self.as_mut_ptr();
284 if mem::size_of::<T>() == 0 {
286 end: (p as uint + self.len()) as *mut T,
287 marker: marker::ContravariantLifetime::<'a>}
290 end: p.offset(self.len() as int),
291 marker: marker::ContravariantLifetime::<'a>}
297 fn last_mut(&mut self) -> Option<&mut T> {
298 let len = self.len();
299 if len == 0 { return None; }
300 Some(&mut self[len - 1])
304 fn first_mut(&mut self) -> Option<&mut T> {
305 if self.len() == 0 { None } else { Some(&mut self[0]) }
309 fn tail_mut(&mut self) -> &mut [T] {
314 fn init_mut(&mut self) -> &mut [T] {
315 let len = self.len();
316 &mut self[.. (len - 1)]
320 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
321 SplitMut { v: self, pred: pred, finished: false }
325 fn splitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> SplitNMut<'a, T, P> where
329 inner: GenericSplitN {
330 iter: self.split_mut(pred),
338 fn rsplitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> RSplitNMut<'a, T, P> where
339 P: FnMut(&T) -> bool,
342 inner: GenericSplitN {
343 iter: self.split_mut(pred),
351 fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<T> {
352 assert!(chunk_size > 0);
353 ChunksMut { v: self, chunk_size: chunk_size }
356 fn swap(&mut self, a: uint, b: uint) {
358 // Can't take two mutable loans from one vector, so instead just cast
359 // them to their raw pointers to do the swap
360 let pa: *mut T = &mut self[a];
361 let pb: *mut T = &mut self[b];
366 fn reverse(&mut self) {
370 // Unsafe swap to avoid the bounds check in safe swap.
372 let pa: *mut T = self.get_unchecked_mut(i);
373 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
381 unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T {
382 transmute((self.repr().data as *mut T).offset(index as int))
386 fn as_mut_ptr(&mut self) -> *mut T {
387 self.repr().data as *mut T
391 fn position_elem(&self, x: &T) -> Option<uint> where T: PartialEq {
392 self.iter().position(|y| *x == *y)
396 fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
397 self.iter().rposition(|x| *x == *t)
401 fn contains(&self, x: &T) -> bool where T: PartialEq {
402 self.iter().any(|elt| *x == *elt)
406 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
407 let n = needle.len();
408 self.len() >= n && needle == &self[..n]
412 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
413 let (m, n) = (self.len(), needle.len());
414 m >= n && needle == &self[m-n..]
417 #[unstable(feature = "core")]
418 fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
419 self.binary_search_by(|p| p.cmp(x))
422 #[unstable(feature = "core")]
423 fn next_permutation(&mut self) -> bool where T: Ord {
424 // These cases only have 1 permutation each, so we can't do anything.
425 if self.len() < 2 { return false; }
427 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
428 let mut i = self.len() - 1;
429 while i > 0 && self[i-1] >= self[i] {
433 // If that is the entire vector, this is the last-ordered permutation.
438 // Step 2: Find the rightmost element larger than the pivot (i-1)
439 let mut j = self.len() - 1;
440 while j >= i && self[j] <= self[i-1] {
444 // Step 3: Swap that element with the pivot
447 // Step 4: Reverse the (previously) weakly decreasing part
453 #[unstable(feature = "core")]
454 fn prev_permutation(&mut self) -> bool where T: Ord {
455 // These cases only have 1 permutation each, so we can't do anything.
456 if self.len() < 2 { return false; }
458 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
459 let mut i = self.len() - 1;
460 while i > 0 && self[i-1] <= self[i] {
464 // If that is the entire vector, this is the first-ordered permutation.
469 // Step 2: Reverse the weakly increasing part
472 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
473 let mut j = self.len() - 1;
474 while j >= i && self[j-1] < self[i-1] {
478 // Step 4: Swap that element with the pivot
485 fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
486 let min = cmp::min(self.len(), src.len());
487 let dst = &mut self[.. min];
488 let src = &src[.. min];
490 dst[i].clone_from(&src[i]);
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<T> ops::Index<uint> for [T] {
500 fn index(&self, &index: &uint) -> &T {
501 assert!(index < self.len());
503 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
507 #[stable(feature = "rust1", since = "1.0.0")]
508 impl<T> ops::IndexMut<uint> for [T] {
511 fn index_mut(&mut self, &index: &uint) -> &mut T {
512 assert!(index < self.len());
514 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
518 #[stable(feature = "rust1", since = "1.0.0")]
519 impl<T> ops::Index<ops::Range<uint>> for [T] {
522 fn index(&self, index: &ops::Range<uint>) -> &[T] {
523 assert!(index.start <= index.end);
524 assert!(index.end <= self.len());
527 data: self.as_ptr().offset(index.start as int),
528 len: index.end - index.start
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
537 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
538 self.index(&ops::Range{ start: 0, end: index.end })
541 #[stable(feature = "rust1", since = "1.0.0")]
542 impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
545 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
546 self.index(&ops::Range{ start: index.start, end: self.len() })
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl<T> ops::Index<RangeFull> for [T] {
553 fn index(&self, _index: &RangeFull) -> &[T] {
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
562 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
563 assert!(index.start <= index.end);
564 assert!(index.end <= self.len());
567 data: self.as_ptr().offset(index.start as int),
568 len: index.end - index.start
573 #[stable(feature = "rust1", since = "1.0.0")]
574 impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
577 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
578 self.index_mut(&ops::Range{ start: 0, end: index.end })
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
585 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
586 let len = self.len();
587 self.index_mut(&ops::Range{ start: index.start, end: len })
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<T> ops::IndexMut<RangeFull> for [T] {
594 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
600 ////////////////////////////////////////////////////////////////////////////////
602 ////////////////////////////////////////////////////////////////////////////////
604 /// Data that is viewable as a slice.
605 #[unstable(feature = "core",
606 reason = "will be replaced by slice syntax")]
607 pub trait AsSlice<T> {
608 /// Work with `self` as a slice.
609 fn as_slice<'a>(&'a self) -> &'a [T];
612 #[unstable(feature = "core", reason = "trait is experimental")]
613 impl<T> AsSlice<T> for [T] {
615 fn as_slice<'a>(&'a self) -> &'a [T] { self }
618 #[unstable(feature = "core", reason = "trait is experimental")]
619 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
621 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
624 #[unstable(feature = "core", reason = "trait is experimental")]
625 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
627 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<'a, T> Default for &'a [T] {
632 #[stable(feature = "rust1", since = "1.0.0")]
633 fn default() -> &'a [T] { &[] }
640 impl<'a, T> IntoIterator for &'a [T] {
641 type Iter = Iter<'a, T>;
643 fn into_iter(self) -> Iter<'a, T> {
648 impl<'a, T> IntoIterator for &'a mut [T] {
649 type Iter = IterMut<'a, T>;
651 fn into_iter(self) -> IterMut<'a, T> {
656 // The shared definition of the `Iter` and `IterMut` iterators
657 macro_rules! iterator {
658 (struct $name:ident -> $ptr:ty, $elem:ty) => {
659 #[stable(feature = "rust1", since = "1.0.0")]
660 impl<'a, T> Iterator for $name<'a, T> {
664 fn next(&mut self) -> Option<$elem> {
665 // could be implemented with slices, but this avoids bounds checks
667 if self.ptr == self.end {
670 if mem::size_of::<T>() == 0 {
671 // purposefully don't use 'ptr.offset' because for
672 // vectors with 0-size elements this would return the
674 self.ptr = transmute(self.ptr as uint + 1);
676 // Use a non-null pointer value
677 Some(&mut *(1 as *mut _))
680 self.ptr = self.ptr.offset(1);
689 fn size_hint(&self) -> (uint, Option<uint>) {
690 let diff = (self.end as uint) - (self.ptr as uint);
691 let size = mem::size_of::<T>();
692 let exact = diff / (if size == 0 {1} else {size});
697 #[stable(feature = "rust1", since = "1.0.0")]
698 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
700 fn next_back(&mut self) -> Option<$elem> {
701 // could be implemented with slices, but this avoids bounds checks
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 uint - 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 uint - $start as uint;
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::ContravariantLifetime<'a>
746 #[unstable(feature = "core")]
747 impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
750 fn index(&self, index: &ops::Range<uint>) -> &[T] {
751 self.as_slice().index(index)
755 #[unstable(feature = "core")]
756 impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
759 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
760 self.as_slice().index(index)
764 #[unstable(feature = "core")]
765 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
768 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
769 self.as_slice().index(index)
774 #[unstable(feature = "core")]
775 impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
778 fn index(&self, _index: &ops::FullRange) -> &[T] {
783 #[unstable(feature = "core")]
784 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
787 fn index(&self, _index: &RangeFull) -> &[T] {
792 impl<'a, T> Iter<'a, T> {
793 /// View the underlying data as a subslice of the original data.
795 /// This has the same lifetime as the original slice, and so the
796 /// iterator can continue to be used while this exists.
797 #[unstable(feature = "core")]
798 pub fn as_slice(&self) -> &'a [T] {
799 make_slice!(T => &'a [T]: self.ptr, self.end)
803 impl<'a,T> Copy for Iter<'a,T> {}
805 iterator!{struct Iter -> *const T, &'a T}
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
810 #[stable(feature = "rust1", since = "1.0.0")]
811 impl<'a, T> Clone for Iter<'a, T> {
812 fn clone(&self) -> Iter<'a, T> { *self }
815 #[unstable(feature = "core", reason = "trait is experimental")]
816 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
818 fn indexable(&self) -> uint {
819 let (exact, _) = self.size_hint();
824 fn idx(&mut self, index: uint) -> Option<&'a T> {
826 if index < self.indexable() {
827 if mem::size_of::<T>() == 0 {
828 // Use a non-null pointer value
829 Some(&mut *(1 as *mut _))
831 Some(transmute(self.ptr.offset(index as int)))
840 /// Mutable slice iterator.
841 #[stable(feature = "rust1", since = "1.0.0")]
842 pub struct IterMut<'a, T: 'a> {
845 marker: marker::ContravariantLifetime<'a>,
849 #[unstable(feature = "core")]
850 impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
853 fn index(&self, index: &ops::Range<uint>) -> &[T] {
854 self.index(&RangeFull).index(index)
857 #[unstable(feature = "core")]
858 impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
861 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
862 self.index(&RangeFull).index(index)
865 #[unstable(feature = "core")]
866 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
869 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
870 self.index(&RangeFull).index(index)
873 #[unstable(feature = "core")]
874 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
877 fn index(&self, _index: &RangeFull) -> &[T] {
878 make_slice!(T => &[T]: self.ptr, self.end)
882 #[unstable(feature = "core")]
883 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
886 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
887 self.index_mut(&RangeFull).index_mut(index)
890 #[unstable(feature = "core")]
891 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
894 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
895 self.index_mut(&RangeFull).index_mut(index)
898 #[unstable(feature = "core")]
899 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
902 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
903 self.index_mut(&RangeFull).index_mut(index)
906 #[unstable(feature = "core")]
907 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
910 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
911 make_slice!(T => &mut [T]: self.ptr, self.end)
916 impl<'a, T> IterMut<'a, T> {
917 /// View the underlying data as a subslice of the original data.
919 /// To avoid creating `&mut` references that alias, this is forced
920 /// to consume the iterator. Consider using the `Slice` and
921 /// `SliceMut` implementations for obtaining slices with more
922 /// restricted lifetimes that do not consume the iterator.
923 #[unstable(feature = "core")]
924 pub fn into_slice(self) -> &'a mut [T] {
925 make_slice!(T => &'a mut [T]: self.ptr, self.end)
929 iterator!{struct IterMut -> *mut T, &'a mut T}
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
934 /// An internal abstraction over the splitting iterators, so that
935 /// splitn, splitn_mut etc can be implemented once.
936 trait SplitIter: DoubleEndedIterator {
937 /// Mark the underlying iterator as complete, extracting the remaining
938 /// portion of the slice.
939 fn finish(&mut self) -> Option<Self::Item>;
942 /// An iterator over subslices separated by elements that match a predicate
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
951 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
954 fn clone(&self) -> Split<'a, T, P> {
957 pred: self.pred.clone(),
958 finished: self.finished,
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
968 fn next(&mut self) -> Option<&'a [T]> {
969 if self.finished { return None; }
971 match self.v.iter().position(|x| (self.pred)(x)) {
972 None => self.finish(),
974 let ret = Some(&self.v[..idx]);
975 self.v = &self.v[idx + 1..];
982 fn size_hint(&self) -> (uint, Option<uint>) {
986 (1, Some(self.v.len() + 1))
991 #[stable(feature = "rust1", since = "1.0.0")]
992 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
994 fn next_back(&mut self) -> Option<&'a [T]> {
995 if self.finished { return None; }
997 match self.v.iter().rposition(|x| (self.pred)(x)) {
998 None => self.finish(),
1000 let ret = Some(&self.v[idx + 1..]);
1001 self.v = &self.v[..idx];
1008 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1010 fn finish(&mut self) -> Option<&'a [T]> {
1011 if self.finished { None } else { self.finished = true; Some(self.v) }
1015 /// An iterator over the subslices of the vector which are separated
1016 /// by elements that match `pred`.
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1024 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1026 fn finish(&mut self) -> Option<&'a mut [T]> {
1030 self.finished = true;
1031 Some(mem::replace(&mut self.v, &mut []))
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1038 type Item = &'a mut [T];
1041 fn next(&mut self) -> Option<&'a mut [T]> {
1042 if self.finished { return None; }
1044 let idx_opt = { // work around borrowck limitations
1045 let pred = &mut self.pred;
1046 self.v.iter().position(|x| (*pred)(x))
1049 None => self.finish(),
1051 let tmp = mem::replace(&mut self.v, &mut []);
1052 let (head, tail) = tmp.split_at_mut(idx);
1053 self.v = &mut tail[1..];
1060 fn size_hint(&self) -> (uint, Option<uint>) {
1064 // if the predicate doesn't match anything, we yield one slice
1065 // if it matches every element, we yield len+1 empty slices.
1066 (1, Some(self.v.len() + 1))
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1073 P: FnMut(&T) -> bool,
1076 fn next_back(&mut self) -> Option<&'a mut [T]> {
1077 if self.finished { return None; }
1079 let idx_opt = { // work around borrowck limitations
1080 let pred = &mut self.pred;
1081 self.v.iter().rposition(|x| (*pred)(x))
1084 None => self.finish(),
1086 let tmp = mem::replace(&mut self.v, &mut []);
1087 let (head, tail) = tmp.split_at_mut(idx);
1089 Some(&mut tail[1..])
1095 /// An private iterator over subslices separated by elements that
1096 /// match a predicate function, splitting at most a fixed number of
1098 struct GenericSplitN<I> {
1104 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1108 fn next(&mut self) -> Option<T> {
1109 if self.count == 0 {
1113 if self.invert { self.iter.next_back() } else { self.iter.next() }
1118 fn size_hint(&self) -> (uint, Option<uint>) {
1119 let (lower, upper_opt) = self.iter.size_hint();
1120 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1124 /// An iterator over subslices separated by elements that match a predicate
1125 /// function, limited to a given number of splits.
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1128 inner: GenericSplitN<Split<'a, T, P>>
1131 /// An iterator over subslices separated by elements that match a
1132 /// predicate function, limited to a given number of splits, starting
1133 /// from the end of the slice.
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1136 inner: GenericSplitN<Split<'a, T, P>>
1139 /// An iterator over subslices separated by elements that match a predicate
1140 /// function, limited to a given number of splits.
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1143 inner: GenericSplitN<SplitMut<'a, T, P>>
1146 /// An iterator over subslices separated by elements that match a
1147 /// predicate function, limited to a given number of splits, starting
1148 /// from the end of the slice.
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1151 inner: GenericSplitN<SplitMut<'a, T, P>>
1154 macro_rules! forward_iterator {
1155 ($name:ident: $elem:ident, $iter_of:ty) => {
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1158 P: FnMut(&T) -> bool
1160 type Item = $iter_of;
1163 fn next(&mut self) -> Option<$iter_of> {
1168 fn size_hint(&self) -> (uint, Option<uint>) {
1169 self.inner.size_hint()
1175 forward_iterator! { SplitN: T, &'a [T] }
1176 forward_iterator! { RSplitN: T, &'a [T] }
1177 forward_iterator! { SplitNMut: T, &'a mut [T] }
1178 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1180 /// An iterator over overlapping subslices of length `size`.
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 pub struct Windows<'a, T:'a> {
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) -> (uint, Option<uint>) {
1205 if self.size > self.v.len() {
1208 let x = self.v.len() - self.size;
1209 (x.saturating_add(1), x.checked_add(1))
1214 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1217 /// When the slice len is not evenly divided by the chunk size, the last slice
1218 /// of the iteration will be the remainder.
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub struct Chunks<'a, T:'a> {
1226 #[stable(feature = "rust1", since = "1.0.0")]
1227 impl<'a, T> Iterator for Chunks<'a, T> {
1228 type Item = &'a [T];
1231 fn next(&mut self) -> Option<&'a [T]> {
1232 if self.v.len() == 0 {
1235 let chunksz = cmp::min(self.v.len(), self.size);
1236 let (fst, snd) = self.v.split_at(chunksz);
1243 fn size_hint(&self) -> (uint, Option<uint>) {
1244 if self.v.len() == 0 {
1247 let n = self.v.len() / self.size;
1248 let rem = self.v.len() % self.size;
1249 let n = if rem > 0 { n+1 } else { n };
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1258 fn next_back(&mut self) -> Option<&'a [T]> {
1259 if self.v.len() == 0 {
1262 let remainder = self.v.len() % self.size;
1263 let chunksz = if remainder != 0 { remainder } else { self.size };
1264 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1271 #[stable(feature = "rust1", since = "1.0.0")]
1272 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1274 #[unstable(feature = "core", reason = "trait is experimental")]
1275 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1277 fn indexable(&self) -> uint {
1278 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1282 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1283 if index < self.indexable() {
1284 let lo = index * self.size;
1285 let mut hi = lo + self.size;
1286 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1288 Some(&self.v[lo..hi])
1295 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1296 /// elements at a time). When the slice len is not evenly divided by the chunk
1297 /// size, the last slice of the iteration will be the remainder.
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 pub struct ChunksMut<'a, T:'a> {
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<'a, T> Iterator for ChunksMut<'a, T> {
1306 type Item = &'a mut [T];
1309 fn next(&mut self) -> Option<&'a mut [T]> {
1310 if self.v.len() == 0 {
1313 let sz = cmp::min(self.v.len(), self.chunk_size);
1314 let tmp = mem::replace(&mut self.v, &mut []);
1315 let (head, tail) = tmp.split_at_mut(sz);
1322 fn size_hint(&self) -> (uint, Option<uint>) {
1323 if self.v.len() == 0 {
1326 let n = self.v.len() / self.chunk_size;
1327 let rem = self.v.len() % self.chunk_size;
1328 let n = if rem > 0 { n + 1 } else { n };
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1337 fn next_back(&mut self) -> Option<&'a mut [T]> {
1338 if self.v.len() == 0 {
1341 let remainder = self.v.len() % self.chunk_size;
1342 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1343 let tmp = mem::replace(&mut self.v, &mut []);
1344 let tmp_len = tmp.len();
1345 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1352 #[stable(feature = "rust1", since = "1.0.0")]
1353 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1359 /// Converts a pointer to A into a slice of length 1 (without copying).
1360 #[unstable(feature = "core")]
1361 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1363 transmute(RawSlice { data: s, len: 1 })
1367 /// Converts a pointer to A into a slice of length 1 (without copying).
1368 #[unstable(feature = "core")]
1369 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1371 let ptr: *const A = transmute(s);
1372 transmute(RawSlice { data: ptr, len: 1 })
1376 /// Forms a slice from a pointer and a length.
1378 /// The pointer given is actually a reference to the base of the slice. This
1379 /// reference is used to give a concrete lifetime to tie the returned slice to.
1380 /// Typically this should indicate that the slice is valid for as long as the
1381 /// pointer itself is valid.
1383 /// The `len` argument is the number of **elements**, not the number of bytes.
1385 /// This function is unsafe as there is no guarantee that the given pointer is
1386 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1387 /// lifetime for the returned slice.
1394 /// // manifest a slice out of thin air!
1395 /// let ptr = 0x1234 as *const uint;
1398 /// let slice = slice::from_raw_buf(&ptr, amt);
1402 #[unstable(feature = "core",
1403 reason = "should be renamed to from_raw_parts")]
1404 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1405 transmute(RawSlice { data: *p, len: len })
1408 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1409 /// slice is returned.
1411 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1412 /// not being able to provide a non-aliasing guarantee of the returned mutable
1415 #[unstable(feature = "core",
1416 reason = "should be renamed to from_raw_parts_mut")]
1417 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1418 transmute(RawSlice { data: *p, len: len })
1425 /// Operations on `[u8]`.
1426 #[unstable(feature = "core", reason = "needs review")]
1429 use slice::SliceExt;
1431 /// A trait for operations on mutable `[u8]`s.
1432 pub trait MutableByteVector {
1433 /// Sets all bytes of the receiver to the given value.
1434 fn set_memory(&mut self, value: u8);
1437 impl MutableByteVector for [u8] {
1439 fn set_memory(&mut self, value: u8) {
1440 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1444 /// Copies data from `src` to `dst`
1446 /// Panics if the length of `dst` is less than the length of `src`.
1448 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1449 let len_src = src.len();
1450 assert!(dst.len() >= len_src);
1451 // `dst` is unaliasable, so we know statically it doesn't overlap
1454 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1464 // Boilerplate traits
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1469 fn eq(&self, other: &[B]) -> bool {
1470 self.len() == other.len() &&
1471 order::eq(self.iter(), other.iter())
1473 fn ne(&self, other: &[B]) -> bool {
1474 self.len() != other.len() ||
1475 order::ne(self.iter(), other.iter())
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<T: Eq> Eq for [T] {}
1482 #[stable(feature = "rust1", since = "1.0.0")]
1483 impl<T: Ord> Ord for [T] {
1484 fn cmp(&self, other: &[T]) -> Ordering {
1485 order::cmp(self.iter(), other.iter())
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl<T: PartialOrd> PartialOrd for [T] {
1492 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1493 order::partial_cmp(self.iter(), other.iter())
1496 fn lt(&self, other: &[T]) -> bool {
1497 order::lt(self.iter(), other.iter())
1500 fn le(&self, other: &[T]) -> bool {
1501 order::le(self.iter(), other.iter())
1504 fn ge(&self, other: &[T]) -> bool {
1505 order::ge(self.iter(), other.iter())
1508 fn gt(&self, other: &[T]) -> bool {
1509 order::gt(self.iter(), other.iter())
1513 /// Extension methods for slices containing integers.
1514 #[unstable(feature = "core")]
1515 pub trait IntSliceExt<U, S> {
1516 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1517 fn as_unsigned<'a>(&'a self) -> &'a [U];
1518 /// Converts the slice to an immutable slice of signed integers with the same width.
1519 fn as_signed<'a>(&'a self) -> &'a [S];
1521 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1522 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1523 /// Converts the slice to a mutable slice of signed integers with the same width.
1524 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1527 macro_rules! impl_int_slice {
1528 ($u:ty, $s:ty, $t:ty) => {
1529 #[unstable(feature = "core")]
1530 impl IntSliceExt<$u, $s> for [$t] {
1532 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1534 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1536 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1538 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1543 macro_rules! impl_int_slices {
1545 impl_int_slice! { $u, $s, $u }
1546 impl_int_slice! { $u, $s, $s }
1550 impl_int_slices! { u8, i8 }
1551 impl_int_slices! { u16, i16 }
1552 impl_int_slices! { u32, i32 }
1553 impl_int_slices! { u64, i64 }
1554 impl_int_slices! { uint, int }