]> git.lizzy.rs Git - rust.git/blob - src/libcore/slice.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / libcore / slice.rs
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.
4 //
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.
10
11 //! Slice management and manipulation
12 //!
13 //! For more details `std::slice`.
14
15 #![stable]
16 #![doc(primitive = "slice")]
17
18 // How this module is organized.
19 //
20 // The library infrastructure for slices is fairly messy. There's
21 // a lot of stuff defined here. Let's keep it clean.
22 //
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.
26 //
27 // The layout of this file is thus:
28 //
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.
33 // * Free functions.
34 // * The `raw` and `bytes` submodules.
35 // * Boilerplate trait implementations.
36
37 use mem::transmute;
38 use clone::Clone;
39 use cmp::{Ordering, PartialEq, PartialOrd, Eq, Ord, Equiv};
40 use cmp::Ordering::{Less, Equal, Greater};
41 use cmp;
42 use default::Default;
43 use iter::*;
44 use kinds::Copy;
45 use num::Int;
46 use ops;
47 use option::Option;
48 use option::Option::{None, Some};
49 use ptr;
50 use ptr::RawPtr;
51 use mem;
52 use mem::size_of;
53 use kinds::{Sized, marker};
54 use raw::Repr;
55 // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module.
56 use raw::Slice as RawSlice;
57
58
59 //
60 // Extension traits
61 //
62
63 /// Extension methods for slices.
64 #[unstable = "may merge with other traits"]
65 pub trait SlicePrelude<T> for Sized? {
66     /// Returns a subslice spanning the interval [`start`, `end`).
67     ///
68     /// Panics when the end of the new slice lies beyond the end of the
69     /// original slice (i.e. when `end > self.len()`) or when `start > end`.
70     ///
71     /// Slicing with `start` equal to `end` yields an empty slice.
72     #[unstable = "waiting on final error conventions/slicing syntax"]
73     fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T];
74
75     /// Returns a subslice from `start` to the end of the slice.
76     ///
77     /// Panics when `start` is strictly greater than the length of the original slice.
78     ///
79     /// Slicing from `self.len()` yields an empty slice.
80     #[unstable = "waiting on final error conventions/slicing syntax"]
81     fn slice_from<'a>(&'a self, start: uint) -> &'a [T];
82
83     /// Returns a subslice from the start of the slice to `end`.
84     ///
85     /// Panics when `end` is strictly greater than the length of the original slice.
86     ///
87     /// Slicing to `0` yields an empty slice.
88     #[unstable = "waiting on final error conventions/slicing syntax"]
89     fn slice_to<'a>(&'a self, end: uint) -> &'a [T];
90
91     /// Divides one slice into two at an index.
92     ///
93     /// The first will contain all indices from `[0, mid)` (excluding
94     /// the index `mid` itself) and the second will contain all
95     /// indices from `[mid, len)` (excluding the index `len` itself).
96     ///
97     /// Panics if `mid > len`.
98     #[unstable = "waiting on final error conventions"]
99     fn split_at<'a>(&'a self, mid: uint) -> (&'a [T], &'a [T]);
100
101     /// Returns an iterator over the slice
102     #[unstable = "iterator type may change"]
103     fn iter<'a>(&'a self) -> Items<'a, T>;
104
105     /// Returns an iterator over subslices separated by elements that match
106     /// `pred`.  The matched element is not contained in the subslices.
107     #[unstable = "iterator type may change, waiting on unboxed closures"]
108     fn split<'a>(&'a self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
109
110     /// Returns an iterator over subslices separated by elements that match
111     /// `pred`, limited to splitting at most `n` times.  The matched element is
112     /// not contained in the subslices.
113     #[unstable = "iterator type may change"]
114     fn splitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;
115
116     /// Returns an iterator over subslices separated by elements that match
117     /// `pred` limited to splitting at most `n` times. This starts at the end of
118     /// the slice and works backwards.  The matched element is not contained in
119     /// the subslices.
120     #[unstable = "iterator type may change"]
121     fn rsplitn<'a>(&'a self,  n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>>;
122
123     /// Returns an iterator over all contiguous windows of length
124     /// `size`. The windows overlap. If the slice is shorter than
125     /// `size`, the iterator returns no values.
126     ///
127     /// # Panics
128     ///
129     /// Panics if `size` is 0.
130     ///
131     /// # Example
132     ///
133     /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
134     /// `[3,4]`):
135     ///
136     /// ```rust
137     /// let v = &[1i, 2, 3, 4];
138     /// for win in v.windows(2) {
139     ///     println!("{}", win);
140     /// }
141     /// ```
142     #[unstable = "iterator type may change"]
143     fn windows<'a>(&'a self, size: uint) -> Windows<'a, T>;
144
145     /// Returns an iterator over `size` elements of the slice at a
146     /// time. The chunks do not overlap. If `size` does not divide the
147     /// length of the slice, then the last chunk will not have length
148     /// `size`.
149     ///
150     /// # Panics
151     ///
152     /// Panics if `size` is 0.
153     ///
154     /// # Example
155     ///
156     /// Print the slice two elements at a time (i.e. `[1,2]`,
157     /// `[3,4]`, `[5]`):
158     ///
159     /// ```rust
160     /// let v = &[1i, 2, 3, 4, 5];
161     /// for win in v.chunks(2) {
162     ///     println!("{}", win);
163     /// }
164     /// ```
165     #[unstable = "iterator type may change"]
166     fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, T>;
167
168     /// Returns the element of a slice at the given index, or `None` if the
169     /// index is out of bounds.
170     #[unstable = "waiting on final collection conventions"]
171     fn get<'a>(&'a self, index: uint) -> Option<&'a T>;
172
173     /// Returns the first element of a slice, or `None` if it is empty.
174     #[unstable = "name may change"]
175     fn head<'a>(&'a self) -> Option<&'a T>;
176
177     /// Returns all but the first element of a slice.
178     #[unstable = "name may change"]
179     fn tail<'a>(&'a self) -> &'a [T];
180
181     /// Returns all but the last element of a slice.
182     #[unstable = "name may change"]
183     fn init<'a>(&'a self) -> &'a [T];
184
185     /// Returns the last element of a slice, or `None` if it is empty.
186     #[unstable = "name may change"]
187     fn last<'a>(&'a self) -> Option<&'a T>;
188
189     /// Returns a pointer to the element at the given index, without doing
190     /// bounds checking.
191     #[unstable]
192     unsafe fn unsafe_get<'a>(&'a self, index: uint) -> &'a T;
193
194     /// Returns an unsafe pointer to the slice's buffer
195     ///
196     /// The caller must ensure that the slice outlives the pointer this
197     /// function returns, or else it will end up pointing to garbage.
198     ///
199     /// Modifying the slice may cause its buffer to be reallocated, which
200     /// would also make any pointers to it invalid.
201     #[unstable]
202     fn as_ptr(&self) -> *const T;
203
204     /// Binary search a sorted slice with a comparator function.
205     ///
206     /// The comparator function should implement an order consistent
207     /// with the sort order of the underlying slice, returning an
208     /// order code that indicates whether its argument is `Less`,
209     /// `Equal` or `Greater` the desired target.
210     ///
211     /// If a matching value is found then returns `Found`, containing
212     /// the index for the matched element; if no match is found then
213     /// `NotFound` is returned, containing the index where a matching
214     /// element could be inserted while maintaining sorted order.
215     ///
216     /// # Example
217     ///
218     /// Looks up a series of four elements. The first is found, with a
219     /// uniquely determined position; the second and third are not
220     /// found; the fourth could match any position in `[1,4]`.
221     ///
222     /// ```rust
223     /// use std::slice::BinarySearchResult::{Found, NotFound};
224     /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
225     /// let s = s.as_slice();
226     ///
227     /// let seek = 13;
228     /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), Found(9));
229     /// let seek = 4;
230     /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), NotFound(7));
231     /// let seek = 100;
232     /// assert_eq!(s.binary_search(|probe| probe.cmp(&seek)), NotFound(13));
233     /// let seek = 1;
234     /// let r = s.binary_search(|probe| probe.cmp(&seek));
235     /// assert!(match r { Found(1...4) => true, _ => false, });
236     /// ```
237     #[unstable = "waiting on unboxed closures"]
238     fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult;
239
240     /// Return the number of elements in the slice
241     ///
242     /// # Example
243     ///
244     /// ```
245     /// let a = [1i, 2, 3];
246     /// assert_eq!(a.len(), 3);
247     /// ```
248     #[experimental = "not triaged yet"]
249     fn len(&self) -> uint;
250
251     /// Returns true if the slice has a length of 0
252     ///
253     /// # Example
254     ///
255     /// ```
256     /// let a = [1i, 2, 3];
257     /// assert!(!a.is_empty());
258     /// ```
259     #[inline]
260     #[experimental = "not triaged yet"]
261     fn is_empty(&self) -> bool { self.len() == 0 }
262     /// Returns a mutable reference to the element at the given index,
263     /// or `None` if the index is out of bounds
264     #[unstable = "waiting on final error conventions"]
265     fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T>;
266
267     /// Work with `self` as a mut slice.
268     /// Primarily intended for getting a &mut [T] from a [T, ..N].
269     fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T];
270
271     /// Returns a mutable subslice spanning the interval [`start`, `end`).
272     ///
273     /// Panics when the end of the new slice lies beyond the end of the
274     /// original slice (i.e. when `end > self.len()`) or when `start > end`.
275     ///
276     /// Slicing with `start` equal to `end` yields an empty slice.
277     #[unstable = "waiting on final error conventions"]
278     fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T];
279
280     /// Returns a mutable subslice from `start` to the end of the slice.
281     ///
282     /// Panics when `start` is strictly greater than the length of the original slice.
283     ///
284     /// Slicing from `self.len()` yields an empty slice.
285     #[unstable = "waiting on final error conventions"]
286     fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T];
287
288     /// Returns a mutable subslice from the start of the slice to `end`.
289     ///
290     /// Panics when `end` is strictly greater than the length of the original slice.
291     ///
292     /// Slicing to `0` yields an empty slice.
293     #[unstable = "waiting on final error conventions"]
294     fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T];
295
296     /// Returns an iterator that allows modifying each value
297     #[unstable = "waiting on iterator type name conventions"]
298     fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T>;
299
300     /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
301     #[unstable = "name may change"]
302     fn head_mut<'a>(&'a mut self) -> Option<&'a mut T>;
303
304     /// Returns all but the first element of a mutable slice
305     #[unstable = "name may change"]
306     fn tail_mut<'a>(&'a mut self) -> &'a mut [T];
307
308     /// Returns all but the last element of a mutable slice
309     #[unstable = "name may change"]
310     fn init_mut<'a>(&'a mut self) -> &'a mut [T];
311
312     /// Returns a mutable pointer to the last item in the slice.
313     #[unstable = "name may change"]
314     fn last_mut<'a>(&'a mut self) -> Option<&'a mut T>;
315
316     /// Returns an iterator over mutable subslices separated by elements that
317     /// match `pred`.  The matched element is not contained in the subslices.
318     #[unstable = "waiting on unboxed closures, iterator type name conventions"]
319     fn split_mut<'a>(&'a mut self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
320
321     /// Returns an iterator over subslices separated by elements that match
322     /// `pred`, limited to splitting at most `n` times.  The matched element is
323     /// not contained in the subslices.
324     #[unstable = "waiting on unboxed closures, iterator type name conventions"]
325     fn splitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;
326
327     /// Returns an iterator over subslices separated by elements that match
328     /// `pred` limited to splitting at most `n` times. This starts at the end of
329     /// the slice and works backwards.  The matched element is not contained in
330     /// the subslices.
331     #[unstable = "waiting on unboxed closures, iterator type name conventions"]
332     fn rsplitn_mut<'a>(&'a mut self,  n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;
333
334     /// Returns an iterator over `chunk_size` elements of the slice at a time.
335     /// The chunks are mutable and do not overlap. If `chunk_size` does
336     /// not divide the length of the slice, then the last chunk will not
337     /// have length `chunk_size`.
338     ///
339     /// # Panics
340     ///
341     /// Panics if `chunk_size` is 0.
342     #[unstable = "waiting on iterator type name conventions"]
343     fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> MutChunks<'a, T>;
344
345     /// Swaps two elements in a slice.
346     ///
347     /// Panics if `a` or `b` are out of bounds.
348     ///
349     /// # Arguments
350     ///
351     /// * a - The index of the first element
352     /// * b - The index of the second element
353     ///
354     /// # Example
355     ///
356     /// ```rust
357     /// let mut v = ["a", "b", "c", "d"];
358     /// v.swap(1, 3);
359     /// assert!(v == ["a", "d", "c", "b"]);
360     /// ```
361     #[unstable = "waiting on final error conventions"]
362     fn swap(&mut self, a: uint, b: uint);
363
364     /// Divides one `&mut` into two at an index.
365     ///
366     /// The first will contain all indices from `[0, mid)` (excluding
367     /// the index `mid` itself) and the second will contain all
368     /// indices from `[mid, len)` (excluding the index `len` itself).
369     ///
370     /// Panics if `mid > len`.
371     ///
372     /// # Example
373     ///
374     /// ```rust
375     /// let mut v = [1i, 2, 3, 4, 5, 6];
376     ///
377     /// // scoped to restrict the lifetime of the borrows
378     /// {
379     ///    let (left, right) = v.split_at_mut(0);
380     ///    assert!(left == []);
381     ///    assert!(right == [1i, 2, 3, 4, 5, 6]);
382     /// }
383     ///
384     /// {
385     ///     let (left, right) = v.split_at_mut(2);
386     ///     assert!(left == [1i, 2]);
387     ///     assert!(right == [3i, 4, 5, 6]);
388     /// }
389     ///
390     /// {
391     ///     let (left, right) = v.split_at_mut(6);
392     ///     assert!(left == [1i, 2, 3, 4, 5, 6]);
393     ///     assert!(right == []);
394     /// }
395     /// ```
396     #[unstable = "waiting on final error conventions"]
397     fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]);
398
399     /// Reverse the order of elements in a slice, in place.
400     ///
401     /// # Example
402     ///
403     /// ```rust
404     /// let mut v = [1i, 2, 3];
405     /// v.reverse();
406     /// assert!(v == [3i, 2, 1]);
407     /// ```
408     #[experimental = "may be moved to iterators instead"]
409     fn reverse(&mut self);
410
411     /// Returns an unsafe mutable pointer to the element in index
412     #[experimental = "waiting on unsafe conventions"]
413     unsafe fn unsafe_mut<'a>(&'a mut self, index: uint) -> &'a mut T;
414
415     /// Return an unsafe mutable pointer to the slice's buffer.
416     ///
417     /// The caller must ensure that the slice outlives the pointer this
418     /// function returns, or else it will end up pointing to garbage.
419     ///
420     /// Modifying the slice may cause its buffer to be reallocated, which
421     /// would also make any pointers to it invalid.
422     #[inline]
423     #[unstable]
424     fn as_mut_ptr(&mut self) -> *mut T;
425 }
426
427 #[unstable]
428 impl<T> SlicePrelude<T> for [T] {
429     #[inline]
430     fn slice(&self, start: uint, end: uint) -> &[T] {
431         assert!(start <= end);
432         assert!(end <= self.len());
433         unsafe {
434             transmute(RawSlice {
435                 data: self.as_ptr().offset(start as int),
436                 len: (end - start)
437             })
438         }
439     }
440
441     #[inline]
442     fn slice_from(&self, start: uint) -> &[T] {
443         self.slice(start, self.len())
444     }
445
446     #[inline]
447     fn slice_to(&self, end: uint) -> &[T] {
448         self.slice(0, end)
449     }
450
451     #[inline]
452     fn split_at(&self, mid: uint) -> (&[T], &[T]) {
453         (self[..mid], self[mid..])
454     }
455
456     #[inline]
457     fn iter<'a>(&'a self) -> Items<'a, T> {
458         unsafe {
459             let p = self.as_ptr();
460             if mem::size_of::<T>() == 0 {
461                 Items{ptr: p,
462                       end: (p as uint + self.len()) as *const T,
463                       marker: marker::ContravariantLifetime::<'a>}
464             } else {
465                 Items{ptr: p,
466                       end: p.offset(self.len() as int),
467                       marker: marker::ContravariantLifetime::<'a>}
468             }
469         }
470     }
471
472     #[inline]
473     fn split<'a>(&'a self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
474         Splits {
475             v: self,
476             pred: pred,
477             finished: false
478         }
479     }
480
481     #[inline]
482     fn splitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
483         SplitsN {
484             iter: self.split(pred),
485             count: n,
486             invert: false
487         }
488     }
489
490     #[inline]
491     fn rsplitn<'a>(&'a self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<Splits<'a, T>> {
492         SplitsN {
493             iter: self.split(pred),
494             count: n,
495             invert: true
496         }
497     }
498
499     #[inline]
500     fn windows(&self, size: uint) -> Windows<T> {
501         assert!(size != 0);
502         Windows { v: self, size: size }
503     }
504
505     #[inline]
506     fn chunks(&self, size: uint) -> Chunks<T> {
507         assert!(size != 0);
508         Chunks { v: self, size: size }
509     }
510
511     #[inline]
512     fn get(&self, index: uint) -> Option<&T> {
513         if index < self.len() { Some(&self[index]) } else { None }
514     }
515
516     #[inline]
517     fn head(&self) -> Option<&T> {
518         if self.len() == 0 { None } else { Some(&self[0]) }
519     }
520
521     #[inline]
522     fn tail(&self) -> &[T] { self[1..] }
523
524     #[inline]
525     fn init(&self) -> &[T] {
526         self[..self.len() - 1]
527     }
528
529     #[inline]
530     fn last(&self) -> Option<&T> {
531         if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
532     }
533
534     #[inline]
535     unsafe fn unsafe_get(&self, index: uint) -> &T {
536         transmute(self.repr().data.offset(index as int))
537     }
538
539     #[inline]
540     fn as_ptr(&self) -> *const T {
541         self.repr().data
542     }
543
544     #[unstable]
545     fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult {
546         let mut base : uint = 0;
547         let mut lim : uint = self.len();
548
549         while lim != 0 {
550             let ix = base + (lim >> 1);
551             match f(&self[ix]) {
552                 Equal => return BinarySearchResult::Found(ix),
553                 Less => {
554                     base = ix + 1;
555                     lim -= 1;
556                 }
557                 Greater => ()
558             }
559             lim >>= 1;
560         }
561         return BinarySearchResult::NotFound(base);
562     }
563
564     #[inline]
565     fn len(&self) -> uint { self.repr().len }
566
567     #[inline]
568     fn get_mut(&mut self, index: uint) -> Option<&mut T> {
569         if index < self.len() { Some(&mut self[index]) } else { None }
570     }
571
572     #[inline]
573     fn as_mut_slice(&mut self) -> &mut [T] { self }
574
575     fn slice_mut(&mut self, start: uint, end: uint) -> &mut [T] {
576         self[mut start..end]
577     }
578
579     #[inline]
580     fn slice_from_mut(&mut self, start: uint) -> &mut [T] {
581         self[mut start..]
582     }
583
584     #[inline]
585     fn slice_to_mut(&mut self, end: uint) -> &mut [T] {
586         self[mut ..end]
587     }
588
589     #[inline]
590     fn split_at_mut(&mut self, mid: uint) -> (&mut [T], &mut [T]) {
591         unsafe {
592             let self2: &mut [T] = mem::transmute_copy(&self);
593             (self[mut ..mid], self2[mut mid..])
594         }
595     }
596
597     #[inline]
598     fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
599         unsafe {
600             let p = self.as_mut_ptr();
601             if mem::size_of::<T>() == 0 {
602                 MutItems{ptr: p,
603                          end: (p as uint + self.len()) as *mut T,
604                          marker: marker::ContravariantLifetime::<'a>,
605                          marker2: marker::NoCopy}
606             } else {
607                 MutItems{ptr: p,
608                          end: p.offset(self.len() as int),
609                          marker: marker::ContravariantLifetime::<'a>,
610                          marker2: marker::NoCopy}
611             }
612         }
613     }
614
615     #[inline]
616     fn last_mut(&mut self) -> Option<&mut T> {
617         let len = self.len();
618         if len == 0 { return None; }
619         Some(&mut self[len - 1])
620     }
621
622     #[inline]
623     fn head_mut(&mut self) -> Option<&mut T> {
624         if self.len() == 0 { None } else { Some(&mut self[0]) }
625     }
626
627     #[inline]
628     fn tail_mut(&mut self) -> &mut [T] {
629         let len = self.len();
630         self[mut 1..len]
631     }
632
633     #[inline]
634     fn init_mut(&mut self) -> &mut [T] {
635         let len = self.len();
636         self[mut 0..len - 1]
637     }
638
639     #[inline]
640     fn split_mut<'a>(&'a mut self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
641         MutSplits { v: self, pred: pred, finished: false }
642     }
643
644     #[inline]
645     fn splitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
646         SplitsN {
647             iter: self.split_mut(pred),
648             count: n,
649             invert: false
650         }
651     }
652
653     #[inline]
654     fn rsplitn_mut<'a>(&'a mut self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>> {
655         SplitsN {
656             iter: self.split_mut(pred),
657             count: n,
658             invert: true
659         }
660    }
661
662     #[inline]
663     fn chunks_mut(&mut self, chunk_size: uint) -> MutChunks<T> {
664         assert!(chunk_size > 0);
665         MutChunks { v: self, chunk_size: chunk_size }
666     }
667
668     fn swap(&mut self, a: uint, b: uint) {
669         unsafe {
670             // Can't take two mutable loans from one vector, so instead just cast
671             // them to their raw pointers to do the swap
672             let pa: *mut T = &mut self[a];
673             let pb: *mut T = &mut self[b];
674             ptr::swap(pa, pb);
675         }
676     }
677
678     fn reverse(&mut self) {
679         let mut i: uint = 0;
680         let ln = self.len();
681         while i < ln / 2 {
682             // Unsafe swap to avoid the bounds check in safe swap.
683             unsafe {
684                 let pa: *mut T = self.unsafe_mut(i);
685                 let pb: *mut T = self.unsafe_mut(ln - i - 1);
686                 ptr::swap(pa, pb);
687             }
688             i += 1;
689         }
690     }
691
692     #[inline]
693     unsafe fn unsafe_mut(&mut self, index: uint) -> &mut T {
694         transmute((self.repr().data as *mut T).offset(index as int))
695     }
696
697     #[inline]
698     fn as_mut_ptr(&mut self) -> *mut T {
699         self.repr().data as *mut T
700     }
701 }
702
703 impl<T> ops::Index<uint, T> for [T] {
704     fn index(&self, &index: &uint) -> &T {
705         assert!(index < self.len());
706
707         unsafe { mem::transmute(self.repr().data.offset(index as int)) }
708     }
709 }
710
711 impl<T> ops::IndexMut<uint, T> for [T] {
712     fn index_mut(&mut self, &index: &uint) -> &mut T {
713         assert!(index < self.len());
714
715         unsafe { mem::transmute(self.repr().data.offset(index as int)) }
716     }
717 }
718
719 impl<T> ops::Slice<uint, [T]> for [T] {
720     #[inline]
721     fn as_slice_<'a>(&'a self) -> &'a [T] {
722         self
723     }
724
725     #[inline]
726     fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
727         self.slice_or_fail(start, &self.len())
728     }
729
730     #[inline]
731     fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
732         self.slice_or_fail(&0, end)
733     }
734     #[inline]
735     fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
736         assert!(*start <= *end);
737         assert!(*end <= self.len());
738         unsafe {
739             transmute(RawSlice {
740                     data: self.as_ptr().offset(*start as int),
741                     len: (*end - *start)
742                 })
743         }
744     }
745 }
746
747 impl<T> ops::SliceMut<uint, [T]> for [T] {
748     #[inline]
749     fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
750         self
751     }
752
753     #[inline]
754     fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
755         let len = &self.len();
756         self.slice_or_fail_mut(start, len)
757     }
758
759     #[inline]
760     fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
761         self.slice_or_fail_mut(&0, end)
762     }
763     #[inline]
764     fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
765         assert!(*start <= *end);
766         assert!(*end <= self.len());
767         unsafe {
768             transmute(RawSlice {
769                     data: self.as_ptr().offset(*start as int),
770                     len: (*end - *start)
771                 })
772         }
773     }
774 }
775
776 /// Extension methods for slices containing `PartialEq` elements.
777 #[unstable = "may merge with other traits"]
778 pub trait PartialEqSlicePrelude<T: PartialEq> for Sized? {
779     /// Find the first index containing a matching value.
780     fn position_elem(&self, t: &T) -> Option<uint>;
781
782     /// Find the last index containing a matching value.
783     fn rposition_elem(&self, t: &T) -> Option<uint>;
784
785     /// Return true if the slice contains an element with the given value.
786     fn contains(&self, x: &T) -> bool;
787
788     /// Returns true if `needle` is a prefix of the slice.
789     fn starts_with(&self, needle: &[T]) -> bool;
790
791     /// Returns true if `needle` is a suffix of the slice.
792     fn ends_with(&self, needle: &[T]) -> bool;
793 }
794
795 #[unstable = "trait is unstable"]
796 impl<T: PartialEq> PartialEqSlicePrelude<T> for [T] {
797     #[inline]
798     fn position_elem(&self, x: &T) -> Option<uint> {
799         self.iter().position(|y| *x == *y)
800     }
801
802     #[inline]
803     fn rposition_elem(&self, t: &T) -> Option<uint> {
804         self.iter().rposition(|x| *x == *t)
805     }
806
807     #[inline]
808     fn contains(&self, x: &T) -> bool {
809         self.iter().any(|elt| *x == *elt)
810     }
811
812     #[inline]
813     fn starts_with(&self, needle: &[T]) -> bool {
814         let n = needle.len();
815         self.len() >= n && needle == self[..n]
816     }
817
818     #[inline]
819     fn ends_with(&self, needle: &[T]) -> bool {
820         let (m, n) = (self.len(), needle.len());
821         m >= n && needle == self[m-n..]
822     }
823 }
824
825 /// Extension methods for slices containing `Ord` elements.
826 #[unstable = "may merge with other traits"]
827 pub trait OrdSlicePrelude<T: Ord> for Sized? {
828     /// Binary search a sorted slice for a given element.
829     ///
830     /// If the value is found then `Found` is returned, containing the
831     /// index of the matching element; if the value is not found then
832     /// `NotFound` is returned, containing the index where a matching
833     /// element could be inserted while maintaining sorted order.
834     ///
835     /// # Example
836     ///
837     /// Looks up a series of four elements. The first is found, with a
838     /// uniquely determined position; the second and third are not
839     /// found; the fourth could match any position in `[1,4]`.
840     ///
841     /// ```rust
842     /// use std::slice::BinarySearchResult::{Found, NotFound};
843     /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
844     /// let s = s.as_slice();
845     ///
846     /// assert_eq!(s.binary_search_elem(&13),  Found(9));
847     /// assert_eq!(s.binary_search_elem(&4),   NotFound(7));
848     /// assert_eq!(s.binary_search_elem(&100), NotFound(13));
849     /// let r = s.binary_search_elem(&1);
850     /// assert!(match r { Found(1...4) => true, _ => false, });
851     /// ```
852     #[unstable = "name likely to change"]
853     fn binary_search_elem(&self, x: &T) -> BinarySearchResult;
854
855     /// Mutates the slice to the next lexicographic permutation.
856     ///
857     /// Returns `true` if successful and `false` if the slice is at the
858     /// last-ordered permutation.
859     ///
860     /// # Example
861     ///
862     /// ```rust
863     /// let v: &mut [_] = &mut [0i, 1, 2];
864     /// v.next_permutation();
865     /// let b: &mut [_] = &mut [0i, 2, 1];
866     /// assert!(v == b);
867     /// v.next_permutation();
868     /// let b: &mut [_] = &mut [1i, 0, 2];
869     /// assert!(v == b);
870     /// ```
871     #[experimental]
872     fn next_permutation(&mut self) -> bool;
873
874     /// Mutates the slice to the previous lexicographic permutation.
875     ///
876     /// Returns `true` if successful and `false` if the slice is at the
877     /// first-ordered permutation.
878     ///
879     /// # Example
880     ///
881     /// ```rust
882     /// let v: &mut [_] = &mut [1i, 0, 2];
883     /// v.prev_permutation();
884     /// let b: &mut [_] = &mut [0i, 2, 1];
885     /// assert!(v == b);
886     /// v.prev_permutation();
887     /// let b: &mut [_] = &mut [0i, 1, 2];
888     /// assert!(v == b);
889     /// ```
890     #[experimental]
891     fn prev_permutation(&mut self) -> bool;
892 }
893
894 #[unstable = "trait is unstable"]
895 impl<T: Ord> OrdSlicePrelude<T> for [T] {
896     #[unstable]
897     fn binary_search_elem(&self, x: &T) -> BinarySearchResult {
898         self.binary_search(|p| p.cmp(x))
899     }
900
901     #[experimental]
902     fn next_permutation(&mut self) -> bool {
903         // These cases only have 1 permutation each, so we can't do anything.
904         if self.len() < 2 { return false; }
905
906         // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
907         let mut i = self.len() - 1;
908         while i > 0 && self[i-1] >= self[i] {
909             i -= 1;
910         }
911
912         // If that is the entire vector, this is the last-ordered permutation.
913         if i == 0 {
914             return false;
915         }
916
917         // Step 2: Find the rightmost element larger than the pivot (i-1)
918         let mut j = self.len() - 1;
919         while j >= i && self[j] <= self[i-1]  {
920             j -= 1;
921         }
922
923         // Step 3: Swap that element with the pivot
924         self.swap(j, i-1);
925
926         // Step 4: Reverse the (previously) weakly decreasing part
927         self[mut i..].reverse();
928
929         true
930     }
931
932     #[experimental]
933     fn prev_permutation(&mut self) -> bool {
934         // These cases only have 1 permutation each, so we can't do anything.
935         if self.len() < 2 { return false; }
936
937         // Step 1: Identify the longest, rightmost weakly increasing part of the vector
938         let mut i = self.len() - 1;
939         while i > 0 && self[i-1] <= self[i] {
940             i -= 1;
941         }
942
943         // If that is the entire vector, this is the first-ordered permutation.
944         if i == 0 {
945             return false;
946         }
947
948         // Step 2: Reverse the weakly increasing part
949         self[mut i..].reverse();
950
951         // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
952         let mut j = self.len() - 1;
953         while j >= i && self[j-1] < self[i-1]  {
954             j -= 1;
955         }
956
957         // Step 4: Swap that element with the pivot
958         self.swap(i-1, j);
959
960         true
961     }
962 }
963
964 /// Extension methods for slices on Clone elements
965 #[unstable = "may merge with other traits"]
966 pub trait CloneSlicePrelude<T> for Sized? {
967     /// Copies as many elements from `src` as it can into `self` (the
968     /// shorter of `self.len()` and `src.len()`). Returns the number
969     /// of elements copied.
970     ///
971     /// # Example
972     ///
973     /// ```rust
974     /// use std::slice::CloneSlicePrelude;
975     ///
976     /// let mut dst = [0i, 0, 0];
977     /// let src = [1i, 2];
978     ///
979     /// assert!(dst.clone_from_slice(&src) == 2);
980     /// assert!(dst == [1, 2, 0]);
981     ///
982     /// let src2 = [3i, 4, 5, 6];
983     /// assert!(dst.clone_from_slice(&src2) == 3);
984     /// assert!(dst == [3i, 4, 5]);
985     /// ```
986     fn clone_from_slice(&mut self, &[T]) -> uint;
987 }
988
989 #[unstable = "trait is unstable"]
990 impl<T: Clone> CloneSlicePrelude<T> for [T] {
991     #[inline]
992     fn clone_from_slice(&mut self, src: &[T]) -> uint {
993         let min = cmp::min(self.len(), src.len());
994         let dst = self.slice_to_mut(min);
995         let src = src.slice_to(min);
996         for i in range(0, min) {
997             dst[i].clone_from(&src[i]);
998         }
999         min
1000     }
1001 }
1002
1003
1004
1005
1006 //
1007 // Common traits
1008 //
1009
1010 /// Data that is viewable as a slice.
1011 #[unstable = "may merge with other traits"]
1012 pub trait AsSlice<T> for Sized? {
1013     /// Work with `self` as a slice.
1014     fn as_slice<'a>(&'a self) -> &'a [T];
1015 }
1016
1017 #[unstable = "trait is unstable"]
1018 impl<T> AsSlice<T> for [T] {
1019     #[inline(always)]
1020     fn as_slice<'a>(&'a self) -> &'a [T] { self }
1021 }
1022
1023 impl<'a, T, Sized? U: AsSlice<T>> AsSlice<T> for &'a U {
1024     #[inline(always)]
1025     fn as_slice<'a>(&'a self) -> &'a [T] { AsSlice::as_slice(*self) }
1026 }
1027
1028 impl<'a, T, Sized? U: AsSlice<T>> AsSlice<T> for &'a mut U {
1029     #[inline(always)]
1030     fn as_slice<'a>(&'a self) -> &'a [T] { AsSlice::as_slice(*self) }
1031 }
1032
1033 #[unstable = "waiting for DST"]
1034 impl<'a, T> Default for &'a [T] {
1035     fn default() -> &'a [T] { &[] }
1036 }
1037
1038 //
1039 // Iterators
1040 //
1041
1042 // The shared definition of the `Item` and `MutItems` iterators
1043 macro_rules! iterator {
1044     (struct $name:ident -> $ptr:ty, $elem:ty) => {
1045         #[experimental = "needs review"]
1046         impl<'a, T> Iterator<$elem> for $name<'a, T> {
1047             #[inline]
1048             fn next(&mut self) -> Option<$elem> {
1049                 // could be implemented with slices, but this avoids bounds checks
1050                 unsafe {
1051                     if self.ptr == self.end {
1052                         None
1053                     } else {
1054                         if mem::size_of::<T>() == 0 {
1055                             // purposefully don't use 'ptr.offset' because for
1056                             // vectors with 0-size elements this would return the
1057                             // same pointer.
1058                             self.ptr = transmute(self.ptr as uint + 1);
1059
1060                             // Use a non-null pointer value
1061                             Some(transmute(1u))
1062                         } else {
1063                             let old = self.ptr;
1064                             self.ptr = self.ptr.offset(1);
1065
1066                             Some(transmute(old))
1067                         }
1068                     }
1069                 }
1070             }
1071
1072             #[inline]
1073             fn size_hint(&self) -> (uint, Option<uint>) {
1074                 let diff = (self.end as uint) - (self.ptr as uint);
1075                 let size = mem::size_of::<T>();
1076                 let exact = diff / (if size == 0 {1} else {size});
1077                 (exact, Some(exact))
1078             }
1079         }
1080
1081         #[experimental = "needs review"]
1082         impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
1083             #[inline]
1084             fn next_back(&mut self) -> Option<$elem> {
1085                 // could be implemented with slices, but this avoids bounds checks
1086                 unsafe {
1087                     if self.end == self.ptr {
1088                         None
1089                     } else {
1090                         if mem::size_of::<T>() == 0 {
1091                             // See above for why 'ptr.offset' isn't used
1092                             self.end = transmute(self.end as uint - 1);
1093
1094                             // Use a non-null pointer value
1095                             Some(transmute(1u))
1096                         } else {
1097                             self.end = self.end.offset(-1);
1098
1099                             Some(transmute(self.end))
1100                         }
1101                     }
1102                 }
1103             }
1104         }
1105     }
1106 }
1107
1108 macro_rules! make_slice {
1109     ($t: ty -> $result: ty: $start: expr, $end: expr) => {{
1110         let diff = $end as uint - $start as uint;
1111         let len = if mem::size_of::<T>() == 0 {
1112             diff
1113         } else {
1114             diff / mem::size_of::<$t>()
1115         };
1116         unsafe {
1117             transmute::<_, $result>(RawSlice { data: $start as *const T, len: len })
1118         }
1119     }}
1120 }
1121
1122
1123 /// Immutable slice iterator
1124 #[experimental = "needs review"]
1125 pub struct Items<'a, T: 'a> {
1126     ptr: *const T,
1127     end: *const T,
1128     marker: marker::ContravariantLifetime<'a>
1129 }
1130
1131 #[experimental]
1132 impl<'a, T> ops::Slice<uint, [T]> for Items<'a, T> {
1133     fn as_slice_(&self) -> &[T] {
1134         self.as_slice()
1135     }
1136     fn slice_from_or_fail<'b>(&'b self, from: &uint) -> &'b [T] {
1137         use ops::Slice;
1138         self.as_slice().slice_from_or_fail(from)
1139     }
1140     fn slice_to_or_fail<'b>(&'b self, to: &uint) -> &'b [T] {
1141         use ops::Slice;
1142         self.as_slice().slice_to_or_fail(to)
1143     }
1144     fn slice_or_fail<'b>(&'b self, from: &uint, to: &uint) -> &'b [T] {
1145         use ops::Slice;
1146         self.as_slice().slice_or_fail(from, to)
1147     }
1148 }
1149
1150 impl<'a, T> Items<'a, T> {
1151     /// View the underlying data as a subslice of the original data.
1152     ///
1153     /// This has the same lifetime as the original slice, and so the
1154     /// iterator can continue to be used while this exists.
1155     #[experimental]
1156     pub fn as_slice(&self) -> &'a [T] {
1157         make_slice!(T -> &'a [T]: self.ptr, self.end)
1158     }
1159 }
1160
1161 impl<'a,T> Copy for Items<'a,T> {}
1162
1163 iterator!{struct Items -> *const T, &'a T}
1164
1165 #[experimental = "needs review"]
1166 impl<'a, T> ExactSizeIterator<&'a T> for Items<'a, T> {}
1167
1168 #[experimental = "needs review"]
1169 impl<'a, T> Clone for Items<'a, T> {
1170     fn clone(&self) -> Items<'a, T> { *self }
1171 }
1172
1173 #[experimental = "needs review"]
1174 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
1175     #[inline]
1176     fn indexable(&self) -> uint {
1177         let (exact, _) = self.size_hint();
1178         exact
1179     }
1180
1181     #[inline]
1182     fn idx(&mut self, index: uint) -> Option<&'a T> {
1183         unsafe {
1184             if index < self.indexable() {
1185                 if mem::size_of::<T>() == 0 {
1186                     // Use a non-null pointer value
1187                     Some(transmute(1u))
1188                 } else {
1189                     Some(transmute(self.ptr.offset(index as int)))
1190                 }
1191             } else {
1192                 None
1193             }
1194         }
1195     }
1196 }
1197
1198 /// Mutable slice iterator.
1199 #[experimental = "needs review"]
1200 pub struct MutItems<'a, T: 'a> {
1201     ptr: *mut T,
1202     end: *mut T,
1203     marker: marker::ContravariantLifetime<'a>,
1204     marker2: marker::NoCopy
1205 }
1206
1207 #[experimental]
1208 impl<'a, T> ops::Slice<uint, [T]> for MutItems<'a, T> {
1209     fn as_slice_<'b>(&'b self) -> &'b [T] {
1210         make_slice!(T -> &'b [T]: self.ptr, self.end)
1211     }
1212     fn slice_from_or_fail<'b>(&'b self, from: &uint) -> &'b [T] {
1213         use ops::Slice;
1214         self.as_slice_().slice_from_or_fail(from)
1215     }
1216     fn slice_to_or_fail<'b>(&'b self, to: &uint) -> &'b [T] {
1217         use ops::Slice;
1218         self.as_slice_().slice_to_or_fail(to)
1219     }
1220     fn slice_or_fail<'b>(&'b self, from: &uint, to: &uint) -> &'b [T] {
1221         use ops::Slice;
1222         self.as_slice_().slice_or_fail(from, to)
1223     }
1224 }
1225
1226 #[experimental]
1227 impl<'a, T> ops::SliceMut<uint, [T]> for MutItems<'a, T> {
1228     fn as_mut_slice_<'b>(&'b mut self) -> &'b mut [T] {
1229         make_slice!(T -> &'b mut [T]: self.ptr, self.end)
1230     }
1231     fn slice_from_or_fail_mut<'b>(&'b mut self, from: &uint) -> &'b mut [T] {
1232         use ops::SliceMut;
1233         self.as_mut_slice_().slice_from_or_fail_mut(from)
1234     }
1235     fn slice_to_or_fail_mut<'b>(&'b mut self, to: &uint) -> &'b mut [T] {
1236         use ops::SliceMut;
1237         self.as_mut_slice_().slice_to_or_fail_mut(to)
1238     }
1239     fn slice_or_fail_mut<'b>(&'b mut self, from: &uint, to: &uint) -> &'b mut [T] {
1240         use ops::SliceMut;
1241         self.as_mut_slice_().slice_or_fail_mut(from, to)
1242     }
1243 }
1244
1245 impl<'a, T> MutItems<'a, T> {
1246     /// View the underlying data as a subslice of the original data.
1247     ///
1248     /// To avoid creating `&mut` references that alias, this is forced
1249     /// to consume the iterator. Consider using the `Slice` and
1250     /// `SliceMut` implementations for obtaining slices with more
1251     /// restricted lifetimes that do not consume the iterator.
1252     #[experimental]
1253     pub fn into_slice(self) -> &'a mut [T] {
1254         make_slice!(T -> &'a mut [T]: self.ptr, self.end)
1255     }
1256 }
1257
1258 iterator!{struct MutItems -> *mut T, &'a mut T}
1259
1260 #[experimental = "needs review"]
1261 impl<'a, T> ExactSizeIterator<&'a mut T> for MutItems<'a, T> {}
1262
1263 /// An abstraction over the splitting iterators, so that splitn, splitn_mut etc
1264 /// can be implemented once.
1265 trait SplitsIter<E>: DoubleEndedIterator<E> {
1266     /// Mark the underlying iterator as complete, extracting the remaining
1267     /// portion of the slice.
1268     fn finish(&mut self) -> Option<E>;
1269 }
1270
1271 /// An iterator over subslices separated by elements that match a predicate
1272 /// function.
1273 #[experimental = "needs review"]
1274 pub struct Splits<'a, T:'a> {
1275     v: &'a [T],
1276     pred: |t: &T|: 'a -> bool,
1277     finished: bool
1278 }
1279
1280 #[experimental = "needs review"]
1281 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
1282     #[inline]
1283     fn next(&mut self) -> Option<&'a [T]> {
1284         if self.finished { return None; }
1285
1286         match self.v.iter().position(|x| (self.pred)(x)) {
1287             None => self.finish(),
1288             Some(idx) => {
1289                 let ret = Some(self.v[..idx]);
1290                 self.v = self.v[idx + 1..];
1291                 ret
1292             }
1293         }
1294     }
1295
1296     #[inline]
1297     fn size_hint(&self) -> (uint, Option<uint>) {
1298         if self.finished {
1299             (0, Some(0))
1300         } else {
1301             (1, Some(self.v.len() + 1))
1302         }
1303     }
1304 }
1305
1306 #[experimental = "needs review"]
1307 impl<'a, T> DoubleEndedIterator<&'a [T]> for Splits<'a, T> {
1308     #[inline]
1309     fn next_back(&mut self) -> Option<&'a [T]> {
1310         if self.finished { return None; }
1311
1312         match self.v.iter().rposition(|x| (self.pred)(x)) {
1313             None => self.finish(),
1314             Some(idx) => {
1315                 let ret = Some(self.v[idx + 1..]);
1316                 self.v = self.v[..idx];
1317                 ret
1318             }
1319         }
1320     }
1321 }
1322
1323 impl<'a, T> SplitsIter<&'a [T]> for Splits<'a, T> {
1324     #[inline]
1325     fn finish(&mut self) -> Option<&'a [T]> {
1326         if self.finished { None } else { self.finished = true; Some(self.v) }
1327     }
1328 }
1329
1330 /// An iterator over the subslices of the vector which are separated
1331 /// by elements that match `pred`.
1332 #[experimental = "needs review"]
1333 pub struct MutSplits<'a, T:'a> {
1334     v: &'a mut [T],
1335     pred: |t: &T|: 'a -> bool,
1336     finished: bool
1337 }
1338
1339 impl<'a, T> SplitsIter<&'a mut [T]> for MutSplits<'a, T> {
1340     #[inline]
1341     fn finish(&mut self) -> Option<&'a mut [T]> {
1342         if self.finished {
1343             None
1344         } else {
1345             self.finished = true;
1346             Some(mem::replace(&mut self.v, &mut []))
1347         }
1348     }
1349 }
1350
1351 #[experimental = "needs review"]
1352 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
1353     #[inline]
1354     fn next(&mut self) -> Option<&'a mut [T]> {
1355         if self.finished { return None; }
1356
1357         let idx_opt = { // work around borrowck limitations
1358             let pred = &mut self.pred;
1359             self.v.iter().position(|x| (*pred)(x))
1360         };
1361         match idx_opt {
1362             None => self.finish(),
1363             Some(idx) => {
1364                 let tmp = mem::replace(&mut self.v, &mut []);
1365                 let (head, tail) = tmp.split_at_mut(idx);
1366                 self.v = tail[mut 1..];
1367                 Some(head)
1368             }
1369         }
1370     }
1371
1372     #[inline]
1373     fn size_hint(&self) -> (uint, Option<uint>) {
1374         if self.finished {
1375             (0, Some(0))
1376         } else {
1377             // if the predicate doesn't match anything, we yield one slice
1378             // if it matches every element, we yield len+1 empty slices.
1379             (1, Some(self.v.len() + 1))
1380         }
1381     }
1382 }
1383
1384 #[experimental = "needs review"]
1385 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
1386     #[inline]
1387     fn next_back(&mut self) -> Option<&'a mut [T]> {
1388         if self.finished { return None; }
1389
1390         let idx_opt = { // work around borrowck limitations
1391             let pred = &mut self.pred;
1392             self.v.iter().rposition(|x| (*pred)(x))
1393         };
1394         match idx_opt {
1395             None => self.finish(),
1396             Some(idx) => {
1397                 let tmp = mem::replace(&mut self.v, &mut []);
1398                 let (head, tail) = tmp.split_at_mut(idx);
1399                 self.v = head;
1400                 Some(tail[mut 1..])
1401             }
1402         }
1403     }
1404 }
1405
1406 /// An iterator over subslices separated by elements that match a predicate
1407 /// function, splitting at most a fixed number of times.
1408 #[experimental = "needs review"]
1409 pub struct SplitsN<I> {
1410     iter: I,
1411     count: uint,
1412     invert: bool
1413 }
1414
1415 #[experimental = "needs review"]
1416 impl<E, I: SplitsIter<E>> Iterator<E> for SplitsN<I> {
1417     #[inline]
1418     fn next(&mut self) -> Option<E> {
1419         if self.count == 0 {
1420             self.iter.finish()
1421         } else {
1422             self.count -= 1;
1423             if self.invert { self.iter.next_back() } else { self.iter.next() }
1424         }
1425     }
1426
1427     #[inline]
1428     fn size_hint(&self) -> (uint, Option<uint>) {
1429         let (lower, upper_opt) = self.iter.size_hint();
1430         (lower, upper_opt.map(|upper| cmp::min(self.count + 1, upper)))
1431     }
1432 }
1433
1434 /// An iterator over overlapping subslices of length `size`.
1435 #[deriving(Clone)]
1436 #[experimental = "needs review"]
1437 pub struct Windows<'a, T:'a> {
1438     v: &'a [T],
1439     size: uint
1440 }
1441
1442 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
1443     #[inline]
1444     fn next(&mut self) -> Option<&'a [T]> {
1445         if self.size > self.v.len() {
1446             None
1447         } else {
1448             let ret = Some(self.v[..self.size]);
1449             self.v = self.v[1..];
1450             ret
1451         }
1452     }
1453
1454     #[inline]
1455     fn size_hint(&self) -> (uint, Option<uint>) {
1456         if self.size > self.v.len() {
1457             (0, Some(0))
1458         } else {
1459             let x = self.v.len() - self.size;
1460             (x.saturating_add(1), x.checked_add(1u))
1461         }
1462     }
1463 }
1464
1465 /// An iterator over a slice in (non-overlapping) chunks (`size` elements at a
1466 /// time).
1467 ///
1468 /// When the slice len is not evenly divided by the chunk size, the last slice
1469 /// of the iteration will be the remainder.
1470 #[deriving(Clone)]
1471 #[experimental = "needs review"]
1472 pub struct Chunks<'a, T:'a> {
1473     v: &'a [T],
1474     size: uint
1475 }
1476
1477 #[experimental = "needs review"]
1478 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
1479     #[inline]
1480     fn next(&mut self) -> Option<&'a [T]> {
1481         if self.v.len() == 0 {
1482             None
1483         } else {
1484             let chunksz = cmp::min(self.v.len(), self.size);
1485             let (fst, snd) = self.v.split_at(chunksz);
1486             self.v = snd;
1487             Some(fst)
1488         }
1489     }
1490
1491     #[inline]
1492     fn size_hint(&self) -> (uint, Option<uint>) {
1493         if self.v.len() == 0 {
1494             (0, Some(0))
1495         } else {
1496             let n = self.v.len() / self.size;
1497             let rem = self.v.len() % self.size;
1498             let n = if rem > 0 { n+1 } else { n };
1499             (n, Some(n))
1500         }
1501     }
1502 }
1503
1504 #[experimental = "needs review"]
1505 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
1506     #[inline]
1507     fn next_back(&mut self) -> Option<&'a [T]> {
1508         if self.v.len() == 0 {
1509             None
1510         } else {
1511             let remainder = self.v.len() % self.size;
1512             let chunksz = if remainder != 0 { remainder } else { self.size };
1513             let (fst, snd) = self.v.split_at(self.v.len() - chunksz);
1514             self.v = fst;
1515             Some(snd)
1516         }
1517     }
1518 }
1519
1520 #[experimental = "needs review"]
1521 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
1522     #[inline]
1523     fn indexable(&self) -> uint {
1524         self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
1525     }
1526
1527     #[inline]
1528     fn idx(&mut self, index: uint) -> Option<&'a [T]> {
1529         if index < self.indexable() {
1530             let lo = index * self.size;
1531             let mut hi = lo + self.size;
1532             if hi < lo || hi > self.v.len() { hi = self.v.len(); }
1533
1534             Some(self.v[lo..hi])
1535         } else {
1536             None
1537         }
1538     }
1539 }
1540
1541 /// An iterator over a slice in (non-overlapping) mutable chunks (`size`
1542 /// elements at a time). When the slice len is not evenly divided by the chunk
1543 /// size, the last slice of the iteration will be the remainder.
1544 #[experimental = "needs review"]
1545 pub struct MutChunks<'a, T:'a> {
1546     v: &'a mut [T],
1547     chunk_size: uint
1548 }
1549
1550 #[experimental = "needs review"]
1551 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
1552     #[inline]
1553     fn next(&mut self) -> Option<&'a mut [T]> {
1554         if self.v.len() == 0 {
1555             None
1556         } else {
1557             let sz = cmp::min(self.v.len(), self.chunk_size);
1558             let tmp = mem::replace(&mut self.v, &mut []);
1559             let (head, tail) = tmp.split_at_mut(sz);
1560             self.v = tail;
1561             Some(head)
1562         }
1563     }
1564
1565     #[inline]
1566     fn size_hint(&self) -> (uint, Option<uint>) {
1567         if self.v.len() == 0 {
1568             (0, Some(0))
1569         } else {
1570             let n = self.v.len() / self.chunk_size;
1571             let rem = self.v.len() % self.chunk_size;
1572             let n = if rem > 0 { n + 1 } else { n };
1573             (n, Some(n))
1574         }
1575     }
1576 }
1577
1578 #[experimental = "needs review"]
1579 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
1580     #[inline]
1581     fn next_back(&mut self) -> Option<&'a mut [T]> {
1582         if self.v.len() == 0 {
1583             None
1584         } else {
1585             let remainder = self.v.len() % self.chunk_size;
1586             let sz = if remainder != 0 { remainder } else { self.chunk_size };
1587             let tmp = mem::replace(&mut self.v, &mut []);
1588             let tmp_len = tmp.len();
1589             let (head, tail) = tmp.split_at_mut(tmp_len - sz);
1590             self.v = head;
1591             Some(tail)
1592         }
1593     }
1594 }
1595
1596
1597
1598 /// The result of calling `binary_search`.
1599 ///
1600 /// `Found` means the search succeeded, and the contained value is the
1601 /// index of the matching element. `NotFound` means the search
1602 /// succeeded, and the contained value is an index where a matching
1603 /// value could be inserted while maintaining sort order.
1604 #[deriving(PartialEq, Show)]
1605 #[experimental = "needs review"]
1606 pub enum BinarySearchResult {
1607     /// The index of the found value.
1608     Found(uint),
1609     /// The index where the value should have been found.
1610     NotFound(uint)
1611 }
1612
1613 impl Copy for BinarySearchResult {}
1614
1615 #[experimental = "needs review"]
1616 impl BinarySearchResult {
1617     /// Converts a `Found` to `Some`, `NotFound` to `None`.
1618     /// Similar to `Result::ok`.
1619     pub fn found(&self) -> Option<uint> {
1620         match *self {
1621             BinarySearchResult::Found(i) => Some(i),
1622             BinarySearchResult::NotFound(_) => None
1623         }
1624     }
1625
1626     /// Convert a `Found` to `None`, `NotFound` to `Some`.
1627     /// Similar to `Result::err`.
1628     pub fn not_found(&self) -> Option<uint> {
1629         match *self {
1630             BinarySearchResult::Found(_) => None,
1631             BinarySearchResult::NotFound(i) => Some(i)
1632         }
1633     }
1634 }
1635
1636
1637
1638 //
1639 // Free functions
1640 //
1641
1642 /// Converts a pointer to A into a slice of length 1 (without copying).
1643 #[unstable = "waiting for DST"]
1644 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
1645     unsafe {
1646         transmute(RawSlice { data: s, len: 1 })
1647     }
1648 }
1649
1650 /// Converts a pointer to A into a slice of length 1 (without copying).
1651 #[unstable = "waiting for DST"]
1652 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
1653     unsafe {
1654         let ptr: *const A = transmute(s);
1655         transmute(RawSlice { data: ptr, len: 1 })
1656     }
1657 }
1658
1659 /// Forms a slice from a pointer and a length.
1660 ///
1661 /// The pointer given is actually a reference to the base of the slice. This
1662 /// reference is used to give a concrete lifetime to tie the returned slice to.
1663 /// Typically this should indicate that the slice is valid for as long as the
1664 /// pointer itself is valid.
1665 ///
1666 /// The `len` argument is the number of **elements**, not the number of bytes.
1667 ///
1668 /// This function is unsafe as there is no guarantee that the given pointer is
1669 /// valid for `len` elements, nor whether the lifetime provided is a suitable
1670 /// lifetime for the returned slice.
1671 ///
1672 /// # Example
1673 ///
1674 /// ```rust
1675 /// use std::slice;
1676 ///
1677 /// // manifest a slice out of thin air!
1678 /// let ptr = 0x1234 as *const uint;
1679 /// let amt = 10;
1680 /// unsafe {
1681 ///     let slice = slice::from_raw_buf(&ptr, amt);
1682 /// }
1683 /// ```
1684 #[inline]
1685 #[unstable = "just renamed from `mod raw`"]
1686 pub unsafe fn from_raw_buf<'a, T>(p: &'a *const T, len: uint) -> &'a [T] {
1687     transmute(RawSlice { data: *p, len: len })
1688 }
1689
1690 /// Performs the same functionality as `from_raw_buf`, except that a mutable
1691 /// slice is returned.
1692 ///
1693 /// This function is unsafe for the same reasons as `from_raw_buf`, as well as
1694 /// not being able to provide a non-aliasing guarantee of the returned mutable
1695 /// slice.
1696 #[inline]
1697 #[unstable = "just renamed from `mod raw`"]
1698 pub unsafe fn from_raw_mut_buf<'a, T>(p: &'a *mut T, len: uint) -> &'a mut [T] {
1699     transmute(RawSlice { data: *p as *const T, len: len })
1700 }
1701
1702 //
1703 // Submodules
1704 //
1705
1706 /// Unsafe operations
1707 #[deprecated]
1708 pub mod raw {
1709     use mem::transmute;
1710     use ptr::RawPtr;
1711     use raw::Slice;
1712     use option::Option;
1713     use option::Option::{None, Some};
1714
1715     /// Form a slice from a pointer and length (as a number of units,
1716     /// not bytes).
1717     #[inline]
1718     #[deprecated = "renamed to slice::from_raw_buf"]
1719     pub unsafe fn buf_as_slice<T,U>(p: *const T, len: uint, f: |v: &[T]| -> U)
1720                                -> U {
1721         f(transmute(Slice {
1722             data: p,
1723             len: len
1724         }))
1725     }
1726
1727     /// Form a slice from a pointer and length (as a number of units,
1728     /// not bytes).
1729     #[inline]
1730     #[deprecated = "renamed to slice::from_raw_mut_buf"]
1731     pub unsafe fn mut_buf_as_slice<T,
1732                                    U>(
1733                                    p: *mut T,
1734                                    len: uint,
1735                                    f: |v: &mut [T]| -> U)
1736                                    -> U {
1737         f(transmute(Slice {
1738             data: p as *const T,
1739             len: len
1740         }))
1741     }
1742
1743     /// Returns a pointer to first element in slice and adjusts
1744     /// slice so it no longer contains that element. Returns None
1745     /// if the slice is empty. O(1).
1746     #[inline]
1747     #[deprecated = "inspect `Slice::{data, len}` manually (increment data by 1)"]
1748     pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1749         if slice.len == 0 { return None; }
1750         let head: *const T = slice.data;
1751         slice.data = slice.data.offset(1);
1752         slice.len -= 1;
1753         Some(head)
1754     }
1755
1756     /// Returns a pointer to last element in slice and adjusts
1757     /// slice so it no longer contains that element. Returns None
1758     /// if the slice is empty. O(1).
1759     #[inline]
1760     #[deprecated = "inspect `Slice::{data, len}` manually (decrement len by 1)"]
1761     pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> Option<*const T> {
1762         if slice.len == 0 { return None; }
1763         let tail: *const T = slice.data.offset((slice.len - 1) as int);
1764         slice.len -= 1;
1765         Some(tail)
1766     }
1767 }
1768
1769 /// Operations on `[u8]`.
1770 #[experimental = "needs review"]
1771 pub mod bytes {
1772     use kinds::Sized;
1773     use ptr;
1774     use slice::SlicePrelude;
1775
1776     /// A trait for operations on mutable `[u8]`s.
1777     pub trait MutableByteVector for Sized? {
1778         /// Sets all bytes of the receiver to the given value.
1779         fn set_memory(&mut self, value: u8);
1780     }
1781
1782     impl MutableByteVector for [u8] {
1783         #[inline]
1784         #[allow(experimental)]
1785         fn set_memory(&mut self, value: u8) {
1786             unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1787         }
1788     }
1789
1790     /// Copies data from `src` to `dst`
1791     ///
1792     /// Panics if the length of `dst` is less than the length of `src`.
1793     #[inline]
1794     pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1795         let len_src = src.len();
1796         assert!(dst.len() >= len_src);
1797         // `dst` is unaliasable, so we know statically it doesn't overlap
1798         // with `src`.
1799         unsafe {
1800             ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
1801                                             src.as_ptr(),
1802                                             len_src);
1803         }
1804     }
1805 }
1806
1807
1808
1809 //
1810 // Boilerplate traits
1811 //
1812
1813 #[unstable = "waiting for DST"]
1814 impl<A, B> PartialEq<[B]> for [A] where A: PartialEq<B> {
1815     fn eq(&self, other: &[B]) -> bool {
1816         self.len() == other.len() &&
1817             order::eq(self.iter(), other.iter())
1818     }
1819     fn ne(&self, other: &[B]) -> bool {
1820         self.len() != other.len() ||
1821             order::ne(self.iter(), other.iter())
1822     }
1823 }
1824
1825 #[unstable = "waiting for DST"]
1826 impl<T: Eq> Eq for [T] {}
1827
1828 #[allow(deprecated)]
1829 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
1830 impl<T: PartialEq, Sized? V: AsSlice<T>> Equiv<V> for [T] {
1831     #[inline]
1832     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
1833 }
1834
1835 #[allow(deprecated)]
1836 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
1837 impl<'a,T:PartialEq, Sized? V: AsSlice<T>> Equiv<V> for &'a mut [T] {
1838     #[inline]
1839     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
1840 }
1841
1842 #[unstable = "waiting for DST"]
1843 impl<T: Ord> Ord for [T] {
1844     fn cmp(&self, other: &[T]) -> Ordering {
1845         order::cmp(self.iter(), other.iter())
1846     }
1847 }
1848
1849 #[unstable = "waiting for DST"]
1850 impl<T: PartialOrd> PartialOrd for [T] {
1851     #[inline]
1852     fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
1853         order::partial_cmp(self.iter(), other.iter())
1854     }
1855     #[inline]
1856     fn lt(&self, other: &[T]) -> bool {
1857         order::lt(self.iter(), other.iter())
1858     }
1859     #[inline]
1860     fn le(&self, other: &[T]) -> bool {
1861         order::le(self.iter(), other.iter())
1862     }
1863     #[inline]
1864     fn ge(&self, other: &[T]) -> bool {
1865         order::ge(self.iter(), other.iter())
1866     }
1867     #[inline]
1868     fn gt(&self, other: &[T]) -> bool {
1869         order::gt(self.iter(), other.iter())
1870     }
1871 }
1872
1873 /// Extension methods for immutable slices containing integers.
1874 #[experimental]
1875 pub trait ImmutableIntSlice<U, S> for Sized? {
1876     /// Converts the slice to an immutable slice of unsigned integers with the same width.
1877     fn as_unsigned<'a>(&'a self) -> &'a [U];
1878     /// Converts the slice to an immutable slice of signed integers with the same width.
1879     fn as_signed<'a>(&'a self) -> &'a [S];
1880 }
1881
1882 /// Extension methods for mutable slices containing integers.
1883 #[experimental]
1884 pub trait MutableIntSlice<U, S> for Sized?: ImmutableIntSlice<U, S> {
1885     /// Converts the slice to a mutable slice of unsigned integers with the same width.
1886     fn as_unsigned_mut<'a>(&'a mut self) -> &'a mut [U];
1887     /// Converts the slice to a mutable slice of signed integers with the same width.
1888     fn as_signed_mut<'a>(&'a mut self) -> &'a mut [S];
1889 }
1890
1891 macro_rules! impl_immut_int_slice {
1892     ($u:ty, $s:ty, $t:ty) => {
1893         #[experimental]
1894         impl ImmutableIntSlice<$u, $s> for [$t] {
1895             #[inline]
1896             fn as_unsigned(&self) -> &[$u] { unsafe { transmute(self) } }
1897             #[inline]
1898             fn as_signed(&self) -> &[$s] { unsafe { transmute(self) } }
1899         }
1900     }
1901 }
1902 macro_rules! impl_mut_int_slice {
1903     ($u:ty, $s:ty, $t:ty) => {
1904         #[experimental]
1905         impl MutableIntSlice<$u, $s> for [$t] {
1906             #[inline]
1907             fn as_unsigned_mut(&mut self) -> &mut [$u] { unsafe { transmute(self) } }
1908             #[inline]
1909             fn as_signed_mut(&mut self) -> &mut [$s] { unsafe { transmute(self) } }
1910         }
1911     }
1912 }
1913
1914 macro_rules! impl_int_slice {
1915     ($u:ty, $s:ty) => {
1916         impl_immut_int_slice!($u, $s, $u)
1917         impl_immut_int_slice!($u, $s, $s)
1918         impl_mut_int_slice!($u, $s, $u)
1919         impl_mut_int_slice!($u, $s, $s)
1920     }
1921 }
1922
1923 impl_int_slice!(u8,   i8)
1924 impl_int_slice!(u16,  i16)
1925 impl_int_slice!(u32,  i32)
1926 impl_int_slice!(u64,  i64)
1927 impl_int_slice!(uint, int)
1928