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 // The shared definition of the `Iter` and `IterMut` iterators
641 macro_rules! iterator {
642 (struct $name:ident -> $ptr:ty, $elem:ty) => {
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<'a, T> Iterator for $name<'a, T> {
648 fn next(&mut self) -> Option<$elem> {
649 // could be implemented with slices, but this avoids bounds checks
651 if self.ptr == self.end {
654 if mem::size_of::<T>() == 0 {
655 // purposefully don't use 'ptr.offset' because for
656 // vectors with 0-size elements this would return the
658 self.ptr = transmute(self.ptr as uint + 1);
660 // Use a non-null pointer value
661 Some(&mut *(1 as *mut _))
664 self.ptr = self.ptr.offset(1);
673 fn size_hint(&self) -> (uint, Option<uint>) {
674 let diff = (self.end as uint) - (self.ptr as uint);
675 let size = mem::size_of::<T>();
676 let exact = diff / (if size == 0 {1} else {size});
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
684 fn next_back(&mut self) -> Option<$elem> {
685 // could be implemented with slices, but this avoids bounds checks
687 if self.end == self.ptr {
690 if mem::size_of::<T>() == 0 {
691 // See above for why 'ptr.offset' isn't used
692 self.end = transmute(self.end as uint - 1);
694 // Use a non-null pointer value
695 Some(&mut *(1 as *mut _))
697 self.end = self.end.offset(-1);
699 Some(transmute(self.end))
708 macro_rules! make_slice {
709 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
710 let diff = $end as uint - $start as uint;
711 let len = if mem::size_of::<T>() == 0 {
714 diff / mem::size_of::<$t>()
717 transmute::<_, $result>(RawSlice { data: $start, len: len })
722 /// Immutable slice iterator
723 #[stable(feature = "rust1", since = "1.0.0")]
724 pub struct Iter<'a, T: 'a> {
727 marker: marker::ContravariantLifetime<'a>
730 #[unstable(feature = "core")]
731 impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
734 fn index(&self, index: &ops::Range<uint>) -> &[T] {
735 self.as_slice().index(index)
739 #[unstable(feature = "core")]
740 impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
743 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
744 self.as_slice().index(index)
748 #[unstable(feature = "core")]
749 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
752 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
753 self.as_slice().index(index)
758 #[unstable(feature = "core")]
759 impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
762 fn index(&self, _index: &ops::FullRange) -> &[T] {
767 #[unstable(feature = "core")]
768 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
771 fn index(&self, _index: &RangeFull) -> &[T] {
776 impl<'a, T> Iter<'a, T> {
777 /// View the underlying data as a subslice of the original data.
779 /// This has the same lifetime as the original slice, and so the
780 /// iterator can continue to be used while this exists.
781 #[unstable(feature = "core")]
782 pub fn as_slice(&self) -> &'a [T] {
783 make_slice!(T => &'a [T]: self.ptr, self.end)
787 impl<'a,T> Copy for Iter<'a,T> {}
789 iterator!{struct Iter -> *const T, &'a T}
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl<'a, T> Clone for Iter<'a, T> {
796 fn clone(&self) -> Iter<'a, T> { *self }
799 #[unstable(feature = "core", reason = "trait is experimental")]
800 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
802 fn indexable(&self) -> uint {
803 let (exact, _) = self.size_hint();
808 fn idx(&mut self, index: uint) -> Option<&'a T> {
810 if index < self.indexable() {
811 if mem::size_of::<T>() == 0 {
812 // Use a non-null pointer value
813 Some(&mut *(1 as *mut _))
815 Some(transmute(self.ptr.offset(index as int)))
824 /// Mutable slice iterator.
825 #[stable(feature = "rust1", since = "1.0.0")]
826 pub struct IterMut<'a, T: 'a> {
829 marker: marker::ContravariantLifetime<'a>,
833 #[unstable(feature = "core")]
834 impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
837 fn index(&self, index: &ops::Range<uint>) -> &[T] {
838 self.index(&RangeFull).index(index)
841 #[unstable(feature = "core")]
842 impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
845 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
846 self.index(&RangeFull).index(index)
849 #[unstable(feature = "core")]
850 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
853 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
854 self.index(&RangeFull).index(index)
857 #[unstable(feature = "core")]
858 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
861 fn index(&self, _index: &RangeFull) -> &[T] {
862 make_slice!(T => &[T]: self.ptr, self.end)
866 #[unstable(feature = "core")]
867 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
870 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
871 self.index_mut(&RangeFull).index_mut(index)
874 #[unstable(feature = "core")]
875 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
878 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
879 self.index_mut(&RangeFull).index_mut(index)
882 #[unstable(feature = "core")]
883 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
886 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
887 self.index_mut(&RangeFull).index_mut(index)
890 #[unstable(feature = "core")]
891 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
894 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
895 make_slice!(T => &mut [T]: self.ptr, self.end)
900 impl<'a, T> IterMut<'a, T> {
901 /// View the underlying data as a subslice of the original data.
903 /// To avoid creating `&mut` references that alias, this is forced
904 /// to consume the iterator. Consider using the `Slice` and
905 /// `SliceMut` implementations for obtaining slices with more
906 /// restricted lifetimes that do not consume the iterator.
907 #[unstable(feature = "core")]
908 pub fn into_slice(self) -> &'a mut [T] {
909 make_slice!(T => &'a mut [T]: self.ptr, self.end)
913 iterator!{struct IterMut -> *mut T, &'a mut T}
915 #[stable(feature = "rust1", since = "1.0.0")]
916 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
918 /// An internal abstraction over the splitting iterators, so that
919 /// splitn, splitn_mut etc can be implemented once.
920 trait SplitIter: DoubleEndedIterator {
921 /// Mark the underlying iterator as complete, extracting the remaining
922 /// portion of the slice.
923 fn finish(&mut self) -> Option<Self::Item>;
926 /// An iterator over subslices separated by elements that match a predicate
928 #[stable(feature = "rust1", since = "1.0.0")]
929 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
935 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
936 #[stable(feature = "rust1", since = "1.0.0")]
937 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
938 fn clone(&self) -> Split<'a, T, P> {
941 pred: self.pred.clone(),
942 finished: self.finished,
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
952 fn next(&mut self) -> Option<&'a [T]> {
953 if self.finished { return None; }
955 match self.v.iter().position(|x| (self.pred)(x)) {
956 None => self.finish(),
958 let ret = Some(&self.v[..idx]);
959 self.v = &self.v[idx + 1..];
966 fn size_hint(&self) -> (uint, Option<uint>) {
970 (1, Some(self.v.len() + 1))
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
978 fn next_back(&mut self) -> Option<&'a [T]> {
979 if self.finished { return None; }
981 match self.v.iter().rposition(|x| (self.pred)(x)) {
982 None => self.finish(),
984 let ret = Some(&self.v[idx + 1..]);
985 self.v = &self.v[..idx];
992 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
994 fn finish(&mut self) -> Option<&'a [T]> {
995 if self.finished { None } else { self.finished = true; Some(self.v) }
999 /// An iterator over the subslices of the vector which are separated
1000 /// by elements that match `pred`.
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1008 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1010 fn finish(&mut self) -> Option<&'a mut [T]> {
1014 self.finished = true;
1015 Some(mem::replace(&mut self.v, &mut []))
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1022 type Item = &'a mut [T];
1025 fn next(&mut self) -> Option<&'a mut [T]> {
1026 if self.finished { return None; }
1028 let idx_opt = { // work around borrowck limitations
1029 let pred = &mut self.pred;
1030 self.v.iter().position(|x| (*pred)(x))
1033 None => self.finish(),
1035 let tmp = mem::replace(&mut self.v, &mut []);
1036 let (head, tail) = tmp.split_at_mut(idx);
1037 self.v = &mut tail[1..];
1044 fn size_hint(&self) -> (uint, Option<uint>) {
1048 // if the predicate doesn't match anything, we yield one slice
1049 // if it matches every element, we yield len+1 empty slices.
1050 (1, Some(self.v.len() + 1))
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1057 P: FnMut(&T) -> bool,
1060 fn next_back(&mut self) -> Option<&'a mut [T]> {
1061 if self.finished { return None; }
1063 let idx_opt = { // work around borrowck limitations
1064 let pred = &mut self.pred;
1065 self.v.iter().rposition(|x| (*pred)(x))
1068 None => self.finish(),
1070 let tmp = mem::replace(&mut self.v, &mut []);
1071 let (head, tail) = tmp.split_at_mut(idx);
1073 Some(&mut tail[1..])
1079 /// An private iterator over subslices separated by elements that
1080 /// match a predicate function, splitting at most a fixed number of
1082 struct GenericSplitN<I> {
1088 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1092 fn next(&mut self) -> Option<T> {
1093 if self.count == 0 {
1097 if self.invert { self.iter.next_back() } else { self.iter.next() }
1102 fn size_hint(&self) -> (uint, Option<uint>) {
1103 let (lower, upper_opt) = self.iter.size_hint();
1104 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1108 /// An iterator over subslices separated by elements that match a predicate
1109 /// function, limited to a given number of splits.
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1112 inner: GenericSplitN<Split<'a, T, P>>
1115 /// An iterator over subslices separated by elements that match a
1116 /// predicate function, limited to a given number of splits, starting
1117 /// from the end of the slice.
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1120 inner: GenericSplitN<Split<'a, T, P>>
1123 /// An iterator over subslices separated by elements that match a predicate
1124 /// function, limited to a given number of splits.
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1127 inner: GenericSplitN<SplitMut<'a, T, P>>
1130 /// An iterator over subslices separated by elements that match a
1131 /// predicate function, limited to a given number of splits, starting
1132 /// from the end of the slice.
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1135 inner: GenericSplitN<SplitMut<'a, T, P>>
1138 macro_rules! forward_iterator {
1139 ($name:ident: $elem:ident, $iter_of:ty) => {
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1142 P: FnMut(&T) -> bool
1144 type Item = $iter_of;
1147 fn next(&mut self) -> Option<$iter_of> {
1152 fn size_hint(&self) -> (uint, Option<uint>) {
1153 self.inner.size_hint()
1159 forward_iterator! { SplitN: T, &'a [T] }
1160 forward_iterator! { RSplitN: T, &'a [T] }
1161 forward_iterator! { SplitNMut: T, &'a mut [T] }
1162 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1164 /// An iterator over overlapping subslices of length `size`.
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 pub struct Windows<'a, T:'a> {
1172 #[stable(feature = "rust1", since = "1.0.0")]
1173 impl<'a, T> Iterator for Windows<'a, T> {
1174 type Item = &'a [T];
1177 fn next(&mut self) -> Option<&'a [T]> {
1178 if self.size > self.v.len() {
1181 let ret = Some(&self.v[..self.size]);
1182 self.v = &self.v[1..];
1188 fn size_hint(&self) -> (uint, Option<uint>) {
1189 if self.size > self.v.len() {
1192 let x = self.v.len() - self.size;
1193 (x.saturating_add(1), x.checked_add(1))
1198 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1201 /// When the slice len is not evenly divided by the chunk size, the last slice
1202 /// of the iteration will be the remainder.
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 pub struct Chunks<'a, T:'a> {
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<'a, T> Iterator for Chunks<'a, T> {
1212 type Item = &'a [T];
1215 fn next(&mut self) -> Option<&'a [T]> {
1216 if self.v.len() == 0 {
1219 let chunksz = cmp::min(self.v.len(), self.size);
1220 let (fst, snd) = self.v.split_at(chunksz);
1227 fn size_hint(&self) -> (uint, Option<uint>) {
1228 if self.v.len() == 0 {
1231 let n = self.v.len() / self.size;
1232 let rem = self.v.len() % self.size;
1233 let n = if rem > 0 { n+1 } else { n };
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1242 fn next_back(&mut self) -> Option<&'a [T]> {
1243 if self.v.len() == 0 {
1246 let remainder = self.v.len() % self.size;
1247 let chunksz = if remainder != 0 { remainder } else { self.size };
1248 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1258 #[unstable(feature = "core", reason = "trait is experimental")]
1259 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1261 fn indexable(&self) -> uint {
1262 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1266 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1267 if index < self.indexable() {
1268 let lo = index * self.size;
1269 let mut hi = lo + self.size;
1270 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1272 Some(&self.v[lo..hi])
1279 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1280 /// elements at a time). When the slice len is not evenly divided by the chunk
1281 /// size, the last slice of the iteration will be the remainder.
1282 #[stable(feature = "rust1", since = "1.0.0")]
1283 pub struct ChunksMut<'a, T:'a> {
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<'a, T> Iterator for ChunksMut<'a, T> {
1290 type Item = &'a mut [T];
1293 fn next(&mut self) -> Option<&'a mut [T]> {
1294 if self.v.len() == 0 {
1297 let sz = cmp::min(self.v.len(), self.chunk_size);
1298 let tmp = mem::replace(&mut self.v, &mut []);
1299 let (head, tail) = tmp.split_at_mut(sz);
1306 fn size_hint(&self) -> (uint, Option<uint>) {
1307 if self.v.len() == 0 {
1310 let n = self.v.len() / self.chunk_size;
1311 let rem = self.v.len() % self.chunk_size;
1312 let n = if rem > 0 { n + 1 } else { n };
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1321 fn next_back(&mut self) -> Option<&'a mut [T]> {
1322 if self.v.len() == 0 {
1325 let remainder = self.v.len() % self.chunk_size;
1326 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1327 let tmp = mem::replace(&mut self.v, &mut []);
1328 let tmp_len = tmp.len();
1329 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1343 /// Converts a pointer to A into a slice of length 1 (without copying).
1344 #[unstable(feature = "core")]
1345 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1347 transmute(RawSlice { data: s, len: 1 })
1351 /// Converts a pointer to A into a slice of length 1 (without copying).
1352 #[unstable(feature = "core")]
1353 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1355 let ptr: *const A = transmute(s);
1356 transmute(RawSlice { data: ptr, len: 1 })
1360 /// Forms a slice from a pointer and a length.
1362 /// The pointer given is actually a reference to the base of the slice. This
1363 /// reference is used to give a concrete lifetime to tie the returned slice to.
1364 /// Typically this should indicate that the slice is valid for as long as the
1365 /// pointer itself is valid.
1367 /// The `len` argument is the number of **elements**, not the number of bytes.
1369 /// This function is unsafe as there is no guarantee that the given pointer is
1370 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1371 /// lifetime for the returned slice.
1378 /// // manifest a slice out of thin air!
1379 /// let ptr = 0x1234 as *const uint;
1382 /// let slice = slice::from_raw_buf(&ptr, amt);
1386 #[unstable(feature = "core",
1387 reason = "should be renamed to from_raw_parts")]
1388 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1389 transmute(RawSlice { data: *p, len: len })
1392 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1393 /// slice is returned.
1395 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1396 /// not being able to provide a non-aliasing guarantee of the returned mutable
1399 #[unstable(feature = "core",
1400 reason = "should be renamed to from_raw_parts_mut")]
1401 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1402 transmute(RawSlice { data: *p, len: len })
1409 /// Operations on `[u8]`.
1410 #[unstable(feature = "core", reason = "needs review")]
1413 use slice::SliceExt;
1415 /// A trait for operations on mutable `[u8]`s.
1416 pub trait MutableByteVector {
1417 /// Sets all bytes of the receiver to the given value.
1418 fn set_memory(&mut self, value: u8);
1421 impl MutableByteVector for [u8] {
1423 fn set_memory(&mut self, value: u8) {
1424 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1428 /// Copies data from `src` to `dst`
1430 /// Panics if the length of `dst` is less than the length of `src`.
1432 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1433 let len_src = src.len();
1434 assert!(dst.len() >= len_src);
1435 // `dst` is unaliasable, so we know statically it doesn't overlap
1438 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1448 // Boilerplate traits
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1453 fn eq(&self, other: &[B]) -> bool {
1454 self.len() == other.len() &&
1455 order::eq(self.iter(), other.iter())
1457 fn ne(&self, other: &[B]) -> bool {
1458 self.len() != other.len() ||
1459 order::ne(self.iter(), other.iter())
1463 #[stable(feature = "rust1", since = "1.0.0")]
1464 impl<T: Eq> Eq for [T] {}
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 impl<T: Ord> Ord for [T] {
1468 fn cmp(&self, other: &[T]) -> Ordering {
1469 order::cmp(self.iter(), other.iter())
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<T: PartialOrd> PartialOrd for [T] {
1476 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1477 order::partial_cmp(self.iter(), other.iter())
1480 fn lt(&self, other: &[T]) -> bool {
1481 order::lt(self.iter(), other.iter())
1484 fn le(&self, other: &[T]) -> bool {
1485 order::le(self.iter(), other.iter())
1488 fn ge(&self, other: &[T]) -> bool {
1489 order::ge(self.iter(), other.iter())
1492 fn gt(&self, other: &[T]) -> bool {
1493 order::gt(self.iter(), other.iter())
1497 /// Extension methods for slices containing integers.
1498 #[unstable(feature = "core")]
1499 pub trait IntSliceExt<U, S> {
1500 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1501 fn as_unsigned<'a>(&'a self) -> &'a [U];
1502 /// Converts the slice to an immutable slice of signed integers with the same width.
1503 fn as_signed<'a>(&'a self) -> &'a [S];
1505 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1506 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1507 /// Converts the slice to a mutable slice of signed integers with the same width.
1508 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1511 macro_rules! impl_int_slice {
1512 ($u:ty, $s:ty, $t:ty) => {
1513 #[unstable(feature = "core")]
1514 impl IntSliceExt<$u, $s> for [$t] {
1516 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1518 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1520 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1522 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1527 macro_rules! impl_int_slices {
1529 impl_int_slice! { $u, $s, $u }
1530 impl_int_slice! { $u, $s, $s }
1534 impl_int_slices! { u8, i8 }
1535 impl_int_slices! { u16, i16 }
1536 impl_int_slices! { u32, i32 }
1537 impl_int_slices! { u64, i64 }
1538 impl_int_slices! { uint, int }