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 option::Option::{None, Some};
50 use result::Result::{Ok, Err};
55 use marker::{Sized, self};
57 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
58 use raw::Slice as RawSlice;
65 /// Extension methods for slices.
66 #[allow(missing_docs)] // docs in libcollections
70 fn split_at<'a>(&'a self, mid: uint) -> (&'a [Self::Item], &'a [Self::Item]);
71 fn iter<'a>(&'a self) -> Iter<'a, Self::Item>;
72 fn split<'a, P>(&'a self, pred: P) -> Split<'a, Self::Item, P>
73 where P: FnMut(&Self::Item) -> bool;
74 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, Self::Item, P>
75 where P: FnMut(&Self::Item) -> bool;
76 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, Self::Item, P>
77 where P: FnMut(&Self::Item) -> bool;
78 fn windows<'a>(&'a self, size: uint) -> Windows<'a, Self::Item>;
79 fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, Self::Item>;
80 fn get<'a>(&'a self, index: uint) -> Option<&'a Self::Item>;
81 fn first<'a>(&'a self) -> Option<&'a Self::Item>;
82 fn tail<'a>(&'a self) -> &'a [Self::Item];
83 fn init<'a>(&'a self) -> &'a [Self::Item];
84 fn last<'a>(&'a self) -> Option<&'a Self::Item>;
85 unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a Self::Item;
86 fn as_ptr(&self) -> *const Self::Item;
87 fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
88 F: FnMut(&Self::Item) -> Ordering;
89 fn len(&self) -> uint;
90 fn is_empty(&self) -> bool { self.len() == 0 }
91 fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut Self::Item>;
92 fn as_mut_slice<'a>(&'a mut self) -> &'a mut [Self::Item];
93 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, Self::Item>;
94 fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
95 fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
96 fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
97 fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
98 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
99 where P: FnMut(&Self::Item) -> bool;
100 fn splitn_mut<P>(&mut self, n: uint, pred: P) -> SplitNMut<Self::Item, P>
101 where P: FnMut(&Self::Item) -> bool;
102 fn rsplitn_mut<P>(&mut self, n: uint, pred: P) -> RSplitNMut<Self::Item, P>
103 where P: FnMut(&Self::Item) -> bool;
104 fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, Self::Item>;
105 fn swap(&mut self, a: uint, b: uint);
106 fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [Self::Item], &'a mut [Self::Item]);
107 fn reverse(&mut self);
108 unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut Self::Item;
109 fn as_mut_ptr(&mut self) -> *mut Self::Item;
111 fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
113 fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
115 fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
117 fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
119 fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
121 fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
122 fn next_permutation(&mut self) -> bool where Self::Item: Ord;
123 fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
125 fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
128 #[unstable(feature = "core")]
129 impl<T> SliceExt for [T] {
133 fn split_at(&self, mid: uint) -> (&[T], &[T]) {
134 (&self[..mid], &self[mid..])
138 fn iter<'a>(&'a self) -> Iter<'a, T> {
140 let p = self.as_ptr();
141 if mem::size_of::<T>() == 0 {
143 end: (p as uint + self.len()) as *const T,
144 marker: marker::ContravariantLifetime::<'a>}
147 end: p.offset(self.len() as int),
148 marker: marker::ContravariantLifetime::<'a>}
154 fn split<'a, P>(&'a self, pred: P) -> Split<'a, T, P> where P: FnMut(&T) -> bool {
163 fn splitn<'a, P>(&'a self, n: uint, pred: P) -> SplitN<'a, T, P> where
164 P: FnMut(&T) -> bool,
167 inner: GenericSplitN {
168 iter: self.split(pred),
176 fn rsplitn<'a, P>(&'a self, n: uint, pred: P) -> RSplitN<'a, T, P> where
177 P: FnMut(&T) -> bool,
180 inner: GenericSplitN {
181 iter: self.split(pred),
189 fn windows(&self, size: uint) -> Windows<T> {
191 Windows { v: self, size: size }
195 fn chunks(&self, size: uint) -> Chunks<T> {
197 Chunks { v: self, size: size }
201 fn get(&self, index: uint) -> Option<&T> {
202 if index < self.len() { Some(&self[index]) } else { None }
206 fn first(&self) -> Option<&T> {
207 if self.len() == 0 { None } else { Some(&self[0]) }
211 fn tail(&self) -> &[T] { &self[1..] }
214 fn init(&self) -> &[T] {
215 &self[..self.len() - 1]
219 fn last(&self) -> Option<&T> {
220 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
224 unsafe fn get_unchecked(&self, index: uint) -> &T {
225 transmute(self.repr().data.offset(index as int))
229 fn as_ptr(&self) -> *const T {
233 #[unstable(feature = "core")]
234 fn binary_search_by<F>(&self, mut f: F) -> Result<uint, uint> where
235 F: FnMut(&T) -> Ordering
237 let mut base : uint = 0;
238 let mut lim : uint = self.len();
241 let ix = base + (lim >> 1);
243 Equal => return Ok(ix),
256 fn len(&self) -> uint { self.repr().len }
259 fn get_mut(&mut self, index: uint) -> Option<&mut T> {
260 if index < self.len() { Some(&mut self[index]) } else { None }
264 fn as_mut_slice(&mut self) -> &mut [T] { self }
267 fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
269 let self2: &mut [T] = mem::transmute_copy(&self);
271 (ops::IndexMut::index_mut(self, &ops::RangeTo { end: mid } ),
272 ops::IndexMut::index_mut(self2, &ops::RangeFrom { start: mid } ))
277 fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
279 let p = self.as_mut_ptr();
280 if mem::size_of::<T>() == 0 {
282 end: (p as uint + self.len()) as *mut T,
283 marker: marker::ContravariantLifetime::<'a>}
286 end: p.offset(self.len() as int),
287 marker: marker::ContravariantLifetime::<'a>}
293 fn last_mut(&mut self) -> Option<&mut T> {
294 let len = self.len();
295 if len == 0 { return None; }
296 Some(&mut self[len - 1])
300 fn first_mut(&mut self) -> Option<&mut T> {
301 if self.len() == 0 { None } else { Some(&mut self[0]) }
305 fn tail_mut(&mut self) -> &mut [T] {
310 fn init_mut(&mut self) -> &mut [T] {
311 let len = self.len();
312 &mut self[.. (len - 1)]
316 fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
317 SplitMut { v: self, pred: pred, finished: false }
321 fn splitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> SplitNMut<'a, T, P> where
325 inner: GenericSplitN {
326 iter: self.split_mut(pred),
334 fn rsplitn_mut<'a, P>(&'a mut self, n: uint, pred: P) -> RSplitNMut<'a, T, P> where
335 P: FnMut(&T) -> bool,
338 inner: GenericSplitN {
339 iter: self.split_mut(pred),
347 fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<T> {
348 assert!(chunk_size > 0);
349 ChunksMut { v: self, chunk_size: chunk_size }
352 fn swap(&mut self, a: uint, b: uint) {
354 // Can't take two mutable loans from one vector, so instead just cast
355 // them to their raw pointers to do the swap
356 let pa: *mut T = &mut self[a];
357 let pb: *mut T = &mut self[b];
362 fn reverse(&mut self) {
366 // Unsafe swap to avoid the bounds check in safe swap.
368 let pa: *mut T = self.get_unchecked_mut(i);
369 let pb: *mut T = self.get_unchecked_mut(ln - i - 1);
377 unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut T {
378 transmute((self.repr().data as *mut T).offset(index as int))
382 fn as_mut_ptr(&mut self) -> *mut T {
383 self.repr().data as *mut T
387 fn position_elem(&self, x: &T) -> Option<uint> where T: PartialEq {
388 self.iter().position(|y| *x == *y)
392 fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
393 self.iter().rposition(|x| *x == *t)
397 fn contains(&self, x: &T) -> bool where T: PartialEq {
398 self.iter().any(|elt| *x == *elt)
402 fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
403 let n = needle.len();
404 self.len() >= n && needle == &self[..n]
408 fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
409 let (m, n) = (self.len(), needle.len());
410 m >= n && needle == &self[m-n..]
413 #[unstable(feature = "core")]
414 fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
415 self.binary_search_by(|p| p.cmp(x))
418 #[unstable(feature = "core")]
419 fn next_permutation(&mut self) -> bool where T: Ord {
420 // These cases only have 1 permutation each, so we can't do anything.
421 if self.len() < 2 { return false; }
423 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
424 let mut i = self.len() - 1;
425 while i > 0 && self[i-1] >= self[i] {
429 // If that is the entire vector, this is the last-ordered permutation.
434 // Step 2: Find the rightmost element larger than the pivot (i-1)
435 let mut j = self.len() - 1;
436 while j >= i && self[j] <= self[i-1] {
440 // Step 3: Swap that element with the pivot
443 // Step 4: Reverse the (previously) weakly decreasing part
449 #[unstable(feature = "core")]
450 fn prev_permutation(&mut self) -> bool where T: Ord {
451 // These cases only have 1 permutation each, so we can't do anything.
452 if self.len() < 2 { return false; }
454 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
455 let mut i = self.len() - 1;
456 while i > 0 && self[i-1] <= self[i] {
460 // If that is the entire vector, this is the first-ordered permutation.
465 // Step 2: Reverse the weakly increasing part
468 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
469 let mut j = self.len() - 1;
470 while j >= i && self[j-1] < self[i-1] {
474 // Step 4: Swap that element with the pivot
481 fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
482 let min = cmp::min(self.len(), src.len());
483 let dst = &mut self[.. min];
484 let src = &src[.. min];
485 for i in range(0, min) {
486 dst[i].clone_from(&src[i]);
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl<T> ops::Index<uint> for [T] {
496 fn index(&self, &index: &uint) -> &T {
497 assert!(index < self.len());
499 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl<T> ops::IndexMut<uint> for [T] {
507 fn index_mut(&mut self, &index: &uint) -> &mut T {
508 assert!(index < self.len());
510 unsafe { mem::transmute(self.repr().data.offset(index as int)) }
514 #[stable(feature = "rust1", since = "1.0.0")]
515 impl<T> ops::Index<ops::Range<uint>> for [T] {
518 fn index(&self, index: &ops::Range<uint>) -> &[T] {
519 assert!(index.start <= index.end);
520 assert!(index.end <= self.len());
523 data: self.as_ptr().offset(index.start as int),
524 len: index.end - index.start
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
533 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
534 self.index(&ops::Range{ start: 0, end: index.end })
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
541 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
542 self.index(&ops::Range{ start: index.start, end: self.len() })
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T> ops::Index<ops::FullRange> for [T] {
549 fn index(&self, _index: &ops::FullRange) -> &[T] {
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
558 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
559 assert!(index.start <= index.end);
560 assert!(index.end <= self.len());
563 data: self.as_ptr().offset(index.start as int),
564 len: index.end - index.start
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
573 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
574 self.index_mut(&ops::Range{ start: 0, end: index.end })
577 #[stable(feature = "rust1", since = "1.0.0")]
578 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
581 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
582 let len = self.len();
583 self.index_mut(&ops::Range{ start: index.start, end: len })
586 #[stable(feature = "rust1", since = "1.0.0")]
587 impl<T> ops::IndexMut<ops::FullRange> for [T] {
590 fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
596 ////////////////////////////////////////////////////////////////////////////////
598 ////////////////////////////////////////////////////////////////////////////////
600 /// Data that is viewable as a slice.
601 #[unstable(feature = "core",
602 reason = "will be replaced by slice syntax")]
603 pub trait AsSlice<T> {
604 /// Work with `self` as a slice.
605 fn as_slice<'a>(&'a self) -> &'a [T];
608 #[unstable(feature = "core", reason = "trait is experimental")]
609 impl<T> AsSlice<T> for [T] {
611 fn as_slice<'a>(&'a self) -> &'a [T] { self }
614 #[unstable(feature = "core", reason = "trait is experimental")]
615 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a U {
617 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
620 #[unstable(feature = "core", reason = "trait is experimental")]
621 impl<'a, T, U: ?Sized + AsSlice<T>> AsSlice<T> for &'a mut U {
623 fn as_slice(&self) -> &[T] { AsSlice::as_slice(*self) }
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl<'a, T> Default for &'a [T] {
628 #[stable(feature = "rust1", since = "1.0.0")]
629 fn default() -> &'a [T] { &[] }
636 // The shared definition of the `Iter` and `IterMut` iterators
637 macro_rules! iterator {
638 (struct $name:ident -> $ptr:ty, $elem:ty) => {
639 #[stable(feature = "rust1", since = "1.0.0")]
640 impl<'a, T> Iterator for $name<'a, T> {
644 fn next(&mut self) -> Option<$elem> {
645 // could be implemented with slices, but this avoids bounds checks
647 if self.ptr == self.end {
650 if mem::size_of::<T>() == 0 {
651 // purposefully don't use 'ptr.offset' because for
652 // vectors with 0-size elements this would return the
654 self.ptr = transmute(self.ptr as uint + 1);
656 // Use a non-null pointer value
657 Some(&mut *(1 as *mut _))
660 self.ptr = self.ptr.offset(1);
669 fn size_hint(&self) -> (uint, Option<uint>) {
670 let diff = (self.end as uint) - (self.ptr as uint);
671 let size = mem::size_of::<T>();
672 let exact = diff / (if size == 0 {1} else {size});
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<'a, T> DoubleEndedIterator for $name<'a, T> {
680 fn next_back(&mut self) -> Option<$elem> {
681 // could be implemented with slices, but this avoids bounds checks
683 if self.end == self.ptr {
686 if mem::size_of::<T>() == 0 {
687 // See above for why 'ptr.offset' isn't used
688 self.end = transmute(self.end as uint - 1);
690 // Use a non-null pointer value
691 Some(&mut *(1 as *mut _))
693 self.end = self.end.offset(-1);
695 Some(transmute(self.end))
704 macro_rules! make_slice {
705 ($t: ty => $result: ty: $start: expr, $end: expr) => {{
706 let diff = $end as uint - $start as uint;
707 let len = if mem::size_of::<T>() == 0 {
710 diff / mem::size_of::<$t>()
713 transmute::<_, $result>(RawSlice { data: $start, len: len })
718 /// Immutable slice iterator
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub struct Iter<'a, T: 'a> {
723 marker: marker::ContravariantLifetime<'a>
726 #[unstable(feature = "core")]
727 impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
730 fn index(&self, index: &ops::Range<uint>) -> &[T] {
731 self.as_slice().index(index)
735 #[unstable(feature = "core")]
736 impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
739 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
740 self.as_slice().index(index)
744 #[unstable(feature = "core")]
745 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
748 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
749 self.as_slice().index(index)
753 #[unstable(feature = "core")]
754 impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
757 fn index(&self, _index: &ops::FullRange) -> &[T] {
762 impl<'a, T> Iter<'a, T> {
763 /// View the underlying data as a subslice of the original data.
765 /// This has the same lifetime as the original slice, and so the
766 /// iterator can continue to be used while this exists.
767 #[unstable(feature = "core")]
768 pub fn as_slice(&self) -> &'a [T] {
769 make_slice!(T => &'a [T]: self.ptr, self.end)
773 impl<'a,T> Copy for Iter<'a,T> {}
775 iterator!{struct Iter -> *const T, &'a T}
777 #[stable(feature = "rust1", since = "1.0.0")]
778 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
780 #[stable(feature = "rust1", since = "1.0.0")]
781 impl<'a, T> Clone for Iter<'a, T> {
782 fn clone(&self) -> Iter<'a, T> { *self }
785 #[unstable(feature = "core", reason = "trait is experimental")]
786 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
788 fn indexable(&self) -> uint {
789 let (exact, _) = self.size_hint();
794 fn idx(&mut self, index: uint) -> Option<&'a T> {
796 if index < self.indexable() {
797 if mem::size_of::<T>() == 0 {
798 // Use a non-null pointer value
799 Some(&mut *(1 as *mut _))
801 Some(transmute(self.ptr.offset(index as int)))
810 /// Mutable slice iterator.
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub struct IterMut<'a, T: 'a> {
815 marker: marker::ContravariantLifetime<'a>,
819 #[unstable(feature = "core")]
820 impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
823 fn index(&self, index: &ops::Range<uint>) -> &[T] {
824 self.index(&ops::FullRange).index(index)
827 #[unstable(feature = "core")]
828 impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
831 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
832 self.index(&ops::FullRange).index(index)
835 #[unstable(feature = "core")]
836 impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
839 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
840 self.index(&ops::FullRange).index(index)
843 #[unstable(feature = "core")]
844 impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> {
847 fn index(&self, _index: &ops::FullRange) -> &[T] {
848 make_slice!(T => &[T]: self.ptr, self.end)
852 #[unstable(feature = "core")]
853 impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
856 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
857 self.index_mut(&ops::FullRange).index_mut(index)
860 #[unstable(feature = "core")]
861 impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
864 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
865 self.index_mut(&ops::FullRange).index_mut(index)
868 #[unstable(feature = "core")]
869 impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
872 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
873 self.index_mut(&ops::FullRange).index_mut(index)
876 #[unstable(feature = "core")]
877 impl<'a, T> ops::IndexMut<ops::FullRange> for IterMut<'a, T> {
880 fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
881 make_slice!(T => &mut [T]: self.ptr, self.end)
886 impl<'a, T> IterMut<'a, T> {
887 /// View the underlying data as a subslice of the original data.
889 /// To avoid creating `&mut` references that alias, this is forced
890 /// to consume the iterator. Consider using the `Slice` and
891 /// `SliceMut` implementations for obtaining slices with more
892 /// restricted lifetimes that do not consume the iterator.
893 #[unstable(feature = "core")]
894 pub fn into_slice(self) -> &'a mut [T] {
895 make_slice!(T => &'a mut [T]: self.ptr, self.end)
899 iterator!{struct IterMut -> *mut T, &'a mut T}
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
904 /// An internal abstraction over the splitting iterators, so that
905 /// splitn, splitn_mut etc can be implemented once.
906 trait SplitIter: DoubleEndedIterator {
907 /// Mark the underlying iterator as complete, extracting the remaining
908 /// portion of the slice.
909 fn finish(&mut self) -> Option<Self::Item>;
912 /// An iterator over subslices separated by elements that match a predicate
914 #[stable(feature = "rust1", since = "1.0.0")]
915 pub struct Split<'a, T:'a, P> where P: FnMut(&T) -> bool {
921 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
922 #[stable(feature = "rust1", since = "1.0.0")]
923 impl<'a, T, P> Clone for Split<'a, T, P> where P: Clone + FnMut(&T) -> bool {
924 fn clone(&self) -> Split<'a, T, P> {
927 pred: self.pred.clone(),
928 finished: self.finished,
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<'a, T, P> Iterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
938 fn next(&mut self) -> Option<&'a [T]> {
939 if self.finished { return None; }
941 match self.v.iter().position(|x| (self.pred)(x)) {
942 None => self.finish(),
944 let ret = Some(&self.v[..idx]);
945 self.v = &self.v[idx + 1..];
952 fn size_hint(&self) -> (uint, Option<uint>) {
956 (1, Some(self.v.len() + 1))
961 #[stable(feature = "rust1", since = "1.0.0")]
962 impl<'a, T, P> DoubleEndedIterator for Split<'a, T, P> where P: FnMut(&T) -> bool {
964 fn next_back(&mut self) -> Option<&'a [T]> {
965 if self.finished { return None; }
967 match self.v.iter().rposition(|x| (self.pred)(x)) {
968 None => self.finish(),
970 let ret = Some(&self.v[idx + 1..]);
971 self.v = &self.v[..idx];
978 impl<'a, T, P> SplitIter for Split<'a, T, P> where P: FnMut(&T) -> bool {
980 fn finish(&mut self) -> Option<&'a [T]> {
981 if self.finished { None } else { self.finished = true; Some(self.v) }
985 /// An iterator over the subslices of the vector which are separated
986 /// by elements that match `pred`.
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub struct SplitMut<'a, T:'a, P> where P: FnMut(&T) -> bool {
994 impl<'a, T, P> SplitIter for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
996 fn finish(&mut self) -> Option<&'a mut [T]> {
1000 self.finished = true;
1001 Some(mem::replace(&mut self.v, &mut []))
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<'a, T, P> Iterator for SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
1008 type Item = &'a mut [T];
1011 fn next(&mut self) -> Option<&'a mut [T]> {
1012 if self.finished { return None; }
1014 let idx_opt = { // work around borrowck limitations
1015 let pred = &mut self.pred;
1016 self.v.iter().position(|x| (*pred)(x))
1019 None => self.finish(),
1021 let tmp = mem::replace(&mut self.v, &mut []);
1022 let (head, tail) = tmp.split_at_mut(idx);
1023 self.v = &mut tail[1..];
1030 fn size_hint(&self) -> (uint, Option<uint>) {
1034 // if the predicate doesn't match anything, we yield one slice
1035 // if it matches every element, we yield len+1 empty slices.
1036 (1, Some(self.v.len() + 1))
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<'a, T, P> DoubleEndedIterator for SplitMut<'a, T, P> where
1043 P: FnMut(&T) -> bool,
1046 fn next_back(&mut self) -> Option<&'a mut [T]> {
1047 if self.finished { return None; }
1049 let idx_opt = { // work around borrowck limitations
1050 let pred = &mut self.pred;
1051 self.v.iter().rposition(|x| (*pred)(x))
1054 None => self.finish(),
1056 let tmp = mem::replace(&mut self.v, &mut []);
1057 let (head, tail) = tmp.split_at_mut(idx);
1059 Some(&mut tail[1..])
1065 /// An private iterator over subslices separated by elements that
1066 /// match a predicate function, splitting at most a fixed number of
1068 struct GenericSplitN<I> {
1074 impl<T, I: SplitIter<Item=T>> Iterator for GenericSplitN<I> {
1078 fn next(&mut self) -> Option<T> {
1079 if self.count == 0 {
1083 if self.invert { self.iter.next_back() } else { self.iter.next() }
1088 fn size_hint(&self) -> (uint, Option<uint>) {
1089 let (lower, upper_opt) = self.iter.size_hint();
1090 (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1094 /// An iterator over subslices separated by elements that match a predicate
1095 /// function, limited to a given number of splits.
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 pub struct SplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1098 inner: GenericSplitN<Split<'a, T, P>>
1101 /// An iterator over subslices separated by elements that match a
1102 /// predicate function, limited to a given number of splits, starting
1103 /// from the end of the slice.
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 pub struct RSplitN<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1106 inner: GenericSplitN<Split<'a, T, P>>
1109 /// An iterator over subslices separated by elements that match a predicate
1110 /// function, limited to a given number of splits.
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 pub struct SplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1113 inner: GenericSplitN<SplitMut<'a, T, P>>
1116 /// An iterator over subslices separated by elements that match a
1117 /// predicate function, limited to a given number of splits, starting
1118 /// from the end of the slice.
1119 #[stable(feature = "rust1", since = "1.0.0")]
1120 pub struct RSplitNMut<'a, T: 'a, P> where P: FnMut(&T) -> bool {
1121 inner: GenericSplitN<SplitMut<'a, T, P>>
1124 macro_rules! forward_iterator {
1125 ($name:ident: $elem:ident, $iter_of:ty) => {
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<'a, $elem, P> Iterator for $name<'a, $elem, P> where
1128 P: FnMut(&T) -> bool
1130 type Item = $iter_of;
1133 fn next(&mut self) -> Option<$iter_of> {
1138 fn size_hint(&self) -> (uint, Option<uint>) {
1139 self.inner.size_hint()
1145 forward_iterator! { SplitN: T, &'a [T] }
1146 forward_iterator! { RSplitN: T, &'a [T] }
1147 forward_iterator! { SplitNMut: T, &'a mut [T] }
1148 forward_iterator! { RSplitNMut: T, &'a mut [T] }
1150 /// An iterator over overlapping subslices of length `size`.
1152 #[stable(feature = "rust1", since = "1.0.0")]
1153 pub struct Windows<'a, T:'a> {
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<'a, T> Iterator for Windows<'a, T> {
1160 type Item = &'a [T];
1163 fn next(&mut self) -> Option<&'a [T]> {
1164 if self.size > self.v.len() {
1167 let ret = Some(&self.v[..self.size]);
1168 self.v = &self.v[1..];
1174 fn size_hint(&self) -> (uint, Option<uint>) {
1175 if self.size > self.v.len() {
1178 let x = self.v.len() - self.size;
1179 (x.saturating_add(1), x.checked_add(1))
1184 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1187 /// When the slice len is not evenly divided by the chunk size, the last slice
1188 /// of the iteration will be the remainder.
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 pub struct Chunks<'a, T:'a> {
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl<'a, T> Iterator for Chunks<'a, T> {
1198 type Item = &'a [T];
1201 fn next(&mut self) -> Option<&'a [T]> {
1202 if self.v.len() == 0 {
1205 let chunksz = cmp::min(self.v.len(), self.size);
1206 let (fst, snd) = self.v.split_at(chunksz);
1213 fn size_hint(&self) -> (uint, Option<uint>) {
1214 if self.v.len() == 0 {
1217 let n = self.v.len() / self.size;
1218 let rem = self.v.len() % self.size;
1219 let n = if rem > 0 { n+1 } else { n };
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
1228 fn next_back(&mut self) -> Option<&'a [T]> {
1229 if self.v.len() == 0 {
1232 let remainder = self.v.len() % self.size;
1233 let chunksz = if remainder != 0 { remainder } else { self.size };
1234 let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 impl<'a, T> ExactSizeIterator for Chunks<'a, T> {}
1244 #[unstable(feature = "core", reason = "trait is experimental")]
1245 impl<'a, T> RandomAccessIterator for Chunks<'a, T> {
1247 fn indexable(&self) -> uint {
1248 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1252 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1253 if index < self.indexable() {
1254 let lo = index * self.size;
1255 let mut hi = lo + self.size;
1256 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1258 Some(&self.v[lo..hi])
1265 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1266 /// elements at a time). When the slice len is not evenly divided by the chunk
1267 /// size, the last slice of the iteration will be the remainder.
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 pub struct ChunksMut<'a, T:'a> {
1274 #[stable(feature = "rust1", since = "1.0.0")]
1275 impl<'a, T> Iterator for ChunksMut<'a, T> {
1276 type Item = &'a mut [T];
1279 fn next(&mut self) -> Option<&'a mut [T]> {
1280 if self.v.len() == 0 {
1283 let sz = cmp::min(self.v.len(), self.chunk_size);
1284 let tmp = mem::replace(&mut self.v, &mut []);
1285 let (head, tail) = tmp.split_at_mut(sz);
1292 fn size_hint(&self) -> (uint, Option<uint>) {
1293 if self.v.len() == 0 {
1296 let n = self.v.len() / self.chunk_size;
1297 let rem = self.v.len() % self.chunk_size;
1298 let n = if rem > 0 { n + 1 } else { n };
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
1307 fn next_back(&mut self) -> Option<&'a mut [T]> {
1308 if self.v.len() == 0 {
1311 let remainder = self.v.len() % self.chunk_size;
1312 let sz = if remainder != 0 { remainder } else { self.chunk_size };
1313 let tmp = mem::replace(&mut self.v, &mut []);
1314 let tmp_len = tmp.len();
1315 let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl<'a, T> ExactSizeIterator for ChunksMut<'a, T> {}
1329 /// Converts a pointer to A into a slice of length 1 (without copying).
1330 #[unstable(feature = "core")]
1331 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1333 transmute(RawSlice { data: s, len: 1 })
1337 /// Converts a pointer to A into a slice of length 1 (without copying).
1338 #[unstable(feature = "core")]
1339 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1341 let ptr: *const A = transmute(s);
1342 transmute(RawSlice { data: ptr, len: 1 })
1346 /// Forms a slice from a pointer and a length.
1348 /// The pointer given is actually a reference to the base of the slice. This
1349 /// reference is used to give a concrete lifetime to tie the returned slice to.
1350 /// Typically this should indicate that the slice is valid for as long as the
1351 /// pointer itself is valid.
1353 /// The `len` argument is the number of **elements**, not the number of bytes.
1355 /// This function is unsafe as there is no guarantee that the given pointer is
1356 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1357 /// lifetime for the returned slice.
1364 /// // manifest a slice out of thin air!
1365 /// let ptr = 0x1234 as *const uint;
1368 /// let slice = slice::from_raw_buf(&ptr, amt);
1372 #[unstable(feature = "core",
1373 reason = "should be renamed to from_raw_parts")]
1374 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1375 transmute(RawSlice { data: *p, len: len })
1378 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1379 /// slice is returned.
1381 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1382 /// not being able to provide a non-aliasing guarantee of the returned mutable
1385 #[unstable(feature = "core",
1386 reason = "should be renamed to from_raw_parts_mut")]
1387 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1388 transmute(RawSlice { data: *p, len: len })
1395 /// Operations on `[u8]`.
1396 #[unstable(feature = "core", reason = "needs review")]
1399 use slice::SliceExt;
1401 /// A trait for operations on mutable `[u8]`s.
1402 pub trait MutableByteVector {
1403 /// Sets all bytes of the receiver to the given value.
1404 fn set_memory(&mut self, value: u8);
1407 impl MutableByteVector for [u8] {
1409 fn set_memory(&mut self, value: u8) {
1410 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1414 /// Copies data from `src` to `dst`
1416 /// Panics if the length of `dst` is less than the length of `src`.
1418 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1419 let len_src = src.len();
1420 assert!(dst.len() >= len_src);
1421 // `dst` is unaliasable, so we know statically it doesn't overlap
1424 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1434 // Boilerplate traits
1437 #[stable(feature = "rust1", since = "1.0.0")]
1438 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1439 fn eq(&self, other: &[B]) -> bool {
1440 self.len() == other.len() &&
1441 order::eq(self.iter(), other.iter())
1443 fn ne(&self, other: &[B]) -> bool {
1444 self.len() != other.len() ||
1445 order::ne(self.iter(), other.iter())
1449 #[stable(feature = "rust1", since = "1.0.0")]
1450 impl<T: Eq> Eq for [T] {}
1452 #[stable(feature = "rust1", since = "1.0.0")]
1453 impl<T: Ord> Ord for [T] {
1454 fn cmp(&self, other: &[T]) -> Ordering {
1455 order::cmp(self.iter(), other.iter())
1459 #[stable(feature = "rust1", since = "1.0.0")]
1460 impl<T: PartialOrd> PartialOrd for [T] {
1462 fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1463 order::partial_cmp(self.iter(), other.iter())
1466 fn lt(&self, other: &[T]) -> bool {
1467 order::lt(self.iter(), other.iter())
1470 fn le(&self, other: &[T]) -> bool {
1471 order::le(self.iter(), other.iter())
1474 fn ge(&self, other: &[T]) -> bool {
1475 order::ge(self.iter(), other.iter())
1478 fn gt(&self, other: &[T]) -> bool {
1479 order::gt(self.iter(), other.iter())
1483 /// Extension methods for slices containing integers.
1484 #[unstable(feature = "core")]
1485 pub trait IntSliceExt<U, S> {
1486 /// Converts the slice to an immutable slice of unsigned integers with the same width.
1487 fn as_unsigned<'a>(&'a self) -> &'a [U];
1488 /// Converts the slice to an immutable slice of signed integers with the same width.
1489 fn as_signed<'a>(&'a self) -> &'a [S];
1491 /// Converts the slice to a mutable slice of unsigned integers with the same width.
1492 fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1493 /// Converts the slice to a mutable slice of signed integers with the same width.
1494 fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1497 macro_rules! impl_int_slice {
1498 ($u:ty, $s:ty, $t:ty) => {
1499 #[unstable(feature = "core")]
1500 impl IntSliceExt<$u, $s> for [$t] {
1502 fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1504 fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1506 fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1508 fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1513 macro_rules! impl_int_slices {
1515 impl_int_slice! { $u, $s, $u }
1516 impl_int_slice! { $u, $s, $s }
1520 impl_int_slices! { u8, i8 }
1521 impl_int_slices! { u16, i16 }
1522 impl_int_slices! { u32, i32 }
1523 impl_int_slices! { u64, i64 }
1524 impl_int_slices! { uint, int }