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