]> git.lizzy.rs Git - rust.git/blob - src/libcollections/slice.rs
doc: remove incomplete sentence
[rust.git] / src / libcollections / 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 //! Utilities for slice manipulation
12 //!
13 //! The `slice` module contains useful code to help work with slice values.
14 //! Slices are a view into a block of memory represented as a pointer and a length.
15 //!
16 //! ```rust
17 //! // slicing a Vec
18 //! let vec = vec!(1i, 2, 3);
19 //! let int_slice = vec.as_slice();
20 //! // coercing an array to a slice
21 //! let str_slice: &[&str] = &["one", "two", "three"];
22 //! ```
23 //!
24 //! Slices are either mutable or shared. The shared slice type is `&[T]`,
25 //! while the mutable slice type is `&mut[T]`. For example, you can mutate the
26 //! block of memory that a mutable slice points to:
27 //!
28 //! ```rust
29 //! let x: &mut[int] = &mut [1i, 2, 3];
30 //! x[1] = 7;
31 //! assert_eq!(x[0], 1);
32 //! assert_eq!(x[1], 7);
33 //! assert_eq!(x[2], 3);
34 //! ```
35 //!
36 //! Here are some of the things this module contains:
37 //!
38 //! ## Structs
39 //!
40 //! There are several structs that are useful for slices, such as `Iter`, which
41 //! represents iteration over a slice.
42 //!
43 //! ## Traits
44 //!
45 //! A number of traits add methods that allow you to accomplish tasks
46 //! with slices, the most important being `SliceExt`. Other traits
47 //! apply only to slices of elements satisfying certain bounds (like
48 //! `Ord`).
49 //!
50 //! An example is the `slice` method which enables slicing syntax `[a..b]` that
51 //! returns an immutable "view" into a `Vec` or another slice from the index
52 //! interval `[a, b)`:
53 //!
54 //! ```rust
55 //! #![feature(slicing_syntax)]
56 //! fn main() {
57 //!     let numbers = [0i, 1i, 2i];
58 //!     let last_numbers = numbers[1..3];
59 //!     // last_numbers is now &[1i, 2i]
60 //! }
61 //! ```
62 //!
63 //! ## Implementations of other traits
64 //!
65 //! There are several implementations of common traits for slices. Some examples
66 //! include:
67 //!
68 //! * `Clone`
69 //! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
70 //! * `Hash` - for slices whose element type is `Hash`
71 //!
72 //! ## Iteration
73 //!
74 //! The method `iter()` returns an iteration value for a slice. The iterator
75 //! yields references to the slice's elements, so if the element
76 //! type of the slice is `int`, the element type of the iterator is `&int`.
77 //!
78 //! ```rust
79 //! let numbers = [0i, 1i, 2i];
80 //! for &x in numbers.iter() {
81 //!     println!("{} is a number!", x);
82 //! }
83 //! ```
84 //!
85 //! * `.iter_mut()` returns an iterator that allows modifying each value.
86 //! * Further iterators exist that split, chunk or permute the slice.
87
88 #![doc(primitive = "slice")]
89
90 use alloc::boxed::Box;
91 use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned};
92 use core::clone::Clone;
93 use core::cmp::Ordering::{mod, Greater, Less};
94 use core::cmp::{mod, Ord, PartialEq};
95 use core::iter::{Iterator, IteratorExt, IteratorCloneExt};
96 use core::iter::{range, range_step, MultiplicativeIterator};
97 use core::kinds::Sized;
98 use core::mem::size_of;
99 use core::mem;
100 use core::ops::{FnMut, SliceMut};
101 use core::option::Option::{mod, Some, None};
102 use core::ptr::PtrExt;
103 use core::ptr;
104 use core::result::Result;
105 use core::slice as core_slice;
106 use self::Direction::*;
107
108 use vec::Vec;
109
110 pub use core::slice::{Chunks, AsSlice, Windows};
111 pub use core::slice::{Iter, IterMut};
112 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
113 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
114 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
115 pub use core::slice::{from_raw_buf, from_raw_mut_buf};
116
117 #[deprecated = "use Iter instead"]
118 pub type Items<'a, T:'a> = Iter<'a, T>;
119
120 #[deprecated = "use IterMut instead"]
121 pub type MutItems<'a, T:'a> = IterMut<'a, T>;
122
123 ////////////////////////////////////////////////////////////////////////////////
124 // Basic slice extension methods
125 ////////////////////////////////////////////////////////////////////////////////
126
127 /// Allocating extension methods for slices.
128 #[unstable = "needs associated types, may merge with other traits"]
129 pub trait SliceExt for Sized? {
130     type Item;
131
132     /// Sorts the slice, in place, using `compare` to compare
133     /// elements.
134     ///
135     /// This sort is `O(n log n)` worst-case and stable, but allocates
136     /// approximately `2 * n`, where `n` is the length of `self`.
137     ///
138     /// # Examples
139     ///
140     /// ```rust
141     /// let mut v = [5i, 4, 1, 3, 2];
142     /// v.sort_by(|a, b| a.cmp(b));
143     /// assert!(v == [1, 2, 3, 4, 5]);
144     ///
145     /// // reverse sorting
146     /// v.sort_by(|a, b| b.cmp(a));
147     /// assert!(v == [5, 4, 3, 2, 1]);
148     /// ```
149     #[stable]
150     fn sort_by<F>(&mut self, compare: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering;
151
152     /// Consumes `src` and moves as many elements as it can into `self`
153     /// from the range [start,end).
154     ///
155     /// Returns the number of elements copied (the shorter of `self.len()`
156     /// and `end - start`).
157     ///
158     /// # Arguments
159     ///
160     /// * src - A mutable vector of `T`
161     /// * start - The index into `src` to start copying from
162     /// * end - The index into `src` to stop copying from
163     ///
164     /// # Examples
165     ///
166     /// ```rust
167     /// let mut a = [1i, 2, 3, 4, 5];
168     /// let b = vec![6i, 7, 8];
169     /// let num_moved = a.move_from(b, 0, 3);
170     /// assert_eq!(num_moved, 3);
171     /// assert!(a == [6i, 7, 8, 4, 5]);
172     /// ```
173     #[experimental = "uncertain about this API approach"]
174     fn move_from(&mut self, src: Vec<Self::Item>, start: uint, end: uint) -> uint;
175
176     /// Returns a subslice spanning the interval [`start`, `end`).
177     ///
178     /// Panics when the end of the new slice lies beyond the end of the
179     /// original slice (i.e. when `end > self.len()`) or when `start > end`.
180     ///
181     /// Slicing with `start` equal to `end` yields an empty slice.
182     #[experimental = "will be replaced by slice syntax"]
183     fn slice(&self, start: uint, end: uint) -> &[Self::Item];
184
185     /// Returns a subslice from `start` to the end of the slice.
186     ///
187     /// Panics when `start` is strictly greater than the length of the original slice.
188     ///
189     /// Slicing from `self.len()` yields an empty slice.
190     #[experimental = "will be replaced by slice syntax"]
191     fn slice_from(&self, start: uint) -> &[Self::Item];
192
193     /// Returns a subslice from the start of the slice to `end`.
194     ///
195     /// Panics when `end` is strictly greater than the length of the original slice.
196     ///
197     /// Slicing to `0` yields an empty slice.
198     #[experimental = "will be replaced by slice syntax"]
199     fn slice_to(&self, end: uint) -> &[Self::Item];
200
201     /// Divides one slice into two at an index.
202     ///
203     /// The first will contain all indices from `[0, mid)` (excluding
204     /// the index `mid` itself) and the second will contain all
205     /// indices from `[mid, len)` (excluding the index `len` itself).
206     ///
207     /// Panics if `mid > len`.
208     #[stable]
209     fn split_at(&self, mid: uint) -> (&[Self::Item], &[Self::Item]);
210
211     /// Returns an iterator over the slice
212     #[stable]
213     fn iter(&self) -> Iter<Self::Item>;
214
215     /// Returns an iterator over subslices separated by elements that match
216     /// `pred`.  The matched element is not contained in the subslices.
217     #[stable]
218     fn split<F>(&self, pred: F) -> Split<Self::Item, F>
219                 where F: FnMut(&Self::Item) -> bool;
220
221     /// Returns an iterator over subslices separated by elements that match
222     /// `pred`, limited to splitting at most `n` times.  The matched element is
223     /// not contained in the subslices.
224     #[stable]
225     fn splitn<F>(&self, n: uint, pred: F) -> SplitN<Self::Item, F>
226                  where F: FnMut(&Self::Item) -> bool;
227
228     /// Returns an iterator over subslices separated by elements that match
229     /// `pred` limited to splitting at most `n` times. This starts at the end of
230     /// the slice and works backwards.  The matched element is not contained in
231     /// the subslices.
232     #[stable]
233     fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<Self::Item, F>
234                   where F: FnMut(&Self::Item) -> bool;
235
236     /// Returns an iterator over all contiguous windows of length
237     /// `size`. The windows overlap. If the slice is shorter than
238     /// `size`, the iterator returns no values.
239     ///
240     /// # Panics
241     ///
242     /// Panics if `size` is 0.
243     ///
244     /// # Example
245     ///
246     /// Print the adjacent pairs of a slice (i.e. `[1,2]`, `[2,3]`,
247     /// `[3,4]`):
248     ///
249     /// ```rust
250     /// let v = &[1i, 2, 3, 4];
251     /// for win in v.windows(2) {
252     ///     println!("{}", win);
253     /// }
254     /// ```
255     #[stable]
256     fn windows(&self, size: uint) -> Windows<Self::Item>;
257
258     /// Returns an iterator over `size` elements of the slice at a
259     /// time. The chunks do not overlap. If `size` does not divide the
260     /// length of the slice, then the last chunk will not have length
261     /// `size`.
262     ///
263     /// # Panics
264     ///
265     /// Panics if `size` is 0.
266     ///
267     /// # Example
268     ///
269     /// Print the slice two elements at a time (i.e. `[1,2]`,
270     /// `[3,4]`, `[5]`):
271     ///
272     /// ```rust
273     /// let v = &[1i, 2, 3, 4, 5];
274     /// for win in v.chunks(2) {
275     ///     println!("{}", win);
276     /// }
277     /// ```
278     #[stable]
279     fn chunks(&self, size: uint) -> Chunks<Self::Item>;
280
281     /// Returns the element of a slice at the given index, or `None` if the
282     /// index is out of bounds.
283     #[stable]
284     fn get(&self, index: uint) -> Option<&Self::Item>;
285
286     /// Returns the first element of a slice, or `None` if it is empty.
287     #[stable]
288     fn first(&self) -> Option<&Self::Item>;
289
290     /// Deprecated: renamed to `first`.
291     #[deprecated = "renamed to `first`"]
292     fn head(&self) -> Option<&Self::Item> { self.first() }
293
294     /// Returns all but the first element of a slice.
295     #[experimental = "likely to be renamed"]
296     fn tail(&self) -> &[Self::Item];
297
298     /// Returns all but the last element of a slice.
299     #[experimental = "likely to be renamed"]
300     fn init(&self) -> &[Self::Item];
301
302     /// Returns the last element of a slice, or `None` if it is empty.
303     #[stable]
304     fn last(&self) -> Option<&Self::Item>;
305
306     /// Returns a pointer to the element at the given index, without doing
307     /// bounds checking.
308     #[stable]
309     unsafe fn get_unchecked(&self, index: uint) -> &Self::Item;
310
311     /// Deprecated: renamed to `get_unchecked`.
312     #[deprecated = "renamed to get_unchecked"]
313     unsafe fn unsafe_get(&self, index: uint) -> &Self::Item {
314         self.get_unchecked(index)
315     }
316
317     /// Returns an unsafe pointer to the slice's buffer
318     ///
319     /// The caller must ensure that the slice outlives the pointer this
320     /// function returns, or else it will end up pointing to garbage.
321     ///
322     /// Modifying the slice may cause its buffer to be reallocated, which
323     /// would also make any pointers to it invalid.
324     #[stable]
325     fn as_ptr(&self) -> *const Self::Item;
326
327     /// Binary search a sorted slice with a comparator function.
328     ///
329     /// The comparator function should implement an order consistent
330     /// with the sort order of the underlying slice, returning an
331     /// order code that indicates whether its argument is `Less`,
332     /// `Equal` or `Greater` the desired target.
333     ///
334     /// If a matching value is found then returns `Ok`, containing
335     /// the index for the matched element; if no match is found then
336     /// `Err` is returned, containing the index where a matching
337     /// element could be inserted while maintaining sorted order.
338     ///
339     /// # Example
340     ///
341     /// Looks up a series of four elements. The first is found, with a
342     /// uniquely determined position; the second and third are not
343     /// found; the fourth could match any position in `[1,4]`.
344     ///
345     /// ```rust
346     /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
347     /// let s = s.as_slice();
348     ///
349     /// let seek = 13;
350     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
351     /// let seek = 4;
352     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
353     /// let seek = 100;
354     /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
355     /// let seek = 1;
356     /// let r = s.binary_search_by(|probe| probe.cmp(&seek));
357     /// assert!(match r { Ok(1...4) => true, _ => false, });
358     /// ```
359     #[stable]
360     fn binary_search_by<F>(&self, f: F) -> Result<uint, uint> where
361         F: FnMut(&Self::Item) -> Ordering;
362
363     /// Return the number of elements in the slice
364     ///
365     /// # Example
366     ///
367     /// ```
368     /// let a = [1i, 2, 3];
369     /// assert_eq!(a.len(), 3);
370     /// ```
371     #[stable]
372     fn len(&self) -> uint;
373
374     /// Returns true if the slice has a length of 0
375     ///
376     /// # Example
377     ///
378     /// ```
379     /// let a = [1i, 2, 3];
380     /// assert!(!a.is_empty());
381     /// ```
382     #[inline]
383     #[stable]
384     fn is_empty(&self) -> bool { self.len() == 0 }
385     /// Returns a mutable reference to the element at the given index,
386     /// or `None` if the index is out of bounds
387     #[stable]
388     fn get_mut(&mut self, index: uint) -> Option<&mut Self::Item>;
389
390     /// Work with `self` as a mut slice.
391     /// Primarily intended for getting a &mut [T] from a [T; N].
392     #[stable]
393     fn as_mut_slice(&mut self) -> &mut [Self::Item];
394
395     /// Returns a mutable subslice spanning the interval [`start`, `end`).
396     ///
397     /// Panics when the end of the new slice lies beyond the end of the
398     /// original slice (i.e. when `end > self.len()`) or when `start > end`.
399     ///
400     /// Slicing with `start` equal to `end` yields an empty slice.
401     #[experimental = "will be replaced by slice syntax"]
402     fn slice_mut(&mut self, start: uint, end: uint) -> &mut [Self::Item];
403
404     /// Returns a mutable subslice from `start` to the end of the slice.
405     ///
406     /// Panics when `start` is strictly greater than the length of the original slice.
407     ///
408     /// Slicing from `self.len()` yields an empty slice.
409     #[experimental = "will be replaced by slice syntax"]
410     fn slice_from_mut(&mut self, start: uint) -> &mut [Self::Item];
411
412     /// Returns a mutable subslice from the start of the slice to `end`.
413     ///
414     /// Panics when `end` is strictly greater than the length of the original slice.
415     ///
416     /// Slicing to `0` yields an empty slice.
417     #[experimental = "will be replaced by slice syntax"]
418     fn slice_to_mut(&mut self, end: uint) -> &mut [Self::Item];
419
420     /// Returns an iterator that allows modifying each value
421     #[stable]
422     fn iter_mut(&mut self) -> IterMut<Self::Item>;
423
424     /// Returns a mutable pointer to the first element of a slice, or `None` if it is empty
425     #[stable]
426     fn first_mut(&mut self) -> Option<&mut Self::Item>;
427
428     /// Depreated: renamed to `first_mut`.
429     #[deprecated = "renamed to first_mut"]
430     fn head_mut(&mut self) -> Option<&mut Self::Item> {
431         self.first_mut()
432     }
433
434     /// Returns all but the first element of a mutable slice
435     #[experimental = "likely to be renamed or removed"]
436     fn tail_mut(&mut self) -> &mut [Self::Item];
437
438     /// Returns all but the last element of a mutable slice
439     #[experimental = "likely to be renamed or removed"]
440     fn init_mut(&mut self) -> &mut [Self::Item];
441
442     /// Returns a mutable pointer to the last item in the slice.
443     #[stable]
444     fn last_mut(&mut self) -> Option<&mut Self::Item>;
445
446     /// Returns an iterator over mutable subslices separated by elements that
447     /// match `pred`.  The matched element is not contained in the subslices.
448     #[stable]
449     fn split_mut<F>(&mut self, pred: F) -> SplitMut<Self::Item, F>
450                     where F: FnMut(&Self::Item) -> bool;
451
452     /// Returns an iterator over subslices separated by elements that match
453     /// `pred`, limited to splitting at most `n` times.  The matched element is
454     /// not contained in the subslices.
455     #[stable]
456     fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<Self::Item, F>
457                      where F: FnMut(&Self::Item) -> bool;
458
459     /// Returns an iterator over subslices separated by elements that match
460     /// `pred` limited to splitting at most `n` times. This starts at the end of
461     /// the slice and works backwards.  The matched element is not contained in
462     /// the subslices.
463     #[stable]
464     fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<Self::Item, F>
465                       where F: FnMut(&Self::Item) -> bool;
466
467     /// Returns an iterator over `chunk_size` elements of the slice at a time.
468     /// The chunks are mutable and do not overlap. If `chunk_size` does
469     /// not divide the length of the slice, then the last chunk will not
470     /// have length `chunk_size`.
471     ///
472     /// # Panics
473     ///
474     /// Panics if `chunk_size` is 0.
475     #[stable]
476     fn chunks_mut(&mut self, chunk_size: uint) -> ChunksMut<Self::Item>;
477
478     /// Swaps two elements in a slice.
479     ///
480     /// # Arguments
481     ///
482     /// * a - The index of the first element
483     /// * b - The index of the second element
484     ///
485     /// # Panics
486     ///
487     /// Panics if `a` or `b` are out of bounds.
488     ///
489     /// # Example
490     ///
491     /// ```rust
492     /// let mut v = ["a", "b", "c", "d"];
493     /// v.swap(1, 3);
494     /// assert!(v == ["a", "d", "c", "b"]);
495     /// ```
496     #[stable]
497     fn swap(&mut self, a: uint, b: uint);
498
499     /// Divides one `&mut` into two at an index.
500     ///
501     /// The first will contain all indices from `[0, mid)` (excluding
502     /// the index `mid` itself) and the second will contain all
503     /// indices from `[mid, len)` (excluding the index `len` itself).
504     ///
505     /// # Panics
506     ///
507     /// Panics if `mid > len`.
508     ///
509     /// # Example
510     ///
511     /// ```rust
512     /// let mut v = [1i, 2, 3, 4, 5, 6];
513     ///
514     /// // scoped to restrict the lifetime of the borrows
515     /// {
516     ///    let (left, right) = v.split_at_mut(0);
517     ///    assert!(left == []);
518     ///    assert!(right == [1i, 2, 3, 4, 5, 6]);
519     /// }
520     ///
521     /// {
522     ///     let (left, right) = v.split_at_mut(2);
523     ///     assert!(left == [1i, 2]);
524     ///     assert!(right == [3i, 4, 5, 6]);
525     /// }
526     ///
527     /// {
528     ///     let (left, right) = v.split_at_mut(6);
529     ///     assert!(left == [1i, 2, 3, 4, 5, 6]);
530     ///     assert!(right == []);
531     /// }
532     /// ```
533     #[stable]
534     fn split_at_mut(&mut self, mid: uint) -> (&mut [Self::Item], &mut [Self::Item]);
535
536     /// Reverse the order of elements in a slice, in place.
537     ///
538     /// # Example
539     ///
540     /// ```rust
541     /// let mut v = [1i, 2, 3];
542     /// v.reverse();
543     /// assert!(v == [3i, 2, 1]);
544     /// ```
545     #[stable]
546     fn reverse(&mut self);
547
548     /// Returns an unsafe mutable pointer to the element in index
549     #[stable]
550     unsafe fn get_unchecked_mut(&mut self, index: uint) -> &mut Self::Item;
551
552     /// Deprecated: renamed to `get_unchecked_mut`.
553     #[deprecated = "renamed to get_unchecked_mut"]
554     unsafe fn unchecked_mut(&mut self, index: uint) -> &mut Self::Item {
555         self.get_unchecked_mut(index)
556     }
557
558     /// Return an unsafe mutable pointer to the slice's buffer.
559     ///
560     /// The caller must ensure that the slice outlives the pointer this
561     /// function returns, or else it will end up pointing to garbage.
562     ///
563     /// Modifying the slice may cause its buffer to be reallocated, which
564     /// would also make any pointers to it invalid.
565     #[inline]
566     #[stable]
567     fn as_mut_ptr(&mut self) -> *mut Self::Item;
568
569     /// Copies `self` into a new `Vec`.
570     #[stable]
571     fn to_vec(&self) -> Vec<Self::Item> where Self::Item: Clone;
572
573     /// Deprecated: use `iter().cloned().partition(f)` instead.
574     #[deprecated = "use iter().cloned().partition(f) instead"]
575     fn partitioned<F>(&self, f: F) -> (Vec<Self::Item>, Vec<Self::Item>) where
576         Self::Item: Clone,
577         F: FnMut(&Self::Item) -> bool;
578
579     /// Creates an iterator that yields every possible permutation of the
580     /// vector in succession.
581     ///
582     /// # Examples
583     ///
584     /// ```rust
585     /// let v = [1i, 2, 3];
586     /// let mut perms = v.permutations();
587     ///
588     /// for p in perms {
589     ///   println!("{}", p);
590     /// }
591     /// ```
592     ///
593     /// Iterating through permutations one by one.
594     ///
595     /// ```rust
596     /// let v = [1i, 2, 3];
597     /// let mut perms = v.permutations();
598     ///
599     /// assert_eq!(Some(vec![1i, 2, 3]), perms.next());
600     /// assert_eq!(Some(vec![1i, 3, 2]), perms.next());
601     /// assert_eq!(Some(vec![3i, 1, 2]), perms.next());
602     /// ```
603     #[unstable]
604     fn permutations(&self) -> Permutations<Self::Item> where Self::Item: Clone;
605
606     /// Copies as many elements from `src` as it can into `self` (the
607     /// shorter of `self.len()` and `src.len()`). Returns the number
608     /// of elements copied.
609     ///
610     /// # Example
611     ///
612     /// ```rust
613     /// let mut dst = [0i, 0, 0];
614     /// let src = [1i, 2];
615     ///
616     /// assert!(dst.clone_from_slice(&src) == 2);
617     /// assert!(dst == [1, 2, 0]);
618     ///
619     /// let src2 = [3i, 4, 5, 6];
620     /// assert!(dst.clone_from_slice(&src2) == 3);
621     /// assert!(dst == [3i, 4, 5]);
622     /// ```
623     #[experimental]
624     fn clone_from_slice(&mut self, &[Self::Item]) -> uint where Self::Item: Clone;
625
626     /// Sorts the slice, in place.
627     ///
628     /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
629     ///
630     /// # Examples
631     ///
632     /// ```rust
633     /// let mut v = [-5i, 4, 1, -3, 2];
634     ///
635     /// v.sort();
636     /// assert!(v == [-5i, -3, 1, 2, 4]);
637     /// ```
638     #[stable]
639     fn sort(&mut self) where Self::Item: Ord;
640
641     /// Binary search a sorted slice for a given element.
642     ///
643     /// If the value is found then `Ok` is returned, containing the
644     /// index of the matching element; if the value is not found then
645     /// `Err` is returned, containing the index where a matching
646     /// element could be inserted while maintaining sorted order.
647     ///
648     /// # Example
649     ///
650     /// Looks up a series of four elements. The first is found, with a
651     /// uniquely determined position; the second and third are not
652     /// found; the fourth could match any position in `[1,4]`.
653     ///
654     /// ```rust
655     /// let s = [0i, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
656     /// let s = s.as_slice();
657     ///
658     /// assert_eq!(s.binary_search(&13),  Ok(9));
659     /// assert_eq!(s.binary_search(&4),   Err(7));
660     /// assert_eq!(s.binary_search(&100), Err(13));
661     /// let r = s.binary_search(&1);
662     /// assert!(match r { Ok(1...4) => true, _ => false, });
663     /// ```
664     #[stable]
665     fn binary_search(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord;
666
667     /// Deprecated: use `binary_search` instead.
668     #[deprecated = "use binary_search instead"]
669     fn binary_search_elem(&self, x: &Self::Item) -> Result<uint, uint> where Self::Item: Ord {
670         self.binary_search(x)
671     }
672
673     /// Mutates the slice to the next lexicographic permutation.
674     ///
675     /// Returns `true` if successful and `false` if the slice is at the
676     /// last-ordered permutation.
677     ///
678     /// # Example
679     ///
680     /// ```rust
681     /// let v: &mut [_] = &mut [0i, 1, 2];
682     /// v.next_permutation();
683     /// let b: &mut [_] = &mut [0i, 2, 1];
684     /// assert!(v == b);
685     /// v.next_permutation();
686     /// let b: &mut [_] = &mut [1i, 0, 2];
687     /// assert!(v == b);
688     /// ```
689     #[unstable = "uncertain if this merits inclusion in std"]
690     fn next_permutation(&mut self) -> bool where Self::Item: Ord;
691
692     /// Mutates the slice to the previous lexicographic permutation.
693     ///
694     /// Returns `true` if successful and `false` if the slice is at the
695     /// first-ordered permutation.
696     ///
697     /// # Example
698     ///
699     /// ```rust
700     /// let v: &mut [_] = &mut [1i, 0, 2];
701     /// v.prev_permutation();
702     /// let b: &mut [_] = &mut [0i, 2, 1];
703     /// assert!(v == b);
704     /// v.prev_permutation();
705     /// let b: &mut [_] = &mut [0i, 1, 2];
706     /// assert!(v == b);
707     /// ```
708     #[unstable = "uncertain if this merits inclusion in std"]
709     fn prev_permutation(&mut self) -> bool where Self::Item: Ord;
710
711     /// Find the first index containing a matching value.
712     #[experimental]
713     fn position_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
714
715     /// Find the last index containing a matching value.
716     #[experimental]
717     fn rposition_elem(&self, t: &Self::Item) -> Option<uint> where Self::Item: PartialEq;
718
719     /// Return true if the slice contains an element with the given value.
720     #[stable]
721     fn contains(&self, x: &Self::Item) -> bool where Self::Item: PartialEq;
722
723     /// Returns true if `needle` is a prefix of the slice.
724     #[stable]
725     fn starts_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
726
727     /// Returns true if `needle` is a suffix of the slice.
728     #[stable]
729     fn ends_with(&self, needle: &[Self::Item]) -> bool where Self::Item: PartialEq;
730
731     /// Convert `self` into a vector without clones or allocation.
732     #[experimental]
733     fn into_vec(self: Box<Self>) -> Vec<Self::Item>;
734 }
735
736 #[unstable = "trait is unstable"]
737 impl<T> SliceExt for [T] {
738     type Item = T;
739
740     #[inline]
741     fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
742         merge_sort(self, compare)
743     }
744
745     #[inline]
746     fn move_from(&mut self, mut src: Vec<T>, start: uint, end: uint) -> uint {
747         for (a, b) in self.iter_mut().zip(src.slice_mut(start, end).iter_mut()) {
748             mem::swap(a, b);
749         }
750         cmp::min(self.len(), end-start)
751     }
752
753     #[inline]
754     fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
755         core_slice::SliceExt::slice(self, start, end)
756     }
757
758     #[inline]
759     fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
760         core_slice::SliceExt::slice_from(self, start)
761     }
762
763     #[inline]
764     fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
765         core_slice::SliceExt::slice_to(self, end)
766     }
767
768     #[inline]
769     fn split_at<'a>(&'a self, mid: uint) -> (&'a [T], &'a [T]) {
770         core_slice::SliceExt::split_at(self, mid)
771     }
772
773     #[inline]
774     fn iter<'a>(&'a self) -> Iter<'a, T> {
775         core_slice::SliceExt::iter(self)
776     }
777
778     #[inline]
779     fn split<F>(&self, pred: F) -> Split<T, F>
780                 where F: FnMut(&T) -> bool {
781         core_slice::SliceExt::split(self, pred)
782     }
783
784     #[inline]
785     fn splitn<F>(&self, n: uint, pred: F) -> SplitN<T, F>
786                  where F: FnMut(&T) -> bool {
787         core_slice::SliceExt::splitn(self, n, pred)
788     }
789
790     #[inline]
791     fn rsplitn<F>(&self, n: uint, pred: F) -> RSplitN<T, F>
792                   where F: FnMut(&T) -> bool {
793         core_slice::SliceExt::rsplitn(self, n, pred)
794     }
795
796     #[inline]
797     fn windows<'a>(&'a self, size: uint) -> Windows<'a, T> {
798         core_slice::SliceExt::windows(self, size)
799     }
800
801     #[inline]
802     fn chunks<'a>(&'a self, size: uint) -> Chunks<'a, T> {
803         core_slice::SliceExt::chunks(self, size)
804     }
805
806     #[inline]
807     fn get<'a>(&'a self, index: uint) -> Option<&'a T> {
808         core_slice::SliceExt::get(self, index)
809     }
810
811     #[inline]
812     fn first<'a>(&'a self) -> Option<&'a T> {
813         core_slice::SliceExt::first(self)
814     }
815
816     #[inline]
817     fn tail<'a>(&'a self) -> &'a [T] {
818         core_slice::SliceExt::tail(self)
819     }
820
821     #[inline]
822     fn init<'a>(&'a self) -> &'a [T] {
823         core_slice::SliceExt::init(self)
824     }
825
826     #[inline]
827     fn last<'a>(&'a self) -> Option<&'a T> {
828         core_slice::SliceExt::last(self)
829     }
830
831     #[inline]
832     unsafe fn get_unchecked<'a>(&'a self, index: uint) -> &'a T {
833         core_slice::SliceExt::get_unchecked(self, index)
834     }
835
836     #[inline]
837     fn as_ptr(&self) -> *const T {
838         core_slice::SliceExt::as_ptr(self)
839     }
840
841     #[inline]
842     fn binary_search_by<F>(&self, f: F) -> Result<uint, uint>
843                         where F: FnMut(&T) -> Ordering {
844         core_slice::SliceExt::binary_search_by(self, f)
845     }
846
847     #[inline]
848     fn len(&self) -> uint {
849         core_slice::SliceExt::len(self)
850     }
851
852     #[inline]
853     fn is_empty(&self) -> bool {
854         core_slice::SliceExt::is_empty(self)
855     }
856
857     #[inline]
858     fn get_mut<'a>(&'a mut self, index: uint) -> Option<&'a mut T> {
859         core_slice::SliceExt::get_mut(self, index)
860     }
861
862     #[inline]
863     fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
864         core_slice::SliceExt::as_mut_slice(self)
865     }
866
867     #[inline]
868     fn slice_mut<'a>(&'a mut self, start: uint, end: uint) -> &'a mut [T] {
869         core_slice::SliceExt::slice_mut(self, start, end)
870     }
871
872     #[inline]
873     fn slice_from_mut<'a>(&'a mut self, start: uint) -> &'a mut [T] {
874         core_slice::SliceExt::slice_from_mut(self, start)
875     }
876
877     #[inline]
878     fn slice_to_mut<'a>(&'a mut self, end: uint) -> &'a mut [T] {
879         core_slice::SliceExt::slice_to_mut(self, end)
880     }
881
882     #[inline]
883     fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
884         core_slice::SliceExt::iter_mut(self)
885     }
886
887     #[inline]
888     fn first_mut<'a>(&'a mut self) -> Option<&'a mut T> {
889         core_slice::SliceExt::first_mut(self)
890     }
891
892     #[inline]
893     fn tail_mut<'a>(&'a mut self) -> &'a mut [T] {
894         core_slice::SliceExt::tail_mut(self)
895     }
896
897     #[inline]
898     fn init_mut<'a>(&'a mut self) -> &'a mut [T] {
899         core_slice::SliceExt::init_mut(self)
900     }
901
902     #[inline]
903     fn last_mut<'a>(&'a mut self) -> Option<&'a mut T> {
904         core_slice::SliceExt::last_mut(self)
905     }
906
907     #[inline]
908     fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
909                     where F: FnMut(&T) -> bool {
910         core_slice::SliceExt::split_mut(self, pred)
911     }
912
913     #[inline]
914     fn splitn_mut<F>(&mut self, n: uint, pred: F) -> SplitNMut<T, F>
915                      where F: FnMut(&T) -> bool {
916         core_slice::SliceExt::splitn_mut(self, n, pred)
917     }
918
919     #[inline]
920     fn rsplitn_mut<F>(&mut self,  n: uint, pred: F) -> RSplitNMut<T, F>
921                       where F: FnMut(&T) -> bool {
922         core_slice::SliceExt::rsplitn_mut(self, n, pred)
923     }
924
925     #[inline]
926     fn chunks_mut<'a>(&'a mut self, chunk_size: uint) -> ChunksMut<'a, T> {
927         core_slice::SliceExt::chunks_mut(self, chunk_size)
928     }
929
930     #[inline]
931     fn swap(&mut self, a: uint, b: uint) {
932         core_slice::SliceExt::swap(self, a, b)
933     }
934
935     #[inline]
936     fn split_at_mut<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
937         core_slice::SliceExt::split_at_mut(self, mid)
938     }
939
940     #[inline]
941     fn reverse(&mut self) {
942         core_slice::SliceExt::reverse(self)
943     }
944
945     #[inline]
946     unsafe fn get_unchecked_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
947         core_slice::SliceExt::get_unchecked_mut(self, index)
948     }
949
950     #[inline]
951     fn as_mut_ptr(&mut self) -> *mut T {
952         core_slice::SliceExt::as_mut_ptr(self)
953     }
954
955     /// Returns a copy of `v`.
956     #[inline]
957     fn to_vec(&self) -> Vec<T> where T: Clone {
958         let mut vector = Vec::with_capacity(self.len());
959         vector.push_all(self);
960         vector
961     }
962
963
964     #[inline]
965     fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool, T: Clone {
966         self.iter().cloned().partition(f)
967     }
968
969     /// Returns an iterator over all permutations of a vector.
970     fn permutations(&self) -> Permutations<T> where T: Clone {
971         Permutations{
972             swaps: ElementSwaps::new(self.len()),
973             v: self.to_vec(),
974         }
975     }
976
977     fn clone_from_slice(&mut self, src: &[T]) -> uint where T: Clone {
978         core_slice::SliceExt::clone_from_slice(self, src)
979     }
980
981     #[inline]
982     fn sort(&mut self) where T: Ord {
983         self.sort_by(|a, b| a.cmp(b))
984     }
985
986     fn binary_search(&self, x: &T) -> Result<uint, uint> where T: Ord {
987         core_slice::SliceExt::binary_search(self, x)
988     }
989
990     fn next_permutation(&mut self) -> bool where T: Ord {
991         core_slice::SliceExt::next_permutation(self)
992     }
993
994     fn prev_permutation(&mut self) -> bool where T: Ord {
995         core_slice::SliceExt::prev_permutation(self)
996     }
997
998     fn position_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
999         core_slice::SliceExt::position_elem(self, t)
1000     }
1001
1002     fn rposition_elem(&self, t: &T) -> Option<uint> where T: PartialEq {
1003         core_slice::SliceExt::rposition_elem(self, t)
1004     }
1005
1006     fn contains(&self, x: &T) -> bool where T: PartialEq {
1007         core_slice::SliceExt::contains(self, x)
1008     }
1009
1010     fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq {
1011         core_slice::SliceExt::starts_with(self, needle)
1012     }
1013
1014     fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq {
1015         core_slice::SliceExt::ends_with(self, needle)
1016     }
1017
1018     fn into_vec(mut self: Box<Self>) -> Vec<T> {
1019         unsafe {
1020             let xs = Vec::from_raw_parts(self.as_mut_ptr(), self.len(), self.len());
1021             mem::forget(self);
1022             xs
1023         }
1024     }
1025 }
1026
1027 ////////////////////////////////////////////////////////////////////////////////
1028 // Extension traits for slices over specifc kinds of data
1029 ////////////////////////////////////////////////////////////////////////////////
1030 #[unstable = "U should be an associated type"]
1031 /// An extension trait for concatenating slices
1032 pub trait SliceConcatExt<Sized? T, U> for Sized? {
1033     /// Flattens a slice of `T` into a single value `U`.
1034     #[stable]
1035     fn concat(&self) -> U;
1036
1037     #[deprecated = "renamed to concat"]
1038     fn concat_vec(&self) -> U {
1039         self.concat()
1040     }
1041
1042     /// Flattens a slice of `T` into a single value `U`, placing a
1043     /// given seperator between each.
1044     #[stable]
1045     fn connect(&self, sep: &T) -> U;
1046
1047     #[deprecated = "renamed to connect"]
1048     fn connect_vec(&self, sep: &T) -> U {
1049         self.connect(sep)
1050     }
1051 }
1052
1053 impl<T: Clone, V: AsSlice<T>> SliceConcatExt<T, Vec<T>> for [V] {
1054     fn concat(&self) -> Vec<T> {
1055         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
1056         let mut result = Vec::with_capacity(size);
1057         for v in self.iter() {
1058             result.push_all(v.as_slice())
1059         }
1060         result
1061     }
1062
1063     fn connect(&self, sep: &T) -> Vec<T> {
1064         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
1065         let mut result = Vec::with_capacity(size + self.len());
1066         let mut first = true;
1067         for v in self.iter() {
1068             if first { first = false } else { result.push(sep.clone()) }
1069             result.push_all(v.as_slice())
1070         }
1071         result
1072     }
1073 }
1074
1075 /// An iterator that yields the element swaps needed to produce
1076 /// a sequence of all possible permutations for an indexed sequence of
1077 /// elements. Each permutation is only a single swap apart.
1078 ///
1079 /// The Steinhaus-Johnson-Trotter algorithm is used.
1080 ///
1081 /// Generates even and odd permutations alternately.
1082 ///
1083 /// The last generated swap is always (0, 1), and it returns the
1084 /// sequence to its initial order.
1085 #[experimental]
1086 #[deriving(Clone)]
1087 pub struct ElementSwaps {
1088     sdir: Vec<SizeDirection>,
1089     /// If `true`, emit the last swap that returns the sequence to initial
1090     /// state.
1091     emit_reset: bool,
1092     swaps_made : uint,
1093 }
1094
1095 impl ElementSwaps {
1096     /// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
1097     #[experimental]
1098     pub fn new(length: uint) -> ElementSwaps {
1099         // Initialize `sdir` with a direction that position should move in
1100         // (all negative at the beginning) and the `size` of the
1101         // element (equal to the original index).
1102         ElementSwaps{
1103             emit_reset: true,
1104             sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
1105             swaps_made: 0
1106         }
1107     }
1108 }
1109
1110 ////////////////////////////////////////////////////////////////////////////////
1111 // Standard trait implementations for slices
1112 ////////////////////////////////////////////////////////////////////////////////
1113
1114 #[unstable = "trait is unstable"]
1115 impl<T> BorrowFrom<Vec<T>> for [T] {
1116     fn borrow_from(owned: &Vec<T>) -> &[T] { owned[] }
1117 }
1118
1119 #[unstable = "trait is unstable"]
1120 impl<T> BorrowFromMut<Vec<T>> for [T] {
1121     fn borrow_from_mut(owned: &mut Vec<T>) -> &mut [T] { owned.as_mut_slice_() }
1122 }
1123
1124 #[unstable = "trait is unstable"]
1125 impl<T: Clone> ToOwned<Vec<T>> for [T] {
1126     fn to_owned(&self) -> Vec<T> { self.to_vec() }
1127 }
1128
1129 ////////////////////////////////////////////////////////////////////////////////
1130 // Iterators
1131 ////////////////////////////////////////////////////////////////////////////////
1132
1133 #[deriving(Copy, Clone)]
1134 enum Direction { Pos, Neg }
1135
1136 /// An `Index` and `Direction` together.
1137 #[deriving(Copy, Clone)]
1138 struct SizeDirection {
1139     size: uint,
1140     dir: Direction,
1141 }
1142
1143 impl Iterator for ElementSwaps {
1144     type Item = (uint, uint);
1145
1146     #[inline]
1147     fn next(&mut self) -> Option<(uint, uint)> {
1148         fn new_pos(i: uint, s: Direction) -> uint {
1149             i + match s { Pos => 1, Neg => -1 }
1150         }
1151
1152         // Find the index of the largest mobile element:
1153         // The direction should point into the vector, and the
1154         // swap should be with a smaller `size` element.
1155         let max = self.sdir.iter().map(|&x| x).enumerate()
1156                            .filter(|&(i, sd)|
1157                                 new_pos(i, sd.dir) < self.sdir.len() &&
1158                                 self.sdir[new_pos(i, sd.dir)].size < sd.size)
1159                            .max_by(|&(_, sd)| sd.size);
1160         match max {
1161             Some((i, sd)) => {
1162                 let j = new_pos(i, sd.dir);
1163                 self.sdir.swap(i, j);
1164
1165                 // Swap the direction of each larger SizeDirection
1166                 for x in self.sdir.iter_mut() {
1167                     if x.size > sd.size {
1168                         x.dir = match x.dir { Pos => Neg, Neg => Pos };
1169                     }
1170                 }
1171                 self.swaps_made += 1;
1172                 Some((i, j))
1173             },
1174             None => if self.emit_reset {
1175                 self.emit_reset = false;
1176                 if self.sdir.len() > 1 {
1177                     // The last swap
1178                     self.swaps_made += 1;
1179                     Some((0, 1))
1180                 } else {
1181                     // Vector is of the form [] or [x], and the only permutation is itself
1182                     self.swaps_made += 1;
1183                     Some((0,0))
1184                 }
1185             } else { None }
1186         }
1187     }
1188
1189     #[inline]
1190     fn size_hint(&self) -> (uint, Option<uint>) {
1191         // For a vector of size n, there are exactly n! permutations.
1192         let n = range(2, self.sdir.len() + 1).product();
1193         (n - self.swaps_made, Some(n - self.swaps_made))
1194     }
1195 }
1196
1197 /// An iterator that uses `ElementSwaps` to iterate through
1198 /// all possible permutations of a vector.
1199 ///
1200 /// The first iteration yields a clone of the vector as it is,
1201 /// then each successive element is the vector with one
1202 /// swap applied.
1203 ///
1204 /// Generates even and odd permutations alternately.
1205 #[unstable]
1206 pub struct Permutations<T> {
1207     swaps: ElementSwaps,
1208     v: Vec<T>,
1209 }
1210
1211 #[unstable = "trait is unstable"]
1212 impl<T: Clone> Iterator for Permutations<T> {
1213     type Item = Vec<T>;
1214
1215     #[inline]
1216     fn next(&mut self) -> Option<Vec<T>> {
1217         match self.swaps.next() {
1218             None => None,
1219             Some((0,0)) => Some(self.v.clone()),
1220             Some((a, b)) => {
1221                 let elt = self.v.clone();
1222                 self.v.swap(a, b);
1223                 Some(elt)
1224             }
1225         }
1226     }
1227
1228     #[inline]
1229     fn size_hint(&self) -> (uint, Option<uint>) {
1230         self.swaps.size_hint()
1231     }
1232 }
1233
1234 ////////////////////////////////////////////////////////////////////////////////
1235 // Sorting
1236 ////////////////////////////////////////////////////////////////////////////////
1237
1238 fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1239     let len = v.len() as int;
1240     let buf_v = v.as_mut_ptr();
1241
1242     // 1 <= i < len;
1243     for i in range(1, len) {
1244         // j satisfies: 0 <= j <= i;
1245         let mut j = i;
1246         unsafe {
1247             // `i` is in bounds.
1248             let read_ptr = buf_v.offset(i) as *const T;
1249
1250             // find where to insert, we need to do strict <,
1251             // rather than <=, to maintain stability.
1252
1253             // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1254             while j > 0 &&
1255                     compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1256                 j -= 1;
1257             }
1258
1259             // shift everything to the right, to make space to
1260             // insert this value.
1261
1262             // j + 1 could be `len` (for the last `i`), but in
1263             // that case, `i == j` so we don't copy. The
1264             // `.offset(j)` is always in bounds.
1265
1266             if i != j {
1267                 let tmp = ptr::read(read_ptr);
1268                 ptr::copy_memory(buf_v.offset(j + 1),
1269                                  &*buf_v.offset(j),
1270                                  (i - j) as uint);
1271                 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
1272                                                 &tmp as *const T,
1273                                                 1);
1274                 mem::forget(tmp);
1275             }
1276         }
1277     }
1278 }
1279
1280 fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
1281     // warning: this wildly uses unsafe.
1282     static BASE_INSERTION: uint = 32;
1283     static LARGE_INSERTION: uint = 16;
1284
1285     // FIXME #12092: smaller insertion runs seems to make sorting
1286     // vectors of large elements a little faster on some platforms,
1287     // but hasn't been tested/tuned extensively
1288     let insertion = if size_of::<T>() <= 16 {
1289         BASE_INSERTION
1290     } else {
1291         LARGE_INSERTION
1292     };
1293
1294     let len = v.len();
1295
1296     // short vectors get sorted in-place via insertion sort to avoid allocations
1297     if len <= insertion {
1298         insertion_sort(v, compare);
1299         return;
1300     }
1301
1302     // allocate some memory to use as scratch memory, we keep the
1303     // length 0 so we can keep shallow copies of the contents of `v`
1304     // without risking the dtors running on an object twice if
1305     // `compare` panics.
1306     let mut working_space = Vec::with_capacity(2 * len);
1307     // these both are buffers of length `len`.
1308     let mut buf_dat = working_space.as_mut_ptr();
1309     let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
1310
1311     // length `len`.
1312     let buf_v = v.as_ptr();
1313
1314     // step 1. sort short runs with insertion sort. This takes the
1315     // values from `v` and sorts them into `buf_dat`, leaving that
1316     // with sorted runs of length INSERTION.
1317
1318     // We could hardcode the sorting comparisons here, and we could
1319     // manipulate/step the pointers themselves, rather than repeatedly
1320     // .offset-ing.
1321     for start in range_step(0, len, insertion) {
1322         // start <= i < len;
1323         for i in range(start, cmp::min(start + insertion, len)) {
1324             // j satisfies: start <= j <= i;
1325             let mut j = i as int;
1326             unsafe {
1327                 // `i` is in bounds.
1328                 let read_ptr = buf_v.offset(i as int);
1329
1330                 // find where to insert, we need to do strict <,
1331                 // rather than <=, to maintain stability.
1332
1333                 // start <= j - 1 < len, so .offset(j - 1) is in
1334                 // bounds.
1335                 while j > start as int &&
1336                         compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1337                     j -= 1;
1338                 }
1339
1340                 // shift everything to the right, to make space to
1341                 // insert this value.
1342
1343                 // j + 1 could be `len` (for the last `i`), but in
1344                 // that case, `i == j` so we don't copy. The
1345                 // `.offset(j)` is always in bounds.
1346                 ptr::copy_memory(buf_dat.offset(j + 1),
1347                                  &*buf_dat.offset(j),
1348                                  i - j as uint);
1349                 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1350             }
1351         }
1352     }
1353
1354     // step 2. merge the sorted runs.
1355     let mut width = insertion;
1356     while width < len {
1357         // merge the sorted runs of length `width` in `buf_dat` two at
1358         // a time, placing the result in `buf_tmp`.
1359
1360         // 0 <= start <= len.
1361         for start in range_step(0, len, 2 * width) {
1362             // manipulate pointers directly for speed (rather than
1363             // using a `for` loop with `range` and `.offset` inside
1364             // that loop).
1365             unsafe {
1366                 // the end of the first run & start of the
1367                 // second. Offset of `len` is defined, since this is
1368                 // precisely one byte past the end of the object.
1369                 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
1370                 // end of the second. Similar reasoning to the above re safety.
1371                 let right_end_idx = cmp::min(start + 2 * width, len);
1372                 let right_end = buf_dat.offset(right_end_idx as int);
1373
1374                 // the pointers to the elements under consideration
1375                 // from the two runs.
1376
1377                 // both of these are in bounds.
1378                 let mut left = buf_dat.offset(start as int);
1379                 let mut right = right_start;
1380
1381                 // where we're putting the results, it is a run of
1382                 // length `2*width`, so we step it once for each step
1383                 // of either `left` or `right`.  `buf_tmp` has length
1384                 // `len`, so these are in bounds.
1385                 let mut out = buf_tmp.offset(start as int);
1386                 let out_end = buf_tmp.offset(right_end_idx as int);
1387
1388                 while out < out_end {
1389                     // Either the left or the right run are exhausted,
1390                     // so just copy the remainder from the other run
1391                     // and move on; this gives a huge speed-up (order
1392                     // of 25%) for mostly sorted vectors (the best
1393                     // case).
1394                     if left == right_start {
1395                         // the number remaining in this run.
1396                         let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
1397                         ptr::copy_nonoverlapping_memory(out, &*right, elems);
1398                         break;
1399                     } else if right == right_end {
1400                         let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
1401                         ptr::copy_nonoverlapping_memory(out, &*left, elems);
1402                         break;
1403                     }
1404
1405                     // check which side is smaller, and that's the
1406                     // next element for the new run.
1407
1408                     // `left < right_start` and `right < right_end`,
1409                     // so these are valid.
1410                     let to_copy = if compare(&*left, &*right) == Greater {
1411                         step(&mut right)
1412                     } else {
1413                         step(&mut left)
1414                     };
1415                     ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
1416                     step(&mut out);
1417                 }
1418             }
1419         }
1420
1421         mem::swap(&mut buf_dat, &mut buf_tmp);
1422
1423         width *= 2;
1424     }
1425
1426     // write the result to `v` in one go, so that there are never two copies
1427     // of the same object in `v`.
1428     unsafe {
1429         ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
1430     }
1431
1432     // increment the pointer, returning the old pointer.
1433     #[inline(always)]
1434     unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1435         let old = *ptr;
1436         *ptr = ptr.offset(1);
1437         old
1438     }
1439 }
1440
1441 /// Deprecated, unsafe operations
1442 #[deprecated]
1443 pub mod raw {
1444     pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
1445     pub use core::slice::raw::{shift_ptr, pop_ptr};
1446 }
1447
1448 #[cfg(test)]
1449 mod tests {
1450     use std::boxed::Box;
1451     use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal};
1452     use prelude::{SliceExt, Iterator, IteratorExt};
1453     use prelude::AsSlice;
1454     use prelude::{RandomAccessIterator, Ord, SliceConcatExt};
1455     use core::cell::Cell;
1456     use core::default::Default;
1457     use core::mem;
1458     use std::rand::{Rng, thread_rng};
1459     use std::rc::Rc;
1460     use super::ElementSwaps;
1461
1462     fn square(n: uint) -> uint { n * n }
1463
1464     fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
1465
1466     #[test]
1467     fn test_from_fn() {
1468         // Test on-stack from_fn.
1469         let mut v = Vec::from_fn(3u, square);
1470         {
1471             let v = v.as_slice();
1472             assert_eq!(v.len(), 3u);
1473             assert_eq!(v[0], 0u);
1474             assert_eq!(v[1], 1u);
1475             assert_eq!(v[2], 4u);
1476         }
1477
1478         // Test on-heap from_fn.
1479         v = Vec::from_fn(5u, square);
1480         {
1481             let v = v.as_slice();
1482             assert_eq!(v.len(), 5u);
1483             assert_eq!(v[0], 0u);
1484             assert_eq!(v[1], 1u);
1485             assert_eq!(v[2], 4u);
1486             assert_eq!(v[3], 9u);
1487             assert_eq!(v[4], 16u);
1488         }
1489     }
1490
1491     #[test]
1492     fn test_from_elem() {
1493         // Test on-stack from_elem.
1494         let mut v = Vec::from_elem(2u, 10u);
1495         {
1496             let v = v.as_slice();
1497             assert_eq!(v.len(), 2u);
1498             assert_eq!(v[0], 10u);
1499             assert_eq!(v[1], 10u);
1500         }
1501
1502         // Test on-heap from_elem.
1503         v = Vec::from_elem(6u, 20u);
1504         {
1505             let v = v.as_slice();
1506             assert_eq!(v[0], 20u);
1507             assert_eq!(v[1], 20u);
1508             assert_eq!(v[2], 20u);
1509             assert_eq!(v[3], 20u);
1510             assert_eq!(v[4], 20u);
1511             assert_eq!(v[5], 20u);
1512         }
1513     }
1514
1515     #[test]
1516     fn test_is_empty() {
1517         let xs: [int; 0] = [];
1518         assert!(xs.is_empty());
1519         assert!(![0i].is_empty());
1520     }
1521
1522     #[test]
1523     fn test_len_divzero() {
1524         type Z = [i8; 0];
1525         let v0 : &[Z] = &[];
1526         let v1 : &[Z] = &[[]];
1527         let v2 : &[Z] = &[[], []];
1528         assert_eq!(mem::size_of::<Z>(), 0);
1529         assert_eq!(v0.len(), 0);
1530         assert_eq!(v1.len(), 1);
1531         assert_eq!(v2.len(), 2);
1532     }
1533
1534     #[test]
1535     fn test_get() {
1536         let mut a = vec![11i];
1537         assert_eq!(a.as_slice().get(1), None);
1538         a = vec![11i, 12];
1539         assert_eq!(a.as_slice().get(1).unwrap(), &12);
1540         a = vec![11i, 12, 13];
1541         assert_eq!(a.as_slice().get(1).unwrap(), &12);
1542     }
1543
1544     #[test]
1545     fn test_head() {
1546         let mut a = vec![];
1547         assert_eq!(a.as_slice().head(), None);
1548         a = vec![11i];
1549         assert_eq!(a.as_slice().head().unwrap(), &11);
1550         a = vec![11i, 12];
1551         assert_eq!(a.as_slice().head().unwrap(), &11);
1552     }
1553
1554     #[test]
1555     fn test_head_mut() {
1556         let mut a = vec![];
1557         assert_eq!(a.head_mut(), None);
1558         a = vec![11i];
1559         assert_eq!(*a.head_mut().unwrap(), 11);
1560         a = vec![11i, 12];
1561         assert_eq!(*a.head_mut().unwrap(), 11);
1562     }
1563
1564     #[test]
1565     fn test_tail() {
1566         let mut a = vec![11i];
1567         let b: &[int] = &[];
1568         assert_eq!(a.tail(), b);
1569         a = vec![11i, 12];
1570         let b: &[int] = &[12];
1571         assert_eq!(a.tail(), b);
1572     }
1573
1574     #[test]
1575     fn test_tail_mut() {
1576         let mut a = vec![11i];
1577         let b: &mut [int] = &mut [];
1578         assert!(a.tail_mut() == b);
1579         a = vec![11i, 12];
1580         let b: &mut [int] = &mut [12];
1581         assert!(a.tail_mut() == b);
1582     }
1583
1584     #[test]
1585     #[should_fail]
1586     fn test_tail_empty() {
1587         let a: Vec<int> = vec![];
1588         a.tail();
1589     }
1590
1591     #[test]
1592     #[should_fail]
1593     fn test_tail_mut_empty() {
1594         let mut a: Vec<int> = vec![];
1595         a.tail_mut();
1596     }
1597
1598     #[test]
1599     fn test_init() {
1600         let mut a = vec![11i];
1601         let b: &[int] = &[];
1602         assert_eq!(a.init(), b);
1603         a = vec![11i, 12];
1604         let b: &[int] = &[11];
1605         assert_eq!(a.init(), b);
1606     }
1607
1608     #[test]
1609     fn test_init_mut() {
1610         let mut a = vec![11i];
1611         let b: &mut [int] = &mut [];
1612         assert!(a.init_mut() == b);
1613         a = vec![11i, 12];
1614         let b: &mut [int] = &mut [11];
1615         assert!(a.init_mut() == b);
1616     }
1617
1618     #[test]
1619     #[should_fail]
1620     fn test_init_empty() {
1621         let a: Vec<int> = vec![];
1622         a.init();
1623     }
1624
1625     #[test]
1626     #[should_fail]
1627     fn test_init_mut_empty() {
1628         let mut a: Vec<int> = vec![];
1629         a.init_mut();
1630     }
1631
1632     #[test]
1633     fn test_last() {
1634         let mut a = vec![];
1635         assert_eq!(a.as_slice().last(), None);
1636         a = vec![11i];
1637         assert_eq!(a.as_slice().last().unwrap(), &11);
1638         a = vec![11i, 12];
1639         assert_eq!(a.as_slice().last().unwrap(), &12);
1640     }
1641
1642     #[test]
1643     fn test_last_mut() {
1644         let mut a = vec![];
1645         assert_eq!(a.last_mut(), None);
1646         a = vec![11i];
1647         assert_eq!(*a.last_mut().unwrap(), 11);
1648         a = vec![11i, 12];
1649         assert_eq!(*a.last_mut().unwrap(), 12);
1650     }
1651
1652     #[test]
1653     fn test_slice() {
1654         // Test fixed length vector.
1655         let vec_fixed = [1i, 2, 3, 4];
1656         let v_a = vec_fixed[1u..vec_fixed.len()].to_vec();
1657         assert_eq!(v_a.len(), 3u);
1658         let v_a = v_a.as_slice();
1659         assert_eq!(v_a[0], 2);
1660         assert_eq!(v_a[1], 3);
1661         assert_eq!(v_a[2], 4);
1662
1663         // Test on stack.
1664         let vec_stack: &[_] = &[1i, 2, 3];
1665         let v_b = vec_stack[1u..3u].to_vec();
1666         assert_eq!(v_b.len(), 2u);
1667         let v_b = v_b.as_slice();
1668         assert_eq!(v_b[0], 2);
1669         assert_eq!(v_b[1], 3);
1670
1671         // Test `Box<[T]>`
1672         let vec_unique = vec![1i, 2, 3, 4, 5, 6];
1673         let v_d = vec_unique[1u..6u].to_vec();
1674         assert_eq!(v_d.len(), 5u);
1675         let v_d = v_d.as_slice();
1676         assert_eq!(v_d[0], 2);
1677         assert_eq!(v_d[1], 3);
1678         assert_eq!(v_d[2], 4);
1679         assert_eq!(v_d[3], 5);
1680         assert_eq!(v_d[4], 6);
1681     }
1682
1683     #[test]
1684     fn test_slice_from() {
1685         let vec: &[int] = &[1, 2, 3, 4];
1686         assert_eq!(vec[0..], vec);
1687         let b: &[int] = &[3, 4];
1688         assert_eq!(vec[2..], b);
1689         let b: &[int] = &[];
1690         assert_eq!(vec[4..], b);
1691     }
1692
1693     #[test]
1694     fn test_slice_to() {
1695         let vec: &[int] = &[1, 2, 3, 4];
1696         assert_eq!(vec[..4], vec);
1697         let b: &[int] = &[1, 2];
1698         assert_eq!(vec[..2], b);
1699         let b: &[int] = &[];
1700         assert_eq!(vec[..0], b);
1701     }
1702
1703
1704     #[test]
1705     fn test_pop() {
1706         let mut v = vec![5i];
1707         let e = v.pop();
1708         assert_eq!(v.len(), 0);
1709         assert_eq!(e, Some(5));
1710         let f = v.pop();
1711         assert_eq!(f, None);
1712         let g = v.pop();
1713         assert_eq!(g, None);
1714     }
1715
1716     #[test]
1717     fn test_swap_remove() {
1718         let mut v = vec![1i, 2, 3, 4, 5];
1719         let mut e = v.swap_remove(0);
1720         assert_eq!(e, 1);
1721         assert_eq!(v, vec![5i, 2, 3, 4]);
1722         e = v.swap_remove(3);
1723         assert_eq!(e, 4);
1724         assert_eq!(v, vec![5i, 2, 3]);
1725     }
1726
1727     #[test]
1728     #[should_fail]
1729     fn test_swap_remove_fail() {
1730         let mut v = vec![1i];
1731         let _ = v.swap_remove(0);
1732         let _ = v.swap_remove(0);
1733     }
1734
1735     #[test]
1736     fn test_swap_remove_noncopyable() {
1737         // Tests that we don't accidentally run destructors twice.
1738         let mut v = Vec::new();
1739         v.push(box 0u8);
1740         v.push(box 0u8);
1741         v.push(box 0u8);
1742         let mut _e = v.swap_remove(0);
1743         assert_eq!(v.len(), 2);
1744         _e = v.swap_remove(1);
1745         assert_eq!(v.len(), 1);
1746         _e = v.swap_remove(0);
1747         assert_eq!(v.len(), 0);
1748     }
1749
1750     #[test]
1751     fn test_push() {
1752         // Test on-stack push().
1753         let mut v = vec![];
1754         v.push(1i);
1755         assert_eq!(v.len(), 1u);
1756         assert_eq!(v.as_slice()[0], 1);
1757
1758         // Test on-heap push().
1759         v.push(2i);
1760         assert_eq!(v.len(), 2u);
1761         assert_eq!(v.as_slice()[0], 1);
1762         assert_eq!(v.as_slice()[1], 2);
1763     }
1764
1765     #[test]
1766     fn test_grow() {
1767         // Test on-stack grow().
1768         let mut v = vec![];
1769         v.grow(2u, 1i);
1770         {
1771             let v = v.as_slice();
1772             assert_eq!(v.len(), 2u);
1773             assert_eq!(v[0], 1);
1774             assert_eq!(v[1], 1);
1775         }
1776
1777         // Test on-heap grow().
1778         v.grow(3u, 2i);
1779         {
1780             let v = v.as_slice();
1781             assert_eq!(v.len(), 5u);
1782             assert_eq!(v[0], 1);
1783             assert_eq!(v[1], 1);
1784             assert_eq!(v[2], 2);
1785             assert_eq!(v[3], 2);
1786             assert_eq!(v[4], 2);
1787         }
1788     }
1789
1790     #[test]
1791     fn test_grow_fn() {
1792         let mut v = vec![];
1793         v.grow_fn(3u, square);
1794         let v = v.as_slice();
1795         assert_eq!(v.len(), 3u);
1796         assert_eq!(v[0], 0u);
1797         assert_eq!(v[1], 1u);
1798         assert_eq!(v[2], 4u);
1799     }
1800
1801     #[test]
1802     fn test_truncate() {
1803         let mut v = vec![box 6i,box 5,box 4];
1804         v.truncate(1);
1805         let v = v.as_slice();
1806         assert_eq!(v.len(), 1);
1807         assert_eq!(*(v[0]), 6);
1808         // If the unsafe block didn't drop things properly, we blow up here.
1809     }
1810
1811     #[test]
1812     fn test_clear() {
1813         let mut v = vec![box 6i,box 5,box 4];
1814         v.clear();
1815         assert_eq!(v.len(), 0);
1816         // If the unsafe block didn't drop things properly, we blow up here.
1817     }
1818
1819     #[test]
1820     fn test_dedup() {
1821         fn case(a: Vec<uint>, b: Vec<uint>) {
1822             let mut v = a;
1823             v.dedup();
1824             assert_eq!(v, b);
1825         }
1826         case(vec![], vec![]);
1827         case(vec![1u], vec![1]);
1828         case(vec![1u,1], vec![1]);
1829         case(vec![1u,2,3], vec![1,2,3]);
1830         case(vec![1u,1,2,3], vec![1,2,3]);
1831         case(vec![1u,2,2,3], vec![1,2,3]);
1832         case(vec![1u,2,3,3], vec![1,2,3]);
1833         case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1834     }
1835
1836     #[test]
1837     fn test_dedup_unique() {
1838         let mut v0 = vec![box 1i, box 1, box 2, box 3];
1839         v0.dedup();
1840         let mut v1 = vec![box 1i, box 2, box 2, box 3];
1841         v1.dedup();
1842         let mut v2 = vec![box 1i, box 2, box 3, box 3];
1843         v2.dedup();
1844         /*
1845          * If the boxed pointers were leaked or otherwise misused, valgrind
1846          * and/or rt should raise errors.
1847          */
1848     }
1849
1850     #[test]
1851     fn test_dedup_shared() {
1852         let mut v0 = vec![box 1i, box 1, box 2, box 3];
1853         v0.dedup();
1854         let mut v1 = vec![box 1i, box 2, box 2, box 3];
1855         v1.dedup();
1856         let mut v2 = vec![box 1i, box 2, box 3, box 3];
1857         v2.dedup();
1858         /*
1859          * If the pointers were leaked or otherwise misused, valgrind and/or
1860          * rt should raise errors.
1861          */
1862     }
1863
1864     #[test]
1865     fn test_retain() {
1866         let mut v = vec![1u, 2, 3, 4, 5];
1867         v.retain(is_odd);
1868         assert_eq!(v, vec![1u, 3, 5]);
1869     }
1870
1871     #[test]
1872     fn test_element_swaps() {
1873         let mut v = [1i, 2, 3];
1874         for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1875             v.swap(a, b);
1876             match i {
1877                 0 => assert!(v == [1, 3, 2]),
1878                 1 => assert!(v == [3, 1, 2]),
1879                 2 => assert!(v == [3, 2, 1]),
1880                 3 => assert!(v == [2, 3, 1]),
1881                 4 => assert!(v == [2, 1, 3]),
1882                 5 => assert!(v == [1, 2, 3]),
1883                 _ => panic!(),
1884             }
1885         }
1886     }
1887
1888     #[test]
1889     fn test_permutations() {
1890         {
1891             let v: [int; 0] = [];
1892             let mut it = v.permutations();
1893             let (min_size, max_opt) = it.size_hint();
1894             assert_eq!(min_size, 1);
1895             assert_eq!(max_opt.unwrap(), 1);
1896             assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1897             assert_eq!(it.next(), None);
1898         }
1899         {
1900             let v = ["Hello".to_string()];
1901             let mut it = v.permutations();
1902             let (min_size, max_opt) = it.size_hint();
1903             assert_eq!(min_size, 1);
1904             assert_eq!(max_opt.unwrap(), 1);
1905             assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1906             assert_eq!(it.next(), None);
1907         }
1908         {
1909             let v = [1i, 2, 3];
1910             let mut it = v.permutations();
1911             let (min_size, max_opt) = it.size_hint();
1912             assert_eq!(min_size, 3*2);
1913             assert_eq!(max_opt.unwrap(), 3*2);
1914             assert_eq!(it.next(), Some(vec![1,2,3]));
1915             assert_eq!(it.next(), Some(vec![1,3,2]));
1916             assert_eq!(it.next(), Some(vec![3,1,2]));
1917             let (min_size, max_opt) = it.size_hint();
1918             assert_eq!(min_size, 3);
1919             assert_eq!(max_opt.unwrap(), 3);
1920             assert_eq!(it.next(), Some(vec![3,2,1]));
1921             assert_eq!(it.next(), Some(vec![2,3,1]));
1922             assert_eq!(it.next(), Some(vec![2,1,3]));
1923             assert_eq!(it.next(), None);
1924         }
1925         {
1926             // check that we have N! permutations
1927             let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1928             let mut amt = 0;
1929             let mut it = v.permutations();
1930             let (min_size, max_opt) = it.size_hint();
1931             for _perm in it {
1932                 amt += 1;
1933             }
1934             assert_eq!(amt, it.swaps.swaps_made);
1935             assert_eq!(amt, min_size);
1936             assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1937             assert_eq!(amt, max_opt.unwrap());
1938         }
1939     }
1940
1941     #[test]
1942     fn test_lexicographic_permutations() {
1943         let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1944         assert!(v.prev_permutation() == false);
1945         assert!(v.next_permutation());
1946         let b: &mut[int] = &mut[1, 2, 3, 5, 4];
1947         assert!(v == b);
1948         assert!(v.prev_permutation());
1949         let b: &mut[int] = &mut[1, 2, 3, 4, 5];
1950         assert!(v == b);
1951         assert!(v.next_permutation());
1952         assert!(v.next_permutation());
1953         let b: &mut[int] = &mut[1, 2, 4, 3, 5];
1954         assert!(v == b);
1955         assert!(v.next_permutation());
1956         let b: &mut[int] = &mut[1, 2, 4, 5, 3];
1957         assert!(v == b);
1958
1959         let v : &mut[int] = &mut[1i, 0, 0, 0];
1960         assert!(v.next_permutation() == false);
1961         assert!(v.prev_permutation());
1962         let b: &mut[int] = &mut[0, 1, 0, 0];
1963         assert!(v == b);
1964         assert!(v.prev_permutation());
1965         let b: &mut[int] = &mut[0, 0, 1, 0];
1966         assert!(v == b);
1967         assert!(v.prev_permutation());
1968         let b: &mut[int] = &mut[0, 0, 0, 1];
1969         assert!(v == b);
1970         assert!(v.prev_permutation() == false);
1971     }
1972
1973     #[test]
1974     fn test_lexicographic_permutations_empty_and_short() {
1975         let empty : &mut[int] = &mut[];
1976         assert!(empty.next_permutation() == false);
1977         let b: &mut[int] = &mut[];
1978         assert!(empty == b);
1979         assert!(empty.prev_permutation() == false);
1980         assert!(empty == b);
1981
1982         let one_elem : &mut[int] = &mut[4i];
1983         assert!(one_elem.prev_permutation() == false);
1984         let b: &mut[int] = &mut[4];
1985         assert!(one_elem == b);
1986         assert!(one_elem.next_permutation() == false);
1987         assert!(one_elem == b);
1988
1989         let two_elem : &mut[int] = &mut[1i, 2];
1990         assert!(two_elem.prev_permutation() == false);
1991         let b : &mut[int] = &mut[1, 2];
1992         let c : &mut[int] = &mut[2, 1];
1993         assert!(two_elem == b);
1994         assert!(two_elem.next_permutation());
1995         assert!(two_elem == c);
1996         assert!(two_elem.next_permutation() == false);
1997         assert!(two_elem == c);
1998         assert!(two_elem.prev_permutation());
1999         assert!(two_elem == b);
2000         assert!(two_elem.prev_permutation() == false);
2001         assert!(two_elem == b);
2002     }
2003
2004     #[test]
2005     fn test_position_elem() {
2006         assert!([].position_elem(&1i).is_none());
2007
2008         let v1 = vec![1i, 2, 3, 3, 2, 5];
2009         assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
2010         assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
2011         assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
2012         assert!(v1.as_slice().position_elem(&4).is_none());
2013     }
2014
2015     #[test]
2016     fn test_binary_search() {
2017         assert_eq!([1i,2,3,4,5].binary_search(&5).ok(), Some(4));
2018         assert_eq!([1i,2,3,4,5].binary_search(&4).ok(), Some(3));
2019         assert_eq!([1i,2,3,4,5].binary_search(&3).ok(), Some(2));
2020         assert_eq!([1i,2,3,4,5].binary_search(&2).ok(), Some(1));
2021         assert_eq!([1i,2,3,4,5].binary_search(&1).ok(), Some(0));
2022
2023         assert_eq!([2i,4,6,8,10].binary_search(&1).ok(), None);
2024         assert_eq!([2i,4,6,8,10].binary_search(&5).ok(), None);
2025         assert_eq!([2i,4,6,8,10].binary_search(&4).ok(), Some(1));
2026         assert_eq!([2i,4,6,8,10].binary_search(&10).ok(), Some(4));
2027
2028         assert_eq!([2i,4,6,8].binary_search(&1).ok(), None);
2029         assert_eq!([2i,4,6,8].binary_search(&5).ok(), None);
2030         assert_eq!([2i,4,6,8].binary_search(&4).ok(), Some(1));
2031         assert_eq!([2i,4,6,8].binary_search(&8).ok(), Some(3));
2032
2033         assert_eq!([2i,4,6].binary_search(&1).ok(), None);
2034         assert_eq!([2i,4,6].binary_search(&5).ok(), None);
2035         assert_eq!([2i,4,6].binary_search(&4).ok(), Some(1));
2036         assert_eq!([2i,4,6].binary_search(&6).ok(), Some(2));
2037
2038         assert_eq!([2i,4].binary_search(&1).ok(), None);
2039         assert_eq!([2i,4].binary_search(&5).ok(), None);
2040         assert_eq!([2i,4].binary_search(&2).ok(), Some(0));
2041         assert_eq!([2i,4].binary_search(&4).ok(), Some(1));
2042
2043         assert_eq!([2i].binary_search(&1).ok(), None);
2044         assert_eq!([2i].binary_search(&5).ok(), None);
2045         assert_eq!([2i].binary_search(&2).ok(), Some(0));
2046
2047         assert_eq!([].binary_search(&1i).ok(), None);
2048         assert_eq!([].binary_search(&5i).ok(), None);
2049
2050         assert!([1i,1,1,1,1].binary_search(&1).ok() != None);
2051         assert!([1i,1,1,1,2].binary_search(&1).ok() != None);
2052         assert!([1i,1,1,2,2].binary_search(&1).ok() != None);
2053         assert!([1i,1,2,2,2].binary_search(&1).ok() != None);
2054         assert_eq!([1i,2,2,2,2].binary_search(&1).ok(), Some(0));
2055
2056         assert_eq!([1i,2,3,4,5].binary_search(&6).ok(), None);
2057         assert_eq!([1i,2,3,4,5].binary_search(&0).ok(), None);
2058     }
2059
2060     #[test]
2061     fn test_reverse() {
2062         let mut v: Vec<int> = vec![10i, 20];
2063         assert_eq!(v[0], 10);
2064         assert_eq!(v[1], 20);
2065         v.reverse();
2066         assert_eq!(v[0], 20);
2067         assert_eq!(v[1], 10);
2068
2069         let mut v3: Vec<int> = vec![];
2070         v3.reverse();
2071         assert!(v3.is_empty());
2072     }
2073
2074     #[test]
2075     fn test_sort() {
2076         for len in range(4u, 25) {
2077             for _ in range(0i, 100) {
2078                 let mut v = thread_rng().gen_iter::<uint>().take(len)
2079                                       .collect::<Vec<uint>>();
2080                 let mut v1 = v.clone();
2081
2082                 v.sort();
2083                 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
2084
2085                 v1.sort_by(|a, b| a.cmp(b));
2086                 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
2087
2088                 v1.sort_by(|a, b| b.cmp(a));
2089                 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
2090             }
2091         }
2092
2093         // shouldn't panic
2094         let mut v: [uint; 0] = [];
2095         v.sort();
2096
2097         let mut v = [0xDEADBEEFu];
2098         v.sort();
2099         assert!(v == [0xDEADBEEF]);
2100     }
2101
2102     #[test]
2103     fn test_sort_stability() {
2104         for len in range(4i, 25) {
2105             for _ in range(0u, 10) {
2106                 let mut counts = [0i; 10];
2107
2108                 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
2109                 // where the first item of each tuple is random, but
2110                 // the second item represents which occurrence of that
2111                 // number this element is, i.e. the second elements
2112                 // will occur in sorted order.
2113                 let mut v = range(0, len).map(|_| {
2114                         let n = thread_rng().gen::<uint>() % 10;
2115                         counts[n] += 1;
2116                         (n, counts[n])
2117                     }).collect::<Vec<(uint, int)>>();
2118
2119                 // only sort on the first element, so an unstable sort
2120                 // may mix up the counts.
2121                 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
2122
2123                 // this comparison includes the count (the second item
2124                 // of the tuple), so elements with equal first items
2125                 // will need to be ordered with increasing
2126                 // counts... i.e. exactly asserting that this sort is
2127                 // stable.
2128                 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
2129             }
2130         }
2131     }
2132
2133     #[test]
2134     fn test_partition() {
2135         assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
2136         assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2137         assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2138         assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2139     }
2140
2141     #[test]
2142     fn test_partitioned() {
2143         assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
2144         assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2145         assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2146         assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2147     }
2148
2149     #[test]
2150     fn test_concat() {
2151         let v: [Vec<int>; 0] = [];
2152         let c: Vec<int> = v.concat();
2153         assert_eq!(c, []);
2154         let d: Vec<int> = [vec![1i], vec![2i,3i]].concat();
2155         assert_eq!(d, vec![1i, 2, 3]);
2156
2157         let v: [&[int]; 2] = [&[1], &[2, 3]];
2158         assert_eq!(v.connect(&0), vec![1i, 0, 2, 3]);
2159         let v: [&[int]; 3] = [&[1i], &[2], &[3]];
2160         assert_eq!(v.connect(&0), vec![1i, 0, 2, 0, 3]);
2161     }
2162
2163     #[test]
2164     fn test_connect() {
2165         let v: [Vec<int>; 0] = [];
2166         assert_eq!(v.connect_vec(&0), vec![]);
2167         assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
2168         assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
2169
2170         let v: [&[int]; 2] = [&[1], &[2, 3]];
2171         assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 3]);
2172         let v: [&[int]; 3] = [&[1], &[2], &[3]];
2173         assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
2174     }
2175
2176     #[test]
2177     fn test_insert() {
2178         let mut a = vec![1i, 2, 4];
2179         a.insert(2, 3);
2180         assert_eq!(a, vec![1, 2, 3, 4]);
2181
2182         let mut a = vec![1i, 2, 3];
2183         a.insert(0, 0);
2184         assert_eq!(a, vec![0, 1, 2, 3]);
2185
2186         let mut a = vec![1i, 2, 3];
2187         a.insert(3, 4);
2188         assert_eq!(a, vec![1, 2, 3, 4]);
2189
2190         let mut a = vec![];
2191         a.insert(0, 1i);
2192         assert_eq!(a, vec![1]);
2193     }
2194
2195     #[test]
2196     #[should_fail]
2197     fn test_insert_oob() {
2198         let mut a = vec![1i, 2, 3];
2199         a.insert(4, 5);
2200     }
2201
2202     #[test]
2203     fn test_remove() {
2204         let mut a = vec![1i,2,3,4];
2205
2206         assert_eq!(a.remove(2), 3);
2207         assert_eq!(a, vec![1i,2,4]);
2208
2209         assert_eq!(a.remove(2), 4);
2210         assert_eq!(a, vec![1i,2]);
2211
2212         assert_eq!(a.remove(0), 1);
2213         assert_eq!(a, vec![2i]);
2214
2215         assert_eq!(a.remove(0), 2);
2216         assert_eq!(a, vec![]);
2217     }
2218
2219     #[test]
2220     #[should_fail]
2221     fn test_remove_fail() {
2222         let mut a = vec![1i];
2223         let _ = a.remove(0);
2224         let _ = a.remove(0);
2225     }
2226
2227     #[test]
2228     fn test_capacity() {
2229         let mut v = vec![0u64];
2230         v.reserve_exact(10u);
2231         assert!(v.capacity() >= 11u);
2232         let mut v = vec![0u32];
2233         v.reserve_exact(10u);
2234         assert!(v.capacity() >= 11u);
2235     }
2236
2237     #[test]
2238     fn test_slice_2() {
2239         let v = vec![1i, 2, 3, 4, 5];
2240         let v = v.slice(1u, 3u);
2241         assert_eq!(v.len(), 2u);
2242         assert_eq!(v[0], 2);
2243         assert_eq!(v[1], 3);
2244     }
2245
2246
2247     #[test]
2248     #[should_fail]
2249     fn test_from_fn_fail() {
2250         Vec::from_fn(100, |v| {
2251             if v == 50 { panic!() }
2252             box 0i
2253         });
2254     }
2255
2256     #[test]
2257     #[should_fail]
2258     fn test_from_elem_fail() {
2259
2260         struct S {
2261             f: Cell<int>,
2262             boxes: (Box<int>, Rc<int>)
2263         }
2264
2265         impl Clone for S {
2266             fn clone(&self) -> S {
2267                 self.f.set(self.f.get() + 1);
2268                 if self.f.get() == 10 { panic!() }
2269                 S {
2270                     f: self.f.clone(),
2271                     boxes: self.boxes.clone(),
2272                 }
2273             }
2274         }
2275
2276         let s = S {
2277             f: Cell::new(0),
2278             boxes: (box 0, Rc::new(0)),
2279         };
2280         let _ = Vec::from_elem(100, s);
2281     }
2282
2283     #[test]
2284     #[should_fail]
2285     fn test_grow_fn_fail() {
2286         let mut v = vec![];
2287         v.grow_fn(100, |i| {
2288             if i == 50 {
2289                 panic!()
2290             }
2291             (box 0i, Rc::new(0i))
2292         })
2293     }
2294
2295     #[test]
2296     #[should_fail]
2297     fn test_permute_fail() {
2298         let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
2299                  (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
2300         let mut i = 0u;
2301         for _ in v.permutations() {
2302             if i == 2 {
2303                 panic!()
2304             }
2305             i += 1;
2306         }
2307     }
2308
2309     #[test]
2310     fn test_total_ord() {
2311         let c: &[int] = &[1, 2, 3];
2312         [1, 2, 3, 4][].cmp(c) == Greater;
2313         let c: &[int] = &[1, 2, 3, 4];
2314         [1, 2, 3][].cmp(c) == Less;
2315         let c: &[int] = &[1, 2, 3, 6];
2316         [1, 2, 3, 4][].cmp(c) == Equal;
2317         let c: &[int] = &[1, 2, 3, 4, 5, 6];
2318         [1, 2, 3, 4, 5, 5, 5, 5][].cmp(c) == Less;
2319         let c: &[int] = &[1, 2, 3, 4];
2320         [2, 2][].cmp(c) == Greater;
2321     }
2322
2323     #[test]
2324     fn test_iterator() {
2325         let xs = [1i, 2, 5, 10, 11];
2326         let mut it = xs.iter();
2327         assert_eq!(it.size_hint(), (5, Some(5)));
2328         assert_eq!(it.next().unwrap(), &1);
2329         assert_eq!(it.size_hint(), (4, Some(4)));
2330         assert_eq!(it.next().unwrap(), &2);
2331         assert_eq!(it.size_hint(), (3, Some(3)));
2332         assert_eq!(it.next().unwrap(), &5);
2333         assert_eq!(it.size_hint(), (2, Some(2)));
2334         assert_eq!(it.next().unwrap(), &10);
2335         assert_eq!(it.size_hint(), (1, Some(1)));
2336         assert_eq!(it.next().unwrap(), &11);
2337         assert_eq!(it.size_hint(), (0, Some(0)));
2338         assert!(it.next().is_none());
2339     }
2340
2341     #[test]
2342     fn test_random_access_iterator() {
2343         let xs = [1i, 2, 5, 10, 11];
2344         let mut it = xs.iter();
2345
2346         assert_eq!(it.indexable(), 5);
2347         assert_eq!(it.idx(0).unwrap(), &1);
2348         assert_eq!(it.idx(2).unwrap(), &5);
2349         assert_eq!(it.idx(4).unwrap(), &11);
2350         assert!(it.idx(5).is_none());
2351
2352         assert_eq!(it.next().unwrap(), &1);
2353         assert_eq!(it.indexable(), 4);
2354         assert_eq!(it.idx(0).unwrap(), &2);
2355         assert_eq!(it.idx(3).unwrap(), &11);
2356         assert!(it.idx(4).is_none());
2357
2358         assert_eq!(it.next().unwrap(), &2);
2359         assert_eq!(it.indexable(), 3);
2360         assert_eq!(it.idx(1).unwrap(), &10);
2361         assert!(it.idx(3).is_none());
2362
2363         assert_eq!(it.next().unwrap(), &5);
2364         assert_eq!(it.indexable(), 2);
2365         assert_eq!(it.idx(1).unwrap(), &11);
2366
2367         assert_eq!(it.next().unwrap(), &10);
2368         assert_eq!(it.indexable(), 1);
2369         assert_eq!(it.idx(0).unwrap(), &11);
2370         assert!(it.idx(1).is_none());
2371
2372         assert_eq!(it.next().unwrap(), &11);
2373         assert_eq!(it.indexable(), 0);
2374         assert!(it.idx(0).is_none());
2375
2376         assert!(it.next().is_none());
2377     }
2378
2379     #[test]
2380     fn test_iter_size_hints() {
2381         let mut xs = [1i, 2, 5, 10, 11];
2382         assert_eq!(xs.iter().size_hint(), (5, Some(5)));
2383         assert_eq!(xs.iter_mut().size_hint(), (5, Some(5)));
2384     }
2385
2386     #[test]
2387     fn test_iter_clone() {
2388         let xs = [1i, 2, 5];
2389         let mut it = xs.iter();
2390         it.next();
2391         let mut jt = it.clone();
2392         assert_eq!(it.next(), jt.next());
2393         assert_eq!(it.next(), jt.next());
2394         assert_eq!(it.next(), jt.next());
2395     }
2396
2397     #[test]
2398     fn test_mut_iterator() {
2399         let mut xs = [1i, 2, 3, 4, 5];
2400         for x in xs.iter_mut() {
2401             *x += 1;
2402         }
2403         assert!(xs == [2, 3, 4, 5, 6])
2404     }
2405
2406     #[test]
2407     fn test_rev_iterator() {
2408
2409         let xs = [1i, 2, 5, 10, 11];
2410         let ys = [11, 10, 5, 2, 1];
2411         let mut i = 0;
2412         for &x in xs.iter().rev() {
2413             assert_eq!(x, ys[i]);
2414             i += 1;
2415         }
2416         assert_eq!(i, 5);
2417     }
2418
2419     #[test]
2420     fn test_mut_rev_iterator() {
2421         let mut xs = [1u, 2, 3, 4, 5];
2422         for (i,x) in xs.iter_mut().rev().enumerate() {
2423             *x += i;
2424         }
2425         assert!(xs == [5, 5, 5, 5, 5])
2426     }
2427
2428     #[test]
2429     fn test_move_iterator() {
2430         let xs = vec![1u,2,3,4,5];
2431         assert_eq!(xs.into_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
2432     }
2433
2434     #[test]
2435     fn test_move_rev_iterator() {
2436         let xs = vec![1u,2,3,4,5];
2437         assert_eq!(xs.into_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
2438     }
2439
2440     #[test]
2441     fn test_splitator() {
2442         let xs = &[1i,2,3,4,5];
2443
2444         let splits: &[&[int]] = &[&[1], &[3], &[5]];
2445         assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2446                    splits);
2447         let splits: &[&[int]] = &[&[], &[2,3,4,5]];
2448         assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>(),
2449                    splits);
2450         let splits: &[&[int]] = &[&[1,2,3,4], &[]];
2451         assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(),
2452                    splits);
2453         let splits: &[&[int]] = &[&[1,2,3,4,5]];
2454         assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>(),
2455                    splits);
2456         let splits: &[&[int]] = &[&[], &[], &[], &[], &[], &[]];
2457         assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>(),
2458                    splits);
2459
2460         let xs: &[int] = &[];
2461         let splits: &[&[int]] = &[&[]];
2462         assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>(), splits);
2463     }
2464
2465     #[test]
2466     fn test_splitnator() {
2467         let xs = &[1i,2,3,4,5];
2468
2469         let splits: &[&[int]] = &[&[1,2,3,4,5]];
2470         assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2471                    splits);
2472         let splits: &[&[int]] = &[&[1], &[3,4,5]];
2473         assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2474                    splits);
2475         let splits: &[&[int]] = &[&[], &[], &[], &[4,5]];
2476         assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>(),
2477                    splits);
2478
2479         let xs: &[int] = &[];
2480         let splits: &[&[int]] = &[&[]];
2481         assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
2482     }
2483
2484     #[test]
2485     fn test_splitnator_mut() {
2486         let xs = &mut [1i,2,3,4,5];
2487
2488         let splits: &[&mut [int]] = &[&mut [1,2,3,4,5]];
2489         assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
2490                    splits);
2491         let splits: &[&mut [int]] = &[&mut [1], &mut [3,4,5]];
2492         assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<&mut [int]>>(),
2493                    splits);
2494         let splits: &[&mut [int]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
2495         assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<&mut [int]>>(),
2496                    splits);
2497
2498         let xs: &mut [int] = &mut [];
2499         let splits: &[&mut [int]] = &[&mut []];
2500         assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<&mut [int]>>(),
2501                    splits);
2502     }
2503
2504     #[test]
2505     fn test_rsplitator() {
2506         let xs = &[1i,2,3,4,5];
2507
2508         let splits: &[&[int]] = &[&[5], &[3], &[1]];
2509         assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>(),
2510                    splits);
2511         let splits: &[&[int]] = &[&[2,3,4,5], &[]];
2512         assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>(),
2513                    splits);
2514         let splits: &[&[int]] = &[&[], &[1,2,3,4]];
2515         assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(),
2516                    splits);
2517         let splits: &[&[int]] = &[&[1,2,3,4,5]];
2518         assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>(),
2519                    splits);
2520
2521         let xs: &[int] = &[];
2522         let splits: &[&[int]] = &[&[]];
2523         assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>(), splits);
2524     }
2525
2526     #[test]
2527     fn test_rsplitnator() {
2528         let xs = &[1,2,3,4,5];
2529
2530         let splits: &[&[int]] = &[&[1,2,3,4,5]];
2531         assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2532                    splits);
2533         let splits: &[&[int]] = &[&[5], &[1,2,3]];
2534         assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>(),
2535                    splits);
2536         let splits: &[&[int]] = &[&[], &[], &[], &[1,2]];
2537         assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>(),
2538                    splits);
2539
2540         let xs: &[int] = &[];
2541         let splits: &[&[int]] = &[&[]];
2542         assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>(), splits);
2543     }
2544
2545     #[test]
2546     fn test_windowsator() {
2547         let v = &[1i,2,3,4];
2548
2549         let wins: &[&[int]] = &[&[1,2], &[2,3], &[3,4]];
2550         assert_eq!(v.windows(2).collect::<Vec<&[int]>>(), wins);
2551         let wins: &[&[int]] = &[&[1i,2,3], &[2,3,4]];
2552         assert_eq!(v.windows(3).collect::<Vec<&[int]>>(), wins);
2553         assert!(v.windows(6).next().is_none());
2554     }
2555
2556     #[test]
2557     #[should_fail]
2558     fn test_windowsator_0() {
2559         let v = &[1i,2,3,4];
2560         let _it = v.windows(0);
2561     }
2562
2563     #[test]
2564     fn test_chunksator() {
2565         let v = &[1i,2,3,4,5];
2566
2567         let chunks: &[&[int]] = &[&[1i,2], &[3,4], &[5]];
2568         assert_eq!(v.chunks(2).collect::<Vec<&[int]>>(), chunks);
2569         let chunks: &[&[int]] = &[&[1i,2,3], &[4,5]];
2570         assert_eq!(v.chunks(3).collect::<Vec<&[int]>>(), chunks);
2571         let chunks: &[&[int]] = &[&[1i,2,3,4,5]];
2572         assert_eq!(v.chunks(6).collect::<Vec<&[int]>>(), chunks);
2573
2574         let chunks: &[&[int]] = &[&[5i], &[3,4], &[1,2]];
2575         assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>(), chunks);
2576         let mut it = v.chunks(2);
2577         assert_eq!(it.indexable(), 3);
2578         let chunk: &[int] = &[1,2];
2579         assert_eq!(it.idx(0).unwrap(), chunk);
2580         let chunk: &[int] = &[3,4];
2581         assert_eq!(it.idx(1).unwrap(), chunk);
2582         let chunk: &[int] = &[5];
2583         assert_eq!(it.idx(2).unwrap(), chunk);
2584         assert_eq!(it.idx(3), None);
2585     }
2586
2587     #[test]
2588     #[should_fail]
2589     fn test_chunksator_0() {
2590         let v = &[1i,2,3,4];
2591         let _it = v.chunks(0);
2592     }
2593
2594     #[test]
2595     fn test_move_from() {
2596         let mut a = [1i,2,3,4,5];
2597         let b = vec![6i,7,8];
2598         assert_eq!(a.move_from(b, 0, 3), 3);
2599         assert!(a == [6i,7,8,4,5]);
2600         let mut a = [7i,2,8,1];
2601         let b = vec![3i,1,4,1,5,9];
2602         assert_eq!(a.move_from(b, 0, 6), 4);
2603         assert!(a == [3i,1,4,1]);
2604         let mut a = [1i,2,3,4];
2605         let b = vec![5i,6,7,8,9,0];
2606         assert_eq!(a.move_from(b, 2, 3), 1);
2607         assert!(a == [7i,2,3,4]);
2608         let mut a = [1i,2,3,4,5];
2609         let b = vec![5i,6,7,8,9,0];
2610         assert_eq!(a.slice_mut(2, 4).move_from(b,1,6), 2);
2611         assert!(a == [1i,2,6,7,5]);
2612     }
2613
2614     #[test]
2615     fn test_reverse_part() {
2616         let mut values = [1i,2,3,4,5];
2617         values.slice_mut(1, 4).reverse();
2618         assert!(values == [1,4,3,2,5]);
2619     }
2620
2621     #[test]
2622     fn test_show() {
2623         macro_rules! test_show_vec(
2624             ($x:expr, $x_str:expr) => ({
2625                 let (x, x_str) = ($x, $x_str);
2626                 assert_eq!(format!("{}", x), x_str);
2627                 assert_eq!(format!("{}", x.as_slice()), x_str);
2628             })
2629         );
2630         let empty: Vec<int> = vec![];
2631         test_show_vec!(empty, "[]");
2632         test_show_vec!(vec![1i], "[1]");
2633         test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]");
2634         test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
2635                        "[[], [1], [1, 1]]");
2636
2637         let empty_mut: &mut [int] = &mut[];
2638         test_show_vec!(empty_mut, "[]");
2639         let v: &mut[int] = &mut[1];
2640         test_show_vec!(v, "[1]");
2641         let v: &mut[int] = &mut[1, 2, 3];
2642         test_show_vec!(v, "[1, 2, 3]");
2643         let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]];
2644         test_show_vec!(v, "[[], [1], [1, 1]]");
2645     }
2646
2647     #[test]
2648     fn test_vec_default() {
2649         macro_rules! t (
2650             ($ty:ty) => {{
2651                 let v: $ty = Default::default();
2652                 assert!(v.is_empty());
2653             }}
2654         );
2655
2656         t!(&[int]);
2657         t!(Vec<int>);
2658     }
2659
2660     #[test]
2661     fn test_bytes_set_memory() {
2662         use slice::bytes::MutableByteVector;
2663         let mut values = [1u8,2,3,4,5];
2664         values.slice_mut(0, 5).set_memory(0xAB);
2665         assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
2666         values.slice_mut(2, 4).set_memory(0xFF);
2667         assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
2668     }
2669
2670     #[test]
2671     #[should_fail]
2672     fn test_overflow_does_not_cause_segfault() {
2673         let mut v = vec![];
2674         v.reserve_exact(-1);
2675         v.push(1i);
2676         v.push(2);
2677     }
2678
2679     #[test]
2680     #[should_fail]
2681     fn test_overflow_does_not_cause_segfault_managed() {
2682         let mut v = vec![Rc::new(1i)];
2683         v.reserve_exact(-1);
2684         v.push(Rc::new(2i));
2685     }
2686
2687     #[test]
2688     fn test_mut_split_at() {
2689         let mut values = [1u8,2,3,4,5];
2690         {
2691             let (left, right) = values.split_at_mut(2);
2692             {
2693                 let left: &[_] = left;
2694                 assert!(left[0..left.len()] == [1, 2][]);
2695             }
2696             for p in left.iter_mut() {
2697                 *p += 1;
2698             }
2699
2700             {
2701                 let right: &[_] = right;
2702                 assert!(right[0..right.len()] == [3, 4, 5][]);
2703             }
2704             for p in right.iter_mut() {
2705                 *p += 2;
2706             }
2707         }
2708
2709         assert!(values == [2, 3, 5, 6, 7]);
2710     }
2711
2712     #[deriving(Clone, PartialEq)]
2713     struct Foo;
2714
2715     #[test]
2716     fn test_iter_zero_sized() {
2717         let mut v = vec![Foo, Foo, Foo];
2718         assert_eq!(v.len(), 3);
2719         let mut cnt = 0u;
2720
2721         for f in v.iter() {
2722             assert!(*f == Foo);
2723             cnt += 1;
2724         }
2725         assert_eq!(cnt, 3);
2726
2727         for f in v[1..3].iter() {
2728             assert!(*f == Foo);
2729             cnt += 1;
2730         }
2731         assert_eq!(cnt, 5);
2732
2733         for f in v.iter_mut() {
2734             assert!(*f == Foo);
2735             cnt += 1;
2736         }
2737         assert_eq!(cnt, 8);
2738
2739         for f in v.into_iter() {
2740             assert!(f == Foo);
2741             cnt += 1;
2742         }
2743         assert_eq!(cnt, 11);
2744
2745         let xs: [Foo; 3] = [Foo, Foo, Foo];
2746         cnt = 0;
2747         for f in xs.iter() {
2748             assert!(*f == Foo);
2749             cnt += 1;
2750         }
2751         assert!(cnt == 3);
2752     }
2753
2754     #[test]
2755     fn test_shrink_to_fit() {
2756         let mut xs = vec![0, 1, 2, 3];
2757         for i in range(4i, 100) {
2758             xs.push(i)
2759         }
2760         assert_eq!(xs.capacity(), 128);
2761         xs.shrink_to_fit();
2762         assert_eq!(xs.capacity(), 100);
2763         assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
2764     }
2765
2766     #[test]
2767     fn test_starts_with() {
2768         assert!(b"foobar".starts_with(b"foo"));
2769         assert!(!b"foobar".starts_with(b"oob"));
2770         assert!(!b"foobar".starts_with(b"bar"));
2771         assert!(!b"foo".starts_with(b"foobar"));
2772         assert!(!b"bar".starts_with(b"foobar"));
2773         assert!(b"foobar".starts_with(b"foobar"));
2774         let empty: &[u8] = &[];
2775         assert!(empty.starts_with(empty));
2776         assert!(!empty.starts_with(b"foo"));
2777         assert!(b"foobar".starts_with(empty));
2778     }
2779
2780     #[test]
2781     fn test_ends_with() {
2782         assert!(b"foobar".ends_with(b"bar"));
2783         assert!(!b"foobar".ends_with(b"oba"));
2784         assert!(!b"foobar".ends_with(b"foo"));
2785         assert!(!b"foo".ends_with(b"foobar"));
2786         assert!(!b"bar".ends_with(b"foobar"));
2787         assert!(b"foobar".ends_with(b"foobar"));
2788         let empty: &[u8] = &[];
2789         assert!(empty.ends_with(empty));
2790         assert!(!empty.ends_with(b"foo"));
2791         assert!(b"foobar".ends_with(empty));
2792     }
2793
2794     #[test]
2795     fn test_mut_splitator() {
2796         let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2797         assert_eq!(xs.split_mut(|x| *x == 0).count(), 6);
2798         for slice in xs.split_mut(|x| *x == 0) {
2799             slice.reverse();
2800         }
2801         assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2802
2803         let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2804         for slice in xs.split_mut(|x| *x == 0).take(5) {
2805             slice.reverse();
2806         }
2807         assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2808     }
2809
2810     #[test]
2811     fn test_mut_splitator_rev() {
2812         let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2813         for slice in xs.split_mut(|x| *x == 0).rev().take(4) {
2814             slice.reverse();
2815         }
2816         assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2817     }
2818
2819     #[test]
2820     fn test_get_mut() {
2821         let mut v = [0i,1,2];
2822         assert_eq!(v.get_mut(3), None);
2823         v.get_mut(1).map(|e| *e = 7);
2824         assert_eq!(v[1], 7);
2825         let mut x = 2;
2826         assert_eq!(v.get_mut(2), Some(&mut x));
2827     }
2828
2829     #[test]
2830     fn test_mut_chunks() {
2831         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2832         for (i, chunk) in v.chunks_mut(3).enumerate() {
2833             for x in chunk.iter_mut() {
2834                 *x = i as u8;
2835             }
2836         }
2837         let result = [0u8, 0, 0, 1, 1, 1, 2];
2838         assert!(v == result);
2839     }
2840
2841     #[test]
2842     fn test_mut_chunks_rev() {
2843         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2844         for (i, chunk) in v.chunks_mut(3).rev().enumerate() {
2845             for x in chunk.iter_mut() {
2846                 *x = i as u8;
2847             }
2848         }
2849         let result = [2u8, 2, 2, 1, 1, 1, 0];
2850         assert!(v == result);
2851     }
2852
2853     #[test]
2854     #[should_fail]
2855     fn test_mut_chunks_0() {
2856         let mut v = [1i, 2, 3, 4];
2857         let _it = v.chunks_mut(0);
2858     }
2859
2860     #[test]
2861     fn test_mut_last() {
2862         let mut x = [1i, 2, 3, 4, 5];
2863         let h = x.last_mut();
2864         assert_eq!(*h.unwrap(), 5);
2865
2866         let y: &mut [int] = &mut [];
2867         assert!(y.last_mut().is_none());
2868     }
2869
2870     #[test]
2871     fn test_to_vec() {
2872         let xs = box [1u, 2, 3];
2873         let ys = xs.to_vec();
2874         assert_eq!(ys, [1u, 2, 3]);
2875     }
2876 }
2877
2878 #[cfg(test)]
2879 mod bench {
2880     use prelude::*;
2881     use core::mem;
2882     use core::ptr;
2883     use std::rand::{weak_rng, Rng};
2884     use test::{Bencher, black_box};
2885
2886     #[bench]
2887     fn iterator(b: &mut Bencher) {
2888         // peculiar numbers to stop LLVM from optimising the summation
2889         // out.
2890         let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2891
2892         b.iter(|| {
2893             let mut sum = 0;
2894             for x in v.iter() {
2895                 sum += *x;
2896             }
2897             // sum == 11806, to stop dead code elimination.
2898             if sum == 0 {panic!()}
2899         })
2900     }
2901
2902     #[bench]
2903     fn mut_iterator(b: &mut Bencher) {
2904         let mut v = Vec::from_elem(100, 0i);
2905
2906         b.iter(|| {
2907             let mut i = 0i;
2908             for x in v.iter_mut() {
2909                 *x = i;
2910                 i += 1;
2911             }
2912         })
2913     }
2914
2915     #[bench]
2916     fn concat(b: &mut Bencher) {
2917         let xss: Vec<Vec<uint>> =
2918             Vec::from_fn(100, |i| range(0u, i).collect());
2919         b.iter(|| {
2920             xss.as_slice().concat();
2921         });
2922     }
2923
2924     #[bench]
2925     fn connect(b: &mut Bencher) {
2926         let xss: Vec<Vec<uint>> =
2927             Vec::from_fn(100, |i| range(0u, i).collect());
2928         b.iter(|| {
2929             xss.as_slice().connect_vec(&0)
2930         });
2931     }
2932
2933     #[bench]
2934     fn push(b: &mut Bencher) {
2935         let mut vec: Vec<uint> = vec![];
2936         b.iter(|| {
2937             vec.push(0);
2938             black_box(&vec);
2939         });
2940     }
2941
2942     #[bench]
2943     fn starts_with_same_vector(b: &mut Bencher) {
2944         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2945         b.iter(|| {
2946             vec.as_slice().starts_with(vec.as_slice())
2947         })
2948     }
2949
2950     #[bench]
2951     fn starts_with_single_element(b: &mut Bencher) {
2952         let vec: Vec<uint> = vec![0];
2953         b.iter(|| {
2954             vec.as_slice().starts_with(vec.as_slice())
2955         })
2956     }
2957
2958     #[bench]
2959     fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2960         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2961         let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2962         match_vec.push(0);
2963         b.iter(|| {
2964             vec.as_slice().starts_with(match_vec.as_slice())
2965         })
2966     }
2967
2968     #[bench]
2969     fn ends_with_same_vector(b: &mut Bencher) {
2970         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2971         b.iter(|| {
2972             vec.as_slice().ends_with(vec.as_slice())
2973         })
2974     }
2975
2976     #[bench]
2977     fn ends_with_single_element(b: &mut Bencher) {
2978         let vec: Vec<uint> = vec![0];
2979         b.iter(|| {
2980             vec.as_slice().ends_with(vec.as_slice())
2981         })
2982     }
2983
2984     #[bench]
2985     fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2986         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2987         let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2988         match_vec.as_mut_slice()[0] = 200;
2989         b.iter(|| {
2990             vec.as_slice().starts_with(match_vec.as_slice())
2991         })
2992     }
2993
2994     #[bench]
2995     fn contains_last_element(b: &mut Bencher) {
2996         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2997         b.iter(|| {
2998             vec.contains(&99u)
2999         })
3000     }
3001
3002     #[bench]
3003     fn zero_1kb_from_elem(b: &mut Bencher) {
3004         b.iter(|| {
3005             Vec::from_elem(1024, 0u8)
3006         });
3007     }
3008
3009     #[bench]
3010     fn zero_1kb_set_memory(b: &mut Bencher) {
3011         b.iter(|| {
3012             let mut v: Vec<uint> = Vec::with_capacity(1024);
3013             unsafe {
3014                 let vp = v.as_mut_ptr();
3015                 ptr::set_memory(vp, 0, 1024);
3016                 v.set_len(1024);
3017             }
3018             v
3019         });
3020     }
3021
3022     #[bench]
3023     fn zero_1kb_loop_set(b: &mut Bencher) {
3024         b.iter(|| {
3025             let mut v: Vec<uint> = Vec::with_capacity(1024);
3026             unsafe {
3027                 v.set_len(1024);
3028             }
3029             for i in range(0u, 1024) {
3030                 v[i] = 0;
3031             }
3032         });
3033     }
3034
3035     #[bench]
3036     fn zero_1kb_mut_iter(b: &mut Bencher) {
3037         b.iter(|| {
3038             let mut v = Vec::with_capacity(1024);
3039             unsafe {
3040                 v.set_len(1024);
3041             }
3042             for x in v.iter_mut() {
3043                 *x = 0i;
3044             }
3045             v
3046         });
3047     }
3048
3049     #[bench]
3050     fn random_inserts(b: &mut Bencher) {
3051         let mut rng = weak_rng();
3052         b.iter(|| {
3053                 let mut v = Vec::from_elem(30, (0u, 0u));
3054                 for _ in range(0u, 100) {
3055                     let l = v.len();
3056                     v.insert(rng.gen::<uint>() % (l + 1),
3057                              (1, 1));
3058                 }
3059             })
3060     }
3061     #[bench]
3062     fn random_removes(b: &mut Bencher) {
3063         let mut rng = weak_rng();
3064         b.iter(|| {
3065                 let mut v = Vec::from_elem(130, (0u, 0u));
3066                 for _ in range(0u, 100) {
3067                     let l = v.len();
3068                     v.remove(rng.gen::<uint>() % l);
3069                 }
3070             })
3071     }
3072
3073     #[bench]
3074     fn sort_random_small(b: &mut Bencher) {
3075         let mut rng = weak_rng();
3076         b.iter(|| {
3077             let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
3078             v.as_mut_slice().sort();
3079         });
3080         b.bytes = 5 * mem::size_of::<u64>() as u64;
3081     }
3082
3083     #[bench]
3084     fn sort_random_medium(b: &mut Bencher) {
3085         let mut rng = weak_rng();
3086         b.iter(|| {
3087             let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
3088             v.as_mut_slice().sort();
3089         });
3090         b.bytes = 100 * mem::size_of::<u64>() as u64;
3091     }
3092
3093     #[bench]
3094     fn sort_random_large(b: &mut Bencher) {
3095         let mut rng = weak_rng();
3096         b.iter(|| {
3097             let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
3098             v.as_mut_slice().sort();
3099         });
3100         b.bytes = 10000 * mem::size_of::<u64>() as u64;
3101     }
3102
3103     #[bench]
3104     fn sort_sorted(b: &mut Bencher) {
3105         let mut v = Vec::from_fn(10000, |i| i);
3106         b.iter(|| {
3107             v.sort();
3108         });
3109         b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3110     }
3111
3112     type BigSortable = (u64,u64,u64,u64);
3113
3114     #[bench]
3115     fn sort_big_random_small(b: &mut Bencher) {
3116         let mut rng = weak_rng();
3117         b.iter(|| {
3118             let mut v = rng.gen_iter::<BigSortable>().take(5)
3119                            .collect::<Vec<BigSortable>>();
3120             v.sort();
3121         });
3122         b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
3123     }
3124
3125     #[bench]
3126     fn sort_big_random_medium(b: &mut Bencher) {
3127         let mut rng = weak_rng();
3128         b.iter(|| {
3129             let mut v = rng.gen_iter::<BigSortable>().take(100)
3130                            .collect::<Vec<BigSortable>>();
3131             v.sort();
3132         });
3133         b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
3134     }
3135
3136     #[bench]
3137     fn sort_big_random_large(b: &mut Bencher) {
3138         let mut rng = weak_rng();
3139         b.iter(|| {
3140             let mut v = rng.gen_iter::<BigSortable>().take(10000)
3141                            .collect::<Vec<BigSortable>>();
3142             v.sort();
3143         });
3144         b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
3145     }
3146
3147     #[bench]
3148     fn sort_big_sorted(b: &mut Bencher) {
3149         let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
3150         b.iter(|| {
3151             v.sort();
3152         });
3153         b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3154     }
3155 }