]> git.lizzy.rs Git - rust.git/blob - src/libstd/slice.rs
core: Inherit non-allocating slice functionality
[rust.git] / src / libstd / slice.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /*!
12
13 Utilities for vector manipulation
14
15 The `vec` module contains useful code to help work with vector values.
16 Vectors are Rust's list type. Vectors contain zero or more values of
17 homogeneous types:
18
19 ```rust
20 let int_vector = [1,2,3];
21 let str_vector = ["one", "two", "three"];
22 ```
23
24 This is a big module, but for a high-level overview:
25
26 ## Structs
27
28 Several structs that are useful for vectors, such as `Items`, which
29 represents iteration over a vector.
30
31 ## Traits
32
33 A number of traits add methods that allow you to accomplish tasks with vectors.
34
35 Traits defined for the `&[T]` type (a vector slice), have methods that can be
36 called on either owned vectors, denoted `~[T]`, or on vector slices themselves.
37 These traits include `ImmutableVector`, and `MutableVector` for the `&mut [T]`
38 case.
39
40 An example is the method `.slice(a, b)` that returns an immutable "view" into
41 a vector or a vector slice from the index interval `[a, b)`:
42
43 ```rust
44 let numbers = [0, 1, 2];
45 let last_numbers = numbers.slice(1, 3);
46 // last_numbers is now &[1, 2]
47 ```
48
49 Traits defined for the `~[T]` type, like `OwnedVector`, can only be called
50 on such vectors. These methods deal with adding elements or otherwise changing
51 the allocation of the vector.
52
53 An example is the method `.push(element)` that will add an element at the end
54 of the vector:
55
56 ```rust
57 let mut numbers = vec![0, 1, 2];
58 numbers.push(7);
59 // numbers is now vec![0, 1, 2, 7];
60 ```
61
62 ## Implementations of other traits
63
64 Vectors are a very useful type, and so there's several implementations of
65 traits from other modules. Some notable examples:
66
67 * `Clone`
68 * `Eq`, `Ord`, `TotalEq`, `TotalOrd` -- vectors can be compared,
69   if the element type defines the corresponding trait.
70
71 ## Iteration
72
73 The method `iter()` returns an iteration value for a vector or a vector slice.
74 The iterator yields references to the vector's elements, so if the element
75 type of the vector is `int`, the element type of the iterator is `&int`.
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 * `.mut_iter()` returns an iterator that allows modifying each value.
85 * `.move_iter()` converts an owned vector into an iterator that
86   moves out a value from the vector each iteration.
87 * Further iterators exist that split, chunk or permute the vector.
88
89 ## Function definitions
90
91 There are a number of free functions that create or take vectors, for example:
92
93 * Creating a vector, like `from_elem` and `from_fn`
94 * Creating a vector with a given size: `with_capacity`
95 * Modifying a vector and returning it, like `append`
96 * Operations on paired elements, like `unzip`.
97
98 */
99
100 use cast::transmute;
101 use cast;
102 use clone::Clone;
103 use cmp::{TotalOrd, Ordering, Less, Greater};
104 use cmp;
105 use container::Container;
106 use iter::*;
107 use mem::size_of;
108 use mem;
109 use ops::Drop;
110 use option::{None, Option, Some};
111 use ptr::RawPtr;
112 use ptr;
113 use rt::global_heap::{exchange_free};
114 use unstable::finally::try_finally;
115 use vec::Vec;
116
117 pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
118 pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
119 pub use core::slice::{ImmutableTotalOrdVector, MutableVector, Items, MutItems};
120 pub use core::slice::{RevItems, RevMutItems, MutSplits, MutChunks};
121 pub use core::slice::{bytes, MutableCloneableVector};
122
123 // Functional utilities
124
125 #[allow(missing_doc)]
126 pub trait VectorVector<T> {
127     // FIXME #5898: calling these .concat and .connect conflicts with
128     // StrVector::con{cat,nect}, since they have generic contents.
129     /// Flattens a vector of vectors of T into a single vector of T.
130     fn concat_vec(&self) -> ~[T];
131
132     /// Concatenate a vector of vectors, placing a given separator between each.
133     fn connect_vec(&self, sep: &T) -> ~[T];
134 }
135
136 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
137     fn concat_vec(&self) -> ~[T] {
138         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
139         let mut result = Vec::with_capacity(size);
140         for v in self.iter() {
141             result.push_all(v.as_slice())
142         }
143         result.move_iter().collect()
144     }
145
146     fn connect_vec(&self, sep: &T) -> ~[T] {
147         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
148         let mut result = Vec::with_capacity(size + self.len());
149         let mut first = true;
150         for v in self.iter() {
151             if first { first = false } else { result.push(sep.clone()) }
152             result.push_all(v.as_slice())
153         }
154         result.move_iter().collect()
155     }
156 }
157
158 /**
159  * Convert an iterator of pairs into a pair of vectors.
160  *
161  * Returns a tuple containing two vectors where the i-th element of the first
162  * vector contains the first element of the i-th tuple of the input iterator,
163  * and the i-th element of the second vector contains the second element
164  * of the i-th tuple of the input iterator.
165  */
166 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
167     let (lo, _) = iter.size_hint();
168     let mut ts = Vec::with_capacity(lo);
169     let mut us = Vec::with_capacity(lo);
170     for (t, u) in iter {
171         ts.push(t);
172         us.push(u);
173     }
174     (ts.move_iter().collect(), us.move_iter().collect())
175 }
176
177 /// An Iterator that yields the element swaps needed to produce
178 /// a sequence of all possible permutations for an indexed sequence of
179 /// elements. Each permutation is only a single swap apart.
180 ///
181 /// The Steinhaus–Johnson–Trotter algorithm is used.
182 ///
183 /// Generates even and odd permutations alternately.
184 ///
185 /// The last generated swap is always (0, 1), and it returns the
186 /// sequence to its initial order.
187 pub struct ElementSwaps {
188     sdir: ~[SizeDirection],
189     /// If true, emit the last swap that returns the sequence to initial state
190     emit_reset: bool,
191     swaps_made : uint,
192 }
193
194 impl ElementSwaps {
195     /// Create an `ElementSwaps` iterator for a sequence of `length` elements
196     pub fn new(length: uint) -> ElementSwaps {
197         // Initialize `sdir` with a direction that position should move in
198         // (all negative at the beginning) and the `size` of the
199         // element (equal to the original index).
200         ElementSwaps{
201             emit_reset: true,
202             sdir: range(0, length)
203                     .map(|i| SizeDirection{ size: i, dir: Neg })
204                     .collect::<~[_]>(),
205             swaps_made: 0
206         }
207     }
208 }
209
210 enum Direction { Pos, Neg }
211
212 /// An Index and Direction together
213 struct SizeDirection {
214     size: uint,
215     dir: Direction,
216 }
217
218 impl Iterator<(uint, uint)> for ElementSwaps {
219     #[inline]
220     fn next(&mut self) -> Option<(uint, uint)> {
221         fn new_pos(i: uint, s: Direction) -> uint {
222             i + match s { Pos => 1, Neg => -1 }
223         }
224
225         // Find the index of the largest mobile element:
226         // The direction should point into the vector, and the
227         // swap should be with a smaller `size` element.
228         let max = self.sdir.iter().map(|&x| x).enumerate()
229                            .filter(|&(i, sd)|
230                                 new_pos(i, sd.dir) < self.sdir.len() &&
231                                 self.sdir[new_pos(i, sd.dir)].size < sd.size)
232                            .max_by(|&(_, sd)| sd.size);
233         match max {
234             Some((i, sd)) => {
235                 let j = new_pos(i, sd.dir);
236                 self.sdir.swap(i, j);
237
238                 // Swap the direction of each larger SizeDirection
239                 for x in self.sdir.mut_iter() {
240                     if x.size > sd.size {
241                         x.dir = match x.dir { Pos => Neg, Neg => Pos };
242                     }
243                 }
244                 self.swaps_made += 1;
245                 Some((i, j))
246             },
247             None => if self.emit_reset {
248                 self.emit_reset = false;
249                 if self.sdir.len() > 1 {
250                     // The last swap
251                     self.swaps_made += 1;
252                     Some((0, 1))
253                 } else {
254                     // Vector is of the form [] or [x], and the only permutation is itself
255                     self.swaps_made += 1;
256                     Some((0,0))
257                 }
258             } else { None }
259         }
260     }
261
262     #[inline]
263     fn size_hint(&self) -> (uint, Option<uint>) {
264         // For a vector of size n, there are exactly n! permutations.
265         let n = range(2, self.sdir.len() + 1).product();
266         (n - self.swaps_made, Some(n - self.swaps_made))
267     }
268 }
269
270 /// An Iterator that uses `ElementSwaps` to iterate through
271 /// all possible permutations of a vector.
272 ///
273 /// The first iteration yields a clone of the vector as it is,
274 /// then each successive element is the vector with one
275 /// swap applied.
276 ///
277 /// Generates even and odd permutations alternately.
278 pub struct Permutations<T> {
279     swaps: ElementSwaps,
280     v: ~[T],
281 }
282
283 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
284     #[inline]
285     fn next(&mut self) -> Option<~[T]> {
286         match self.swaps.next() {
287             None => None,
288             Some((0,0)) => Some(self.v.clone()),
289             Some((a, b)) => {
290                 let elt = self.v.clone();
291                 self.v.swap(a, b);
292                 Some(elt)
293             }
294         }
295     }
296
297     #[inline]
298     fn size_hint(&self) -> (uint, Option<uint>) {
299         self.swaps.size_hint()
300     }
301 }
302
303 /// Extension methods for vector slices with cloneable elements
304 pub trait CloneableVector<T> {
305     /// Copy `self` into a new owned vector
306     fn to_owned(&self) -> ~[T];
307
308     /// Convert `self` into an owned vector, not making a copy if possible.
309     fn into_owned(self) -> ~[T];
310 }
311
312 /// Extension methods for vector slices
313 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
314     /// Returns a copy of `v`.
315     #[inline]
316     fn to_owned(&self) -> ~[T] {
317         let len = self.len();
318         let mut result = Vec::with_capacity(len);
319         // Unsafe code so this can be optimised to a memcpy (or something
320         // similarly fast) when T is Copy. LLVM is easily confused, so any
321         // extra operations during the loop can prevent this optimisation
322         unsafe {
323             let mut i = 0;
324             let p = result.as_mut_ptr();
325             // Use try_finally here otherwise the write to length
326             // inside the loop stops LLVM from optimising this.
327             try_finally(
328                 &mut i, (),
329                 |i, ()| while *i < len {
330                     mem::move_val_init(
331                         &mut(*p.offset(*i as int)),
332                         self.unsafe_ref(*i).clone());
333                     *i += 1;
334                 },
335                 |i| result.set_len(*i));
336         }
337         result.move_iter().collect()
338     }
339
340     #[inline(always)]
341     fn into_owned(self) -> ~[T] { self.to_owned() }
342 }
343
344 /// Extension methods for owned vectors
345 impl<T: Clone> CloneableVector<T> for ~[T] {
346     #[inline]
347     fn to_owned(&self) -> ~[T] { self.clone() }
348
349     #[inline(always)]
350     fn into_owned(self) -> ~[T] { self }
351 }
352
353 /// Extension methods for vectors containing `Clone` elements.
354 pub trait ImmutableCloneableVector<T> {
355     /// Partitions the vector into two vectors `(A,B)`, where all
356     /// elements of `A` satisfy `f` and all elements of `B` do not.
357     fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
358
359     /// Create an iterator that yields every possible permutation of the
360     /// vector in succession.
361     fn permutations(self) -> Permutations<T>;
362 }
363
364 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
365     #[inline]
366     fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
367         let mut lefts  = Vec::new();
368         let mut rights = Vec::new();
369
370         for elt in self.iter() {
371             if f(elt) {
372                 lefts.push((*elt).clone());
373             } else {
374                 rights.push((*elt).clone());
375             }
376         }
377
378         (lefts.move_iter().collect(), rights.move_iter().collect())
379     }
380
381     fn permutations(self) -> Permutations<T> {
382         Permutations{
383             swaps: ElementSwaps::new(self.len()),
384             v: self.to_owned(),
385         }
386     }
387
388 }
389
390 /// Extension methods for owned vectors.
391 pub trait OwnedVector<T> {
392     /// Creates a consuming iterator, that is, one that moves each
393     /// value out of the vector (from start to end). The vector cannot
394     /// be used after calling this.
395     ///
396     /// # Examples
397     ///
398     /// ```rust
399     /// let v = ~["a".to_owned(), "b".to_owned()];
400     /// for s in v.move_iter() {
401     ///   // s has type ~str, not &~str
402     ///   println!("{}", s);
403     /// }
404     /// ```
405     fn move_iter(self) -> MoveItems<T>;
406     /// Creates a consuming iterator that moves out of the vector in
407     /// reverse order.
408     #[deprecated = "replaced by .move_iter().rev()"]
409     fn move_rev_iter(self) -> Rev<MoveItems<T>>;
410
411     /**
412      * Partitions the vector into two vectors `(A,B)`, where all
413      * elements of `A` satisfy `f` and all elements of `B` do not.
414      */
415     fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
416 }
417
418 impl<T> OwnedVector<T> for ~[T] {
419     #[inline]
420     fn move_iter(self) -> MoveItems<T> {
421         unsafe {
422             let iter = transmute(self.iter());
423             let ptr = transmute(self);
424             MoveItems { allocation: ptr, iter: iter }
425         }
426     }
427
428     #[inline]
429     #[deprecated = "replaced by .move_iter().rev()"]
430     fn move_rev_iter(self) -> Rev<MoveItems<T>> {
431         self.move_iter().rev()
432     }
433
434     #[inline]
435     fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
436         let mut lefts  = Vec::new();
437         let mut rights = Vec::new();
438
439         for elt in self.move_iter() {
440             if f(&elt) {
441                 lefts.push(elt);
442             } else {
443                 rights.push(elt);
444             }
445         }
446
447         (lefts.move_iter().collect(), rights.move_iter().collect())
448     }
449 }
450
451 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
452     let len = v.len() as int;
453     let buf_v = v.as_mut_ptr();
454
455     // 1 <= i < len;
456     for i in range(1, len) {
457         // j satisfies: 0 <= j <= i;
458         let mut j = i;
459         unsafe {
460             // `i` is in bounds.
461             let read_ptr = buf_v.offset(i) as *T;
462
463             // find where to insert, we need to do strict <,
464             // rather than <=, to maintain stability.
465
466             // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
467             while j > 0 &&
468                     compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
469                 j -= 1;
470             }
471
472             // shift everything to the right, to make space to
473             // insert this value.
474
475             // j + 1 could be `len` (for the last `i`), but in
476             // that case, `i == j` so we don't copy. The
477             // `.offset(j)` is always in bounds.
478
479             if i != j {
480                 let tmp = ptr::read(read_ptr);
481                 ptr::copy_memory(buf_v.offset(j + 1),
482                                  &*buf_v.offset(j),
483                                  (i - j) as uint);
484                 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
485                                                 &tmp as *T,
486                                                 1);
487                 cast::forget(tmp);
488             }
489         }
490     }
491 }
492
493 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
494     // warning: this wildly uses unsafe.
495     static BASE_INSERTION: uint = 32;
496     static LARGE_INSERTION: uint = 16;
497
498     // FIXME #12092: smaller insertion runs seems to make sorting
499     // vectors of large elements a little faster on some platforms,
500     // but hasn't been tested/tuned extensively
501     let insertion = if size_of::<T>() <= 16 {
502         BASE_INSERTION
503     } else {
504         LARGE_INSERTION
505     };
506
507     let len = v.len();
508
509     // short vectors get sorted in-place via insertion sort to avoid allocations
510     if len <= insertion {
511         insertion_sort(v, compare);
512         return;
513     }
514
515     // allocate some memory to use as scratch memory, we keep the
516     // length 0 so we can keep shallow copies of the contents of `v`
517     // without risking the dtors running on an object twice if
518     // `compare` fails.
519     let mut working_space = Vec::with_capacity(2 * len);
520     // these both are buffers of length `len`.
521     let mut buf_dat = working_space.as_mut_ptr();
522     let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
523
524     // length `len`.
525     let buf_v = v.as_ptr();
526
527     // step 1. sort short runs with insertion sort. This takes the
528     // values from `v` and sorts them into `buf_dat`, leaving that
529     // with sorted runs of length INSERTION.
530
531     // We could hardcode the sorting comparisons here, and we could
532     // manipulate/step the pointers themselves, rather than repeatedly
533     // .offset-ing.
534     for start in range_step(0, len, insertion) {
535         // start <= i < len;
536         for i in range(start, cmp::min(start + insertion, len)) {
537             // j satisfies: start <= j <= i;
538             let mut j = i as int;
539             unsafe {
540                 // `i` is in bounds.
541                 let read_ptr = buf_v.offset(i as int);
542
543                 // find where to insert, we need to do strict <,
544                 // rather than <=, to maintain stability.
545
546                 // start <= j - 1 < len, so .offset(j - 1) is in
547                 // bounds.
548                 while j > start as int &&
549                         compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
550                     j -= 1;
551                 }
552
553                 // shift everything to the right, to make space to
554                 // insert this value.
555
556                 // j + 1 could be `len` (for the last `i`), but in
557                 // that case, `i == j` so we don't copy. The
558                 // `.offset(j)` is always in bounds.
559                 ptr::copy_memory(buf_dat.offset(j + 1),
560                                  &*buf_dat.offset(j),
561                                  i - j as uint);
562                 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
563             }
564         }
565     }
566
567     // step 2. merge the sorted runs.
568     let mut width = insertion;
569     while width < len {
570         // merge the sorted runs of length `width` in `buf_dat` two at
571         // a time, placing the result in `buf_tmp`.
572
573         // 0 <= start <= len.
574         for start in range_step(0, len, 2 * width) {
575             // manipulate pointers directly for speed (rather than
576             // using a `for` loop with `range` and `.offset` inside
577             // that loop).
578             unsafe {
579                 // the end of the first run & start of the
580                 // second. Offset of `len` is defined, since this is
581                 // precisely one byte past the end of the object.
582                 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
583                 // end of the second. Similar reasoning to the above re safety.
584                 let right_end_idx = cmp::min(start + 2 * width, len);
585                 let right_end = buf_dat.offset(right_end_idx as int);
586
587                 // the pointers to the elements under consideration
588                 // from the two runs.
589
590                 // both of these are in bounds.
591                 let mut left = buf_dat.offset(start as int);
592                 let mut right = right_start;
593
594                 // where we're putting the results, it is a run of
595                 // length `2*width`, so we step it once for each step
596                 // of either `left` or `right`.  `buf_tmp` has length
597                 // `len`, so these are in bounds.
598                 let mut out = buf_tmp.offset(start as int);
599                 let out_end = buf_tmp.offset(right_end_idx as int);
600
601                 while out < out_end {
602                     // Either the left or the right run are exhausted,
603                     // so just copy the remainder from the other run
604                     // and move on; this gives a huge speed-up (order
605                     // of 25%) for mostly sorted vectors (the best
606                     // case).
607                     if left == right_start {
608                         // the number remaining in this run.
609                         let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
610                         ptr::copy_nonoverlapping_memory(out, &*right, elems);
611                         break;
612                     } else if right == right_end {
613                         let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
614                         ptr::copy_nonoverlapping_memory(out, &*left, elems);
615                         break;
616                     }
617
618                     // check which side is smaller, and that's the
619                     // next element for the new run.
620
621                     // `left < right_start` and `right < right_end`,
622                     // so these are valid.
623                     let to_copy = if compare(&*left, &*right) == Greater {
624                         step(&mut right)
625                     } else {
626                         step(&mut left)
627                     };
628                     ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
629                     step(&mut out);
630                 }
631             }
632         }
633
634         mem::swap(&mut buf_dat, &mut buf_tmp);
635
636         width *= 2;
637     }
638
639     // write the result to `v` in one go, so that there are never two copies
640     // of the same object in `v`.
641     unsafe {
642         ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
643     }
644
645     // increment the pointer, returning the old pointer.
646     #[inline(always)]
647     unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
648         let old = *ptr;
649         *ptr = ptr.offset(1);
650         old
651     }
652 }
653
654 /// Extension methods for vectors such that their elements are
655 /// mutable.
656 pub trait MutableVectorAllocating<'a, T> {
657     /// Sort the vector, in place, using `compare` to compare
658     /// elements.
659     ///
660     /// This sort is `O(n log n)` worst-case and stable, but allocates
661     /// approximately `2 * n`, where `n` is the length of `self`.
662     ///
663     /// # Example
664     ///
665     /// ```rust
666     /// let mut v = [5i, 4, 1, 3, 2];
667     /// v.sort_by(|a, b| a.cmp(b));
668     /// assert!(v == [1, 2, 3, 4, 5]);
669     ///
670     /// // reverse sorting
671     /// v.sort_by(|a, b| b.cmp(a));
672     /// assert!(v == [5, 4, 3, 2, 1]);
673     /// ```
674     fn sort_by(self, compare: |&T, &T| -> Ordering);
675
676     /**
677      * Consumes `src` and moves as many elements as it can into `self`
678      * from the range [start,end).
679      *
680      * Returns the number of elements copied (the shorter of self.len()
681      * and end - start).
682      *
683      * # Arguments
684      *
685      * * src - A mutable vector of `T`
686      * * start - The index into `src` to start copying from
687      * * end - The index into `str` to stop copying from
688      */
689     fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
690 }
691
692 impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
693     #[inline]
694     fn sort_by(self, compare: |&T, &T| -> Ordering) {
695         merge_sort(self, compare)
696     }
697
698     #[inline]
699     fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
700         for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
701             mem::swap(a, b);
702         }
703         cmp::min(self.len(), end-start)
704     }
705 }
706
707 /// Methods for mutable vectors with orderable elements, such as
708 /// in-place sorting.
709 pub trait MutableTotalOrdVector<T> {
710     /// Sort the vector, in place.
711     ///
712     /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
713     ///
714     /// # Example
715     ///
716     /// ```rust
717     /// let mut v = [-5, 4, 1, -3, 2];
718     ///
719     /// v.sort();
720     /// assert!(v == [-5, -3, 1, 2, 4]);
721     /// ```
722     fn sort(self);
723 }
724
725 impl<'a, T: TotalOrd> MutableTotalOrdVector<T> for &'a mut [T] {
726     #[inline]
727     fn sort(self) {
728         self.sort_by(|a,b| a.cmp(b))
729     }
730 }
731
732 /**
733 * Constructs a vector from an unsafe pointer to a buffer
734 *
735 * # Arguments
736 *
737 * * ptr - An unsafe pointer to a buffer of `T`
738 * * elts - The number of elements in the buffer
739 */
740 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
741 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
742     raw::from_buf_raw(ptr, elts)
743 }
744
745 /// Unsafe operations
746 pub mod raw {
747     use iter::Iterator;
748     use ptr;
749     use slice::{MutableVector, OwnedVector};
750     use vec::Vec;
751
752     pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
753     pub use core::slice::raw::{shift_ptr, pop_ptr};
754
755     /**
756     * Constructs a vector from an unsafe pointer to a buffer
757     *
758     * # Arguments
759     *
760     * * ptr - An unsafe pointer to a buffer of `T`
761     * * elts - The number of elements in the buffer
762     */
763     // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
764     #[inline]
765     pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
766         let mut dst = Vec::with_capacity(elts);
767         dst.set_len(elts);
768         ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
769         dst.move_iter().collect()
770     }
771 }
772
773 /// An iterator that moves out of a vector.
774 pub struct MoveItems<T> {
775     allocation: *mut u8, // the block of memory allocated for the vector
776     iter: Items<'static, T>
777 }
778
779 impl<T> Iterator<T> for MoveItems<T> {
780     #[inline]
781     fn next(&mut self) -> Option<T> {
782         unsafe {
783             self.iter.next().map(|x| ptr::read(x))
784         }
785     }
786
787     #[inline]
788     fn size_hint(&self) -> (uint, Option<uint>) {
789         self.iter.size_hint()
790     }
791 }
792
793 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
794     #[inline]
795     fn next_back(&mut self) -> Option<T> {
796         unsafe {
797             self.iter.next_back().map(|x| ptr::read(x))
798         }
799     }
800 }
801
802 #[unsafe_destructor]
803 impl<T> Drop for MoveItems<T> {
804     fn drop(&mut self) {
805         // destroy the remaining elements
806         for _x in *self {}
807         unsafe {
808             exchange_free(self.allocation as *u8)
809         }
810     }
811 }
812
813 /// An iterator that moves out of a vector in reverse order.
814 #[deprecated = "replaced by Rev<MoveItems<'a, T>>"]
815 pub type RevMoveItems<T> = Rev<MoveItems<T>>;
816
817 #[cfg(test)]
818 mod tests {
819     use prelude::*;
820     use cmp::*;
821     use mem;
822     use owned::Box;
823     use rand::{Rng, task_rng};
824     use slice::*;
825
826     fn square(n: uint) -> uint { n * n }
827
828     fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
829
830     #[test]
831     fn test_unsafe_ptrs() {
832         unsafe {
833             // Test on-stack copy-from-buf.
834             let a = box [1, 2, 3];
835             let mut ptr = a.as_ptr();
836             let b = from_buf(ptr, 3u);
837             assert_eq!(b.len(), 3u);
838             assert_eq!(b[0], 1);
839             assert_eq!(b[1], 2);
840             assert_eq!(b[2], 3);
841
842             // Test on-heap copy-from-buf.
843             let c = box [1, 2, 3, 4, 5];
844             ptr = c.as_ptr();
845             let d = from_buf(ptr, 5u);
846             assert_eq!(d.len(), 5u);
847             assert_eq!(d[0], 1);
848             assert_eq!(d[1], 2);
849             assert_eq!(d[2], 3);
850             assert_eq!(d[3], 4);
851             assert_eq!(d[4], 5);
852         }
853     }
854
855     #[test]
856     fn test_from_fn() {
857         // Test on-stack from_fn.
858         let mut v = Vec::from_fn(3u, square);
859         {
860             let v = v.as_slice();
861             assert_eq!(v.len(), 3u);
862             assert_eq!(v[0], 0u);
863             assert_eq!(v[1], 1u);
864             assert_eq!(v[2], 4u);
865         }
866
867         // Test on-heap from_fn.
868         v = Vec::from_fn(5u, square);
869         {
870             let v = v.as_slice();
871             assert_eq!(v.len(), 5u);
872             assert_eq!(v[0], 0u);
873             assert_eq!(v[1], 1u);
874             assert_eq!(v[2], 4u);
875             assert_eq!(v[3], 9u);
876             assert_eq!(v[4], 16u);
877         }
878     }
879
880     #[test]
881     fn test_from_elem() {
882         // Test on-stack from_elem.
883         let mut v = Vec::from_elem(2u, 10u);
884         {
885             let v = v.as_slice();
886             assert_eq!(v.len(), 2u);
887             assert_eq!(v[0], 10u);
888             assert_eq!(v[1], 10u);
889         }
890
891         // Test on-heap from_elem.
892         v = Vec::from_elem(6u, 20u);
893         {
894             let v = v.as_slice();
895             assert_eq!(v[0], 20u);
896             assert_eq!(v[1], 20u);
897             assert_eq!(v[2], 20u);
898             assert_eq!(v[3], 20u);
899             assert_eq!(v[4], 20u);
900             assert_eq!(v[5], 20u);
901         }
902     }
903
904     #[test]
905     fn test_is_empty() {
906         let xs: [int, ..0] = [];
907         assert!(xs.is_empty());
908         assert!(![0].is_empty());
909     }
910
911     #[test]
912     fn test_len_divzero() {
913         type Z = [i8, ..0];
914         let v0 : &[Z] = &[];
915         let v1 : &[Z] = &[[]];
916         let v2 : &[Z] = &[[], []];
917         assert_eq!(mem::size_of::<Z>(), 0);
918         assert_eq!(v0.len(), 0);
919         assert_eq!(v1.len(), 1);
920         assert_eq!(v2.len(), 2);
921     }
922
923     #[test]
924     fn test_get() {
925         let mut a = box [11];
926         assert_eq!(a.get(1), None);
927         a = box [11, 12];
928         assert_eq!(a.get(1).unwrap(), &12);
929         a = box [11, 12, 13];
930         assert_eq!(a.get(1).unwrap(), &12);
931     }
932
933     #[test]
934     fn test_head() {
935         let mut a = box [];
936         assert_eq!(a.head(), None);
937         a = box [11];
938         assert_eq!(a.head().unwrap(), &11);
939         a = box [11, 12];
940         assert_eq!(a.head().unwrap(), &11);
941     }
942
943     #[test]
944     fn test_tail() {
945         let mut a = box [11];
946         assert_eq!(a.tail(), &[]);
947         a = box [11, 12];
948         assert_eq!(a.tail(), &[12]);
949     }
950
951     #[test]
952     #[should_fail]
953     fn test_tail_empty() {
954         let a: ~[int] = box [];
955         a.tail();
956     }
957
958     #[test]
959     fn test_tailn() {
960         let mut a = box [11, 12, 13];
961         assert_eq!(a.tailn(0), &[11, 12, 13]);
962         a = box [11, 12, 13];
963         assert_eq!(a.tailn(2), &[13]);
964     }
965
966     #[test]
967     #[should_fail]
968     fn test_tailn_empty() {
969         let a: ~[int] = box [];
970         a.tailn(2);
971     }
972
973     #[test]
974     fn test_init() {
975         let mut a = box [11];
976         assert_eq!(a.init(), &[]);
977         a = box [11, 12];
978         assert_eq!(a.init(), &[11]);
979     }
980
981     #[test]
982     #[should_fail]
983     fn test_init_empty() {
984         let a: ~[int] = box [];
985         a.init();
986     }
987
988     #[test]
989     fn test_initn() {
990         let mut a = box [11, 12, 13];
991         assert_eq!(a.initn(0), &[11, 12, 13]);
992         a = box [11, 12, 13];
993         assert_eq!(a.initn(2), &[11]);
994     }
995
996     #[test]
997     #[should_fail]
998     fn test_initn_empty() {
999         let a: ~[int] = box [];
1000         a.initn(2);
1001     }
1002
1003     #[test]
1004     fn test_last() {
1005         let mut a = box [];
1006         assert_eq!(a.last(), None);
1007         a = box [11];
1008         assert_eq!(a.last().unwrap(), &11);
1009         a = box [11, 12];
1010         assert_eq!(a.last().unwrap(), &12);
1011     }
1012
1013     #[test]
1014     fn test_slice() {
1015         // Test fixed length vector.
1016         let vec_fixed = [1, 2, 3, 4];
1017         let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
1018         assert_eq!(v_a.len(), 3u);
1019         assert_eq!(v_a[0], 2);
1020         assert_eq!(v_a[1], 3);
1021         assert_eq!(v_a[2], 4);
1022
1023         // Test on stack.
1024         let vec_stack = &[1, 2, 3];
1025         let v_b = vec_stack.slice(1u, 3u).to_owned();
1026         assert_eq!(v_b.len(), 2u);
1027         assert_eq!(v_b[0], 2);
1028         assert_eq!(v_b[1], 3);
1029
1030         // Test on exchange heap.
1031         let vec_unique = box [1, 2, 3, 4, 5, 6];
1032         let v_d = vec_unique.slice(1u, 6u).to_owned();
1033         assert_eq!(v_d.len(), 5u);
1034         assert_eq!(v_d[0], 2);
1035         assert_eq!(v_d[1], 3);
1036         assert_eq!(v_d[2], 4);
1037         assert_eq!(v_d[3], 5);
1038         assert_eq!(v_d[4], 6);
1039     }
1040
1041     #[test]
1042     fn test_slice_from() {
1043         let vec = &[1, 2, 3, 4];
1044         assert_eq!(vec.slice_from(0), vec);
1045         assert_eq!(vec.slice_from(2), &[3, 4]);
1046         assert_eq!(vec.slice_from(4), &[]);
1047     }
1048
1049     #[test]
1050     fn test_slice_to() {
1051         let vec = &[1, 2, 3, 4];
1052         assert_eq!(vec.slice_to(4), vec);
1053         assert_eq!(vec.slice_to(2), &[1, 2]);
1054         assert_eq!(vec.slice_to(0), &[]);
1055     }
1056
1057
1058     #[test]
1059     fn test_pop() {
1060         let mut v = vec![5];
1061         let e = v.pop();
1062         assert_eq!(v.len(), 0);
1063         assert_eq!(e, Some(5));
1064         let f = v.pop();
1065         assert_eq!(f, None);
1066         let g = v.pop();
1067         assert_eq!(g, None);
1068     }
1069
1070     #[test]
1071     fn test_swap_remove() {
1072         let mut v = vec![1, 2, 3, 4, 5];
1073         let mut e = v.swap_remove(0);
1074         assert_eq!(e, Some(1));
1075         assert_eq!(v, vec![5, 2, 3, 4]);
1076         e = v.swap_remove(3);
1077         assert_eq!(e, Some(4));
1078         assert_eq!(v, vec![5, 2, 3]);
1079
1080         e = v.swap_remove(3);
1081         assert_eq!(e, None);
1082         assert_eq!(v, vec![5, 2, 3]);
1083     }
1084
1085     #[test]
1086     fn test_swap_remove_noncopyable() {
1087         // Tests that we don't accidentally run destructors twice.
1088         let mut v = vec![::unstable::sync::Exclusive::new(()),
1089                          ::unstable::sync::Exclusive::new(()),
1090                          ::unstable::sync::Exclusive::new(())];
1091         let mut _e = v.swap_remove(0);
1092         assert_eq!(v.len(), 2);
1093         _e = v.swap_remove(1);
1094         assert_eq!(v.len(), 1);
1095         _e = v.swap_remove(0);
1096         assert_eq!(v.len(), 0);
1097     }
1098
1099     #[test]
1100     fn test_push() {
1101         // Test on-stack push().
1102         let mut v = vec![];
1103         v.push(1);
1104         assert_eq!(v.len(), 1u);
1105         assert_eq!(v.as_slice()[0], 1);
1106
1107         // Test on-heap push().
1108         v.push(2);
1109         assert_eq!(v.len(), 2u);
1110         assert_eq!(v.as_slice()[0], 1);
1111         assert_eq!(v.as_slice()[1], 2);
1112     }
1113
1114     #[test]
1115     fn test_grow() {
1116         // Test on-stack grow().
1117         let mut v = vec![];
1118         v.grow(2u, &1);
1119         {
1120             let v = v.as_slice();
1121             assert_eq!(v.len(), 2u);
1122             assert_eq!(v[0], 1);
1123             assert_eq!(v[1], 1);
1124         }
1125
1126         // Test on-heap grow().
1127         v.grow(3u, &2);
1128         {
1129             let v = v.as_slice();
1130             assert_eq!(v.len(), 5u);
1131             assert_eq!(v[0], 1);
1132             assert_eq!(v[1], 1);
1133             assert_eq!(v[2], 2);
1134             assert_eq!(v[3], 2);
1135             assert_eq!(v[4], 2);
1136         }
1137     }
1138
1139     #[test]
1140     fn test_grow_fn() {
1141         let mut v = vec![];
1142         v.grow_fn(3u, square);
1143         let v = v.as_slice();
1144         assert_eq!(v.len(), 3u);
1145         assert_eq!(v[0], 0u);
1146         assert_eq!(v[1], 1u);
1147         assert_eq!(v[2], 4u);
1148     }
1149
1150     #[test]
1151     fn test_grow_set() {
1152         let mut v = vec![1, 2, 3];
1153         v.grow_set(4u, &4, 5);
1154         let v = v.as_slice();
1155         assert_eq!(v.len(), 5u);
1156         assert_eq!(v[0], 1);
1157         assert_eq!(v[1], 2);
1158         assert_eq!(v[2], 3);
1159         assert_eq!(v[3], 4);
1160         assert_eq!(v[4], 5);
1161     }
1162
1163     #[test]
1164     fn test_truncate() {
1165         let mut v = vec![box 6,box 5,box 4];
1166         v.truncate(1);
1167         let v = v.as_slice();
1168         assert_eq!(v.len(), 1);
1169         assert_eq!(*(v[0]), 6);
1170         // If the unsafe block didn't drop things properly, we blow up here.
1171     }
1172
1173     #[test]
1174     fn test_clear() {
1175         let mut v = vec![box 6,box 5,box 4];
1176         v.clear();
1177         assert_eq!(v.len(), 0);
1178         // If the unsafe block didn't drop things properly, we blow up here.
1179     }
1180
1181     #[test]
1182     fn test_dedup() {
1183         fn case(a: Vec<uint>, b: Vec<uint>) {
1184             let mut v = a;
1185             v.dedup();
1186             assert_eq!(v, b);
1187         }
1188         case(vec![], vec![]);
1189         case(vec![1], vec![1]);
1190         case(vec![1,1], vec![1]);
1191         case(vec![1,2,3], vec![1,2,3]);
1192         case(vec![1,1,2,3], vec![1,2,3]);
1193         case(vec![1,2,2,3], vec![1,2,3]);
1194         case(vec![1,2,3,3], vec![1,2,3]);
1195         case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
1196     }
1197
1198     #[test]
1199     fn test_dedup_unique() {
1200         let mut v0 = vec![box 1, box 1, box 2, box 3];
1201         v0.dedup();
1202         let mut v1 = vec![box 1, box 2, box 2, box 3];
1203         v1.dedup();
1204         let mut v2 = vec![box 1, box 2, box 3, box 3];
1205         v2.dedup();
1206         /*
1207          * If the boxed pointers were leaked or otherwise misused, valgrind
1208          * and/or rustrt should raise errors.
1209          */
1210     }
1211
1212     #[test]
1213     fn test_dedup_shared() {
1214         let mut v0 = vec![box 1, box 1, box 2, box 3];
1215         v0.dedup();
1216         let mut v1 = vec![box 1, box 2, box 2, box 3];
1217         v1.dedup();
1218         let mut v2 = vec![box 1, box 2, box 3, box 3];
1219         v2.dedup();
1220         /*
1221          * If the pointers were leaked or otherwise misused, valgrind and/or
1222          * rustrt should raise errors.
1223          */
1224     }
1225
1226     #[test]
1227     fn test_retain() {
1228         let mut v = vec![1, 2, 3, 4, 5];
1229         v.retain(is_odd);
1230         assert_eq!(v, vec![1, 3, 5]);
1231     }
1232
1233     #[test]
1234     fn test_zip_unzip() {
1235         let z1 = vec![(1, 4), (2, 5), (3, 6)];
1236
1237         let (left, right) = unzip(z1.iter().map(|&x| x));
1238
1239         assert_eq!((1, 4), (left[0], right[0]));
1240         assert_eq!((2, 5), (left[1], right[1]));
1241         assert_eq!((3, 6), (left[2], right[2]));
1242     }
1243
1244     #[test]
1245     fn test_element_swaps() {
1246         let mut v = [1, 2, 3];
1247         for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1248             v.swap(a, b);
1249             match i {
1250                 0 => assert!(v == [1, 3, 2]),
1251                 1 => assert!(v == [3, 1, 2]),
1252                 2 => assert!(v == [3, 2, 1]),
1253                 3 => assert!(v == [2, 3, 1]),
1254                 4 => assert!(v == [2, 1, 3]),
1255                 5 => assert!(v == [1, 2, 3]),
1256                 _ => fail!(),
1257             }
1258         }
1259     }
1260
1261     #[test]
1262     fn test_permutations() {
1263         {
1264             let v: [int, ..0] = [];
1265             let mut it = v.permutations();
1266             let (min_size, max_opt) = it.size_hint();
1267             assert_eq!(min_size, 1);
1268             assert_eq!(max_opt.unwrap(), 1);
1269             assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1270             assert_eq!(it.next(), None);
1271         }
1272         {
1273             let v = ["Hello".to_owned()];
1274             let mut it = v.permutations();
1275             let (min_size, max_opt) = it.size_hint();
1276             assert_eq!(min_size, 1);
1277             assert_eq!(max_opt.unwrap(), 1);
1278             assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1279             assert_eq!(it.next(), None);
1280         }
1281         {
1282             let v = [1, 2, 3];
1283             let mut it = v.permutations();
1284             let (min_size, max_opt) = it.size_hint();
1285             assert_eq!(min_size, 3*2);
1286             assert_eq!(max_opt.unwrap(), 3*2);
1287             assert_eq!(it.next(), Some(box [1,2,3]));
1288             assert_eq!(it.next(), Some(box [1,3,2]));
1289             assert_eq!(it.next(), Some(box [3,1,2]));
1290             let (min_size, max_opt) = it.size_hint();
1291             assert_eq!(min_size, 3);
1292             assert_eq!(max_opt.unwrap(), 3);
1293             assert_eq!(it.next(), Some(box [3,2,1]));
1294             assert_eq!(it.next(), Some(box [2,3,1]));
1295             assert_eq!(it.next(), Some(box [2,1,3]));
1296             assert_eq!(it.next(), None);
1297         }
1298         {
1299             // check that we have N! permutations
1300             let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1301             let mut amt = 0;
1302             let mut it = v.permutations();
1303             let (min_size, max_opt) = it.size_hint();
1304             for _perm in it {
1305                 amt += 1;
1306             }
1307             assert_eq!(amt, it.swaps.swaps_made);
1308             assert_eq!(amt, min_size);
1309             assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1310             assert_eq!(amt, max_opt.unwrap());
1311         }
1312     }
1313
1314     #[test]
1315     fn test_position_elem() {
1316         assert!([].position_elem(&1).is_none());
1317
1318         let v1 = box [1, 2, 3, 3, 2, 5];
1319         assert_eq!(v1.position_elem(&1), Some(0u));
1320         assert_eq!(v1.position_elem(&2), Some(1u));
1321         assert_eq!(v1.position_elem(&5), Some(5u));
1322         assert!(v1.position_elem(&4).is_none());
1323     }
1324
1325     #[test]
1326     fn test_bsearch_elem() {
1327         assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
1328         assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
1329         assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
1330         assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
1331         assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
1332
1333         assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
1334         assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
1335         assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
1336         assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
1337
1338         assert_eq!([2,4,6,8].bsearch_elem(&1), None);
1339         assert_eq!([2,4,6,8].bsearch_elem(&5), None);
1340         assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
1341         assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
1342
1343         assert_eq!([2,4,6].bsearch_elem(&1), None);
1344         assert_eq!([2,4,6].bsearch_elem(&5), None);
1345         assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
1346         assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
1347
1348         assert_eq!([2,4].bsearch_elem(&1), None);
1349         assert_eq!([2,4].bsearch_elem(&5), None);
1350         assert_eq!([2,4].bsearch_elem(&2), Some(0));
1351         assert_eq!([2,4].bsearch_elem(&4), Some(1));
1352
1353         assert_eq!([2].bsearch_elem(&1), None);
1354         assert_eq!([2].bsearch_elem(&5), None);
1355         assert_eq!([2].bsearch_elem(&2), Some(0));
1356
1357         assert_eq!([].bsearch_elem(&1), None);
1358         assert_eq!([].bsearch_elem(&5), None);
1359
1360         assert!([1,1,1,1,1].bsearch_elem(&1) != None);
1361         assert!([1,1,1,1,2].bsearch_elem(&1) != None);
1362         assert!([1,1,1,2,2].bsearch_elem(&1) != None);
1363         assert!([1,1,2,2,2].bsearch_elem(&1) != None);
1364         assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
1365
1366         assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
1367         assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
1368     }
1369
1370     #[test]
1371     fn test_reverse() {
1372         let mut v: ~[int] = box [10, 20];
1373         assert_eq!(v[0], 10);
1374         assert_eq!(v[1], 20);
1375         v.reverse();
1376         assert_eq!(v[0], 20);
1377         assert_eq!(v[1], 10);
1378
1379         let mut v3: ~[int] = box [];
1380         v3.reverse();
1381         assert!(v3.is_empty());
1382     }
1383
1384     #[test]
1385     fn test_sort() {
1386         use realstd::slice::Vector;
1387         use realstd::clone::Clone;
1388         for len in range(4u, 25) {
1389             for _ in range(0, 100) {
1390                 let mut v = task_rng().gen_vec::<uint>(len);
1391                 let mut v1 = v.clone();
1392
1393                 v.as_mut_slice().sort();
1394                 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1395
1396                 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1397                 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1398
1399                 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1400                 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1401             }
1402         }
1403
1404         // shouldn't fail/crash
1405         let mut v: [uint, .. 0] = [];
1406         v.sort();
1407
1408         let mut v = [0xDEADBEEFu];
1409         v.sort();
1410         assert!(v == [0xDEADBEEF]);
1411     }
1412
1413     #[test]
1414     fn test_sort_stability() {
1415         for len in range(4, 25) {
1416             for _ in range(0 , 10) {
1417                 let mut counts = [0, .. 10];
1418
1419                 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1420                 // where the first item of each tuple is random, but
1421                 // the second item represents which occurrence of that
1422                 // number this element is, i.e. the second elements
1423                 // will occur in sorted order.
1424                 let mut v = range(0, len).map(|_| {
1425                         let n = task_rng().gen::<uint>() % 10;
1426                         counts[n] += 1;
1427                         (n, counts[n])
1428                     }).collect::<~[(uint, int)]>();
1429
1430                 // only sort on the first element, so an unstable sort
1431                 // may mix up the counts.
1432                 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1433
1434                 // this comparison includes the count (the second item
1435                 // of the tuple), so elements with equal first items
1436                 // will need to be ordered with increasing
1437                 // counts... i.e. exactly asserting that this sort is
1438                 // stable.
1439                 assert!(v.windows(2).all(|w| w[0] <= w[1]));
1440             }
1441         }
1442     }
1443
1444     #[test]
1445     fn test_partition() {
1446         assert_eq!((box []).partition(|x: &int| *x < 3), (box [], box []));
1447         assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 4), (box [1, 2, 3], box []));
1448         assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 2), (box [1], box [2, 3]));
1449         assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 0), (box [], box [1, 2, 3]));
1450     }
1451
1452     #[test]
1453     fn test_partitioned() {
1454         assert_eq!(([]).partitioned(|x: &int| *x < 3), (box [], box []))
1455         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (box [1, 2, 3], box []));
1456         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (box [1], box [2, 3]));
1457         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (box [], box [1, 2, 3]));
1458     }
1459
1460     #[test]
1461     fn test_concat() {
1462         let v: [~[int], ..0] = [];
1463         assert_eq!(v.concat_vec(), box []);
1464         assert_eq!([box [1], box [2,3]].concat_vec(), box [1, 2, 3]);
1465
1466         assert_eq!([&[1], &[2,3]].concat_vec(), box [1, 2, 3]);
1467     }
1468
1469     #[test]
1470     fn test_connect() {
1471         let v: [~[int], ..0] = [];
1472         assert_eq!(v.connect_vec(&0), box []);
1473         assert_eq!([box [1], box [2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
1474         assert_eq!([box [1], box [2], box [3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
1475
1476         assert_eq!(v.connect_vec(&0), box []);
1477         assert_eq!([&[1], &[2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
1478         assert_eq!([&[1], &[2], &[3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
1479     }
1480
1481     #[test]
1482     fn test_shift() {
1483         let mut x = vec![1, 2, 3];
1484         assert_eq!(x.shift(), Some(1));
1485         assert_eq!(&x, &vec![2, 3]);
1486         assert_eq!(x.shift(), Some(2));
1487         assert_eq!(x.shift(), Some(3));
1488         assert_eq!(x.shift(), None);
1489         assert_eq!(x.len(), 0);
1490     }
1491
1492     #[test]
1493     fn test_unshift() {
1494         let mut x = vec![1, 2, 3];
1495         x.unshift(0);
1496         assert_eq!(x, vec![0, 1, 2, 3]);
1497     }
1498
1499     #[test]
1500     fn test_insert() {
1501         let mut a = vec![1, 2, 4];
1502         a.insert(2, 3);
1503         assert_eq!(a, vec![1, 2, 3, 4]);
1504
1505         let mut a = vec![1, 2, 3];
1506         a.insert(0, 0);
1507         assert_eq!(a, vec![0, 1, 2, 3]);
1508
1509         let mut a = vec![1, 2, 3];
1510         a.insert(3, 4);
1511         assert_eq!(a, vec![1, 2, 3, 4]);
1512
1513         let mut a = vec![];
1514         a.insert(0, 1);
1515         assert_eq!(a, vec![1]);
1516     }
1517
1518     #[test]
1519     #[should_fail]
1520     fn test_insert_oob() {
1521         let mut a = vec![1, 2, 3];
1522         a.insert(4, 5);
1523     }
1524
1525     #[test]
1526     fn test_remove() {
1527         let mut a = vec![1,2,3,4];
1528
1529         assert_eq!(a.remove(2), Some(3));
1530         assert_eq!(a, vec![1,2,4]);
1531
1532         assert_eq!(a.remove(2), Some(4));
1533         assert_eq!(a, vec![1,2]);
1534
1535         assert_eq!(a.remove(2), None);
1536         assert_eq!(a, vec![1,2]);
1537
1538         assert_eq!(a.remove(0), Some(1));
1539         assert_eq!(a, vec![2]);
1540
1541         assert_eq!(a.remove(0), Some(2));
1542         assert_eq!(a, vec![]);
1543
1544         assert_eq!(a.remove(0), None);
1545         assert_eq!(a.remove(10), None);
1546     }
1547
1548     #[test]
1549     fn test_capacity() {
1550         let mut v = vec![0u64];
1551         v.reserve_exact(10u);
1552         assert_eq!(v.capacity(), 10u);
1553         let mut v = vec![0u32];
1554         v.reserve_exact(10u);
1555         assert_eq!(v.capacity(), 10u);
1556     }
1557
1558     #[test]
1559     fn test_slice_2() {
1560         let v = vec![1, 2, 3, 4, 5];
1561         let v = v.slice(1u, 3u);
1562         assert_eq!(v.len(), 2u);
1563         assert_eq!(v[0], 2);
1564         assert_eq!(v[1], 3);
1565     }
1566
1567
1568     #[test]
1569     #[should_fail]
1570     fn test_from_fn_fail() {
1571         Vec::from_fn(100, |v| {
1572             if v == 50 { fail!() }
1573             box 0
1574         });
1575     }
1576
1577     #[test]
1578     #[should_fail]
1579     fn test_from_elem_fail() {
1580         use cast;
1581         use cell::Cell;
1582         use rc::Rc;
1583
1584         struct S {
1585             f: Cell<int>,
1586             boxes: (Box<int>, Rc<int>)
1587         }
1588
1589         impl Clone for S {
1590             fn clone(&self) -> S {
1591                 self.f.set(self.f.get() + 1);
1592                 if self.f.get() == 10 { fail!() }
1593                 S { f: self.f, boxes: self.boxes.clone() }
1594             }
1595         }
1596
1597         let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1598         let _ = Vec::from_elem(100, s);
1599     }
1600
1601     #[test]
1602     #[should_fail]
1603     fn test_grow_fn_fail() {
1604         use rc::Rc;
1605         let mut v = vec![];
1606         v.grow_fn(100, |i| {
1607             if i == 50 {
1608                 fail!()
1609             }
1610             (box 0, Rc::new(0))
1611         })
1612     }
1613
1614     #[test]
1615     #[should_fail]
1616     fn test_permute_fail() {
1617         use rc::Rc;
1618         let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
1619                  (box 0, Rc::new(0)), (box 0, Rc::new(0))];
1620         let mut i = 0;
1621         for _ in v.permutations() {
1622             if i == 2 {
1623                 fail!()
1624             }
1625             i += 1;
1626         }
1627     }
1628
1629     #[test]
1630     #[should_fail]
1631     fn test_copy_memory_oob() {
1632         unsafe {
1633             let mut a = [1, 2, 3, 4];
1634             let b = [1, 2, 3, 4, 5];
1635             a.copy_memory(b);
1636         }
1637     }
1638
1639     #[test]
1640     fn test_total_ord() {
1641         [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
1642         [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
1643         [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
1644         [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
1645         [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
1646     }
1647
1648     #[test]
1649     fn test_iterator() {
1650         use iter::*;
1651         let xs = [1, 2, 5, 10, 11];
1652         let mut it = xs.iter();
1653         assert_eq!(it.size_hint(), (5, Some(5)));
1654         assert_eq!(it.next().unwrap(), &1);
1655         assert_eq!(it.size_hint(), (4, Some(4)));
1656         assert_eq!(it.next().unwrap(), &2);
1657         assert_eq!(it.size_hint(), (3, Some(3)));
1658         assert_eq!(it.next().unwrap(), &5);
1659         assert_eq!(it.size_hint(), (2, Some(2)));
1660         assert_eq!(it.next().unwrap(), &10);
1661         assert_eq!(it.size_hint(), (1, Some(1)));
1662         assert_eq!(it.next().unwrap(), &11);
1663         assert_eq!(it.size_hint(), (0, Some(0)));
1664         assert!(it.next().is_none());
1665     }
1666
1667     #[test]
1668     fn test_random_access_iterator() {
1669         use iter::*;
1670         let xs = [1, 2, 5, 10, 11];
1671         let mut it = xs.iter();
1672
1673         assert_eq!(it.indexable(), 5);
1674         assert_eq!(it.idx(0).unwrap(), &1);
1675         assert_eq!(it.idx(2).unwrap(), &5);
1676         assert_eq!(it.idx(4).unwrap(), &11);
1677         assert!(it.idx(5).is_none());
1678
1679         assert_eq!(it.next().unwrap(), &1);
1680         assert_eq!(it.indexable(), 4);
1681         assert_eq!(it.idx(0).unwrap(), &2);
1682         assert_eq!(it.idx(3).unwrap(), &11);
1683         assert!(it.idx(4).is_none());
1684
1685         assert_eq!(it.next().unwrap(), &2);
1686         assert_eq!(it.indexable(), 3);
1687         assert_eq!(it.idx(1).unwrap(), &10);
1688         assert!(it.idx(3).is_none());
1689
1690         assert_eq!(it.next().unwrap(), &5);
1691         assert_eq!(it.indexable(), 2);
1692         assert_eq!(it.idx(1).unwrap(), &11);
1693
1694         assert_eq!(it.next().unwrap(), &10);
1695         assert_eq!(it.indexable(), 1);
1696         assert_eq!(it.idx(0).unwrap(), &11);
1697         assert!(it.idx(1).is_none());
1698
1699         assert_eq!(it.next().unwrap(), &11);
1700         assert_eq!(it.indexable(), 0);
1701         assert!(it.idx(0).is_none());
1702
1703         assert!(it.next().is_none());
1704     }
1705
1706     #[test]
1707     fn test_iter_size_hints() {
1708         use iter::*;
1709         let mut xs = [1, 2, 5, 10, 11];
1710         assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1711         assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1712     }
1713
1714     #[test]
1715     fn test_iter_clone() {
1716         let xs = [1, 2, 5];
1717         let mut it = xs.iter();
1718         it.next();
1719         let mut jt = it.clone();
1720         assert_eq!(it.next(), jt.next());
1721         assert_eq!(it.next(), jt.next());
1722         assert_eq!(it.next(), jt.next());
1723     }
1724
1725     #[test]
1726     fn test_mut_iterator() {
1727         use iter::*;
1728         let mut xs = [1, 2, 3, 4, 5];
1729         for x in xs.mut_iter() {
1730             *x += 1;
1731         }
1732         assert!(xs == [2, 3, 4, 5, 6])
1733     }
1734
1735     #[test]
1736     fn test_rev_iterator() {
1737         use iter::*;
1738
1739         let xs = [1, 2, 5, 10, 11];
1740         let ys = [11, 10, 5, 2, 1];
1741         let mut i = 0;
1742         for &x in xs.iter().rev() {
1743             assert_eq!(x, ys[i]);
1744             i += 1;
1745         }
1746         assert_eq!(i, 5);
1747     }
1748
1749     #[test]
1750     fn test_mut_rev_iterator() {
1751         use iter::*;
1752         let mut xs = [1u, 2, 3, 4, 5];
1753         for (i,x) in xs.mut_iter().rev().enumerate() {
1754             *x += i;
1755         }
1756         assert!(xs == [5, 5, 5, 5, 5])
1757     }
1758
1759     #[test]
1760     fn test_move_iterator() {
1761         use iter::*;
1762         let xs = box [1u,2,3,4,5];
1763         assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1764     }
1765
1766     #[test]
1767     fn test_move_rev_iterator() {
1768         use iter::*;
1769         let xs = box [1u,2,3,4,5];
1770         assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1771     }
1772
1773     #[test]
1774     fn test_splitator() {
1775         let xs = &[1i,2,3,4,5];
1776
1777         assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
1778                    box [&[1], &[3], &[5]]);
1779         assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
1780                    box [&[], &[2,3,4,5]]);
1781         assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
1782                    box [&[1,2,3,4], &[]]);
1783         assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
1784                    box [&[1,2,3,4,5]]);
1785         assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
1786                    box [&[], &[], &[], &[], &[], &[]]);
1787
1788         let xs: &[int] = &[];
1789         assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1790     }
1791
1792     #[test]
1793     fn test_splitnator() {
1794         let xs = &[1i,2,3,4,5];
1795
1796         assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1797                    box [&[1,2,3,4,5]]);
1798         assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1799                    box [&[1], &[3,4,5]]);
1800         assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
1801                    box [&[], &[], &[], &[4,5]]);
1802
1803         let xs: &[int] = &[];
1804         assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1805     }
1806
1807     #[test]
1808     fn test_rsplitator() {
1809         let xs = &[1i,2,3,4,5];
1810
1811         assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<~[&[int]]>(),
1812                    box [&[5], &[3], &[1]]);
1813         assert_eq!(xs.split(|x| *x == 1).rev().collect::<~[&[int]]>(),
1814                    box [&[2,3,4,5], &[]]);
1815         assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(),
1816                    box [&[], &[1,2,3,4]]);
1817         assert_eq!(xs.split(|x| *x == 10).rev().collect::<~[&[int]]>(),
1818                    box [&[1,2,3,4,5]]);
1819
1820         let xs: &[int] = &[];
1821         assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(), box [&[]]);
1822     }
1823
1824     #[test]
1825     fn test_rsplitnator() {
1826         let xs = &[1,2,3,4,5];
1827
1828         assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1829                    box [&[1,2,3,4,5]]);
1830         assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1831                    box [&[5], &[1,2,3]]);
1832         assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
1833                    box [&[], &[], &[], &[1,2]]);
1834
1835         let xs: &[int] = &[];
1836         assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1837     }
1838
1839     #[test]
1840     fn test_windowsator() {
1841         let v = &[1i,2,3,4];
1842
1843         assert_eq!(v.windows(2).collect::<~[&[int]]>(), box [&[1,2], &[2,3], &[3,4]]);
1844         assert_eq!(v.windows(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[2,3,4]]);
1845         assert!(v.windows(6).next().is_none());
1846     }
1847
1848     #[test]
1849     #[should_fail]
1850     fn test_windowsator_0() {
1851         let v = &[1i,2,3,4];
1852         let _it = v.windows(0);
1853     }
1854
1855     #[test]
1856     fn test_chunksator() {
1857         let v = &[1i,2,3,4,5];
1858
1859         assert_eq!(v.chunks(2).collect::<~[&[int]]>(), box [&[1i,2], &[3,4], &[5]]);
1860         assert_eq!(v.chunks(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[4,5]]);
1861         assert_eq!(v.chunks(6).collect::<~[&[int]]>(), box [&[1i,2,3,4,5]]);
1862
1863         assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), box [&[5i], &[3,4], &[1,2]]);
1864         let mut it = v.chunks(2);
1865         assert_eq!(it.indexable(), 3);
1866         assert_eq!(it.idx(0).unwrap(), &[1,2]);
1867         assert_eq!(it.idx(1).unwrap(), &[3,4]);
1868         assert_eq!(it.idx(2).unwrap(), &[5]);
1869         assert_eq!(it.idx(3), None);
1870     }
1871
1872     #[test]
1873     #[should_fail]
1874     fn test_chunksator_0() {
1875         let v = &[1i,2,3,4];
1876         let _it = v.chunks(0);
1877     }
1878
1879     #[test]
1880     fn test_move_from() {
1881         let mut a = [1,2,3,4,5];
1882         let b = box [6,7,8];
1883         assert_eq!(a.move_from(b, 0, 3), 3);
1884         assert!(a == [6,7,8,4,5]);
1885         let mut a = [7,2,8,1];
1886         let b = box [3,1,4,1,5,9];
1887         assert_eq!(a.move_from(b, 0, 6), 4);
1888         assert!(a == [3,1,4,1]);
1889         let mut a = [1,2,3,4];
1890         let b = box [5,6,7,8,9,0];
1891         assert_eq!(a.move_from(b, 2, 3), 1);
1892         assert!(a == [7,2,3,4]);
1893         let mut a = [1,2,3,4,5];
1894         let b = box [5,6,7,8,9,0];
1895         assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1896         assert!(a == [1,2,6,7,5]);
1897     }
1898
1899     #[test]
1900     fn test_copy_from() {
1901         let mut a = [1,2,3,4,5];
1902         let b = [6,7,8];
1903         assert_eq!(a.copy_from(b), 3);
1904         assert!(a == [6,7,8,4,5]);
1905         let mut c = [7,2,8,1];
1906         let d = [3,1,4,1,5,9];
1907         assert_eq!(c.copy_from(d), 4);
1908         assert!(c == [3,1,4,1]);
1909     }
1910
1911     #[test]
1912     fn test_reverse_part() {
1913         let mut values = [1,2,3,4,5];
1914         values.mut_slice(1, 4).reverse();
1915         assert!(values == [1,4,3,2,5]);
1916     }
1917
1918     #[test]
1919     fn test_show() {
1920         macro_rules! test_show_vec(
1921             ($x:expr, $x_str:expr) => ({
1922                 let (x, x_str) = ($x, $x_str);
1923                 assert_eq!(format!("{}", x), x_str);
1924                 assert_eq!(format!("{}", x.as_slice()), x_str);
1925             })
1926         )
1927         let empty: ~[int] = box [];
1928         test_show_vec!(empty, "[]".to_owned());
1929         test_show_vec!(box [1], "[1]".to_owned());
1930         test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_owned());
1931         test_show_vec!(box [box [], box [1u], box [1u, 1u]], "[[], [1], [1, 1]]".to_owned());
1932
1933         let empty_mut: &mut [int] = &mut[];
1934         test_show_vec!(empty_mut, "[]".to_owned());
1935         test_show_vec!(&mut[1], "[1]".to_owned());
1936         test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_owned());
1937         test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]], "[[], [1], [1, 1]]".to_owned());
1938     }
1939
1940     #[test]
1941     fn test_vec_default() {
1942         use default::Default;
1943         macro_rules! t (
1944             ($ty:ty) => {{
1945                 let v: $ty = Default::default();
1946                 assert!(v.is_empty());
1947             }}
1948         );
1949
1950         t!(&[int]);
1951         t!(~[int]);
1952         t!(Vec<int>);
1953     }
1954
1955     #[test]
1956     fn test_bytes_set_memory() {
1957         use slice::bytes::MutableByteVector;
1958         let mut values = [1u8,2,3,4,5];
1959         values.mut_slice(0,5).set_memory(0xAB);
1960         assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1961         values.mut_slice(2,4).set_memory(0xFF);
1962         assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1963     }
1964
1965     #[test]
1966     #[should_fail]
1967     fn test_overflow_does_not_cause_segfault() {
1968         let mut v = vec![];
1969         v.reserve_exact(-1);
1970         v.push(1);
1971         v.push(2);
1972     }
1973
1974     #[test]
1975     #[should_fail]
1976     fn test_overflow_does_not_cause_segfault_managed() {
1977         use rc::Rc;
1978         let mut v = vec![Rc::new(1)];
1979         v.reserve_exact(-1);
1980         v.push(Rc::new(2));
1981     }
1982
1983     #[test]
1984     fn test_mut_split_at() {
1985         let mut values = [1u8,2,3,4,5];
1986         {
1987             let (left, right) = values.mut_split_at(2);
1988             assert!(left.slice(0, left.len()) == [1, 2]);
1989             for p in left.mut_iter() {
1990                 *p += 1;
1991             }
1992
1993             assert!(right.slice(0, right.len()) == [3, 4, 5]);
1994             for p in right.mut_iter() {
1995                 *p += 2;
1996             }
1997         }
1998
1999         assert!(values == [2, 3, 5, 6, 7]);
2000     }
2001
2002     #[deriving(Clone, Eq)]
2003     struct Foo;
2004
2005     #[test]
2006     fn test_iter_zero_sized() {
2007         let mut v = vec![Foo, Foo, Foo];
2008         assert_eq!(v.len(), 3);
2009         let mut cnt = 0;
2010
2011         for f in v.iter() {
2012             assert!(*f == Foo);
2013             cnt += 1;
2014         }
2015         assert_eq!(cnt, 3);
2016
2017         for f in v.slice(1, 3).iter() {
2018             assert!(*f == Foo);
2019             cnt += 1;
2020         }
2021         assert_eq!(cnt, 5);
2022
2023         for f in v.mut_iter() {
2024             assert!(*f == Foo);
2025             cnt += 1;
2026         }
2027         assert_eq!(cnt, 8);
2028
2029         for f in v.move_iter() {
2030             assert!(f == Foo);
2031             cnt += 1;
2032         }
2033         assert_eq!(cnt, 11);
2034
2035         let xs: [Foo, ..3] = [Foo, Foo, Foo];
2036         cnt = 0;
2037         for f in xs.iter() {
2038             assert!(*f == Foo);
2039             cnt += 1;
2040         }
2041         assert!(cnt == 3);
2042     }
2043
2044     #[test]
2045     fn test_shrink_to_fit() {
2046         let mut xs = vec![0, 1, 2, 3];
2047         for i in range(4, 100) {
2048             xs.push(i)
2049         }
2050         assert_eq!(xs.capacity(), 128);
2051         xs.shrink_to_fit();
2052         assert_eq!(xs.capacity(), 100);
2053         assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
2054     }
2055
2056     #[test]
2057     fn test_starts_with() {
2058         assert!(bytes!("foobar").starts_with(bytes!("foo")));
2059         assert!(!bytes!("foobar").starts_with(bytes!("oob")));
2060         assert!(!bytes!("foobar").starts_with(bytes!("bar")));
2061         assert!(!bytes!("foo").starts_with(bytes!("foobar")));
2062         assert!(!bytes!("bar").starts_with(bytes!("foobar")));
2063         assert!(bytes!("foobar").starts_with(bytes!("foobar")));
2064         let empty: &[u8] = [];
2065         assert!(empty.starts_with(empty));
2066         assert!(!empty.starts_with(bytes!("foo")));
2067         assert!(bytes!("foobar").starts_with(empty));
2068     }
2069
2070     #[test]
2071     fn test_ends_with() {
2072         assert!(bytes!("foobar").ends_with(bytes!("bar")));
2073         assert!(!bytes!("foobar").ends_with(bytes!("oba")));
2074         assert!(!bytes!("foobar").ends_with(bytes!("foo")));
2075         assert!(!bytes!("foo").ends_with(bytes!("foobar")));
2076         assert!(!bytes!("bar").ends_with(bytes!("foobar")));
2077         assert!(bytes!("foobar").ends_with(bytes!("foobar")));
2078         let empty: &[u8] = [];
2079         assert!(empty.ends_with(empty));
2080         assert!(!empty.ends_with(bytes!("foo")));
2081         assert!(bytes!("foobar").ends_with(empty));
2082     }
2083
2084     #[test]
2085     fn test_shift_ref() {
2086         let mut x: &[int] = [1, 2, 3, 4, 5];
2087         let h = x.shift_ref();
2088         assert_eq!(*h.unwrap(), 1);
2089         assert_eq!(x.len(), 4);
2090         assert_eq!(x[0], 2);
2091         assert_eq!(x[3], 5);
2092
2093         let mut y: &[int] = [];
2094         assert_eq!(y.shift_ref(), None);
2095     }
2096
2097     #[test]
2098     fn test_pop_ref() {
2099         let mut x: &[int] = [1, 2, 3, 4, 5];
2100         let h = x.pop_ref();
2101         assert_eq!(*h.unwrap(), 5);
2102         assert_eq!(x.len(), 4);
2103         assert_eq!(x[0], 1);
2104         assert_eq!(x[3], 4);
2105
2106         let mut y: &[int] = [];
2107         assert!(y.pop_ref().is_none());
2108     }
2109
2110     #[test]
2111     fn test_mut_splitator() {
2112         let mut xs = [0,1,0,2,3,0,0,4,5,0];
2113         assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
2114         for slice in xs.mut_split(|x| *x == 0) {
2115             slice.reverse();
2116         }
2117         assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2118
2119         let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
2120         for slice in xs.mut_split(|x| *x == 0).take(5) {
2121             slice.reverse();
2122         }
2123         assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2124     }
2125
2126     #[test]
2127     fn test_mut_splitator_rev() {
2128         let mut xs = [1,2,0,3,4,0,0,5,6,0];
2129         for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2130             slice.reverse();
2131         }
2132         assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2133     }
2134
2135     #[test]
2136     fn test_mut_chunks() {
2137         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2138         for (i, chunk) in v.mut_chunks(3).enumerate() {
2139             for x in chunk.mut_iter() {
2140                 *x = i as u8;
2141             }
2142         }
2143         let result = [0u8, 0, 0, 1, 1, 1, 2];
2144         assert!(v == result);
2145     }
2146
2147     #[test]
2148     fn test_mut_chunks_rev() {
2149         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2150         for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2151             for x in chunk.mut_iter() {
2152                 *x = i as u8;
2153             }
2154         }
2155         let result = [2u8, 2, 2, 1, 1, 1, 0];
2156         assert!(v == result);
2157     }
2158
2159     #[test]
2160     #[should_fail]
2161     fn test_mut_chunks_0() {
2162         let mut v = [1, 2, 3, 4];
2163         let _it = v.mut_chunks(0);
2164     }
2165
2166     #[test]
2167     fn test_mut_shift_ref() {
2168         let mut x: &mut [int] = [1, 2, 3, 4, 5];
2169         let h = x.mut_shift_ref();
2170         assert_eq!(*h.unwrap(), 1);
2171         assert_eq!(x.len(), 4);
2172         assert_eq!(x[0], 2);
2173         assert_eq!(x[3], 5);
2174
2175         let mut y: &mut [int] = [];
2176         assert!(y.mut_shift_ref().is_none());
2177     }
2178
2179     #[test]
2180     fn test_mut_pop_ref() {
2181         let mut x: &mut [int] = [1, 2, 3, 4, 5];
2182         let h = x.mut_pop_ref();
2183         assert_eq!(*h.unwrap(), 5);
2184         assert_eq!(x.len(), 4);
2185         assert_eq!(x[0], 1);
2186         assert_eq!(x[3], 4);
2187
2188         let mut y: &mut [int] = [];
2189         assert!(y.mut_pop_ref().is_none());
2190     }
2191
2192     #[test]
2193     fn test_mut_last() {
2194         let mut x = [1, 2, 3, 4, 5];
2195         let h = x.mut_last();
2196         assert_eq!(*h.unwrap(), 5);
2197
2198         let y: &mut [int] = [];
2199         assert!(y.mut_last().is_none());
2200     }
2201 }
2202
2203 #[cfg(test)]
2204 mod bench {
2205     extern crate test;
2206     use self::test::Bencher;
2207     use mem;
2208     use prelude::*;
2209     use ptr;
2210     use rand::{weak_rng, Rng};
2211
2212     #[bench]
2213     fn iterator(b: &mut Bencher) {
2214         // peculiar numbers to stop LLVM from optimising the summation
2215         // out.
2216         let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2217
2218         b.iter(|| {
2219             let mut sum = 0;
2220             for x in v.iter() {
2221                 sum += *x;
2222             }
2223             // sum == 11806, to stop dead code elimination.
2224             if sum == 0 {fail!()}
2225         })
2226     }
2227
2228     #[bench]
2229     fn mut_iterator(b: &mut Bencher) {
2230         let mut v = Vec::from_elem(100, 0);
2231
2232         b.iter(|| {
2233             let mut i = 0;
2234             for x in v.mut_iter() {
2235                 *x = i;
2236                 i += 1;
2237             }
2238         })
2239     }
2240
2241     #[bench]
2242     fn add(b: &mut Bencher) {
2243         let xs: &[int] = [5, ..10];
2244         let ys: &[int] = [5, ..10];
2245         b.iter(|| {
2246             xs + ys;
2247         });
2248     }
2249
2250     #[bench]
2251     fn concat(b: &mut Bencher) {
2252         let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2253         b.iter(|| {
2254             xss.as_slice().concat_vec()
2255         });
2256     }
2257
2258     #[bench]
2259     fn connect(b: &mut Bencher) {
2260         let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2261         b.iter(|| {
2262             xss.as_slice().connect_vec(&0)
2263         });
2264     }
2265
2266     #[bench]
2267     fn push(b: &mut Bencher) {
2268         let mut vec: Vec<uint> = vec![];
2269         b.iter(|| {
2270             vec.push(0);
2271             &vec
2272         })
2273     }
2274
2275     #[bench]
2276     fn starts_with_same_vector(b: &mut Bencher) {
2277         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2278         b.iter(|| {
2279             vec.as_slice().starts_with(vec.as_slice())
2280         })
2281     }
2282
2283     #[bench]
2284     fn starts_with_single_element(b: &mut Bencher) {
2285         let vec: Vec<uint> = vec![0];
2286         b.iter(|| {
2287             vec.as_slice().starts_with(vec.as_slice())
2288         })
2289     }
2290
2291     #[bench]
2292     fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2293         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2294         let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2295         match_vec.push(0);
2296         b.iter(|| {
2297             vec.as_slice().starts_with(match_vec.as_slice())
2298         })
2299     }
2300
2301     #[bench]
2302     fn ends_with_same_vector(b: &mut Bencher) {
2303         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2304         b.iter(|| {
2305             vec.as_slice().ends_with(vec.as_slice())
2306         })
2307     }
2308
2309     #[bench]
2310     fn ends_with_single_element(b: &mut Bencher) {
2311         let vec: Vec<uint> = vec![0];
2312         b.iter(|| {
2313             vec.as_slice().ends_with(vec.as_slice())
2314         })
2315     }
2316
2317     #[bench]
2318     fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2319         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2320         let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2321         match_vec.as_mut_slice()[0] = 200;
2322         b.iter(|| {
2323             vec.as_slice().starts_with(match_vec.as_slice())
2324         })
2325     }
2326
2327     #[bench]
2328     fn contains_last_element(b: &mut Bencher) {
2329         let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2330         b.iter(|| {
2331             vec.contains(&99u)
2332         })
2333     }
2334
2335     #[bench]
2336     fn zero_1kb_from_elem(b: &mut Bencher) {
2337         b.iter(|| {
2338             Vec::from_elem(1024, 0u8)
2339         });
2340     }
2341
2342     #[bench]
2343     fn zero_1kb_set_memory(b: &mut Bencher) {
2344         b.iter(|| {
2345             let mut v: Vec<uint> = Vec::with_capacity(1024);
2346             unsafe {
2347                 let vp = v.as_mut_ptr();
2348                 ptr::set_memory(vp, 0, 1024);
2349                 v.set_len(1024);
2350             }
2351             v
2352         });
2353     }
2354
2355     #[bench]
2356     fn zero_1kb_fixed_repeat(b: &mut Bencher) {
2357         b.iter(|| {
2358             box [0u8, ..1024]
2359         });
2360     }
2361
2362     #[bench]
2363     fn zero_1kb_loop_set(b: &mut Bencher) {
2364         b.iter(|| {
2365             let mut v: Vec<uint> = Vec::with_capacity(1024);
2366             unsafe {
2367                 v.set_len(1024);
2368             }
2369             for i in range(0u, 1024) {
2370                 *v.get_mut(i) = 0;
2371             }
2372         });
2373     }
2374
2375     #[bench]
2376     fn zero_1kb_mut_iter(b: &mut Bencher) {
2377         b.iter(|| {
2378             let mut v = Vec::with_capacity(1024);
2379             unsafe {
2380                 v.set_len(1024);
2381             }
2382             for x in v.mut_iter() {
2383                 *x = 0;
2384             }
2385             v
2386         });
2387     }
2388
2389     #[bench]
2390     fn random_inserts(b: &mut Bencher) {
2391         let mut rng = weak_rng();
2392         b.iter(|| {
2393                 let mut v = Vec::from_elem(30, (0u, 0u));
2394                 for _ in range(0, 100) {
2395                     let l = v.len();
2396                     v.insert(rng.gen::<uint>() % (l + 1),
2397                              (1, 1));
2398                 }
2399             })
2400     }
2401     #[bench]
2402     fn random_removes(b: &mut Bencher) {
2403         let mut rng = weak_rng();
2404         b.iter(|| {
2405                 let mut v = Vec::from_elem(130, (0u, 0u));
2406                 for _ in range(0, 100) {
2407                     let l = v.len();
2408                     v.remove(rng.gen::<uint>() % l);
2409                 }
2410             })
2411     }
2412
2413     #[bench]
2414     fn sort_random_small(b: &mut Bencher) {
2415         let mut rng = weak_rng();
2416         b.iter(|| {
2417             let mut v = rng.gen_vec::<u64>(5);
2418             v.as_mut_slice().sort();
2419         });
2420         b.bytes = 5 * mem::size_of::<u64>() as u64;
2421     }
2422
2423     #[bench]
2424     fn sort_random_medium(b: &mut Bencher) {
2425         let mut rng = weak_rng();
2426         b.iter(|| {
2427             let mut v = rng.gen_vec::<u64>(100);
2428             v.as_mut_slice().sort();
2429         });
2430         b.bytes = 100 * mem::size_of::<u64>() as u64;
2431     }
2432
2433     #[bench]
2434     fn sort_random_large(b: &mut Bencher) {
2435         let mut rng = weak_rng();
2436         b.iter(|| {
2437             let mut v = rng.gen_vec::<u64>(10000);
2438             v.as_mut_slice().sort();
2439         });
2440         b.bytes = 10000 * mem::size_of::<u64>() as u64;
2441     }
2442
2443     #[bench]
2444     fn sort_sorted(b: &mut Bencher) {
2445         let mut v = Vec::from_fn(10000, |i| i);
2446         b.iter(|| {
2447             v.sort();
2448         });
2449         b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2450     }
2451
2452     type BigSortable = (u64,u64,u64,u64);
2453
2454     #[bench]
2455     fn sort_big_random_small(b: &mut Bencher) {
2456         let mut rng = weak_rng();
2457         b.iter(|| {
2458             let mut v = rng.gen_vec::<BigSortable>(5);
2459             v.sort();
2460         });
2461         b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2462     }
2463
2464     #[bench]
2465     fn sort_big_random_medium(b: &mut Bencher) {
2466         let mut rng = weak_rng();
2467         b.iter(|| {
2468             let mut v = rng.gen_vec::<BigSortable>(100);
2469             v.sort();
2470         });
2471         b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2472     }
2473
2474     #[bench]
2475     fn sort_big_random_large(b: &mut Bencher) {
2476         let mut rng = weak_rng();
2477         b.iter(|| {
2478             let mut v = rng.gen_vec::<BigSortable>(10000);
2479             v.sort();
2480         });
2481         b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2482     }
2483
2484     #[bench]
2485     fn sort_big_sorted(b: &mut Bencher) {
2486         let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2487         b.iter(|| {
2488             v.sort();
2489         });
2490         b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2491     }
2492 }