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