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