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};
45 use ops::{FnMut, self, Index};
47 use ops::FullRange as RangeFull;
51 use option::Option::{None, Some};
53 use result::Result::{Ok, Err};
58 use marker::{Sized, self};
60 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
61 use raw::Slice as RawSlice;
68 /// Extension methods for slices.
69 #[allow(missing_docs)] // docs in libcollections
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 iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
97 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
98 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
99 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
100 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
101 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
102 where P: FnMut(&Self::Item) -> bool;
103 fn splitn_mut<P>(&mut self, n: uint, pred: P) -> SplitNMut<Self::Item, P>
104 where P: FnMut(&Self::Item) -> bool;
105 fn rsplitn_mut<P>(&mut self, n: uint, pred: P) -> RSplitNMut<Self::Item, P>
106 where P: FnMut(&Self::Item) -> bool;
107 fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, Self::Item>;
108 fn swap(&mut self, a: uint, b: uint);
109 fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
110 fn reverse(&mut self);
111 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut Self::Item;
112 fn as_mut_ptr(&mut self) -> *mut Self::Item;
114 fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
116 fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
118 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
120 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
122 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
124 fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
125 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
126 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
128 fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
131 #[unstable(feature = "core")]
132 impl<T> SliceExt for [T] {
136 fn split_at(&self, mid: uint) -> (&[T], &[T]) {
137 (&self[..mid], &self[mid..])
141 fn iter<'a>(&'a self) -> Iter<'a, T> {
143 let p = self.as_ptr();
144 if mem::size_of::<T>() == 0 {
146 end: (p as uint + self.len()) as *const T,
147 marker: marker::ContravariantLifetime::<'a>}
150 end: p.offset(self.len() as int),
151 marker: marker::ContravariantLifetime::<'a>}
157 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
166 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, T, P> where
167 P: FnMut(&T) -> bool,
170 inner: GenericSplitN {
171 iter: self.split(pred),
179 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, T, P> where
180 P: FnMut(&T) -> bool,
183 inner: GenericSplitN {
184 iter: self.split(pred),
192 fn windows(&self, size: uint) -> Windows<T> {
194 Windows { v: self, size: size }
198 fn chunks(&self, size: uint) -> Chunks<T> {
200 Chunks { v: self, size: size }
204 fn get(&self, index: uint) -> Option<&T> {
205 if index < self.len() { Some(&self[index]) } else { None }
209 fn first(&self) -> Option<&T> {
210 if self.len() == 0 { None } else { Some(&self[0]) }
214 fn tail(&self) -> &[T] { &self[1..] }
217 fn init(&self) -> &[T] {
218 &self[..self.len() - 1]
222 fn last(&self) -> Option<&T> {
223 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
227 unsafe fn get_unchecked(&self, index: uint) -> &T {
228 transmute(self.repr().data.offset(index as int))
232 fn as_ptr(&self) -> *const T {
236 #[unstable(feature = "core")]
237 fn binary_search_by<F>(&self, mut f: F) -> Result<uint, uint> where
238 F: FnMut(&T) -> Ordering
240 let mut base : uint = 0;
241 let mut lim : uint = self.len();
244 let ix = base + (lim >> 1);
246 Equal => return Ok(ix),
259 fn len(&self) -> uint { self.repr().len }
262 fn get_mut(&mut self, index: uint) -> Option<&mut T> {
263 if index < self.len() { Some(&mut self[index]) } else { None }
267 fn as_mut_slice(&mut self) -> &mut [T] { self }
270 fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
272 let self2: &mut [T] = mem::transmute_copy(&self);
274 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
275 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
280 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
282 let p = self.as_mut_ptr();
283 if mem::size_of::<T>() == 0 {
285 end: (p as uint + self.len()) as *mut T,
286 marker: marker::ContravariantLifetime::<'a>}
289 end: p.offset(self.len() as int),
290 marker: marker::ContravariantLifetime::<'a>}
296 fn last_mut(&mut self) -> Option<&mut T> {
297 let len = self.len();
298 if len == 0 { return None; }
299 Some(&mut self[len - 1])
303 fn first_mut(&mut self) -> Option<&mut T> {
304 if self.len() == 0 { None } else { Some(&mut self[0]) }
308 fn tail_mut(&mut self) -> &mut [T] {
313 fn init_mut(&mut self) -> &mut [T] {
314 let len = self.len();
315 &mut self[.. (len - 1)]
319 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
320 SplitMut { v: self, pred: pred, finished: false }
324 fn splitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> SplitNMut<'a, T, P> where
328 inner: GenericSplitN {
329 iter: self.split_mut(pred),
337 fn rsplitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> RSplitNMut<'a, T, P> where
338 P: FnMut(&T) -> bool,
341 inner: GenericSplitN {
342 iter: self.split_mut(pred),
350 fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<T> {
351 assert!(chunk_size > 0);
352 ChunksMut { v: self, chunk_size: chunk_size }
355 fn swap(&mut self, a: uint, b: uint) {
357 // Can't take two mutable loans from one vector, so instead just cast
358 // them to their raw pointers to do the swap
359 let pa: *mut T = &mut self[a];
360 let pb: *mut T = &mut self[b];
365 fn reverse(&mut self) {
369 // Unsafe swap to avoid the bounds check in safe swap.
371 let pa: *mut T = self.get_unchecked_mut(i);
372 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
380 unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T {
381 transmute((self.repr().data as *mut T).offset(index as int))
385 fn as_mut_ptr(&mut self) -> *mut T {
386 self.repr().data as *mut T
390 fn position_elem(&self, x: &T) -> Option<uint> where T: PartialEq {
391 self.iter().position(|y| *x == *y)
395 fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
396 self.iter().rposition(|x| *x == *t)
400 fn contains(&self, x: &T) -> bool where T: PartialEq {
401 self.iter().any(|elt| *x == *elt)
405 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
406 let n = needle.len();
407 self.len() >= n && needle == &self[..n]
411 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
412 let (m, n) = (self.len(), needle.len());
413 m >= n && needle == &self[m-n..]
416 #[unstable(feature = "core")]
417 fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
418 self.binary_search_by(|p| p.cmp(x))
421 #[unstable(feature = "core")]
422 fn next_permutation(&mut self) -> bool where T: Ord {
423 // These cases only have 1 permutation each, so we can't do anything.
424 if self.len() < 2 { return false; }
426 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
427 let mut i = self.len() - 1;
428 while i > 0 && self[i-1] >= self[i] {
432 // If that is the entire vector, this is the last-ordered permutation.
437 // Step 2: Find the rightmost element larger than the pivot (i-1)
438 let mut j = self.len() - 1;
439 while j >= i && self[j] <= self[i-1] {
443 // Step 3: Swap that element with the pivot
446 // Step 4: Reverse the (previously) weakly decreasing part
452 #[unstable(feature = "core")]
453 fn prev_permutation(&mut self) -> bool where T: Ord {
454 // These cases only have 1 permutation each, so we can't do anything.
455 if self.len() < 2 { return false; }
457 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
458 let mut i = self.len() - 1;
459 while i > 0 && self[i-1] <= self[i] {
463 // If that is the entire vector, this is the first-ordered permutation.
468 // Step 2: Reverse the weakly increasing part
471 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
472 let mut j = self.len() - 1;
473 while j >= i && self[j-1] < self[i-1] {
477 // Step 4: Swap that element with the pivot
484 fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
485 let min = cmp::min(self.len(), src.len());
486 let dst = &mut self[.. min];
487 let src = &src[.. min];
489 dst[i].clone_from(&src[i]);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl<T> ops::Index<uint> for [T] {
499 fn index(&self, &index: &uint) -> &T {
500 assert!(index < self.len());
502 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl<T> ops::IndexMut<uint> for [T] {
510 fn index_mut(&mut self, &index: &uint) -> &mut T {
511 assert!(index < self.len());
513 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
517 #[stable(feature = "rust1", since = "1.0.0")]
518 impl<T> ops::Index<ops::Range<uint>> for [T] {
521 fn index(&self, index: &ops::Range<uint>) -> &[T] {
522 assert!(index.start <= index.end);
523 assert!(index.end <= self.len());
526 data: self.as_ptr().offset(index.start as int),
527 len: index.end - index.start
532 #[stable(feature = "rust1", since = "1.0.0")]
533 impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
536 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
537 self.index(&ops::Range{ start: 0, end: index.end })
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
544 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
545 self.index(&ops::Range{ start: index.start, end: self.len() })
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<T> ops::Index<RangeFull> for [T] {
552 fn index(&self, _index: &RangeFull) -> &[T] {
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
561 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
562 assert!(index.start <= index.end);
563 assert!(index.end <= self.len());
566 data: self.as_ptr().offset(index.start as int),
567 len: index.end - index.start
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
576 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
577 self.index_mut(&ops::Range{ start: 0, end: index.end })
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
584 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
585 let len = self.len();
586 self.index_mut(&ops::Range{ start: index.start, end: len })
589 #[stable(feature = "rust1", since = "1.0.0")]
590 impl<T> ops::IndexMut<RangeFull> for [T] {
593 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
599 ////////////////////////////////////////////////////////////////////////////////
601 ////////////////////////////////////////////////////////////////////////////////
603 /// Data that is viewable as a slice.
604 #[unstable(feature = "core",
605 reason = "will be replaced by slice syntax")]
606 pub trait AsSlice<T> {
607 /// Work with `self` as a slice.
608 fn as_slice<'a>(&'a self) -> &'a [T];
611 #[unstable(feature = "core", reason = "trait is experimental")]
612 impl<T> AsSlice<T> for [T] {
614 fn as_slice<'a>(&'a self) -> &'a [T] { self }
617 #[unstable(feature = "core", reason = "trait is experimental")]
618 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
620 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
623 #[unstable(feature = "core", reason = "trait is experimental")]
624 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
626 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
629 #[stable(feature = "rust1", since = "1.0.0")]
630 impl<'a, T> Default for &'a [T] {
631 #[stable(feature = "rust1", since = "1.0.0")]
632 fn default() -> &'a [T] { &[] }
639 impl<'a, T> IntoIterator for &'a [T] {
640 type Iter = Iter<'a, T>;
642 fn into_iter(self) -> Iter<'a, T> {
647 impl<'a, T> IntoIterator for &'a mut [T] {
648 type Iter = IterMut<'a, T>;
650 fn into_iter(self) -> IterMut<'a, T> {
655 // The shared definition of the `Iter` and `IterMut` iterators
656 macro_rules! iterator {
657 (struct $name:ident -> $ptr:ty, $elem:ty) => {
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a, T> Iterator for $name<'a, T> {
663 fn next(&mut self) -> Option<$elem> {
664 // could be implemented with slices, but this avoids bounds checks
666 if self.ptr == self.end {
669 if mem::size_of::<T>() == 0 {
670 // purposefully don't use 'ptr.offset' because for
671 // vectors with 0-size elements this would return the
673 self.ptr = transmute(self.ptr as uint + 1);
675 // Use a non-null pointer value
676 Some(&mut *(1 as *mut _))
679 self.ptr = self.ptr.offset(1);
688 fn size_hint(&self) -> (uint, Option<uint>) {
689 let diff = (self.end as uint) - (self.ptr as uint);
690 let size = mem::size_of::<T>();
691 let exact = diff / (if size == 0 {1} else {size});
696 #[stable(feature = "rust1", since = "1.0.0")]
697 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
699 fn next_back(&mut self) -> Option<$elem> {
700 // could be implemented with slices, but this avoids bounds checks
702 if self.end == self.ptr {
705 if mem::size_of::<T>() == 0 {
706 // See above for why 'ptr.offset' isn't used
707 self.end = transmute(self.end as uint - 1);
709 // Use a non-null pointer value
710 Some(&mut *(1 as *mut _))
712 self.end = self.end.offset(-1);
714 Some(transmute(self.end))
723 macro_rules! make_slice {
724 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
725 let diff = $end as uint - $start as uint;
726 let len = if mem::size_of::<T>() == 0 {
729 diff / mem::size_of::<$t>()
732 transmute::<_, $result>(RawSlice { data: $start, len: len })
737 /// Immutable slice iterator
738 #[stable(feature = "rust1", since = "1.0.0")]
739 pub struct Iter<'a, T: 'a> {
742 marker: marker::ContravariantLifetime<'a>
745 #[unstable(feature = "core")]
746 impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
749 fn index(&self, index: &ops::Range<uint>) -> &[T] {
750 self.as_slice().index(index)
754 #[unstable(feature = "core")]
755 impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
758 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
759 self.as_slice().index(index)
763 #[unstable(feature = "core")]
764 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
767 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
768 self.as_slice().index(index)
773 #[unstable(feature = "core")]
774 impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
777 fn index(&self, _index: &ops::FullRange) -> &[T] {
782 #[unstable(feature = "core")]
783 impl<'a, T> ops::Index<RangeFull> for Iter<'a, T> {
786 fn index(&self, _index: &RangeFull) -> &[T] {
791 impl<'a, T> Iter<'a, T> {
792 /// View the underlying data as a subslice of the original data.
794 /// This has the same lifetime as the original slice, and so the
795 /// iterator can continue to be used while this exists.
796 #[unstable(feature = "core")]
797 pub fn as_slice(&self) -> &'a [T] {
798 make_slice!(T => &'a [T]: self.ptr, self.end)
802 iterator!{struct Iter -> *const T, &'a T}
804 #[stable(feature = "rust1", since = "1.0.0")]
805 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
807 #[stable(feature = "rust1", since = "1.0.0")]
808 impl<'a, T> Clone for Iter<'a, T> {
809 fn clone(&self) -> Iter<'a, T> { Iter { ptr: self.ptr, end: self.end, marker: self.marker } }
812 #[unstable(feature = "core", reason = "trait is experimental")]
813 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
815 fn indexable(&self) -> uint {
816 let (exact, _) = self.size_hint();
821 fn idx(&mut self, index: uint) -> Option<&'a T> {
823 if index < self.indexable() {
824 if mem::size_of::<T>() == 0 {
825 // Use a non-null pointer value
826 Some(&mut *(1 as *mut _))
828 Some(transmute(self.ptr.offset(index as int)))
837 /// Mutable slice iterator.
838 #[stable(feature = "rust1", since = "1.0.0")]
839 pub struct IterMut<'a, T: 'a> {
842 marker: marker::ContravariantLifetime<'a>,
846 #[unstable(feature = "core")]
847 impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
850 fn index(&self, index: &ops::Range<uint>) -> &[T] {
851 self.index(&RangeFull).index(index)
854 #[unstable(feature = "core")]
855 impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
858 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
859 self.index(&RangeFull).index(index)
862 #[unstable(feature = "core")]
863 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
866 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
867 self.index(&RangeFull).index(index)
870 #[unstable(feature = "core")]
871 impl<'a, T> ops::Index<RangeFull> for IterMut<'a, T> {
874 fn index(&self, _index: &RangeFull) -> &[T] {
875 make_slice!(T => &[T]: self.ptr, self.end)
879 #[unstable(feature = "core")]
880 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
883 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
884 self.index_mut(&RangeFull).index_mut(index)
887 #[unstable(feature = "core")]
888 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
891 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
892 self.index_mut(&RangeFull).index_mut(index)
895 #[unstable(feature = "core")]
896 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
899 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
900 self.index_mut(&RangeFull).index_mut(index)
903 #[unstable(feature = "core")]
904 impl<'a, T> ops::IndexMut<RangeFull> for IterMut<'a, T> {
907 fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] {
908 make_slice!(T => &mut [T]: self.ptr, self.end)
913 impl<'a, T> IterMut<'a, T> {
914 /// View the underlying data as a subslice of the original data.
916 /// To avoid creating `&mut` references that alias, this is forced
917 /// to consume the iterator. Consider using the `Slice` and
918 /// `SliceMut` implementations for obtaining slices with more
919 /// restricted lifetimes that do not consume the iterator.
920 #[unstable(feature = "core")]
921 pub fn into_slice(self) -> &'a mut [T] {
922 make_slice!(T => &'a mut [T]: self.ptr, self.end)
926 iterator!{struct IterMut -> *mut T, &'a mut T}
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
931 /// An internal abstraction over the splitting iterators, so that
932 /// splitn, splitn_mut etc can be implemented once.
933 trait SplitIter: DoubleEndedIterator {
934 /// Mark the underlying iterator as complete, extracting the remaining
935 /// portion of the slice.
936 fn finish(&mut self) -> Option<Self::Item>;
939 /// An iterator over subslices separated by elements that match a predicate
941 #[stable(feature = "rust1", since = "1.0.0")]
942 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
948 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
949 #[stable(feature = "rust1", since = "1.0.0")]
950 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
951 fn clone(&self) -> Split<'a, T, P> {
954 pred: self.pred.clone(),
955 finished: self.finished,
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
965 fn next(&mut self) -> Option<&'a [T]> {
966 if self.finished { return None; }
968 match self.v.iter().position(|x| (self.pred)(x)) {
969 None => self.finish(),
971 let ret = Some(&self.v[..idx]);
972 self.v = &self.v[idx + 1..];
979 fn size_hint(&self) -> (uint, Option<uint>) {
983 (1, Some(self.v.len() + 1))
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
991 fn next_back(&mut self) -> Option<&'a [T]> {
992 if self.finished { return None; }
994 match self.v.iter().rposition(|x| (self.pred)(x)) {
995 None => self.finish(),
997 let ret = Some(&self.v[idx + 1..]);
998 self.v = &self.v[..idx];
1005 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
1007 fn finish(&mut self) -> Option<&'a [T]> {
1008 if self.finished { None } else { self.finished = true; Some(self.v) }
1012 /// An iterator over the subslices of the vector which are separated
1013 /// by elements that match `pred`.
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
1021 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1023 fn finish(&mut self) -> Option<&'a mut [T]> {
1027 self.finished = true;
1028 Some(mem::replace(&mut self.v, &mut []))
1033 #[stable(feature = "rust1", since = "1.0.0")]
1034 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1035 type Item = &'a mut [T];
1038 fn next(&mut self) -> Option<&'a mut [T]> {
1039 if self.finished { return None; }
1041 let idx_opt = { // work around borrowck limitations
1042 let pred = &mut self.pred;
1043 self.v.iter().position(|x| (*pred)(x))
1046 None => self.finish(),
1048 let tmp = mem::replace(&mut self.v, &mut []);
1049 let (head, tail) = tmp.split_at_mut(idx);
1050 self.v = &mut tail[1..];
1057 fn size_hint(&self) -> (uint, Option<uint>) {
1061 // if the predicate doesn't match anything, we yield one slice
1062 // if it matches every element, we yield len+1 empty slices.
1063 (1, Some(self.v.len() + 1))
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1070 P: FnMut(&T) -> bool,
1073 fn next_back(&mut self) -> Option<&'a mut [T]> {
1074 if self.finished { return None; }
1076 let idx_opt = { // work around borrowck limitations
1077 let pred = &mut self.pred;
1078 self.v.iter().rposition(|x| (*pred)(x))
1081 None => self.finish(),
1083 let tmp = mem::replace(&mut self.v, &mut []);
1084 let (head, tail) = tmp.split_at_mut(idx);
1086 Some(&mut tail[1..])
1092 /// An private iterator over subslices separated by elements that
1093 /// match a predicate function, splitting at most a fixed number of
1095 struct GenericSplitN<I> {
1101 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1105 fn next(&mut self) -> Option<T> {
1106 if self.count == 0 {
1110 if self.invert { self.iter.next_back() } else { self.iter.next() }
1115 fn size_hint(&self) -> (uint, Option<uint>) {
1116 let (lower, upper_opt) = self.iter.size_hint();
1117 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1121 /// An iterator over subslices separated by elements that match a predicate
1122 /// function, limited to a given number of splits.
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1125 inner: GenericSplitN<Split<'a, T, P>>
1128 /// An iterator over subslices separated by elements that match a
1129 /// predicate function, limited to a given number of splits, starting
1130 /// from the end of the slice.
1131 #[stable(feature = "rust1", since = "1.0.0")]
1132 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1133 inner: GenericSplitN<Split<'a, T, P>>
1136 /// An iterator over subslices separated by elements that match a predicate
1137 /// function, limited to a given number of splits.
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1140 inner: GenericSplitN<SplitMut<'a, T, P>>
1143 /// An iterator over subslices separated by elements that match a
1144 /// predicate function, limited to a given number of splits, starting
1145 /// from the end of the slice.
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1148 inner: GenericSplitN<SplitMut<'a, T, P>>
1151 macro_rules! forward_iterator {
1152 ($name:ident: $elem:ident, $iter_of:ty) => {
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1155 P: FnMut(&T) -> bool
1157 type Item = $iter_of;
1160 fn next(&mut self) -> Option<$iter_of> {
1165 fn size_hint(&self) -> (uint, Option<uint>) {
1166 self.inner.size_hint()
1172 forward_iterator! { SplitN: T, &'a [T] }
1173 forward_iterator! { RSplitN: T, &'a [T] }
1174 forward_iterator! { SplitNMut: T, &'a mut [T] }
1175 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1177 /// An iterator over overlapping subslices of length `size`.
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub struct Windows<'a, T:'a> {
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<'a, T> Iterator for Windows<'a, T> {
1187 type Item = &'a [T];
1190 fn next(&mut self) -> Option<&'a [T]> {
1191 if self.size > self.v.len() {
1194 let ret = Some(&self.v[..self.size]);
1195 self.v = &self.v[1..];
1201 fn size_hint(&self) -> (uint, Option<uint>) {
1202 if self.size > self.v.len() {
1205 let x = self.v.len() - self.size;
1206 (x.saturating_add(1), x.checked_add(1))
1211 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1214 /// When the slice len is not evenly divided by the chunk size, the last slice
1215 /// of the iteration will be the remainder.
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub struct Chunks<'a, T:'a> {
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<'a, T> Iterator for Chunks<'a, T> {
1225 type Item = &'a [T];
1228 fn next(&mut self) -> Option<&'a [T]> {
1229 if self.v.len() == 0 {
1232 let chunksz = cmp::min(self.v.len(), self.size);
1233 let (fst, snd) = self.v.split_at(chunksz);
1240 fn size_hint(&self) -> (uint, Option<uint>) {
1241 if self.v.len() == 0 {
1244 let n = self.v.len() / self.size;
1245 let rem = self.v.len() % self.size;
1246 let n = if rem > 0 { n+1 } else { n };
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1255 fn next_back(&mut self) -> Option<&'a [T]> {
1256 if self.v.len() == 0 {
1259 let remainder = self.v.len() % self.size;
1260 let chunksz = if remainder != 0 { remainder } else { self.size };
1261 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1271 #[unstable(feature = "core", reason = "trait is experimental")]
1272 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1274 fn indexable(&self) -> uint {
1275 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1279 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1280 if index < self.indexable() {
1281 let lo = index * self.size;
1282 let mut hi = lo + self.size;
1283 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1285 Some(&self.v[lo..hi])
1292 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1293 /// elements at a time). When the slice len is not evenly divided by the chunk
1294 /// size, the last slice of the iteration will be the remainder.
1295 #[stable(feature = "rust1", since = "1.0.0")]
1296 pub struct ChunksMut<'a, T:'a> {
1301 #[stable(feature = "rust1", since = "1.0.0")]
1302 impl<'a, T> Iterator for ChunksMut<'a, T> {
1303 type Item = &'a mut [T];
1306 fn next(&mut self) -> Option<&'a mut [T]> {
1307 if self.v.len() == 0 {
1310 let sz = cmp::min(self.v.len(), self.chunk_size);
1311 let tmp = mem::replace(&mut self.v, &mut []);
1312 let (head, tail) = tmp.split_at_mut(sz);
1319 fn size_hint(&self) -> (uint, Option<uint>) {
1320 if self.v.len() == 0 {
1323 let n = self.v.len() / self.chunk_size;
1324 let rem = self.v.len() % self.chunk_size;
1325 let n = if rem > 0 { n + 1 } else { n };
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1334 fn next_back(&mut self) -> Option<&'a mut [T]> {
1335 if self.v.len() == 0 {
1338 let remainder = self.v.len() % self.chunk_size;
1339 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1340 let tmp = mem::replace(&mut self.v, &mut []);
1341 let tmp_len = tmp.len();
1342 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1356 /// Converts a pointer to A into a slice of length 1 (without copying).
1357 #[unstable(feature = "core")]
1358 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1360 transmute(RawSlice { data: s, len: 1 })
1364 /// Converts a pointer to A into a slice of length 1 (without copying).
1365 #[unstable(feature = "core")]
1366 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1368 let ptr: *const A = transmute(s);
1369 transmute(RawSlice { data: ptr, len: 1 })
1373 /// Forms a slice from a pointer and a length.
1375 /// The pointer given is actually a reference to the base of the slice. This
1376 /// reference is used to give a concrete lifetime to tie the returned slice to.
1377 /// Typically this should indicate that the slice is valid for as long as the
1378 /// pointer itself is valid.
1380 /// The `len` argument is the number of **elements**, not the number of bytes.
1382 /// This function is unsafe as there is no guarantee that the given pointer is
1383 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1384 /// lifetime for the returned slice.
1391 /// // manifest a slice out of thin air!
1392 /// let ptr = 0x1234 as *const uint;
1395 /// let slice = slice::from_raw_buf(&ptr, amt);
1399 #[unstable(feature = "core",
1400 reason = "should be renamed to from_raw_parts")]
1401 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1402 transmute(RawSlice { data: *p, len: len })
1405 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1406 /// slice is returned.
1408 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1409 /// not being able to provide a non-aliasing guarantee of the returned mutable
1412 #[unstable(feature = "core",
1413 reason = "should be renamed to from_raw_parts_mut")]
1414 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1415 transmute(RawSlice { data: *p, len: len })
1422 /// Operations on `[u8]`.
1423 #[unstable(feature = "core", reason = "needs review")]
1426 use slice::SliceExt;
1428 /// A trait for operations on mutable `[u8]`s.
1429 pub trait MutableByteVector {
1430 /// Sets all bytes of the receiver to the given value.
1431 fn set_memory(&mut self, value: u8);
1434 impl MutableByteVector for [u8] {
1436 fn set_memory(&mut self, value: u8) {
1437 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1441 /// Copies data from `src` to `dst`
1443 /// Panics if the length of `dst` is less than the length of `src`.
1445 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1446 let len_src = src.len();
1447 assert!(dst.len() >= len_src);
1448 // `dst` is unaliasable, so we know statically it doesn't overlap
1451 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1461 // Boilerplate traits
1464 #[stable(feature = "rust1", since = "1.0.0")]
1465 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1466 fn eq(&self, other: &[B]) -> bool {
1467 self.len() == other.len() &&
1468 order::eq(self.iter(), other.iter())
1470 fn ne(&self, other: &[B]) -> bool {
1471 self.len() != other.len() ||
1472 order::ne(self.iter(), other.iter())
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<T: Eq> Eq for [T] {}
1479 #[stable(feature = "rust1", since = "1.0.0")]
1480 impl<T: Ord> Ord for [T] {
1481 fn cmp(&self, other: &[T]) -> Ordering {
1482 order::cmp(self.iter(), other.iter())
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 impl<T: PartialOrd> PartialOrd for [T] {
1489 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1490 order::partial_cmp(self.iter(), other.iter())
1493 fn lt(&self, other: &[T]) -> bool {
1494 order::lt(self.iter(), other.iter())
1497 fn le(&self, other: &[T]) -> bool {
1498 order::le(self.iter(), other.iter())
1501 fn ge(&self, other: &[T]) -> bool {
1502 order::ge(self.iter(), other.iter())
1505 fn gt(&self, other: &[T]) -> bool {
1506 order::gt(self.iter(), other.iter())
1510 /// Extension methods for slices containing integers.
1511 #[unstable(feature = "core")]
1512 pub trait IntSliceExt<U, S> {
1513 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1514 fn as_unsigned<'a>(&'a self) -> &'a [U];
1515 /// Converts the slice to an immutable slice of signed integers with the same width.
1516 fn as_signed<'a>(&'a self) -> &'a [S];
1518 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1519 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1520 /// Converts the slice to a mutable slice of signed integers with the same width.
1521 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1524 macro_rules! impl_int_slice {
1525 ($u:ty, $s:ty, $t:ty) => {
1526 #[unstable(feature = "core")]
1527 impl IntSliceExt<$u, $s> for [$t] {
1529 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1531 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1533 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1535 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1540 macro_rules! impl_int_slices {
1542 impl_int_slice! { $u, $s, $u }
1543 impl_int_slice! { $u, $s, $s }
1547 impl_int_slices! { u8, i8 }
1548 impl_int_slices! { u16, i16 }
1549 impl_int_slices! { u32, i32 }
1550 impl_int_slices! { u64, i64 }
1551 impl_int_slices! { uint, int }