]> git.lizzy.rs Git - rust.git/blob - src/libcollections/slice.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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[i32] = &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 //! fn main() {
56 //!     let numbers = [0, 1, 2];
57 //!     let last_numbers = &numbers[1..3];
58 //!     // last_numbers is now &[1, 2]
59 //! }
60 //! ```
61 //!
62 //! ## Implementations of other traits
63 //!
64 //! There are several implementations of common traits for slices. Some examples
65 //! include:
66 //!
67 //! * `Clone`
68 //! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
69 //! * `Hash` - for slices whose element type is `Hash`
70 //!
71 //! ## Iteration
72 //!
73 //! The method `iter()` returns an iteration value for a slice. The iterator
74 //! yields references to the slice's elements, so if the element
75 //! type of the slice is `isize`, the element type of the iterator is `&isize`.
76 //!
77 //! ```rust
78 //! let numbers = [0, 1, 2];
79 //! for &x in numbers.iter() {
80 //!     println!("{} is a number!", x);
81 //! }
82 //! ```
83 //!
84 //! * `.iter_mut()` returns an iterator that allows modifying each value.
85 //! * Further iterators exist that split, chunk or permute the slice.
86
87 #![doc(primitive = "slice")]
88 #![stable(feature = "rust1", since = "1.0.0")]
89
90 use alloc::boxed::Box;
91 use core::borrow::{BorrowFrom, BorrowFromMut, ToOwned};
92 use core::clone::Clone;
93 use core::cmp::Ordering::{self, Greater, Less};
94 use core::cmp::{self, Ord, PartialEq};
95 use core::iter::{Iterator, IteratorExt};
96 use core::iter::{range_step, MultiplicativeIterator};
97 use core::marker::Sized;
98 use core::mem::size_of;
99 use core::mem;
100 use core::ops::FnMut;
101 use core::option::Option::{self, Some, None};
102 use core::ptr::PtrExt;
103 use core::ptr;
104 use core::result::Result;
105 use core::slice as core_slice;
106 use self::Direction::*;
107
108 use vec::Vec;
109
110 pub use core::slice::{Chunks, AsSlice, Windows};
111 pub use core::slice::{Iter, IterMut};
112 pub use core::slice::{IntSliceExt, SplitMut, ChunksMut, Split};
113 pub use core::slice::{SplitN, RSplitN, SplitNMut, RSplitNMut};
114 pub use core::slice::{bytes, mut_ref_slice, ref_slice};
115 pub use core::slice::{from_raw_parts, from_raw_parts_mut};
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: usize, end: usize) -> usize;
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: usize, end: usize) -> &[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: usize) -> &[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: usize) -> &[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: usize) -> (&[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: usize, 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: usize, 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: usize) -> 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: usize) -> 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: usize) -> 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: usize) -> &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<usize, usize> 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) -> usize;
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: usize) -> 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: usize, end: usize) -> &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: usize) -> &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: usize) -> &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: usize, 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: usize, 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: usize) -> 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: usize, b: usize);
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: usize) -> (&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: usize) -> &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]) -> usize 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<usize, usize> 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<usize, usize> 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<usize> 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<usize> 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: usize, end: usize) -> usize {
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(&self, start: usize, end: usize) -> &[T] {
816         &self[start .. end]
817     }
818
819     #[inline]
820     fn slice_from(&self, start: usize) -> &[T] {
821         &self[start ..]
822     }
823
824     #[inline]
825     fn slice_to(&self, end: usize) -> &[T] {
826         &self[.. end]
827     }
828
829     #[inline]
830     fn split_at(&self, mid: usize) -> (&[T], &[T]) {
831         core_slice::SliceExt::split_at(self, mid)
832     }
833
834     #[inline]
835     fn iter(&self) -> Iter<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: usize, 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: usize, 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(&self, size: usize) -> Windows<T> {
859         core_slice::SliceExt::windows(self, size)
860     }
861
862     #[inline]
863     fn chunks(&self, size: usize) -> Chunks<T> {
864         core_slice::SliceExt::chunks(self, size)
865     }
866
867     #[inline]
868     fn get(&self, index: usize) -> Option<&T> {
869         core_slice::SliceExt::get(self, index)
870     }
871
872     #[inline]
873     fn first(&self) -> Option<&T> {
874         core_slice::SliceExt::first(self)
875     }
876
877     #[inline]
878     fn tail(&self) -> &[T] {
879         core_slice::SliceExt::tail(self)
880     }
881
882     #[inline]
883     fn init(&self) -> &[T] {
884         core_slice::SliceExt::init(self)
885     }
886
887     #[inline]
888     fn last(&self) -> Option<&T> {
889         core_slice::SliceExt::last(self)
890     }
891
892     #[inline]
893     unsafe fn get_unchecked(&self, index: usize) -> &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<usize, usize>
904                         where F: FnMut(&T) -> Ordering {
905         core_slice::SliceExt::binary_search_by(self, f)
906     }
907
908     #[inline]
909     fn len(&self) -> usize {
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(&mut self, index: usize) -> Option<&mut T> {
920         core_slice::SliceExt::get_mut(self, index)
921     }
922
923     #[inline]
924     fn as_mut_slice(&mut self) -> &mut [T] {
925         core_slice::SliceExt::as_mut_slice(self)
926     }
927
928     #[inline]
929     fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] {
930         &mut self[start .. end]
931     }
932
933     #[inline]
934     fn slice_from_mut(&mut self, start: usize) -> &mut [T] {
935         &mut self[start ..]
936     }
937
938     #[inline]
939     fn slice_to_mut(&mut self, end: usize) -> &mut [T] {
940         &mut self[.. end]
941     }
942
943     #[inline]
944     fn iter_mut(&mut self) -> IterMut<T> {
945         core_slice::SliceExt::iter_mut(self)
946     }
947
948     #[inline]
949     fn first_mut(&mut self) -> Option<&mut T> {
950         core_slice::SliceExt::first_mut(self)
951     }
952
953     #[inline]
954     fn tail_mut(&mut self) -> &mut [T] {
955         core_slice::SliceExt::tail_mut(self)
956     }
957
958     #[inline]
959     fn init_mut(&mut self) -> &mut [T] {
960         core_slice::SliceExt::init_mut(self)
961     }
962
963     #[inline]
964     fn last_mut(&mut self) -> Option<&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: usize, 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: usize, 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(&mut self, chunk_size: usize) -> ChunksMut<T> {
988         core_slice::SliceExt::chunks_mut(self, chunk_size)
989     }
990
991     #[inline]
992     fn swap(&mut self, a: usize, b: usize) {
993         core_slice::SliceExt::swap(self, a, b)
994     }
995
996     #[inline]
997     fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &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(&mut self, index: usize) -> &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]) -> usize 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<usize, usize> 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<usize> where T: PartialEq {
1054         core_slice::SliceExt::position_elem(self, t)
1055     }
1056
1057     fn rposition_elem(&self, t: &T) -> Option<usize> 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(0, |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(0, |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 : usize,
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: usize) -> 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: usize,
1204     dir: Direction,
1205 }
1206
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl Iterator for ElementSwaps {
1209     type Item = (usize, usize);
1210
1211     #[inline]
1212     fn next(&mut self) -> Option<(usize, usize)> {
1213         fn new_pos(i: usize, s: Direction) -> usize {
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().cloned().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) -> (usize, Option<usize>) {
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) -> (usize, Option<usize>) {
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 isize;
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 usize);
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: usize = 32;
1348     static LARGE_INSERTION: usize = 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 isize)};
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 isize;
1391             unsafe {
1392                 // `i` is in bounds.
1393                 let read_ptr = buf_v.offset(i as isize);
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 isize &&
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 usize);
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 isize);
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 isize);
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 isize);
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 isize);
1451                 let out_end = buf_tmp.offset(right_end_idx as isize);
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 usize - right as usize) / 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 usize - left as usize) / 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, 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: usize) -> usize { n * n }
1523
1524     fn is_odd(n: &usize) -> bool { *n % 2 == 1 }
1525
1526     #[test]
1527     fn test_from_fn() {
1528         // Test on-stack from_fn.
1529         let mut v: Vec<_> = (0..3).map(square).collect();
1530         {
1531             let v = v;
1532             assert_eq!(v.len(), 3);
1533             assert_eq!(v[0], 0);
1534             assert_eq!(v[1], 1);
1535             assert_eq!(v[2], 4);
1536         }
1537
1538         // Test on-heap from_fn.
1539         v = (0..5).map(square).collect();
1540         {
1541             let v = v;
1542             assert_eq!(v.len(), 5);
1543             assert_eq!(v[0], 0);
1544             assert_eq!(v[1], 1);
1545             assert_eq!(v[2], 4);
1546             assert_eq!(v[3], 9);
1547             assert_eq!(v[4], 16);
1548         }
1549     }
1550
1551     #[test]
1552     fn test_from_elem() {
1553         // Test on-stack from_elem.
1554         let mut v = vec![10, 10];
1555         {
1556             let v = v;
1557             assert_eq!(v.len(), 2);
1558             assert_eq!(v[0], 10);
1559             assert_eq!(v[1], 10);
1560         }
1561
1562         // Test on-heap from_elem.
1563         v = vec![20; 6];
1564         {
1565             let v = v.as_slice();
1566             assert_eq!(v[0], 20);
1567             assert_eq!(v[1], 20);
1568             assert_eq!(v[2], 20);
1569             assert_eq!(v[3], 20);
1570             assert_eq!(v[4], 20);
1571             assert_eq!(v[5], 20);
1572         }
1573     }
1574
1575     #[test]
1576     fn test_is_empty() {
1577         let xs: [i32; 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: &[i32] = &[];
1628         assert_eq!(a.tail(), b);
1629         a = vec![11, 12];
1630         let b: &[i32] = &[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 [i32] = &mut [];
1638         assert!(a.tail_mut() == b);
1639         a = vec![11, 12];
1640         let b: &mut [_] = &mut [12];
1641         assert!(a.tail_mut() == b);
1642     }
1643
1644     #[test]
1645     #[should_fail]
1646     fn test_tail_empty() {
1647         let a = Vec::<i32>::new();
1648         a.tail();
1649     }
1650
1651     #[test]
1652     #[should_fail]
1653     fn test_tail_mut_empty() {
1654         let mut a = Vec::<i32>::new();
1655         a.tail_mut();
1656     }
1657
1658     #[test]
1659     fn test_init() {
1660         let mut a = vec![11];
1661         let b: &[i32] = &[];
1662         assert_eq!(a.init(), b);
1663         a = vec![11, 12];
1664         let b: &[_] = &[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 [i32] = &mut [];
1672         assert!(a.init_mut() == b);
1673         a = vec![11, 12];
1674         let b: &mut [_] = &mut [11];
1675         assert!(a.init_mut() == b);
1676     }
1677
1678     #[test]
1679     #[should_fail]
1680     fn test_init_empty() {
1681         let a = Vec::<i32>::new();
1682         a.init();
1683     }
1684
1685     #[test]
1686     #[should_fail]
1687     fn test_init_mut_empty() {
1688         let mut a = Vec::<i32>::new();
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[1..vec_fixed.len()].to_vec();
1717         assert_eq!(v_a.len(), 3);
1718
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[1..3].to_vec();
1726         assert_eq!(v_b.len(), 2);
1727
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[1..6].to_vec();
1734         assert_eq!(v_d.len(), 5);
1735
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: &[_] = &[1, 2, 3, 4];
1746         assert_eq!(&vec[], vec);
1747         let b: &[_] = &[3, 4];
1748         assert_eq!(&vec[2..], b);
1749         let b: &[_] = &[];
1750         assert_eq!(&vec[4..], b);
1751     }
1752
1753     #[test]
1754     fn test_slice_to() {
1755         let vec: &[_] = &[1, 2, 3, 4];
1756         assert_eq!(&vec[..4], vec);
1757         let b: &[_] = &[1, 2];
1758         assert_eq!(&vec[..2], b);
1759         let b: &[_] = &[];
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(), 1);
1816         assert_eq!(v[0], 1);
1817
1818         // Test on-heap push().
1819         v.push(2);
1820         assert_eq!(v.len(), 2);
1821         assert_eq!(v[0], 1);
1822         assert_eq!(v[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;
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<i32>, b: Vec<i32>) {
1846             let mut v = a;
1847             v.dedup();
1848             assert_eq!(v, b);
1849         }
1850         case(vec![], vec![]);
1851         case(vec![1], vec![1]);
1852         case(vec![1,1], vec![1]);
1853         case(vec![1,2,3], vec![1,2,3]);
1854         case(vec![1,1,2,3], vec![1,2,3]);
1855         case(vec![1,2,2,3], vec![1,2,3]);
1856         case(vec![1,2,3,3], vec![1,2,3]);
1857         case(vec![1,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![1, 2, 3, 4, 5];
1891         v.retain(is_odd);
1892         assert_eq!(v, vec![1, 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: [i32; 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[_] = &mut[1, 2, 3, 4, 5];
1968         assert!(v.prev_permutation() == false);
1969         assert!(v.next_permutation());
1970         let b: &mut[_] = &mut[1, 2, 3, 5, 4];
1971         assert!(v == b);
1972         assert!(v.prev_permutation());
1973         let b: &mut[_] = &mut[1, 2, 3, 4, 5];
1974         assert!(v == b);
1975         assert!(v.next_permutation());
1976         assert!(v.next_permutation());
1977         let b: &mut[_] = &mut[1, 2, 4, 3, 5];
1978         assert!(v == b);
1979         assert!(v.next_permutation());
1980         let b: &mut[_] = &mut[1, 2, 4, 5, 3];
1981         assert!(v == b);
1982
1983         let v : &mut[_] = &mut[1, 0, 0, 0];
1984         assert!(v.next_permutation() == false);
1985         assert!(v.prev_permutation());
1986         let b: &mut[_] = &mut[0, 1, 0, 0];
1987         assert!(v == b);
1988         assert!(v.prev_permutation());
1989         let b: &mut[_] = &mut[0, 0, 1, 0];
1990         assert!(v == b);
1991         assert!(v.prev_permutation());
1992         let b: &mut[_] = &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[i32] = &mut[];
2000         assert!(empty.next_permutation() == false);
2001         let b: &mut[i32] = &mut[];
2002         assert!(empty == b);
2003         assert!(empty.prev_permutation() == false);
2004         assert!(empty == b);
2005
2006         let one_elem : &mut[_] = &mut[4];
2007         assert!(one_elem.prev_permutation() == false);
2008         let b: &mut[_] = &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[_] = &mut[1, 2];
2014         assert!(two_elem.prev_permutation() == false);
2015         let b : &mut[_] = &mut[1, 2];
2016         let c : &mut[_] = &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(0));
2034         assert_eq!(v1.position_elem(&2), Some(1));
2035         assert_eq!(v1.position_elem(&5), Some(5));
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![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::<i32>::new();
2094         v3.reverse();
2095         assert!(v3.is_empty());
2096     }
2097
2098     #[test]
2099     fn test_sort() {
2100         for len in 4..25 {
2101             for _ in 0..100 {
2102                 let mut v: Vec<_> = thread_rng().gen_iter::<i32>().take(len).collect();
2103                 let mut v1 = v.clone();
2104
2105                 v.sort();
2106                 assert!(v.windows(2).all(|w| w[0] <= w[1]));
2107
2108                 v1.sort_by(|a, b| a.cmp(b));
2109                 assert!(v1.windows(2).all(|w| w[0] <= w[1]));
2110
2111                 v1.sort_by(|a, b| b.cmp(a));
2112                 assert!(v1.windows(2).all(|w| w[0] >= w[1]));
2113             }
2114         }
2115
2116         // shouldn't panic
2117         let mut v: [i32; 0] = [];
2118         v.sort();
2119
2120         let mut v = [0xDEADBEEFu64];
2121         v.sort();
2122         assert!(v == [0xDEADBEEF]);
2123     }
2124
2125     #[test]
2126     fn test_sort_stability() {
2127         for len in 4..25 {
2128             for _ in 0..10 {
2129                 let mut counts = [0; 10];
2130
2131                 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
2132                 // where the first item of each tuple is random, but
2133                 // the second item represents which occurrence of that
2134                 // number this element is, i.e. the second elements
2135                 // will occur in sorted order.
2136                 let mut v: Vec<_> = (0..len).map(|_| {
2137                         let n = thread_rng().gen::<usize>() % 10;
2138                         counts[n] += 1;
2139                         (n, counts[n])
2140                     }).collect();
2141
2142                 // only sort on the first element, so an unstable sort
2143                 // may mix up the counts.
2144                 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
2145
2146                 // this comparison includes the count (the second item
2147                 // of the tuple), so elements with equal first items
2148                 // will need to be ordered with increasing
2149                 // counts... i.e. exactly asserting that this sort is
2150                 // stable.
2151                 assert!(v.windows(2).all(|w| w[0] <= w[1]));
2152             }
2153         }
2154     }
2155
2156     #[test]
2157     fn test_concat() {
2158         let v: [Vec<i32>; 0] = [];
2159         let c = v.concat();
2160         assert_eq!(c, []);
2161         let d = [vec![1], vec![2,3]].concat();
2162         assert_eq!(d, vec![1, 2, 3]);
2163
2164         let v: &[&[_]] = &[&[1], &[2, 3]];
2165         assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
2166         let v: &[&[_]] = &[&[1], &[2], &[3]];
2167         assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
2168     }
2169
2170     #[test]
2171     fn test_connect() {
2172         let v: [Vec<i32>; 0] = [];
2173         assert_eq!(v.connect(&0), vec![]);
2174         assert_eq!([vec![1], vec![2, 3]].connect(&0), vec![1, 0, 2, 3]);
2175         assert_eq!([vec![1], vec![2], vec![3]].connect(&0), vec![1, 0, 2, 0, 3]);
2176
2177         let v: [&[_]; 2] = [&[1], &[2, 3]];
2178         assert_eq!(v.connect(&0), vec![1, 0, 2, 3]);
2179         let v: [&[_]; 3] = [&[1], &[2], &[3]];
2180         assert_eq!(v.connect(&0), vec![1, 0, 2, 0, 3]);
2181     }
2182
2183     #[test]
2184     fn test_insert() {
2185         let mut a = vec![1, 2, 4];
2186         a.insert(2, 3);
2187         assert_eq!(a, vec![1, 2, 3, 4]);
2188
2189         let mut a = vec![1, 2, 3];
2190         a.insert(0, 0);
2191         assert_eq!(a, vec![0, 1, 2, 3]);
2192
2193         let mut a = vec![1, 2, 3];
2194         a.insert(3, 4);
2195         assert_eq!(a, vec![1, 2, 3, 4]);
2196
2197         let mut a = vec![];
2198         a.insert(0, 1);
2199         assert_eq!(a, vec![1]);
2200     }
2201
2202     #[test]
2203     #[should_fail]
2204     fn test_insert_oob() {
2205         let mut a = vec![1, 2, 3];
2206         a.insert(4, 5);
2207     }
2208
2209     #[test]
2210     fn test_remove() {
2211         let mut a = vec![1, 2, 3, 4];
2212
2213         assert_eq!(a.remove(2), 3);
2214         assert_eq!(a, vec![1, 2, 4]);
2215
2216         assert_eq!(a.remove(2), 4);
2217         assert_eq!(a, vec![1, 2]);
2218
2219         assert_eq!(a.remove(0), 1);
2220         assert_eq!(a, vec![2]);
2221
2222         assert_eq!(a.remove(0), 2);
2223         assert_eq!(a, vec![]);
2224     }
2225
2226     #[test]
2227     #[should_fail]
2228     fn test_remove_fail() {
2229         let mut a = vec![1];
2230         let _ = a.remove(0);
2231         let _ = a.remove(0);
2232     }
2233
2234     #[test]
2235     fn test_capacity() {
2236         let mut v = vec![0];
2237         v.reserve_exact(10);
2238         assert!(v.capacity() >= 11);
2239     }
2240
2241     #[test]
2242     fn test_slice_2() {
2243         let v = vec![1, 2, 3, 4, 5];
2244         let v = v.slice(1, 3);
2245         assert_eq!(v.len(), 2);
2246         assert_eq!(v[0], 2);
2247         assert_eq!(v[1], 3);
2248     }
2249
2250     #[test]
2251     #[should_fail]
2252     fn test_permute_fail() {
2253         let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
2254                  (box 0, Rc::new(0)), (box 0, Rc::new(0))];
2255         let mut i = 0;
2256         for _ in v.permutations() {
2257             if i == 2 {
2258                 panic!()
2259             }
2260             i += 1;
2261         }
2262     }
2263
2264     #[test]
2265     fn test_total_ord() {
2266         let c = &[1, 2, 3];
2267         [1, 2, 3, 4][].cmp(c) == Greater;
2268         let c = &[1, 2, 3, 4];
2269         [1, 2, 3][].cmp(c) == Less;
2270         let c = &[1, 2, 3, 6];
2271         [1, 2, 3, 4][].cmp(c) == Equal;
2272         let c = &[1, 2, 3, 4, 5, 6];
2273         [1, 2, 3, 4, 5, 5, 5, 5][].cmp(c) == Less;
2274         let c = &[1, 2, 3, 4];
2275         [2, 2][].cmp(c) == Greater;
2276     }
2277
2278     #[test]
2279     fn test_iterator() {
2280         let xs = [1, 2, 5, 10, 11];
2281         let mut it = xs.iter();
2282         assert_eq!(it.size_hint(), (5, Some(5)));
2283         assert_eq!(it.next().unwrap(), &1);
2284         assert_eq!(it.size_hint(), (4, Some(4)));
2285         assert_eq!(it.next().unwrap(), &2);
2286         assert_eq!(it.size_hint(), (3, Some(3)));
2287         assert_eq!(it.next().unwrap(), &5);
2288         assert_eq!(it.size_hint(), (2, Some(2)));
2289         assert_eq!(it.next().unwrap(), &10);
2290         assert_eq!(it.size_hint(), (1, Some(1)));
2291         assert_eq!(it.next().unwrap(), &11);
2292         assert_eq!(it.size_hint(), (0, Some(0)));
2293         assert!(it.next().is_none());
2294     }
2295
2296     #[test]
2297     fn test_random_access_iterator() {
2298         let xs = [1, 2, 5, 10, 11];
2299         let mut it = xs.iter();
2300
2301         assert_eq!(it.indexable(), 5);
2302         assert_eq!(it.idx(0).unwrap(), &1);
2303         assert_eq!(it.idx(2).unwrap(), &5);
2304         assert_eq!(it.idx(4).unwrap(), &11);
2305         assert!(it.idx(5).is_none());
2306
2307         assert_eq!(it.next().unwrap(), &1);
2308         assert_eq!(it.indexable(), 4);
2309         assert_eq!(it.idx(0).unwrap(), &2);
2310         assert_eq!(it.idx(3).unwrap(), &11);
2311         assert!(it.idx(4).is_none());
2312
2313         assert_eq!(it.next().unwrap(), &2);
2314         assert_eq!(it.indexable(), 3);
2315         assert_eq!(it.idx(1).unwrap(), &10);
2316         assert!(it.idx(3).is_none());
2317
2318         assert_eq!(it.next().unwrap(), &5);
2319         assert_eq!(it.indexable(), 2);
2320         assert_eq!(it.idx(1).unwrap(), &11);
2321
2322         assert_eq!(it.next().unwrap(), &10);
2323         assert_eq!(it.indexable(), 1);
2324         assert_eq!(it.idx(0).unwrap(), &11);
2325         assert!(it.idx(1).is_none());
2326
2327         assert_eq!(it.next().unwrap(), &11);
2328         assert_eq!(it.indexable(), 0);
2329         assert!(it.idx(0).is_none());
2330
2331         assert!(it.next().is_none());
2332     }
2333
2334     #[test]
2335     fn test_iter_size_hints() {
2336         let mut xs = [1, 2, 5, 10, 11];
2337         assert_eq!(xs.iter().size_hint(), (5, Some(5)));
2338         assert_eq!(xs.iter_mut().size_hint(), (5, Some(5)));
2339     }
2340
2341     #[test]
2342     fn test_iter_clone() {
2343         let xs = [1, 2, 5];
2344         let mut it = xs.iter();
2345         it.next();
2346         let mut jt = it.clone();
2347         assert_eq!(it.next(), jt.next());
2348         assert_eq!(it.next(), jt.next());
2349         assert_eq!(it.next(), jt.next());
2350     }
2351
2352     #[test]
2353     fn test_mut_iterator() {
2354         let mut xs = [1, 2, 3, 4, 5];
2355         for x in &mut xs {
2356             *x += 1;
2357         }
2358         assert!(xs == [2, 3, 4, 5, 6])
2359     }
2360
2361     #[test]
2362     fn test_rev_iterator() {
2363
2364         let xs = [1, 2, 5, 10, 11];
2365         let ys = [11, 10, 5, 2, 1];
2366         let mut i = 0;
2367         for &x in xs.iter().rev() {
2368             assert_eq!(x, ys[i]);
2369             i += 1;
2370         }
2371         assert_eq!(i, 5);
2372     }
2373
2374     #[test]
2375     fn test_mut_rev_iterator() {
2376         let mut xs = [1, 2, 3, 4, 5];
2377         for (i,x) in xs.iter_mut().rev().enumerate() {
2378             *x += i;
2379         }
2380         assert!(xs == [5, 5, 5, 5, 5])
2381     }
2382
2383     #[test]
2384     fn test_move_iterator() {
2385         let xs = vec![1,2,3,4,5];
2386         assert_eq!(xs.into_iter().fold(0, |a: usize, b: usize| 10*a + b), 12345);
2387     }
2388
2389     #[test]
2390     fn test_move_rev_iterator() {
2391         let xs = vec![1,2,3,4,5];
2392         assert_eq!(xs.into_iter().rev().fold(0, |a: usize, b: usize| 10*a + b), 54321);
2393     }
2394
2395     #[test]
2396     fn test_splitator() {
2397         let xs = &[1,2,3,4,5];
2398
2399         let splits: &[&[_]] = &[&[1], &[3], &[5]];
2400         assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<_>>(),
2401                    splits);
2402         let splits: &[&[_]] = &[&[], &[2,3,4,5]];
2403         assert_eq!(xs.split(|x| *x == 1).collect::<Vec<_>>(),
2404                    splits);
2405         let splits: &[&[_]] = &[&[1,2,3,4], &[]];
2406         assert_eq!(xs.split(|x| *x == 5).collect::<Vec<_>>(),
2407                    splits);
2408         let splits: &[&[_]] = &[&[1,2,3,4,5]];
2409         assert_eq!(xs.split(|x| *x == 10).collect::<Vec<_>>(),
2410                    splits);
2411         let splits: &[&[_]] = &[&[], &[], &[], &[], &[], &[]];
2412         assert_eq!(xs.split(|_| true).collect::<Vec<&[i32]>>(),
2413                    splits);
2414
2415         let xs: &[i32] = &[];
2416         let splits: &[&[i32]] = &[&[]];
2417         assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[i32]>>(), splits);
2418     }
2419
2420     #[test]
2421     fn test_splitnator() {
2422         let xs = &[1,2,3,4,5];
2423
2424         let splits: &[&[_]] = &[&[1,2,3,4,5]];
2425         assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2426                    splits);
2427         let splits: &[&[_]] = &[&[1], &[3,4,5]];
2428         assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2429                    splits);
2430         let splits: &[&[_]] = &[&[], &[], &[], &[4,5]];
2431         assert_eq!(xs.splitn(3, |_| true).collect::<Vec<_>>(),
2432                    splits);
2433
2434         let xs: &[i32] = &[];
2435         let splits: &[&[i32]] = &[&[]];
2436         assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<_>>(), splits);
2437     }
2438
2439     #[test]
2440     fn test_splitnator_mut() {
2441         let xs = &mut [1,2,3,4,5];
2442
2443         let splits: &[&mut[_]] = &[&mut [1,2,3,4,5]];
2444         assert_eq!(xs.splitn_mut(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2445                    splits);
2446         let splits: &[&mut[_]] = &[&mut [1], &mut [3,4,5]];
2447         assert_eq!(xs.splitn_mut(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2448                    splits);
2449         let splits: &[&mut[_]] = &[&mut [], &mut [], &mut [], &mut [4,5]];
2450         assert_eq!(xs.splitn_mut(3, |_| true).collect::<Vec<_>>(),
2451                    splits);
2452
2453         let xs: &mut [i32] = &mut [];
2454         let splits: &[&mut[i32]] = &[&mut []];
2455         assert_eq!(xs.splitn_mut(1, |x| *x == 5).collect::<Vec<_>>(),
2456                    splits);
2457     }
2458
2459     #[test]
2460     fn test_rsplitator() {
2461         let xs = &[1,2,3,4,5];
2462
2463         let splits: &[&[_]] = &[&[5], &[3], &[1]];
2464         assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<_>>(),
2465                    splits);
2466         let splits: &[&[_]] = &[&[2,3,4,5], &[]];
2467         assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<_>>(),
2468                    splits);
2469         let splits: &[&[_]] = &[&[], &[1,2,3,4]];
2470         assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<_>>(),
2471                    splits);
2472         let splits: &[&[_]] = &[&[1,2,3,4,5]];
2473         assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<_>>(),
2474                    splits);
2475
2476         let xs: &[i32] = &[];
2477         let splits: &[&[i32]] = &[&[]];
2478         assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[i32]>>(), splits);
2479     }
2480
2481     #[test]
2482     fn test_rsplitnator() {
2483         let xs = &[1,2,3,4,5];
2484
2485         let splits: &[&[_]] = &[&[1,2,3,4,5]];
2486         assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<_>>(),
2487                    splits);
2488         let splits: &[&[_]] = &[&[5], &[1,2,3]];
2489         assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<_>>(),
2490                    splits);
2491         let splits: &[&[_]] = &[&[], &[], &[], &[1,2]];
2492         assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<_>>(),
2493                    splits);
2494
2495         let xs: &[i32]  = &[];
2496         let splits: &[&[i32]] = &[&[]];
2497         assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[i32]>>(), splits);
2498     }
2499
2500     #[test]
2501     fn test_windowsator() {
2502         let v = &[1,2,3,4];
2503
2504         let wins: &[&[_]] = &[&[1,2], &[2,3], &[3,4]];
2505         assert_eq!(v.windows(2).collect::<Vec<_>>(), wins);
2506
2507         let wins: &[&[_]] = &[&[1,2,3], &[2,3,4]];
2508         assert_eq!(v.windows(3).collect::<Vec<_>>(), wins);
2509         assert!(v.windows(6).next().is_none());
2510
2511         let wins: &[&[_]] = &[&[3,4], &[2,3], &[1,2]];
2512         assert_eq!(v.windows(2).rev().collect::<Vec<&[_]>>(), wins);
2513         let mut it = v.windows(2);
2514         assert_eq!(it.indexable(), 3);
2515         let win: &[_] = &[1,2];
2516         assert_eq!(it.idx(0).unwrap(), win);
2517         let win: &[_] = &[2,3];
2518         assert_eq!(it.idx(1).unwrap(), win);
2519         let win: &[_] = &[3,4];
2520         assert_eq!(it.idx(2).unwrap(), win);
2521         assert_eq!(it.idx(3), None);
2522     }
2523
2524     #[test]
2525     #[should_fail]
2526     fn test_windowsator_0() {
2527         let v = &[1,2,3,4];
2528         let _it = v.windows(0);
2529     }
2530
2531     #[test]
2532     fn test_chunksator() {
2533         use core::iter::ExactSizeIterator;
2534
2535         let v = &[1,2,3,4,5];
2536
2537         assert_eq!(v.chunks(2).len(), 3);
2538
2539         let chunks: &[&[_]] = &[&[1,2], &[3,4], &[5]];
2540         assert_eq!(v.chunks(2).collect::<Vec<_>>(), chunks);
2541         let chunks: &[&[_]] = &[&[1,2,3], &[4,5]];
2542         assert_eq!(v.chunks(3).collect::<Vec<_>>(), chunks);
2543         let chunks: &[&[_]] = &[&[1,2,3,4,5]];
2544         assert_eq!(v.chunks(6).collect::<Vec<_>>(), chunks);
2545
2546         let chunks: &[&[_]] = &[&[5], &[3,4], &[1,2]];
2547         assert_eq!(v.chunks(2).rev().collect::<Vec<_>>(), chunks);
2548         let mut it = v.chunks(2);
2549         assert_eq!(it.indexable(), 3);
2550
2551         let chunk: &[_] = &[1,2];
2552         assert_eq!(it.idx(0).unwrap(), chunk);
2553         let chunk: &[_] = &[3,4];
2554         assert_eq!(it.idx(1).unwrap(), chunk);
2555         let chunk: &[_] = &[5];
2556         assert_eq!(it.idx(2).unwrap(), chunk);
2557         assert_eq!(it.idx(3), None);
2558     }
2559
2560     #[test]
2561     #[should_fail]
2562     fn test_chunksator_0() {
2563         let v = &[1,2,3,4];
2564         let _it = v.chunks(0);
2565     }
2566
2567     #[test]
2568     fn test_move_from() {
2569         let mut a = [1,2,3,4,5];
2570         let b = vec![6,7,8];
2571         assert_eq!(a.move_from(b, 0, 3), 3);
2572         assert!(a == [6,7,8,4,5]);
2573         let mut a = [7,2,8,1];
2574         let b = vec![3,1,4,1,5,9];
2575         assert_eq!(a.move_from(b, 0, 6), 4);
2576         assert!(a == [3,1,4,1]);
2577         let mut a = [1,2,3,4];
2578         let b = vec![5,6,7,8,9,0];
2579         assert_eq!(a.move_from(b, 2, 3), 1);
2580         assert!(a == [7,2,3,4]);
2581         let mut a = [1,2,3,4,5];
2582         let b = vec![5,6,7,8,9,0];
2583         assert_eq!(a[2..4].move_from(b,1,6), 2);
2584         assert!(a == [1,2,6,7,5]);
2585     }
2586
2587     #[test]
2588     fn test_reverse_part() {
2589         let mut values = [1,2,3,4,5];
2590         values[1..4].reverse();
2591         assert!(values == [1,4,3,2,5]);
2592     }
2593
2594     #[test]
2595     fn test_show() {
2596         macro_rules! test_show_vec {
2597             ($x:expr, $x_str:expr) => ({
2598                 let (x, x_str) = ($x, $x_str);
2599                 assert_eq!(format!("{:?}", x), x_str);
2600                 assert_eq!(format!("{:?}", x), x_str);
2601             })
2602         }
2603         let empty = Vec::<i32>::new();
2604         test_show_vec!(empty, "[]");
2605         test_show_vec!(vec![1], "[1]");
2606         test_show_vec!(vec![1, 2, 3], "[1, 2, 3]");
2607         test_show_vec!(vec![vec![], vec![1], vec![1, 1]],
2608                        "[[], [1], [1, 1]]");
2609
2610         let empty_mut: &mut [i32] = &mut[];
2611         test_show_vec!(empty_mut, "[]");
2612         let v = &mut[1];
2613         test_show_vec!(v, "[1]");
2614         let v = &mut[1, 2, 3];
2615         test_show_vec!(v, "[1, 2, 3]");
2616         let v: &mut[&mut[_]] = &mut[&mut[], &mut[1], &mut[1, 1]];
2617         test_show_vec!(v, "[[], [1], [1, 1]]");
2618     }
2619
2620     #[test]
2621     fn test_vec_default() {
2622         macro_rules! t {
2623             ($ty:ty) => {{
2624                 let v: $ty = Default::default();
2625                 assert!(v.is_empty());
2626             }}
2627         }
2628
2629         t!(&[i32]);
2630         t!(Vec<i32>);
2631     }
2632
2633     #[test]
2634     fn test_bytes_set_memory() {
2635         use slice::bytes::MutableByteVector;
2636         let mut values = [1u8,2,3,4,5];
2637         values[0..5].set_memory(0xAB);
2638         assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
2639         values[2..4].set_memory(0xFF);
2640         assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
2641     }
2642
2643     #[test]
2644     #[should_fail]
2645     fn test_overflow_does_not_cause_segfault() {
2646         let mut v = vec![];
2647         v.reserve_exact(-1);
2648         v.push(1);
2649         v.push(2);
2650     }
2651
2652     #[test]
2653     #[should_fail]
2654     fn test_overflow_does_not_cause_segfault_managed() {
2655         let mut v = vec![Rc::new(1)];
2656         v.reserve_exact(-1);
2657         v.push(Rc::new(2));
2658     }
2659
2660     #[test]
2661     fn test_mut_split_at() {
2662         let mut values = [1u8,2,3,4,5];
2663         {
2664             let (left, right) = values.split_at_mut(2);
2665             {
2666                 let left: &[_] = left;
2667                 assert!(left[..left.len()] == [1, 2][]);
2668             }
2669             for p in left {
2670                 *p += 1;
2671             }
2672
2673             {
2674                 let right: &[_] = right;
2675                 assert!(right[..right.len()] == [3, 4, 5][]);
2676             }
2677             for p in right {
2678                 *p += 2;
2679             }
2680         }
2681
2682         assert!(values == [2, 3, 5, 6, 7]);
2683     }
2684
2685     #[derive(Clone, PartialEq)]
2686     struct Foo;
2687
2688     #[test]
2689     fn test_iter_zero_sized() {
2690         let mut v = vec![Foo, Foo, Foo];
2691         assert_eq!(v.len(), 3);
2692         let mut cnt = 0;
2693
2694         for f in &v {
2695             assert!(*f == Foo);
2696             cnt += 1;
2697         }
2698         assert_eq!(cnt, 3);
2699
2700         for f in &v[1..3] {
2701             assert!(*f == Foo);
2702             cnt += 1;
2703         }
2704         assert_eq!(cnt, 5);
2705
2706         for f in &mut v {
2707             assert!(*f == Foo);
2708             cnt += 1;
2709         }
2710         assert_eq!(cnt, 8);
2711
2712         for f in v {
2713             assert!(f == Foo);
2714             cnt += 1;
2715         }
2716         assert_eq!(cnt, 11);
2717
2718         let xs: [Foo; 3] = [Foo, Foo, Foo];
2719         cnt = 0;
2720         for f in &xs {
2721             assert!(*f == Foo);
2722             cnt += 1;
2723         }
2724         assert!(cnt == 3);
2725     }
2726
2727     #[test]
2728     fn test_shrink_to_fit() {
2729         let mut xs = vec![0, 1, 2, 3];
2730         for i in 4..100 {
2731             xs.push(i)
2732         }
2733         assert_eq!(xs.capacity(), 128);
2734         xs.shrink_to_fit();
2735         assert_eq!(xs.capacity(), 100);
2736         assert_eq!(xs, (0..100).collect::<Vec<_>>());
2737     }
2738
2739     #[test]
2740     fn test_starts_with() {
2741         assert!(b"foobar".starts_with(b"foo"));
2742         assert!(!b"foobar".starts_with(b"oob"));
2743         assert!(!b"foobar".starts_with(b"bar"));
2744         assert!(!b"foo".starts_with(b"foobar"));
2745         assert!(!b"bar".starts_with(b"foobar"));
2746         assert!(b"foobar".starts_with(b"foobar"));
2747         let empty: &[u8] = &[];
2748         assert!(empty.starts_with(empty));
2749         assert!(!empty.starts_with(b"foo"));
2750         assert!(b"foobar".starts_with(empty));
2751     }
2752
2753     #[test]
2754     fn test_ends_with() {
2755         assert!(b"foobar".ends_with(b"bar"));
2756         assert!(!b"foobar".ends_with(b"oba"));
2757         assert!(!b"foobar".ends_with(b"foo"));
2758         assert!(!b"foo".ends_with(b"foobar"));
2759         assert!(!b"bar".ends_with(b"foobar"));
2760         assert!(b"foobar".ends_with(b"foobar"));
2761         let empty: &[u8] = &[];
2762         assert!(empty.ends_with(empty));
2763         assert!(!empty.ends_with(b"foo"));
2764         assert!(b"foobar".ends_with(empty));
2765     }
2766
2767     #[test]
2768     fn test_mut_splitator() {
2769         let mut xs = [0,1,0,2,3,0,0,4,5,0];
2770         assert_eq!(xs.split_mut(|x| *x == 0).count(), 6);
2771         for slice in xs.split_mut(|x| *x == 0) {
2772             slice.reverse();
2773         }
2774         assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2775
2776         let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
2777         for slice in xs.split_mut(|x| *x == 0).take(5) {
2778             slice.reverse();
2779         }
2780         assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2781     }
2782
2783     #[test]
2784     fn test_mut_splitator_rev() {
2785         let mut xs = [1,2,0,3,4,0,0,5,6,0];
2786         for slice in xs.split_mut(|x| *x == 0).rev().take(4) {
2787             slice.reverse();
2788         }
2789         assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2790     }
2791
2792     #[test]
2793     fn test_get_mut() {
2794         let mut v = [0,1,2];
2795         assert_eq!(v.get_mut(3), None);
2796         v.get_mut(1).map(|e| *e = 7);
2797         assert_eq!(v[1], 7);
2798         let mut x = 2;
2799         assert_eq!(v.get_mut(2), Some(&mut x));
2800     }
2801
2802     #[test]
2803     fn test_mut_chunks() {
2804         use core::iter::ExactSizeIterator;
2805
2806         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2807         assert_eq!(v.chunks_mut(2).len(), 4);
2808         for (i, chunk) in v.chunks_mut(3).enumerate() {
2809             for x in chunk {
2810                 *x = i as u8;
2811             }
2812         }
2813         let result = [0u8, 0, 0, 1, 1, 1, 2];
2814         assert!(v == result);
2815     }
2816
2817     #[test]
2818     fn test_mut_chunks_rev() {
2819         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2820         for (i, chunk) in v.chunks_mut(3).rev().enumerate() {
2821             for x in chunk {
2822                 *x = i as u8;
2823             }
2824         }
2825         let result = [2u8, 2, 2, 1, 1, 1, 0];
2826         assert!(v == result);
2827     }
2828
2829     #[test]
2830     #[should_fail]
2831     fn test_mut_chunks_0() {
2832         let mut v = [1, 2, 3, 4];
2833         let _it = v.chunks_mut(0);
2834     }
2835
2836     #[test]
2837     fn test_mut_last() {
2838         let mut x = [1, 2, 3, 4, 5];
2839         let h = x.last_mut();
2840         assert_eq!(*h.unwrap(), 5);
2841
2842         let y: &mut [i32] = &mut [];
2843         assert!(y.last_mut().is_none());
2844     }
2845
2846     #[test]
2847     fn test_to_vec() {
2848         let xs = box [1, 2, 3];
2849         let ys = xs.to_vec();
2850         assert_eq!(ys, [1, 2, 3]);
2851     }
2852 }
2853
2854 #[cfg(test)]
2855 mod bench {
2856     use prelude::*;
2857     use core::mem;
2858     use core::ptr;
2859     use core::iter::repeat;
2860     use std::rand::{weak_rng, Rng};
2861     use test::{Bencher, black_box};
2862
2863     #[bench]
2864     fn iterator(b: &mut Bencher) {
2865         // peculiar numbers to stop LLVM from optimising the summation
2866         // out.
2867         let v: Vec<_> = (0..100).map(|i| i ^ (i << 1) ^ (i >> 1)).collect();
2868
2869         b.iter(|| {
2870             let mut sum = 0;
2871             for x in &v {
2872                 sum += *x;
2873             }
2874             // sum == 11806, to stop dead code elimination.
2875             if sum == 0 {panic!()}
2876         })
2877     }
2878
2879     #[bench]
2880     fn mut_iterator(b: &mut Bencher) {
2881         let mut v: Vec<_> = repeat(0).take(100).collect();
2882
2883         b.iter(|| {
2884             let mut i = 0;
2885             for x in &mut v {
2886                 *x = i;
2887                 i += 1;
2888             }
2889         })
2890     }
2891
2892     #[bench]
2893     fn concat(b: &mut Bencher) {
2894         let xss: Vec<Vec<i32>> =
2895             (0..100).map(|i| (0..i).collect()).collect();
2896         b.iter(|| {
2897             xss.concat();
2898         });
2899     }
2900
2901     #[bench]
2902     fn connect(b: &mut Bencher) {
2903         let xss: Vec<Vec<i32>> =
2904             (0..100).map(|i| (0..i).collect()).collect();
2905         b.iter(|| {
2906             xss.connect(&0)
2907         });
2908     }
2909
2910     #[bench]
2911     fn push(b: &mut Bencher) {
2912         let mut vec = Vec::<i32>::new();
2913         b.iter(|| {
2914             vec.push(0);
2915             black_box(&vec);
2916         });
2917     }
2918
2919     #[bench]
2920     fn starts_with_same_vector(b: &mut Bencher) {
2921         let vec: Vec<_> = (0..100).collect();
2922         b.iter(|| {
2923             vec.starts_with(&vec)
2924         })
2925     }
2926
2927     #[bench]
2928     fn starts_with_single_element(b: &mut Bencher) {
2929         let vec: Vec<_> = vec![0];
2930         b.iter(|| {
2931             vec.starts_with(&vec)
2932         })
2933     }
2934
2935     #[bench]
2936     fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2937         let vec: Vec<_> = (0..100).collect();
2938         let mut match_vec: Vec<_> = (0..99).collect();
2939         match_vec.push(0);
2940         b.iter(|| {
2941             vec.starts_with(&match_vec)
2942         })
2943     }
2944
2945     #[bench]
2946     fn ends_with_same_vector(b: &mut Bencher) {
2947         let vec: Vec<_> = (0..100).collect();
2948         b.iter(|| {
2949             vec.ends_with(&vec)
2950         })
2951     }
2952
2953     #[bench]
2954     fn ends_with_single_element(b: &mut Bencher) {
2955         let vec: Vec<_> = vec![0];
2956         b.iter(|| {
2957             vec.ends_with(&vec)
2958         })
2959     }
2960
2961     #[bench]
2962     fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2963         let vec: Vec<_> = (0..100).collect();
2964         let mut match_vec: Vec<_> = (0..100).collect();
2965         match_vec[0] = 200;
2966         b.iter(|| {
2967             vec.starts_with(&match_vec)
2968         })
2969     }
2970
2971     #[bench]
2972     fn contains_last_element(b: &mut Bencher) {
2973         let vec: Vec<_> = (0..100).collect();
2974         b.iter(|| {
2975             vec.contains(&99)
2976         })
2977     }
2978
2979     #[bench]
2980     fn zero_1kb_from_elem(b: &mut Bencher) {
2981         b.iter(|| {
2982             repeat(0u8).take(1024).collect::<Vec<_>>()
2983         });
2984     }
2985
2986     #[bench]
2987     fn zero_1kb_set_memory(b: &mut Bencher) {
2988         b.iter(|| {
2989             let mut v = Vec::<u8>::with_capacity(1024);
2990             unsafe {
2991                 let vp = v.as_mut_ptr();
2992                 ptr::set_memory(vp, 0, 1024);
2993                 v.set_len(1024);
2994             }
2995             v
2996         });
2997     }
2998
2999     #[bench]
3000     fn zero_1kb_loop_set(b: &mut Bencher) {
3001         b.iter(|| {
3002             let mut v = Vec::<u8>::with_capacity(1024);
3003             unsafe {
3004                 v.set_len(1024);
3005             }
3006             for i in 0..1024 {
3007                 v[i] = 0;
3008             }
3009         });
3010     }
3011
3012     #[bench]
3013     fn zero_1kb_mut_iter(b: &mut Bencher) {
3014         b.iter(|| {
3015             let mut v = Vec::<u8>::with_capacity(1024);
3016             unsafe {
3017                 v.set_len(1024);
3018             }
3019             for x in &mut v {
3020                 *x = 0;
3021             }
3022             v
3023         });
3024     }
3025
3026     #[bench]
3027     fn random_inserts(b: &mut Bencher) {
3028         let mut rng = weak_rng();
3029         b.iter(|| {
3030             let mut v: Vec<_> = repeat((0, 0)).take(30).collect();
3031             for _ in 0..100 {
3032                 let l = v.len();
3033                 v.insert(rng.gen::<usize>() % (l + 1),
3034                          (1, 1));
3035             }
3036         })
3037     }
3038     #[bench]
3039     fn random_removes(b: &mut Bencher) {
3040         let mut rng = weak_rng();
3041         b.iter(|| {
3042             let mut v: Vec<_> = repeat((0, 0)).take(130).collect();
3043             for _ in 0..100 {
3044                 let l = v.len();
3045                 v.remove(rng.gen::<usize>() % l);
3046             }
3047         })
3048     }
3049
3050     #[bench]
3051     fn sort_random_small(b: &mut Bencher) {
3052         let mut rng = weak_rng();
3053         b.iter(|| {
3054             let mut v: Vec<_> = rng.gen_iter::<u64>().take(5).collect();
3055             v.sort();
3056         });
3057         b.bytes = 5 * mem::size_of::<u64>() as u64;
3058     }
3059
3060     #[bench]
3061     fn sort_random_medium(b: &mut Bencher) {
3062         let mut rng = weak_rng();
3063         b.iter(|| {
3064             let mut v: Vec<_> = rng.gen_iter::<u64>().take(100).collect();
3065             v.sort();
3066         });
3067         b.bytes = 100 * mem::size_of::<u64>() as u64;
3068     }
3069
3070     #[bench]
3071     fn sort_random_large(b: &mut Bencher) {
3072         let mut rng = weak_rng();
3073         b.iter(|| {
3074             let mut v: Vec<_> = rng.gen_iter::<u64>().take(10000).collect();
3075             v.sort();
3076         });
3077         b.bytes = 10000 * mem::size_of::<u64>() as u64;
3078     }
3079
3080     #[bench]
3081     fn sort_sorted(b: &mut Bencher) {
3082         let mut v: Vec<_> = (0..10000).collect();
3083         b.iter(|| {
3084             v.sort();
3085         });
3086         b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3087     }
3088
3089     type BigSortable = (u64, u64, u64, u64);
3090
3091     #[bench]
3092     fn sort_big_random_small(b: &mut Bencher) {
3093         let mut rng = weak_rng();
3094         b.iter(|| {
3095             let mut v = rng.gen_iter::<BigSortable>().take(5)
3096                            .collect::<Vec<BigSortable>>();
3097             v.sort();
3098         });
3099         b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
3100     }
3101
3102     #[bench]
3103     fn sort_big_random_medium(b: &mut Bencher) {
3104         let mut rng = weak_rng();
3105         b.iter(|| {
3106             let mut v = rng.gen_iter::<BigSortable>().take(100)
3107                            .collect::<Vec<BigSortable>>();
3108             v.sort();
3109         });
3110         b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
3111     }
3112
3113     #[bench]
3114     fn sort_big_random_large(b: &mut Bencher) {
3115         let mut rng = weak_rng();
3116         b.iter(|| {
3117             let mut v = rng.gen_iter::<BigSortable>().take(10000)
3118                            .collect::<Vec<BigSortable>>();
3119             v.sort();
3120         });
3121         b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
3122     }
3123
3124     #[bench]
3125     fn sort_big_sorted(b: &mut Bencher) {
3126         let mut v: Vec<BigSortable> = (0..10000).map(|i| (i, i, i, i)).collect();
3127         b.iter(|| {
3128             v.sort();
3129         });
3130         b.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
3131     }
3132 }