]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
auto merge of #15421 : catharsis/rust/doc-ffi-minor-fixes, r=alexcrichton
[rust.git] / src / libcollections / vec.rs
1 // Copyright 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 //! An owned, growable vector.
12
13 use core::prelude::*;
14
15 use alloc::heap::{allocate, reallocate, deallocate};
16 use core::raw::Slice;
17 use core::cmp::max;
18 use core::default::Default;
19 use core::fmt;
20 use core::mem;
21 use core::num::{CheckedMul, CheckedAdd};
22 use core::num;
23 use core::ptr;
24 use core::uint;
25
26 use {Collection, Mutable};
27 use slice::{MutableOrdVector, MutableVectorAllocating, CloneableVector};
28 use slice::{Items, MutItems};
29
30
31 #[doc(hidden)]
32 pub static PTR_MARKER: u8 = 0;
33
34 /// An owned, growable vector.
35 ///
36 /// # Examples
37 ///
38 /// ```rust
39 /// # use std::vec::Vec;
40 /// let mut vec = Vec::new();
41 /// vec.push(1i);
42 /// vec.push(2i);
43 ///
44 /// assert_eq!(vec.len(), 2);
45 /// assert_eq!(vec.get(0), &1);
46 ///
47 /// assert_eq!(vec.pop(), Some(2));
48 /// assert_eq!(vec.len(), 1);
49 /// ```
50 ///
51 /// The `vec!` macro is provided to make initialization more convenient:
52 ///
53 /// ```rust
54 /// let mut vec = vec!(1i, 2i, 3i);
55 /// vec.push(4);
56 /// assert_eq!(vec, vec!(1, 2, 3, 4));
57 /// ```
58 #[unsafe_no_drop_flag]
59 pub struct Vec<T> {
60     len: uint,
61     cap: uint,
62     ptr: *mut T
63 }
64
65 impl<T> Vec<T> {
66     /// Constructs a new, empty `Vec`.
67     ///
68     /// The vector will not allocate until elements are pushed onto it.
69     ///
70     /// # Example
71     ///
72     /// ```rust
73     /// # use std::vec::Vec;
74     /// let mut vec: Vec<int> = Vec::new();
75     /// ```
76     #[inline]
77     pub fn new() -> Vec<T> {
78         // We want ptr to never be NULL so instead we set it to some arbitrary
79         // non-null value which is fine since we never call deallocate on the ptr
80         // if cap is 0. The reason for this is because the pointer of a slice
81         // being NULL would break the null pointer optimization for enums.
82         Vec { len: 0, cap: 0, ptr: &PTR_MARKER as *const _ as *mut T }
83     }
84
85     /// Constructs a new, empty `Vec` with the specified capacity.
86     ///
87     /// The vector will be able to hold exactly `capacity` elements without
88     /// reallocating. If `capacity` is 0, the vector will not allocate.
89     ///
90     /// # Example
91     ///
92     /// ```rust
93     /// # use std::vec::Vec;
94     /// let vec: Vec<int> = Vec::with_capacity(10);
95     /// ```
96     #[inline]
97     pub fn with_capacity(capacity: uint) -> Vec<T> {
98         if mem::size_of::<T>() == 0 {
99             Vec { len: 0, cap: uint::MAX, ptr: &PTR_MARKER as *const _ as *mut T }
100         } else if capacity == 0 {
101             Vec::new()
102         } else {
103             let size = capacity.checked_mul(&mem::size_of::<T>())
104                                .expect("capacity overflow");
105             let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
106             Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
107         }
108     }
109
110     /// Creates and initializes a `Vec`.
111     ///
112     /// Creates a `Vec` of size `length` and initializes the elements to the
113     /// value returned by the closure `op`.
114     ///
115     /// # Example
116     ///
117     /// ```rust
118     /// # use std::vec::Vec;
119     /// let vec = Vec::from_fn(3, |idx| idx * 2);
120     /// assert_eq!(vec, vec!(0, 2, 4));
121     /// ```
122     #[inline]
123     pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
124         unsafe {
125             let mut xs = Vec::with_capacity(length);
126             while xs.len < length {
127                 let len = xs.len;
128                 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len), op(len));
129                 xs.len += 1;
130             }
131             xs
132         }
133     }
134
135     /// Create a `Vec<T>` directly from the raw constituents.
136     ///
137     /// This is highly unsafe:
138     ///
139     /// - if `ptr` is null, then `length` and `capacity` should be 0
140     /// - `ptr` must point to an allocation of size `capacity`
141     /// - there must be `length` valid instances of type `T` at the
142     ///   beginning of that allocation
143     /// - `ptr` must be allocated by the default `Vec` allocator
144     pub unsafe fn from_raw_parts(length: uint, capacity: uint,
145                                  ptr: *mut T) -> Vec<T> {
146         Vec { len: length, cap: capacity, ptr: ptr }
147     }
148
149     /// Consumes the `Vec`, partitioning it based on a predicate.
150     ///
151     /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
152     /// satisfy `f` and all elements of `B` do not. The order of elements is
153     /// preserved.
154     ///
155     /// # Example
156     ///
157     /// ```rust
158     /// let vec = vec!(1i, 2i, 3i, 4i);
159     /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
160     /// assert_eq!(even, vec!(2, 4));
161     /// assert_eq!(odd, vec!(1, 3));
162     /// ```
163     #[inline]
164     pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
165         let mut lefts  = Vec::new();
166         let mut rights = Vec::new();
167
168         for elt in self.move_iter() {
169             if f(&elt) {
170                 lefts.push(elt);
171             } else {
172                 rights.push(elt);
173             }
174         }
175
176         (lefts, rights)
177     }
178 }
179
180 impl<T: Clone> Vec<T> {
181     /// Iterates over the `second` vector, copying each element and appending it to
182     /// the `first`. Afterwards, the `first` is then returned for use again.
183     ///
184     /// # Example
185     ///
186     /// ```rust
187     /// let vec = vec!(1i, 2i);
188     /// let vec = vec.append([3i, 4i]);
189     /// assert_eq!(vec, vec!(1, 2, 3, 4));
190     /// ```
191     #[inline]
192     pub fn append(mut self, second: &[T]) -> Vec<T> {
193         self.push_all(second);
194         self
195     }
196
197     /// Constructs a `Vec` by cloning elements of a slice.
198     ///
199     /// # Example
200     ///
201     /// ```rust
202     /// # use std::vec::Vec;
203     /// let slice = [1i, 2, 3];
204     /// let vec = Vec::from_slice(slice);
205     /// ```
206     #[inline]
207     pub fn from_slice(values: &[T]) -> Vec<T> {
208         let mut vector = Vec::new();
209         vector.push_all(values);
210         vector
211     }
212
213     /// Constructs a `Vec` with copies of a value.
214     ///
215     /// Creates a `Vec` with `length` copies of `value`.
216     ///
217     /// # Example
218     /// ```rust
219     /// # use std::vec::Vec;
220     /// let vec = Vec::from_elem(3, "hi");
221     /// println!("{}", vec); // prints [hi, hi, hi]
222     /// ```
223     #[inline]
224     pub fn from_elem(length: uint, value: T) -> Vec<T> {
225         unsafe {
226             let mut xs = Vec::with_capacity(length);
227             while xs.len < length {
228                 let len = xs.len;
229                 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len),
230                            value.clone());
231                 xs.len += 1;
232             }
233             xs
234         }
235     }
236
237     /// Appends all elements in a slice to the `Vec`.
238     ///
239     /// Iterates over the slice `other`, clones each element, and then appends
240     /// it to this `Vec`. The `other` vector is traversed in-order.
241     ///
242     /// # Example
243     ///
244     /// ```rust
245     /// let mut vec = vec!(1i);
246     /// vec.push_all([2i, 3, 4]);
247     /// assert_eq!(vec, vec!(1, 2, 3, 4));
248     /// ```
249     #[inline]
250     pub fn push_all(&mut self, other: &[T]) {
251         self.reserve_additional(other.len());
252
253         for i in range(0, other.len()) {
254             let len = self.len();
255
256             // Unsafe code so this can be optimised to a memcpy (or something similarly
257             // fast) when T is Copy. LLVM is easily confused, so any extra operations
258             // during the loop can prevent this optimisation.
259             unsafe {
260                 ptr::write(
261                     self.as_mut_slice().unsafe_mut_ref(len),
262                     other.unsafe_ref(i).clone());
263                 self.set_len(len + 1);
264             }
265         }
266     }
267
268     /// Grows the `Vec` in-place.
269     ///
270     /// Adds `n` copies of `value` to the `Vec`.
271     ///
272     /// # Example
273     ///
274     /// ```rust
275     /// let mut vec = vec!("hello");
276     /// vec.grow(2, &("world"));
277     /// assert_eq!(vec, vec!("hello", "world", "world"));
278     /// ```
279     pub fn grow(&mut self, n: uint, value: &T) {
280         self.reserve_additional(n);
281         let mut i: uint = 0u;
282
283         while i < n {
284             self.push((*value).clone());
285             i += 1u;
286         }
287     }
288
289     /// Sets the value of a vector element at a given index, growing the vector
290     /// as needed.
291     ///
292     /// Sets the element at position `index` to `value`. If `index` is past the
293     /// end of the vector, expands the vector by replicating `initval` to fill
294     /// the intervening space.
295     ///
296     /// # Example
297     ///
298     /// ```rust
299     /// let mut vec = vec!("a", "b", "c");
300     /// vec.grow_set(1, &("fill"), "d");
301     /// vec.grow_set(4, &("fill"), "e");
302     /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
303     /// ```
304     pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
305         let l = self.len();
306         if index >= l {
307             self.grow(index - l + 1u, initval);
308         }
309         *self.get_mut(index) = value;
310     }
311
312     /// Partitions a vector based on a predicate.
313     ///
314     /// Clones the elements of the vector, partitioning them into two `Vec`s
315     /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
316     /// do not. The order of elements is preserved.
317     ///
318     /// # Example
319     ///
320     /// ```rust
321     /// let vec = vec!(1i, 2, 3, 4);
322     /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
323     /// assert_eq!(even, vec!(2i, 4));
324     /// assert_eq!(odd, vec!(1i, 3));
325     /// ```
326     pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
327         let mut lefts = Vec::new();
328         let mut rights = Vec::new();
329
330         for elt in self.iter() {
331             if f(elt) {
332                 lefts.push(elt.clone());
333             } else {
334                 rights.push(elt.clone());
335             }
336         }
337
338         (lefts, rights)
339     }
340 }
341
342 #[unstable]
343 impl<T:Clone> Clone for Vec<T> {
344     fn clone(&self) -> Vec<T> {
345         Vec::from_slice(self.as_slice())
346     }
347
348     fn clone_from(&mut self, other: &Vec<T>) {
349         // drop anything in self that will not be overwritten
350         if self.len() > other.len() {
351             self.truncate(other.len())
352         }
353
354         // reuse the contained values' allocations/resources.
355         for (place, thing) in self.mut_iter().zip(other.iter()) {
356             place.clone_from(thing)
357         }
358
359         // self.len <= other.len due to the truncate above, so the
360         // slice here is always in-bounds.
361         let slice = other.slice_from(self.len());
362         self.push_all(slice);
363     }
364 }
365
366 impl<T> FromIterator<T> for Vec<T> {
367     #[inline]
368     fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
369         let (lower, _) = iterator.size_hint();
370         let mut vector = Vec::with_capacity(lower);
371         for element in iterator {
372             vector.push(element)
373         }
374         vector
375     }
376 }
377
378 impl<T> Extendable<T> for Vec<T> {
379     #[inline]
380     fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
381         let (lower, _) = iterator.size_hint();
382         self.reserve_additional(lower);
383         for element in iterator {
384             self.push(element)
385         }
386     }
387 }
388
389 impl<T: PartialEq> PartialEq for Vec<T> {
390     #[inline]
391     fn eq(&self, other: &Vec<T>) -> bool {
392         self.as_slice() == other.as_slice()
393     }
394 }
395
396 impl<T: PartialOrd> PartialOrd for Vec<T> {
397     #[inline]
398     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
399         self.as_slice().partial_cmp(&other.as_slice())
400     }
401 }
402
403 impl<T: Eq> Eq for Vec<T> {}
404
405 impl<T: PartialEq, V: Vector<T>> Equiv<V> for Vec<T> {
406     #[inline]
407     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
408 }
409
410 impl<T: Ord> Ord for Vec<T> {
411     #[inline]
412     fn cmp(&self, other: &Vec<T>) -> Ordering {
413         self.as_slice().cmp(&other.as_slice())
414     }
415 }
416
417 impl<T> Collection for Vec<T> {
418     #[inline]
419     fn len(&self) -> uint {
420         self.len
421     }
422 }
423
424 impl<T: Clone> CloneableVector<T> for Vec<T> {
425     fn to_owned(&self) -> Vec<T> { self.clone() }
426     fn into_owned(self) -> Vec<T> { self }
427 }
428
429 // FIXME: #13996: need a way to mark the return value as `noalias`
430 #[inline(never)]
431 unsafe fn alloc_or_realloc<T>(ptr: *mut T, size: uint, old_size: uint) -> *mut T {
432     if old_size == 0 {
433         allocate(size, mem::min_align_of::<T>()) as *mut T
434     } else {
435         reallocate(ptr as *mut u8, size,
436                    mem::min_align_of::<T>(), old_size) as *mut T
437     }
438 }
439
440 #[inline]
441 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
442     if mem::size_of::<T>() != 0 {
443         deallocate(ptr as *mut u8,
444                    len * mem::size_of::<T>(),
445                    mem::min_align_of::<T>())
446     }
447 }
448
449 impl<T> Vec<T> {
450     /// Returns the number of elements the vector can hold without
451     /// reallocating.
452     ///
453     /// # Example
454     ///
455     /// ```rust
456     /// # use std::vec::Vec;
457     /// let vec: Vec<int> = Vec::with_capacity(10);
458     /// assert_eq!(vec.capacity(), 10);
459     /// ```
460     #[inline]
461     pub fn capacity(&self) -> uint {
462         self.cap
463     }
464
465      /// Reserves capacity for at least `n` additional elements in the given
466      /// vector.
467      ///
468      /// # Failure
469      ///
470      /// Fails if the new capacity overflows `uint`.
471      ///
472      /// # Example
473      ///
474      /// ```rust
475      /// # use std::vec::Vec;
476      /// let mut vec: Vec<int> = vec!(1i);
477      /// vec.reserve_additional(10);
478      /// assert!(vec.capacity() >= 11);
479      /// ```
480     pub fn reserve_additional(&mut self, extra: uint) {
481         if self.cap - self.len < extra {
482             match self.len.checked_add(&extra) {
483                 None => fail!("Vec::reserve_additional: `uint` overflow"),
484                 Some(new_cap) => self.reserve(new_cap)
485             }
486         }
487     }
488
489     /// Reserves capacity for at least `n` elements in the given vector.
490     ///
491     /// This function will over-allocate in order to amortize the allocation
492     /// costs in scenarios where the caller may need to repeatedly reserve
493     /// additional space.
494     ///
495     /// If the capacity for `self` is already equal to or greater than the
496     /// requested capacity, then no action is taken.
497     ///
498     /// # Example
499     ///
500     /// ```rust
501     /// let mut vec = vec!(1i, 2, 3);
502     /// vec.reserve(10);
503     /// assert!(vec.capacity() >= 10);
504     /// ```
505     pub fn reserve(&mut self, capacity: uint) {
506         if capacity > self.cap {
507             self.reserve_exact(num::next_power_of_two(capacity))
508         }
509     }
510
511     /// Reserves capacity for exactly `capacity` elements in the given vector.
512     ///
513     /// If the capacity for `self` is already equal to or greater than the
514     /// requested capacity, then no action is taken.
515     ///
516     /// # Example
517     ///
518     /// ```rust
519     /// # use std::vec::Vec;
520     /// let mut vec: Vec<int> = Vec::with_capacity(10);
521     /// vec.reserve_exact(11);
522     /// assert_eq!(vec.capacity(), 11);
523     /// ```
524     pub fn reserve_exact(&mut self, capacity: uint) {
525         if mem::size_of::<T>() == 0 { return }
526
527         if capacity > self.cap {
528             let size = capacity.checked_mul(&mem::size_of::<T>())
529                                .expect("capacity overflow");
530             unsafe {
531                 self.ptr = alloc_or_realloc(self.ptr, size,
532                                             self.cap * mem::size_of::<T>());
533             }
534             self.cap = capacity;
535         }
536     }
537
538     /// Shrink the capacity of the vector as much as possible
539     ///
540     /// # Example
541     ///
542     /// ```rust
543     /// let mut vec = vec!(1i, 2, 3);
544     /// vec.shrink_to_fit();
545     /// ```
546     pub fn shrink_to_fit(&mut self) {
547         if mem::size_of::<T>() == 0 { return }
548
549         if self.len == 0 {
550             if self.cap != 0 {
551                 unsafe {
552                     dealloc(self.ptr, self.cap)
553                 }
554                 self.cap = 0;
555             }
556         } else {
557             unsafe {
558                 // Overflow check is unnecessary as the vector is already at
559                 // least this large.
560                 self.ptr = reallocate(self.ptr as *mut u8,
561                                       self.len * mem::size_of::<T>(),
562                                       mem::min_align_of::<T>(),
563                                       self.cap * mem::size_of::<T>()) as *mut T;
564             }
565             self.cap = self.len;
566         }
567     }
568
569     /// Remove the last element from a vector and return it, or `None` if it is
570     /// empty.
571     ///
572     /// # Example
573     ///
574     /// ```rust
575     /// let mut vec = vec!(1i, 2, 3);
576     /// assert_eq!(vec.pop(), Some(3));
577     /// assert_eq!(vec, vec!(1, 2));
578     /// ```
579     #[inline]
580     pub fn pop(&mut self) -> Option<T> {
581         if self.len == 0 {
582             None
583         } else {
584             unsafe {
585                 self.len -= 1;
586                 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
587             }
588         }
589     }
590
591     /// Append an element to a vector.
592     ///
593     /// # Failure
594     ///
595     /// Fails if the number of elements in the vector overflows a `uint`.
596     ///
597     /// # Example
598     ///
599     /// ```rust
600     /// let mut vec = vec!(1i, 2);
601     /// vec.push(3);
602     /// assert_eq!(vec, vec!(1, 2, 3));
603     /// ```
604     #[inline]
605     pub fn push(&mut self, value: T) {
606         if mem::size_of::<T>() == 0 {
607             // zero-size types consume no memory, so we can't rely on the address space running out
608             self.len = self.len.checked_add(&1).expect("length overflow");
609             unsafe { mem::forget(value); }
610             return
611         }
612         if self.len == self.cap {
613             let old_size = self.cap * mem::size_of::<T>();
614             let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
615             if old_size > size { fail!("capacity overflow") }
616             unsafe {
617                 self.ptr = alloc_or_realloc(self.ptr, size,
618                                             self.cap * mem::size_of::<T>());
619             }
620             self.cap = max(self.cap, 2) * 2;
621         }
622
623         unsafe {
624             let end = (self.ptr as *const T).offset(self.len as int) as *mut T;
625             ptr::write(&mut *end, value);
626             self.len += 1;
627         }
628     }
629
630     /// Appends one element to the vector provided. The vector itself is then
631     /// returned for use again.
632     ///
633     /// # Example
634     ///
635     /// ```rust
636     /// let vec = vec!(1i, 2);
637     /// let vec = vec.append_one(3);
638     /// assert_eq!(vec, vec!(1, 2, 3));
639     /// ```
640     #[inline]
641     pub fn append_one(mut self, x: T) -> Vec<T> {
642         self.push(x);
643         self
644     }
645
646     /// Shorten a vector, dropping excess elements.
647     ///
648     /// If `len` is greater than the vector's current length, this has no
649     /// effect.
650     ///
651     /// # Example
652     ///
653     /// ```rust
654     /// let mut vec = vec!(1i, 2, 3, 4);
655     /// vec.truncate(2);
656     /// assert_eq!(vec, vec!(1, 2));
657     /// ```
658     pub fn truncate(&mut self, len: uint) {
659         unsafe {
660             // drop any extra elements
661             while len < self.len {
662                 // decrement len before the read(), so a failure on Drop doesn't
663                 // re-drop the just-failed value.
664                 self.len -= 1;
665                 ptr::read(self.as_slice().unsafe_ref(self.len));
666             }
667         }
668     }
669
670     /// Work with `self` as a mutable slice.
671     ///
672     /// # Example
673     ///
674     /// ```rust
675     /// fn foo(slice: &mut [int]) {}
676     ///
677     /// let mut vec = vec!(1i, 2);
678     /// foo(vec.as_mut_slice());
679     /// ```
680     #[inline]
681     pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
682         unsafe {
683             mem::transmute(Slice {
684                 data: self.as_mut_ptr() as *const T,
685                 len: self.len,
686             })
687         }
688     }
689
690     /// Creates a consuming iterator, that is, one that moves each
691     /// value out of the vector (from start to end). The vector cannot
692     /// be used after calling this.
693     ///
694     /// # Example
695     ///
696     /// ```rust
697     /// let v = vec!("a".to_string(), "b".to_string());
698     /// for s in v.move_iter() {
699     ///     // s has type String, not &String
700     ///     println!("{}", s);
701     /// }
702     /// ```
703     #[inline]
704     pub fn move_iter(self) -> MoveItems<T> {
705         unsafe {
706             let iter = mem::transmute(self.as_slice().iter());
707             let ptr = self.ptr;
708             let cap = self.cap;
709             mem::forget(self);
710             MoveItems { allocation: ptr, cap: cap, iter: iter }
711         }
712     }
713
714
715     /// Sets the length of a vector.
716     ///
717     /// This will explicitly set the size of the vector, without actually
718     /// modifying its buffers, so it is up to the caller to ensure that the
719     /// vector is actually the specified size.
720     #[inline]
721     pub unsafe fn set_len(&mut self, len: uint) {
722         self.len = len;
723     }
724
725     /// Returns a reference to the value at index `index`.
726     ///
727     /// # Failure
728     ///
729     /// Fails if `index` is out of bounds
730     ///
731     /// # Example
732     ///
733     /// ```rust
734     /// let vec = vec!(1i, 2, 3);
735     /// assert!(vec.get(1) == &2);
736     /// ```
737     #[inline]
738     pub fn get<'a>(&'a self, index: uint) -> &'a T {
739         &self.as_slice()[index]
740     }
741
742     /// Returns a mutable reference to the value at index `index`.
743     ///
744     /// # Failure
745     ///
746     /// Fails if `index` is out of bounds
747     ///
748     /// # Example
749     ///
750     /// ```rust
751     /// let mut vec = vec!(1i, 2, 3);
752     /// *vec.get_mut(1) = 4;
753     /// assert_eq!(vec, vec!(1i, 4, 3));
754     /// ```
755     #[inline]
756     pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
757         &mut self.as_mut_slice()[index]
758     }
759
760     /// Returns an iterator over references to the elements of the vector in
761     /// order.
762     ///
763     /// # Example
764     ///
765     /// ```rust
766     /// let vec = vec!(1i, 2, 3);
767     /// for num in vec.iter() {
768     ///     println!("{}", *num);
769     /// }
770     /// ```
771     #[inline]
772     pub fn iter<'a>(&'a self) -> Items<'a,T> {
773         self.as_slice().iter()
774     }
775
776
777     /// Returns an iterator over mutable references to the elements of the
778     /// vector in order.
779     ///
780     /// # Example
781     ///
782     /// ```rust
783     /// let mut vec = vec!(1i, 2, 3);
784     /// for num in vec.mut_iter() {
785     ///     *num = 0;
786     /// }
787     /// ```
788     #[inline]
789     pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
790         self.as_mut_slice().mut_iter()
791     }
792
793     /// Sort the vector, in place, using `compare` to compare elements.
794     ///
795     /// This sort is `O(n log n)` worst-case and stable, but allocates
796     /// approximately `2 * n`, where `n` is the length of `self`.
797     ///
798     /// # Example
799     ///
800     /// ```rust
801     /// let mut v = vec!(5i, 4, 1, 3, 2);
802     /// v.sort_by(|a, b| a.cmp(b));
803     /// assert_eq!(v, vec!(1i, 2, 3, 4, 5));
804     ///
805     /// // reverse sorting
806     /// v.sort_by(|a, b| b.cmp(a));
807     /// assert_eq!(v, vec!(5i, 4, 3, 2, 1));
808     /// ```
809     #[inline]
810     pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
811         self.as_mut_slice().sort_by(compare)
812     }
813
814     /// Returns a slice of self spanning the interval [`start`, `end`).
815     ///
816     /// # Failure
817     ///
818     /// Fails when the slice (or part of it) is outside the bounds of self, or when
819     /// `start` > `end`.
820     ///
821     /// # Example
822     ///
823     /// ```rust
824     /// let vec = vec!(1i, 2, 3, 4);
825     /// assert!(vec.slice(0, 2) == [1, 2]);
826     /// ```
827     #[inline]
828     pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
829         self.as_slice().slice(start, end)
830     }
831
832     /// Returns a slice containing all but the first element of the vector.
833     ///
834     /// # Failure
835     ///
836     /// Fails when the vector is empty.
837     ///
838     /// # Example
839     ///
840     /// ```rust
841     /// let vec = vec!(1i, 2, 3);
842     /// assert!(vec.tail() == [2, 3]);
843     /// ```
844     #[inline]
845     pub fn tail<'a>(&'a self) -> &'a [T] {
846         self.as_slice().tail()
847     }
848
849     /// Returns all but the first `n' elements of a vector.
850     ///
851     /// # Failure
852     ///
853     /// Fails when there are fewer than `n` elements in the vector.
854     ///
855     /// # Example
856     ///
857     /// ```rust
858     /// let vec = vec!(1i, 2, 3, 4);
859     /// assert!(vec.tailn(2) == [3, 4]);
860     /// ```
861     #[inline]
862     pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
863         self.as_slice().tailn(n)
864     }
865
866     /// Returns a reference to the last element of a vector, or `None` if it is
867     /// empty.
868     ///
869     /// # Example
870     ///
871     /// ```rust
872     /// let vec = vec!(1i, 2, 3);
873     /// assert!(vec.last() == Some(&3));
874     /// ```
875     #[inline]
876     pub fn last<'a>(&'a self) -> Option<&'a T> {
877         self.as_slice().last()
878     }
879
880     /// Returns a mutable reference to the last element of a vector, or `None`
881     /// if it is empty.
882     ///
883     /// # Example
884     ///
885     /// ```rust
886     /// let mut vec = vec!(1i, 2, 3);
887     /// *vec.mut_last().unwrap() = 4;
888     /// assert_eq!(vec, vec!(1i, 2, 4));
889     /// ```
890     #[inline]
891     pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
892         self.as_mut_slice().mut_last()
893     }
894
895     /// Remove an element from anywhere in the vector and return it, replacing
896     /// it with the last element. This does not preserve ordering, but is O(1).
897     ///
898     /// Returns `None` if `index` is out of bounds.
899     ///
900     /// # Example
901     /// ```rust
902     /// let mut v = vec!("foo".to_string(), "bar".to_string(),
903     ///                  "baz".to_string(), "qux".to_string());
904     ///
905     /// assert_eq!(v.swap_remove(1), Some("bar".to_string()));
906     /// assert_eq!(v, vec!("foo".to_string(), "qux".to_string(), "baz".to_string()));
907     ///
908     /// assert_eq!(v.swap_remove(0), Some("foo".to_string()));
909     /// assert_eq!(v, vec!("baz".to_string(), "qux".to_string()));
910     ///
911     /// assert_eq!(v.swap_remove(2), None);
912     /// ```
913     #[inline]
914     pub fn swap_remove(&mut self, index: uint) -> Option<T> {
915         let length = self.len();
916         if index < length - 1 {
917             self.as_mut_slice().swap(index, length - 1);
918         } else if index >= length {
919             return None
920         }
921         self.pop()
922     }
923
924     /// Prepend an element to the vector.
925     ///
926     /// # Warning
927     ///
928     /// This is an O(n) operation as it requires copying every element in the
929     /// vector.
930     ///
931     /// # Example
932     ///
933     /// ```rust
934     /// let mut vec = vec!(1i, 2, 3);
935     /// vec.unshift(4);
936     /// assert_eq!(vec, vec!(4, 1, 2, 3));
937     /// ```
938     #[inline]
939     pub fn unshift(&mut self, element: T) {
940         self.insert(0, element)
941     }
942
943     /// Removes the first element from a vector and returns it, or `None` if
944     /// the vector is empty.
945     ///
946     /// # Warning
947     ///
948     /// This is an O(n) operation as it requires copying every element in the
949     /// vector.
950     ///
951     /// # Example
952     ///
953     /// ```rust
954     /// let mut vec = vec!(1i, 2, 3);
955     /// assert!(vec.shift() == Some(1));
956     /// assert_eq!(vec, vec!(2, 3));
957     /// ```
958     #[inline]
959     pub fn shift(&mut self) -> Option<T> {
960         self.remove(0)
961     }
962
963     /// Insert an element at position `index` within the vector, shifting all
964     /// elements after position i one position to the right.
965     ///
966     /// # Failure
967     ///
968     /// Fails if `index` is not between `0` and the vector's length (both
969     /// bounds inclusive).
970     ///
971     /// # Example
972     ///
973     /// ```rust
974     /// let mut vec = vec!(1i, 2, 3);
975     /// vec.insert(1, 4);
976     /// assert_eq!(vec, vec!(1, 4, 2, 3));
977     /// vec.insert(4, 5);
978     /// assert_eq!(vec, vec!(1, 4, 2, 3, 5));
979     /// ```
980     pub fn insert(&mut self, index: uint, element: T) {
981         let len = self.len();
982         assert!(index <= len);
983         // space for the new element
984         self.reserve(len + 1);
985
986         unsafe { // infallible
987             // The spot to put the new value
988             {
989                 let p = self.as_mut_ptr().offset(index as int);
990                 // Shift everything over to make space. (Duplicating the
991                 // `index`th element into two consecutive places.)
992                 ptr::copy_memory(p.offset(1), &*p, len - index);
993                 // Write it in, overwriting the first copy of the `index`th
994                 // element.
995                 ptr::write(&mut *p, element);
996             }
997             self.set_len(len + 1);
998         }
999     }
1000
1001     /// Remove and return the element at position `index` within the vector,
1002     /// shifting all elements after position `index` one position to the left.
1003     /// Returns `None` if `i` is out of bounds.
1004     ///
1005     /// # Example
1006     ///
1007     /// ```rust
1008     /// let mut v = vec!(1i, 2, 3);
1009     /// assert_eq!(v.remove(1), Some(2));
1010     /// assert_eq!(v, vec!(1, 3));
1011     ///
1012     /// assert_eq!(v.remove(4), None);
1013     /// // v is unchanged:
1014     /// assert_eq!(v, vec!(1, 3));
1015     /// ```
1016     pub fn remove(&mut self, index: uint) -> Option<T> {
1017         let len = self.len();
1018         if index < len {
1019             unsafe { // infallible
1020                 let ret;
1021                 {
1022                     // the place we are taking from.
1023                     let ptr = self.as_mut_ptr().offset(index as int);
1024                     // copy it out, unsafely having a copy of the value on
1025                     // the stack and in the vector at the same time.
1026                     ret = Some(ptr::read(ptr as *const T));
1027
1028                     // Shift everything down to fill in that spot.
1029                     ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
1030                 }
1031                 self.set_len(len - 1);
1032                 ret
1033             }
1034         } else {
1035             None
1036         }
1037     }
1038
1039     /// Takes ownership of the vector `other`, moving all elements into
1040     /// the current vector. This does not copy any elements, and it is
1041     /// illegal to use the `other` vector after calling this method
1042     /// (because it is moved here).
1043     ///
1044     /// # Example
1045     ///
1046     /// ```rust
1047     /// let mut vec = vec!(box 1i);
1048     /// vec.push_all_move(vec!(box 2, box 3, box 4));
1049     /// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
1050     /// ```
1051     #[inline]
1052     pub fn push_all_move(&mut self, other: Vec<T>) {
1053         self.extend(other.move_iter());
1054     }
1055
1056     /// Returns a mutable slice of `self` between `start` and `end`.
1057     ///
1058     /// # Failure
1059     ///
1060     /// Fails when `start` or `end` point outside the bounds of `self`, or when
1061     /// `start` > `end`.
1062     ///
1063     /// # Example
1064     ///
1065     /// ```rust
1066     /// let mut vec = vec!(1i, 2, 3, 4);
1067     /// assert!(vec.mut_slice(0, 2) == [1, 2]);
1068     /// ```
1069     #[inline]
1070     pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
1071                          -> &'a mut [T] {
1072         self.as_mut_slice().mut_slice(start, end)
1073     }
1074
1075     /// Returns a mutable slice of self from `start` to the end of the vec.
1076     ///
1077     /// # Failure
1078     ///
1079     /// Fails when `start` points outside the bounds of self.
1080     ///
1081     /// # Example
1082     ///
1083     /// ```rust
1084     /// let mut vec = vec!(1i, 2, 3, 4);
1085     /// assert!(vec.mut_slice_from(2) == [3, 4]);
1086     /// ```
1087     #[inline]
1088     pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
1089         self.as_mut_slice().mut_slice_from(start)
1090     }
1091
1092     /// Returns a mutable slice of self from the start of the vec to `end`.
1093     ///
1094     /// # Failure
1095     ///
1096     /// Fails when `end` points outside the bounds of self.
1097     ///
1098     /// # Example
1099     ///
1100     /// ```rust
1101     /// let mut vec = vec!(1i, 2, 3, 4);
1102     /// assert!(vec.mut_slice_to(2) == [1, 2]);
1103     /// ```
1104     #[inline]
1105     pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
1106         self.as_mut_slice().mut_slice_to(end)
1107     }
1108
1109     /// Returns a pair of mutable slices that divides the vec at an index.
1110     ///
1111     /// The first will contain all indices from `[0, mid)` (excluding
1112     /// the index `mid` itself) and the second will contain all
1113     /// indices from `[mid, len)` (excluding the index `len` itself).
1114     ///
1115     /// # Failure
1116     ///
1117     /// Fails if `mid > len`.
1118     ///
1119     /// # Example
1120     ///
1121     /// ```rust
1122     /// let mut vec = vec!(1i, 2, 3, 4, 5, 6);
1123     ///
1124     /// // scoped to restrict the lifetime of the borrows
1125     /// {
1126     ///    let (left, right) = vec.mut_split_at(0);
1127     ///    assert!(left == &mut []);
1128     ///    assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1129     /// }
1130     ///
1131     /// {
1132     ///     let (left, right) = vec.mut_split_at(2);
1133     ///     assert!(left == &mut [1, 2]);
1134     ///     assert!(right == &mut [3, 4, 5, 6]);
1135     /// }
1136     ///
1137     /// {
1138     ///     let (left, right) = vec.mut_split_at(6);
1139     ///     assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1140     ///     assert!(right == &mut []);
1141     /// }
1142     /// ```
1143     #[inline]
1144     pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1145         self.as_mut_slice().mut_split_at(mid)
1146     }
1147
1148     /// Reverse the order of elements in a vector, in place.
1149     ///
1150     /// # Example
1151     ///
1152     /// ```rust
1153     /// let mut v = vec!(1i, 2, 3);
1154     /// v.reverse();
1155     /// assert_eq!(v, vec!(3i, 2, 1));
1156     /// ```
1157     #[inline]
1158     pub fn reverse(&mut self) {
1159         self.as_mut_slice().reverse()
1160     }
1161
1162     /// Returns a slice of `self` from `start` to the end of the vec.
1163     ///
1164     /// # Failure
1165     ///
1166     /// Fails when `start` points outside the bounds of self.
1167     ///
1168     /// # Example
1169     ///
1170     /// ```rust
1171     /// let vec = vec!(1i, 2, 3);
1172     /// assert!(vec.slice_from(1) == [2, 3]);
1173     /// ```
1174     #[inline]
1175     pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
1176         self.as_slice().slice_from(start)
1177     }
1178
1179     /// Returns a slice of self from the start of the vec to `end`.
1180     ///
1181     /// # Failure
1182     ///
1183     /// Fails when `end` points outside the bounds of self.
1184     ///
1185     /// # Example
1186     ///
1187     /// ```rust
1188     /// let vec = vec!(1i, 2, 3);
1189     /// assert!(vec.slice_to(2) == [1, 2]);
1190     /// ```
1191     #[inline]
1192     pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
1193         self.as_slice().slice_to(end)
1194     }
1195
1196     /// Returns a slice containing all but the last element of the vector.
1197     ///
1198     /// # Failure
1199     ///
1200     /// Fails if the vector is empty
1201     #[inline]
1202     pub fn init<'a>(&'a self) -> &'a [T] {
1203         self.slice(0, self.len() - 1)
1204     }
1205
1206
1207     /// Returns an unsafe pointer to the vector's buffer.
1208     ///
1209     /// The caller must ensure that the vector outlives the pointer this
1210     /// function returns, or else it will end up pointing to garbage.
1211     ///
1212     /// Modifying the vector may cause its buffer to be reallocated, which
1213     /// would also make any pointers to it invalid.
1214     #[inline]
1215     pub fn as_ptr(&self) -> *const T {
1216         self.ptr as *const T
1217     }
1218
1219     /// Returns a mutable unsafe pointer to the vector's buffer.
1220     ///
1221     /// The caller must ensure that the vector outlives the pointer this
1222     /// function returns, or else it will end up pointing to garbage.
1223     ///
1224     /// Modifying the vector may cause its buffer to be reallocated, which
1225     /// would also make any pointers to it invalid.
1226     #[inline]
1227     pub fn as_mut_ptr(&mut self) -> *mut T {
1228         self.ptr
1229     }
1230
1231     /// Retains only the elements specified by the predicate.
1232     ///
1233     /// In other words, remove all elements `e` such that `f(&e)` returns false.
1234     /// This method operates in place and preserves the order the retained elements.
1235     ///
1236     /// # Example
1237     ///
1238     /// ```rust
1239     /// let mut vec = vec!(1i, 2, 3, 4);
1240     /// vec.retain(|x| x%2 == 0);
1241     /// assert_eq!(vec, vec!(2, 4));
1242     /// ```
1243     pub fn retain(&mut self, f: |&T| -> bool) {
1244         let len = self.len();
1245         let mut del = 0u;
1246         {
1247             let v = self.as_mut_slice();
1248
1249             for i in range(0u, len) {
1250                 if !f(&v[i]) {
1251                     del += 1;
1252                 } else if del > 0 {
1253                     v.swap(i-del, i);
1254                 }
1255             }
1256         }
1257         if del > 0 {
1258             self.truncate(len - del);
1259         }
1260     }
1261
1262     /// Expands a vector in place, initializing the new elements to the result of a function.
1263     ///
1264     /// The vector is grown by `n` elements. The i-th new element are initialized to the value
1265     /// returned by `f(i)` where `i` is in the range [0, n).
1266     ///
1267     /// # Example
1268     ///
1269     /// ```rust
1270     /// let mut vec = vec!(0u, 1);
1271     /// vec.grow_fn(3, |i| i);
1272     /// assert_eq!(vec, vec!(0, 1, 0, 1, 2));
1273     /// ```
1274     pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
1275         self.reserve_additional(n);
1276         for i in range(0u, n) {
1277             self.push(f(i));
1278         }
1279     }
1280 }
1281
1282 impl<T:Ord> Vec<T> {
1283     /// Sorts the vector in place.
1284     ///
1285     /// This sort is `O(n log n)` worst-case and stable, but allocates
1286     /// approximately `2 * n`, where `n` is the length of `self`.
1287     ///
1288     /// # Example
1289     ///
1290     /// ```rust
1291     /// let mut vec = vec!(3i, 1, 2);
1292     /// vec.sort();
1293     /// assert_eq!(vec, vec!(1, 2, 3));
1294     /// ```
1295     pub fn sort(&mut self) {
1296         self.as_mut_slice().sort()
1297     }
1298 }
1299
1300 impl<T> Mutable for Vec<T> {
1301     #[inline]
1302     fn clear(&mut self) {
1303         self.truncate(0)
1304     }
1305 }
1306
1307 impl<T:PartialEq> Vec<T> {
1308     /// Return true if a vector contains an element with the given value
1309     ///
1310     /// # Example
1311     ///
1312     /// ```rust
1313     /// let vec = vec!(1i, 2, 3);
1314     /// assert!(vec.contains(&1));
1315     /// ```
1316     #[inline]
1317     pub fn contains(&self, x: &T) -> bool {
1318         self.as_slice().contains(x)
1319     }
1320
1321     /// Remove consecutive repeated elements in the vector.
1322     ///
1323     /// If the vector is sorted, this removes all duplicates.
1324     ///
1325     /// # Example
1326     ///
1327     /// ```rust
1328     /// let mut vec = vec!(1i, 2, 2, 3, 2);
1329     /// vec.dedup();
1330     /// assert_eq!(vec, vec!(1i, 2, 3, 2));
1331     /// ```
1332     pub fn dedup(&mut self) {
1333         unsafe {
1334             // Although we have a mutable reference to `self`, we cannot make
1335             // *arbitrary* changes. The `PartialEq` comparisons could fail, so we
1336             // must ensure that the vector is in a valid state at all time.
1337             //
1338             // The way that we handle this is by using swaps; we iterate
1339             // over all the elements, swapping as we go so that at the end
1340             // the elements we wish to keep are in the front, and those we
1341             // wish to reject are at the back. We can then truncate the
1342             // vector. This operation is still O(n).
1343             //
1344             // Example: We start in this state, where `r` represents "next
1345             // read" and `w` represents "next_write`.
1346             //
1347             //           r
1348             //     +---+---+---+---+---+---+
1349             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1350             //     +---+---+---+---+---+---+
1351             //           w
1352             //
1353             // Comparing self[r] against self[w-1], this is not a duplicate, so
1354             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1355             // r and w, leaving us with:
1356             //
1357             //               r
1358             //     +---+---+---+---+---+---+
1359             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1360             //     +---+---+---+---+---+---+
1361             //               w
1362             //
1363             // Comparing self[r] against self[w-1], this value is a duplicate,
1364             // so we increment `r` but leave everything else unchanged:
1365             //
1366             //                   r
1367             //     +---+---+---+---+---+---+
1368             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1369             //     +---+---+---+---+---+---+
1370             //               w
1371             //
1372             // Comparing self[r] against self[w-1], this is not a duplicate,
1373             // so swap self[r] and self[w] and advance r and w:
1374             //
1375             //                       r
1376             //     +---+---+---+---+---+---+
1377             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1378             //     +---+---+---+---+---+---+
1379             //                   w
1380             //
1381             // Not a duplicate, repeat:
1382             //
1383             //                           r
1384             //     +---+---+---+---+---+---+
1385             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1386             //     +---+---+---+---+---+---+
1387             //                       w
1388             //
1389             // Duplicate, advance r. End of vec. Truncate to w.
1390
1391             let ln = self.len();
1392             if ln < 1 { return; }
1393
1394             // Avoid bounds checks by using unsafe pointers.
1395             let p = self.as_mut_slice().as_mut_ptr();
1396             let mut r = 1;
1397             let mut w = 1;
1398
1399             while r < ln {
1400                 let p_r = p.offset(r as int);
1401                 let p_wm1 = p.offset((w - 1) as int);
1402                 if *p_r != *p_wm1 {
1403                     if r != w {
1404                         let p_w = p_wm1.offset(1);
1405                         mem::swap(&mut *p_r, &mut *p_w);
1406                     }
1407                     w += 1;
1408                 }
1409                 r += 1;
1410             }
1411
1412             self.truncate(w);
1413         }
1414     }
1415 }
1416
1417 impl<T> Vector<T> for Vec<T> {
1418     /// Work with `self` as a slice.
1419     ///
1420     /// # Example
1421     ///
1422     /// ```rust
1423     /// fn foo(slice: &[int]) {}
1424     ///
1425     /// let vec = vec!(1i, 2);
1426     /// foo(vec.as_slice());
1427     /// ```
1428     #[inline]
1429     fn as_slice<'a>(&'a self) -> &'a [T] {
1430         unsafe { mem::transmute(Slice { data: self.as_ptr(), len: self.len }) }
1431     }
1432 }
1433
1434 impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
1435     #[inline]
1436     fn add(&self, rhs: &V) -> Vec<T> {
1437         let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
1438         res.push_all(self.as_slice());
1439         res.push_all(rhs.as_slice());
1440         res
1441     }
1442 }
1443
1444 #[unsafe_destructor]
1445 impl<T> Drop for Vec<T> {
1446     fn drop(&mut self) {
1447         // This is (and should always remain) a no-op if the fields are
1448         // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1449         if self.cap != 0 {
1450             unsafe {
1451                 for x in self.as_mut_slice().iter() {
1452                     ptr::read(x);
1453                 }
1454                 dealloc(self.ptr, self.cap)
1455             }
1456         }
1457     }
1458 }
1459
1460 impl<T> Default for Vec<T> {
1461     fn default() -> Vec<T> {
1462         Vec::new()
1463     }
1464 }
1465
1466 impl<T:fmt::Show> fmt::Show for Vec<T> {
1467     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1468         self.as_slice().fmt(f)
1469     }
1470 }
1471
1472 /// An iterator that moves out of a vector.
1473 pub struct MoveItems<T> {
1474     allocation: *mut T, // the block of memory allocated for the vector
1475     cap: uint, // the capacity of the vector
1476     iter: Items<'static, T>
1477 }
1478
1479 impl<T> Iterator<T> for MoveItems<T> {
1480     #[inline]
1481     fn next(&mut self) -> Option<T> {
1482         unsafe {
1483             self.iter.next().map(|x| ptr::read(x))
1484         }
1485     }
1486
1487     #[inline]
1488     fn size_hint(&self) -> (uint, Option<uint>) {
1489         self.iter.size_hint()
1490     }
1491 }
1492
1493 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1494     #[inline]
1495     fn next_back(&mut self) -> Option<T> {
1496         unsafe {
1497             self.iter.next_back().map(|x| ptr::read(x))
1498         }
1499     }
1500 }
1501
1502 #[unsafe_destructor]
1503 impl<T> Drop for MoveItems<T> {
1504     fn drop(&mut self) {
1505         // destroy the remaining elements
1506         if self.cap != 0 {
1507             for _x in *self {}
1508             unsafe {
1509                 dealloc(self.allocation, self.cap);
1510             }
1511         }
1512     }
1513 }
1514
1515 /**
1516  * Convert an iterator of pairs into a pair of vectors.
1517  *
1518  * Returns a tuple containing two vectors where the i-th element of the first
1519  * vector contains the first element of the i-th tuple of the input iterator,
1520  * and the i-th element of the second vector contains the second element
1521  * of the i-th tuple of the input iterator.
1522  */
1523 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
1524     let (lo, _) = iter.size_hint();
1525     let mut ts = Vec::with_capacity(lo);
1526     let mut us = Vec::with_capacity(lo);
1527     for (t, u) in iter {
1528         ts.push(t);
1529         us.push(u);
1530     }
1531     (ts, us)
1532 }
1533
1534 /// Unsafe operations
1535 pub mod raw {
1536     use super::Vec;
1537     use core::ptr;
1538
1539     /// Constructs a vector from an unsafe pointer to a buffer.
1540     ///
1541     /// The elements of the buffer are copied into the vector without cloning,
1542     /// as if `ptr::read()` were called on them.
1543     #[inline]
1544     pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
1545         let mut dst = Vec::with_capacity(elts);
1546         dst.set_len(elts);
1547         ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
1548         dst
1549     }
1550 }
1551
1552 #[cfg(test)]
1553 mod tests {
1554     extern crate test;
1555
1556     use std::prelude::*;
1557     use std::mem::size_of;
1558     use test::Bencher;
1559     use super::{unzip, raw, Vec};
1560
1561     #[test]
1562     fn test_small_vec_struct() {
1563         assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1564     }
1565
1566     #[test]
1567     fn test_double_drop() {
1568         struct TwoVec<T> {
1569             x: Vec<T>,
1570             y: Vec<T>
1571         }
1572
1573         struct DropCounter<'a> {
1574             count: &'a mut int
1575         }
1576
1577         #[unsafe_destructor]
1578         impl<'a> Drop for DropCounter<'a> {
1579             fn drop(&mut self) {
1580                 *self.count += 1;
1581             }
1582         }
1583
1584         let mut count_x @ mut count_y = 0;
1585         {
1586             let mut tv = TwoVec {
1587                 x: Vec::new(),
1588                 y: Vec::new()
1589             };
1590             tv.x.push(DropCounter {count: &mut count_x});
1591             tv.y.push(DropCounter {count: &mut count_y});
1592
1593             // If Vec had a drop flag, here is where it would be zeroed.
1594             // Instead, it should rely on its internal state to prevent
1595             // doing anything significant when dropped multiple times.
1596             drop(tv.x);
1597
1598             // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1599         }
1600
1601         assert_eq!(count_x, 1);
1602         assert_eq!(count_y, 1);
1603     }
1604
1605     #[test]
1606     fn test_reserve_additional() {
1607         let mut v = Vec::new();
1608         assert_eq!(v.capacity(), 0);
1609
1610         v.reserve_additional(2);
1611         assert!(v.capacity() >= 2);
1612
1613         for i in range(0i, 16) {
1614             v.push(i);
1615         }
1616
1617         assert!(v.capacity() >= 16);
1618         v.reserve_additional(16);
1619         assert!(v.capacity() >= 32);
1620
1621         v.push(16);
1622
1623         v.reserve_additional(16);
1624         assert!(v.capacity() >= 33)
1625     }
1626
1627     #[test]
1628     fn test_extend() {
1629         let mut v = Vec::new();
1630         let mut w = Vec::new();
1631
1632         v.extend(range(0i, 3));
1633         for i in range(0i, 3) { w.push(i) }
1634
1635         assert_eq!(v, w);
1636
1637         v.extend(range(3i, 10));
1638         for i in range(3i, 10) { w.push(i) }
1639
1640         assert_eq!(v, w);
1641     }
1642
1643     #[test]
1644     fn test_mut_slice_from() {
1645         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1646         {
1647             let slice = values.mut_slice_from(2);
1648             assert!(slice == [3, 4, 5]);
1649             for p in slice.mut_iter() {
1650                 *p += 2;
1651             }
1652         }
1653
1654         assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1655     }
1656
1657     #[test]
1658     fn test_mut_slice_to() {
1659         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1660         {
1661             let slice = values.mut_slice_to(2);
1662             assert!(slice == [1, 2]);
1663             for p in slice.mut_iter() {
1664                 *p += 1;
1665             }
1666         }
1667
1668         assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1669     }
1670
1671     #[test]
1672     fn test_mut_split_at() {
1673         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1674         {
1675             let (left, right) = values.mut_split_at(2);
1676             assert!(left.slice(0, left.len()) == [1, 2]);
1677             for p in left.mut_iter() {
1678                 *p += 1;
1679             }
1680
1681             assert!(right.slice(0, right.len()) == [3, 4, 5]);
1682             for p in right.mut_iter() {
1683                 *p += 2;
1684             }
1685         }
1686
1687         assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7]));
1688     }
1689
1690     #[test]
1691     fn test_clone() {
1692         let v: Vec<int> = vec!();
1693         let w = vec!(1i, 2, 3);
1694
1695         assert_eq!(v, v.clone());
1696
1697         let z = w.clone();
1698         assert_eq!(w, z);
1699         // they should be disjoint in memory.
1700         assert!(w.as_ptr() != z.as_ptr())
1701     }
1702
1703     #[test]
1704     fn test_clone_from() {
1705         let mut v = vec!();
1706         let three = vec!(box 1i, box 2, box 3);
1707         let two = vec!(box 4i, box 5);
1708         // zero, long
1709         v.clone_from(&three);
1710         assert_eq!(v, three);
1711
1712         // equal
1713         v.clone_from(&three);
1714         assert_eq!(v, three);
1715
1716         // long, short
1717         v.clone_from(&two);
1718         assert_eq!(v, two);
1719
1720         // short, long
1721         v.clone_from(&three);
1722         assert_eq!(v, three)
1723     }
1724
1725     #[test]
1726     fn test_grow_fn() {
1727         let mut v = Vec::from_slice([0u, 1]);
1728         v.grow_fn(3, |i| i);
1729         assert!(v == Vec::from_slice([0u, 1, 0, 1, 2]));
1730     }
1731
1732     #[test]
1733     fn test_retain() {
1734         let mut vec = Vec::from_slice([1u, 2, 3, 4]);
1735         vec.retain(|x| x%2 == 0);
1736         assert!(vec == Vec::from_slice([2u, 4]));
1737     }
1738
1739     #[test]
1740     fn zero_sized_values() {
1741         let mut v = Vec::new();
1742         assert_eq!(v.len(), 0);
1743         v.push(());
1744         assert_eq!(v.len(), 1);
1745         v.push(());
1746         assert_eq!(v.len(), 2);
1747         assert_eq!(v.pop(), Some(()));
1748         assert_eq!(v.pop(), Some(()));
1749         assert_eq!(v.pop(), None);
1750
1751         assert_eq!(v.iter().count(), 0);
1752         v.push(());
1753         assert_eq!(v.iter().count(), 1);
1754         v.push(());
1755         assert_eq!(v.iter().count(), 2);
1756
1757         for &() in v.iter() {}
1758
1759         assert_eq!(v.mut_iter().count(), 2);
1760         v.push(());
1761         assert_eq!(v.mut_iter().count(), 3);
1762         v.push(());
1763         assert_eq!(v.mut_iter().count(), 4);
1764
1765         for &() in v.mut_iter() {}
1766         unsafe { v.set_len(0); }
1767         assert_eq!(v.mut_iter().count(), 0);
1768     }
1769
1770     #[test]
1771     fn test_partition() {
1772         assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
1773         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1774         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1775         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1776     }
1777
1778     #[test]
1779     fn test_partitioned() {
1780         assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
1781         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1782         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1783         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1784     }
1785
1786     #[test]
1787     fn test_zip_unzip() {
1788         let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
1789
1790         let (left, right) = unzip(z1.iter().map(|&x| x));
1791
1792         let (left, right) = (left.as_slice(), right.as_slice());
1793         assert_eq!((1, 4), (left[0], right[0]));
1794         assert_eq!((2, 5), (left[1], right[1]));
1795         assert_eq!((3, 6), (left[2], right[2]));
1796     }
1797
1798     #[test]
1799     fn test_unsafe_ptrs() {
1800         unsafe {
1801             // Test on-stack copy-from-buf.
1802             let a = [1i, 2, 3];
1803             let ptr = a.as_ptr();
1804             let b = raw::from_buf(ptr, 3u);
1805             assert_eq!(b, vec![1, 2, 3]);
1806
1807             // Test on-heap copy-from-buf.
1808             let c = vec![1i, 2, 3, 4, 5];
1809             let ptr = c.as_ptr();
1810             let d = raw::from_buf(ptr, 5u);
1811             assert_eq!(d, vec![1, 2, 3, 4, 5]);
1812         }
1813     }
1814
1815     #[test]
1816     fn test_vec_truncate_drop() {
1817         static mut drops: uint = 0;
1818         struct Elem(int);
1819         impl Drop for Elem {
1820             fn drop(&mut self) {
1821                 unsafe { drops += 1; }
1822             }
1823         }
1824
1825         let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
1826         assert_eq!(unsafe { drops }, 0);
1827         v.truncate(3);
1828         assert_eq!(unsafe { drops }, 2);
1829         v.truncate(0);
1830         assert_eq!(unsafe { drops }, 5);
1831     }
1832
1833     #[test]
1834     #[should_fail]
1835     fn test_vec_truncate_fail() {
1836         struct BadElem(int);
1837         impl Drop for BadElem {
1838             fn drop(&mut self) {
1839                 let BadElem(ref mut x) = *self;
1840                 if *x == 0xbadbeef {
1841                     fail!("BadElem failure: 0xbadbeef")
1842                 }
1843             }
1844         }
1845
1846         let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
1847         v.truncate(0);
1848     }
1849
1850     #[bench]
1851     fn bench_new(b: &mut Bencher) {
1852         b.iter(|| {
1853             let v: Vec<uint> = Vec::new();
1854             assert_eq!(v.len(), 0);
1855             assert_eq!(v.capacity(), 0);
1856         })
1857     }
1858
1859     fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
1860         b.bytes = src_len as u64;
1861
1862         b.iter(|| {
1863             let v: Vec<uint> = Vec::with_capacity(src_len);
1864             assert_eq!(v.len(), 0);
1865             assert_eq!(v.capacity(), src_len);
1866         })
1867     }
1868
1869     #[bench]
1870     fn bench_with_capacity_0000(b: &mut Bencher) {
1871         do_bench_with_capacity(b, 0)
1872     }
1873
1874     #[bench]
1875     fn bench_with_capacity_0010(b: &mut Bencher) {
1876         do_bench_with_capacity(b, 10)
1877     }
1878
1879     #[bench]
1880     fn bench_with_capacity_0100(b: &mut Bencher) {
1881         do_bench_with_capacity(b, 100)
1882     }
1883
1884     #[bench]
1885     fn bench_with_capacity_1000(b: &mut Bencher) {
1886         do_bench_with_capacity(b, 1000)
1887     }
1888
1889     fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
1890         b.bytes = src_len as u64;
1891
1892         b.iter(|| {
1893             let dst = Vec::from_fn(src_len, |i| i);
1894             assert_eq!(dst.len(), src_len);
1895             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
1896         })
1897     }
1898
1899     #[bench]
1900     fn bench_from_fn_0000(b: &mut Bencher) {
1901         do_bench_from_fn(b, 0)
1902     }
1903
1904     #[bench]
1905     fn bench_from_fn_0010(b: &mut Bencher) {
1906         do_bench_from_fn(b, 10)
1907     }
1908
1909     #[bench]
1910     fn bench_from_fn_0100(b: &mut Bencher) {
1911         do_bench_from_fn(b, 100)
1912     }
1913
1914     #[bench]
1915     fn bench_from_fn_1000(b: &mut Bencher) {
1916         do_bench_from_fn(b, 1000)
1917     }
1918
1919     fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
1920         b.bytes = src_len as u64;
1921
1922         b.iter(|| {
1923             let dst: Vec<uint> = Vec::from_elem(src_len, 5);
1924             assert_eq!(dst.len(), src_len);
1925             assert!(dst.iter().all(|x| *x == 5));
1926         })
1927     }
1928
1929     #[bench]
1930     fn bench_from_elem_0000(b: &mut Bencher) {
1931         do_bench_from_elem(b, 0)
1932     }
1933
1934     #[bench]
1935     fn bench_from_elem_0010(b: &mut Bencher) {
1936         do_bench_from_elem(b, 10)
1937     }
1938
1939     #[bench]
1940     fn bench_from_elem_0100(b: &mut Bencher) {
1941         do_bench_from_elem(b, 100)
1942     }
1943
1944     #[bench]
1945     fn bench_from_elem_1000(b: &mut Bencher) {
1946         do_bench_from_elem(b, 1000)
1947     }
1948
1949     fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
1950         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
1951
1952         b.bytes = src_len as u64;
1953
1954         b.iter(|| {
1955             let dst = Vec::from_slice(src.clone().as_slice());
1956             assert_eq!(dst.len(), src_len);
1957             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
1958         });
1959     }
1960
1961     #[bench]
1962     fn bench_from_slice_0000(b: &mut Bencher) {
1963         do_bench_from_slice(b, 0)
1964     }
1965
1966     #[bench]
1967     fn bench_from_slice_0010(b: &mut Bencher) {
1968         do_bench_from_slice(b, 10)
1969     }
1970
1971     #[bench]
1972     fn bench_from_slice_0100(b: &mut Bencher) {
1973         do_bench_from_slice(b, 100)
1974     }
1975
1976     #[bench]
1977     fn bench_from_slice_1000(b: &mut Bencher) {
1978         do_bench_from_slice(b, 1000)
1979     }
1980
1981     fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
1982         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
1983
1984         b.bytes = src_len as u64;
1985
1986         b.iter(|| {
1987             let dst: Vec<uint> = FromIterator::from_iter(src.clone().move_iter());
1988             assert_eq!(dst.len(), src_len);
1989             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
1990         });
1991     }
1992
1993     #[bench]
1994     fn bench_from_iter_0000(b: &mut Bencher) {
1995         do_bench_from_iter(b, 0)
1996     }
1997
1998     #[bench]
1999     fn bench_from_iter_0010(b: &mut Bencher) {
2000         do_bench_from_iter(b, 10)
2001     }
2002
2003     #[bench]
2004     fn bench_from_iter_0100(b: &mut Bencher) {
2005         do_bench_from_iter(b, 100)
2006     }
2007
2008     #[bench]
2009     fn bench_from_iter_1000(b: &mut Bencher) {
2010         do_bench_from_iter(b, 1000)
2011     }
2012
2013     fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2014         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2015         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2016
2017         b.bytes = src_len as u64;
2018
2019         b.iter(|| {
2020             let mut dst = dst.clone();
2021             dst.extend(src.clone().move_iter());
2022             assert_eq!(dst.len(), dst_len + src_len);
2023             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2024         });
2025     }
2026
2027     #[bench]
2028     fn bench_extend_0000_0000(b: &mut Bencher) {
2029         do_bench_extend(b, 0, 0)
2030     }
2031
2032     #[bench]
2033     fn bench_extend_0000_0010(b: &mut Bencher) {
2034         do_bench_extend(b, 0, 10)
2035     }
2036
2037     #[bench]
2038     fn bench_extend_0000_0100(b: &mut Bencher) {
2039         do_bench_extend(b, 0, 100)
2040     }
2041
2042     #[bench]
2043     fn bench_extend_0000_1000(b: &mut Bencher) {
2044         do_bench_extend(b, 0, 1000)
2045     }
2046
2047     #[bench]
2048     fn bench_extend_0010_0010(b: &mut Bencher) {
2049         do_bench_extend(b, 10, 10)
2050     }
2051
2052     #[bench]
2053     fn bench_extend_0100_0100(b: &mut Bencher) {
2054         do_bench_extend(b, 100, 100)
2055     }
2056
2057     #[bench]
2058     fn bench_extend_1000_1000(b: &mut Bencher) {
2059         do_bench_extend(b, 1000, 1000)
2060     }
2061
2062     fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2063         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2064         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2065
2066         b.bytes = src_len as u64;
2067
2068         b.iter(|| {
2069             let mut dst = dst.clone();
2070             dst.push_all(src.as_slice());
2071             assert_eq!(dst.len(), dst_len + src_len);
2072             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2073         });
2074     }
2075
2076     #[bench]
2077     fn bench_push_all_0000_0000(b: &mut Bencher) {
2078         do_bench_push_all(b, 0, 0)
2079     }
2080
2081     #[bench]
2082     fn bench_push_all_0000_0010(b: &mut Bencher) {
2083         do_bench_push_all(b, 0, 10)
2084     }
2085
2086     #[bench]
2087     fn bench_push_all_0000_0100(b: &mut Bencher) {
2088         do_bench_push_all(b, 0, 100)
2089     }
2090
2091     #[bench]
2092     fn bench_push_all_0000_1000(b: &mut Bencher) {
2093         do_bench_push_all(b, 0, 1000)
2094     }
2095
2096     #[bench]
2097     fn bench_push_all_0010_0010(b: &mut Bencher) {
2098         do_bench_push_all(b, 10, 10)
2099     }
2100
2101     #[bench]
2102     fn bench_push_all_0100_0100(b: &mut Bencher) {
2103         do_bench_push_all(b, 100, 100)
2104     }
2105
2106     #[bench]
2107     fn bench_push_all_1000_1000(b: &mut Bencher) {
2108         do_bench_push_all(b, 1000, 1000)
2109     }
2110
2111     fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2112         let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2113         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2114
2115         b.bytes = src_len as u64;
2116
2117         b.iter(|| {
2118             let mut dst = dst.clone();
2119             dst.push_all_move(src.clone());
2120             assert_eq!(dst.len(), dst_len + src_len);
2121             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2122         });
2123     }
2124
2125     #[bench]
2126     fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2127         do_bench_push_all_move(b, 0, 0)
2128     }
2129
2130     #[bench]
2131     fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2132         do_bench_push_all_move(b, 0, 10)
2133     }
2134
2135     #[bench]
2136     fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2137         do_bench_push_all_move(b, 0, 100)
2138     }
2139
2140     #[bench]
2141     fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2142         do_bench_push_all_move(b, 0, 1000)
2143     }
2144
2145     #[bench]
2146     fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2147         do_bench_push_all_move(b, 10, 10)
2148     }
2149
2150     #[bench]
2151     fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2152         do_bench_push_all_move(b, 100, 100)
2153     }
2154
2155     #[bench]
2156     fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2157         do_bench_push_all_move(b, 1000, 1000)
2158     }
2159
2160     fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2161         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2162
2163         b.bytes = src_len as u64;
2164
2165         b.iter(|| {
2166             let dst = src.clone();
2167             assert_eq!(dst.len(), src_len);
2168             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2169         });
2170     }
2171
2172     #[bench]
2173     fn bench_clone_0000(b: &mut Bencher) {
2174         do_bench_clone(b, 0)
2175     }
2176
2177     #[bench]
2178     fn bench_clone_0010(b: &mut Bencher) {
2179         do_bench_clone(b, 10)
2180     }
2181
2182     #[bench]
2183     fn bench_clone_0100(b: &mut Bencher) {
2184         do_bench_clone(b, 100)
2185     }
2186
2187     #[bench]
2188     fn bench_clone_1000(b: &mut Bencher) {
2189         do_bench_clone(b, 1000)
2190     }
2191
2192     fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2193         let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2194         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2195
2196         b.bytes = (times * src_len) as u64;
2197
2198         b.iter(|| {
2199             let mut dst = dst.clone();
2200
2201             for _ in range(0, times) {
2202                 dst.clone_from(&src);
2203
2204                 assert_eq!(dst.len(), src_len);
2205                 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2206             }
2207         });
2208     }
2209
2210     #[bench]
2211     fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2212         do_bench_clone_from(b, 1, 0, 0)
2213     }
2214
2215     #[bench]
2216     fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2217         do_bench_clone_from(b, 1, 0, 10)
2218     }
2219
2220     #[bench]
2221     fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2222         do_bench_clone_from(b, 1, 0, 100)
2223     }
2224
2225     #[bench]
2226     fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2227         do_bench_clone_from(b, 1, 0, 1000)
2228     }
2229
2230     #[bench]
2231     fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2232         do_bench_clone_from(b, 1, 10, 10)
2233     }
2234
2235     #[bench]
2236     fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2237         do_bench_clone_from(b, 1, 100, 100)
2238     }
2239
2240     #[bench]
2241     fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2242         do_bench_clone_from(b, 1, 1000, 1000)
2243     }
2244
2245     #[bench]
2246     fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2247         do_bench_clone_from(b, 1, 10, 100)
2248     }
2249
2250     #[bench]
2251     fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2252         do_bench_clone_from(b, 1, 100, 1000)
2253     }
2254
2255     #[bench]
2256     fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2257         do_bench_clone_from(b, 1, 10, 0)
2258     }
2259
2260     #[bench]
2261     fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2262         do_bench_clone_from(b, 1, 100, 10)
2263     }
2264
2265     #[bench]
2266     fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2267         do_bench_clone_from(b, 1, 1000, 100)
2268     }
2269
2270     #[bench]
2271     fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2272         do_bench_clone_from(b, 10, 0, 0)
2273     }
2274
2275     #[bench]
2276     fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2277         do_bench_clone_from(b, 10, 0, 10)
2278     }
2279
2280     #[bench]
2281     fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2282         do_bench_clone_from(b, 10, 0, 100)
2283     }
2284
2285     #[bench]
2286     fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2287         do_bench_clone_from(b, 10, 0, 1000)
2288     }
2289
2290     #[bench]
2291     fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2292         do_bench_clone_from(b, 10, 10, 10)
2293     }
2294
2295     #[bench]
2296     fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2297         do_bench_clone_from(b, 10, 100, 100)
2298     }
2299
2300     #[bench]
2301     fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2302         do_bench_clone_from(b, 10, 1000, 1000)
2303     }
2304
2305     #[bench]
2306     fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2307         do_bench_clone_from(b, 10, 10, 100)
2308     }
2309
2310     #[bench]
2311     fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2312         do_bench_clone_from(b, 10, 100, 1000)
2313     }
2314
2315     #[bench]
2316     fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2317         do_bench_clone_from(b, 10, 10, 0)
2318     }
2319
2320     #[bench]
2321     fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2322         do_bench_clone_from(b, 10, 100, 10)
2323     }
2324
2325     #[bench]
2326     fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2327         do_bench_clone_from(b, 10, 1000, 100)
2328     }
2329 }