vec.rs 74.0 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
10

11 12 13
//! A growable list type, written `Vec<T>` but pronounced 'vector.'
//!
//! Vectors have `O(1)` indexing, push (to the end) and pop (from the end).
14

15 16
use core::prelude::*;

17
use alloc::boxed::Box;
18
use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
19 20 21
use core::cmp::max;
use core::default::Default;
use core::fmt;
22
use core::kinds::marker::{ContravariantLifetime, InvariantType};
23
use core::mem;
24
use core::num::{Int, UnsignedInt};
N
Nick Cameron 已提交
25
use core::ops;
26
use core::ptr;
27
use core::raw::Slice as RawSlice;
28 29
use core::uint;

30
use slice::{CloneSliceAllocPrelude};
S
Steven Fackler 已提交
31

32
/// An owned, growable vector.
S
Steven Fackler 已提交
33
///
34
/// # Examples
S
Steven Fackler 已提交
35
///
J
Jonas Hietala 已提交
36
/// ```
37
/// let mut vec = Vec::new();
38 39
/// vec.push(1i);
/// vec.push(2i);
40 41
///
/// assert_eq!(vec.len(), 2);
N
Nick Cameron 已提交
42
/// assert_eq!(vec[0], 1);
43 44 45
///
/// assert_eq!(vec.pop(), Some(2));
/// assert_eq!(vec.len(), 1);
46
///
47
/// vec[0] = 7i;
48 49 50 51 52 53 54 55
/// assert_eq!(vec[0], 7);
///
/// vec.push_all([1, 2, 3]);
///
/// for x in vec.iter() {
///     println!("{}", x);
/// }
/// assert_eq!(vec, vec![7i, 1, 2, 3]);
56 57 58
/// ```
///
/// The `vec!` macro is provided to make initialization more convenient:
S
Steven Fackler 已提交
59
///
J
Jonas Hietala 已提交
60
/// ```
61
/// let mut vec = vec![1i, 2i, 3i];
S
Steven Fackler 已提交
62
/// vec.push(4);
63
/// assert_eq!(vec, vec![1, 2, 3, 4]);
S
Steven Fackler 已提交
64
/// ```
65
///
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/// Use a `Vec` as an efficient stack:
///
/// ```
/// let mut stack = Vec::new();
///
/// stack.push(1i);
/// stack.push(2i);
/// stack.push(3i);
///
/// loop {
///     let top = match stack.pop() {
///         None => break, // empty
///         Some(x) => x,
///     };
///     // Prints 3, 2, 1
///     println!("{}", top);
/// }
/// ```
///
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
/// # Capacity and reallocation
///
/// The capacity of a vector is the amount of space allocated for any future
/// elements that will be added onto the vector. This is not to be confused
/// with the *length* of a vector, which specifies the number of actual
/// elements within the vector. If a vector's length exceeds its capacity,
/// its capacity will automatically be increased, but its elements will
/// have to be reallocated.
///
/// For example, a vector with capacity 10 and length 0 would be an empty
/// vector with space for 10 more elements. Pushing 10 or fewer elements onto
/// the vector will not change its capacity or cause reallocation to occur.
/// However, if the vector's length is increased to 11, it will have to
/// reallocate, which can be slow. For this reason, it is recommended
/// to use `Vec::with_capacity` whenever possible to specify how big the vector
/// is expected to get.
101
#[unsafe_no_drop_flag]
A
Alex Crichton 已提交
102
#[stable]
103
pub struct Vec<T> {
104
    ptr: *mut T,
105 106
    len: uint,
    cap: uint,
107 108 109
}

impl<T> Vec<T> {
S
Steven Fackler 已提交
110 111 112 113 114 115
    /// Constructs a new, empty `Vec`.
    ///
    /// The vector will not allocate until elements are pushed onto it.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
116
    /// ```
S
Steven Fackler 已提交
117 118
    /// let mut vec: Vec<int> = Vec::new();
    /// ```
119
    #[inline]
A
Alex Crichton 已提交
120
    #[stable]
121
    pub fn new() -> Vec<T> {
122 123 124 125
        // We want ptr to never be NULL so instead we set it to some arbitrary
        // non-null value which is fine since we never call deallocate on the ptr
        // if cap is 0. The reason for this is because the pointer of a slice
        // being NULL would break the null pointer optimization for enums.
126
        Vec { ptr: EMPTY as *mut T, len: 0, cap: 0 }
127 128
    }

S
Steven Fackler 已提交
129 130 131 132 133
    /// Constructs a new, empty `Vec` with the specified capacity.
    ///
    /// The vector will be able to hold exactly `capacity` elements without
    /// reallocating. If `capacity` is 0, the vector will not allocate.
    ///
134 135 136 137 138 139
    /// It is important to note that this function does not specify the
    /// *length* of the returned vector, but only the *capacity*. (For an
    /// explanation of the difference between length and capacity, see
    /// the main `Vec` docs above, 'Capacity and reallocation'.) To create
    /// a vector of a given length, use `Vec::from_elem` or `Vec::from_fn`.
    ///
S
Steven Fackler 已提交
140 141
    /// # Example
    ///
J
Jonas Hietala 已提交
142
    /// ```
143 144 145 146 147 148
    /// let mut vec: Vec<int> = Vec::with_capacity(10);
    ///
    /// // The vector contains no items, even though it has capacity for more
    /// assert_eq!(vec.len(), 0);
    ///
    /// // These are all done without reallocating...
A
Alex Crichton 已提交
149
    /// for i in range(0i, 10) {
150 151 152 153 154
    ///     vec.push(i);
    /// }
    ///
    /// // ...but this may make the vector reallocate
    /// vec.push(11);
S
Steven Fackler 已提交
155
    /// ```
156
    #[inline]
A
Alex Crichton 已提交
157
    #[stable]
158
    pub fn with_capacity(capacity: uint) -> Vec<T> {
A
Alex Crichton 已提交
159
        if mem::size_of::<T>() == 0 {
160
            Vec { ptr: EMPTY as *mut T, len: 0, cap: uint::MAX }
A
Alex Crichton 已提交
161
        } else if capacity == 0 {
162 163
            Vec::new()
        } else {
164
            let size = capacity.checked_mul(mem::size_of::<T>())
165
                               .expect("capacity overflow");
A
Alex Crichton 已提交
166
            let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
167
            Vec { ptr: ptr as *mut T, len: 0, cap: capacity }
168 169 170
        }
    }

S
Steven Fackler 已提交
171 172 173 174 175 176 177
    /// Creates and initializes a `Vec`.
    ///
    /// Creates a `Vec` of size `length` and initializes the elements to the
    /// value returned by the closure `op`.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
178
    /// ```
S
Steven Fackler 已提交
179
    /// let vec = Vec::from_fn(3, |idx| idx * 2);
180
    /// assert_eq!(vec, vec![0, 2, 4]);
S
Steven Fackler 已提交
181
    /// ```
182
    #[inline]
A
Alex Crichton 已提交
183 184
    #[unstable = "the naming is uncertain as well as this migrating to unboxed \
                  closures in the future"]
185 186 187 188
    pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
        unsafe {
            let mut xs = Vec::with_capacity(length);
            while xs.len < length {
189
                let len = xs.len;
A
Aaron Turon 已提交
190
                ptr::write(xs.as_mut_slice().unsafe_mut(len), op(len));
191 192 193 194 195
                xs.len += 1;
            }
            xs
        }
    }
196

P
P1start 已提交
197
    /// Creates a `Vec<T>` directly from the raw constituents.
198 199 200 201 202 203 204 205
    ///
    /// This is highly unsafe:
    ///
    /// - if `ptr` is null, then `length` and `capacity` should be 0
    /// - `ptr` must point to an allocation of size `capacity`
    /// - there must be `length` valid instances of type `T` at the
    ///   beginning of that allocation
    /// - `ptr` must be allocated by the default `Vec` allocator
J
Jonas Hietala 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    ///
    /// # Example
    ///
    /// ```
    /// use std::ptr;
    /// use std::mem;
    ///
    /// fn main() {
    ///     let mut v = vec![1i, 2, 3];
    ///
    ///     // Pull out the various important pieces of information about `v`
    ///     let p = v.as_mut_ptr();
    ///     let len = v.len();
    ///     let cap = v.capacity();
    ///
    ///     unsafe {
    ///         // Cast `v` into the void: no destructor run, so we are in
    ///         // complete control of the allocation to which `p` points.
    ///         mem::forget(v);
    ///
    ///         // Overwrite memory with 4, 5, 6
    ///         for i in range(0, len as int) {
    ///             ptr::write(p.offset(i), 4 + i);
    ///         }
    ///
    ///         // Put everything back together into a Vec
232
    ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
J
Jonas Hietala 已提交
233 234 235 236
    ///         assert_eq!(rebuilt, vec![4i, 5i, 6i]);
    ///     }
    /// }
    /// ```
A
Alex Crichton 已提交
237
    #[experimental]
238 239 240
    pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
                                 capacity: uint) -> Vec<T> {
        Vec { ptr: ptr, len: length, cap: capacity }
241 242
    }

J
Joseph Crail 已提交
243
    /// Consumes the `Vec`, partitioning it based on a predicate.
S
Steven Fackler 已提交
244 245 246 247 248 249 250
    ///
    /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
    /// satisfy `f` and all elements of `B` do not. The order of elements is
    /// preserved.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
251
    /// ```
252
    /// let vec = vec![1i, 2i, 3i, 4i];
S
Steven Fackler 已提交
253
    /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
254 255
    /// assert_eq!(even, vec![2, 4]);
    /// assert_eq!(odd, vec![1, 3]);
S
Steven Fackler 已提交
256
    /// ```
257
    #[inline]
A
Alex Crichton 已提交
258
    #[experimental]
259 260 261 262
    pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
        let mut lefts  = Vec::new();
        let mut rights = Vec::new();

A
Aaron Turon 已提交
263
        for elt in self.into_iter() {
264 265 266 267 268 269 270 271 272
            if f(&elt) {
                lefts.push(elt);
            } else {
                rights.push(elt);
            }
        }

        (lefts, rights)
    }
273 274 275
}

impl<T: Clone> Vec<T> {
S
Steven Fackler 已提交
276 277 278 279 280
    /// Constructs a `Vec` with copies of a value.
    ///
    /// Creates a `Vec` with `length` copies of `value`.
    ///
    /// # Example
J
Jonas Hietala 已提交
281
    /// ```
S
Steven Fackler 已提交
282 283 284
    /// let vec = Vec::from_elem(3, "hi");
    /// println!("{}", vec); // prints [hi, hi, hi]
    /// ```
285
    #[inline]
A
Alex Crichton 已提交
286
    #[unstable = "this functionality may become more generic over all collections"]
287 288 289 290
    pub fn from_elem(length: uint, value: T) -> Vec<T> {
        unsafe {
            let mut xs = Vec::with_capacity(length);
            while xs.len < length {
291
                let len = xs.len;
A
Aaron Turon 已提交
292
                ptr::write(xs.as_mut_slice().unsafe_mut(len),
293
                           value.clone());
294 295 296 297 298
                xs.len += 1;
            }
            xs
        }
    }
299

S
Steven Fackler 已提交
300 301 302 303 304 305 306
    /// Appends all elements in a slice to the `Vec`.
    ///
    /// Iterates over the slice `other`, clones each element, and then appends
    /// it to this `Vec`. The `other` vector is traversed in-order.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
307
    /// ```
308
    /// let mut vec = vec![1i];
309
    /// vec.push_all([2i, 3, 4]);
310
    /// assert_eq!(vec, vec![1, 2, 3, 4]);
S
Steven Fackler 已提交
311
    /// ```
312
    #[inline]
A
Alex Crichton 已提交
313
    #[experimental]
314
    pub fn push_all(&mut self, other: &[T]) {
315
        self.reserve(other.len());
316

317 318 319 320 321 322 323 324
        for i in range(0, other.len()) {
            let len = self.len();

            // Unsafe code so this can be optimised to a memcpy (or something similarly
            // fast) when T is Copy. LLVM is easily confused, so any extra operations
            // during the loop can prevent this optimisation.
            unsafe {
                ptr::write(
A
Aaron Turon 已提交
325
                    self.as_mut_slice().unsafe_mut(len),
326
                    other.unsafe_get(i).clone());
327 328
                self.set_len(len + 1);
            }
329
        }
330
    }
331

S
Steven Fackler 已提交
332 333 334 335 336 337
    /// Grows the `Vec` in-place.
    ///
    /// Adds `n` copies of `value` to the `Vec`.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
338
    /// ```
339
    /// let mut vec = vec!["hello"];
A
Alex Crichton 已提交
340
    /// vec.grow(2, "world");
341
    /// assert_eq!(vec, vec!["hello", "world", "world"]);
S
Steven Fackler 已提交
342
    /// ```
A
Alex Crichton 已提交
343 344
    #[stable]
    pub fn grow(&mut self, n: uint, value: T) {
345
        self.reserve(n);
346 347 348
        let mut i: uint = 0u;

        while i < n {
A
Alex Crichton 已提交
349
            self.push(value.clone());
350 351 352 353
            i += 1u;
        }
    }

J
Joseph Crail 已提交
354
    /// Partitions a vector based on a predicate.
S
Steven Fackler 已提交
355 356
    ///
    /// Clones the elements of the vector, partitioning them into two `Vec`s
P
P1start 已提交
357
    /// `(a, b)`, where all elements of `a` satisfy `f` and all elements of `b`
S
Steven Fackler 已提交
358 359 360 361
    /// do not. The order of elements is preserved.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
362
    /// ```
363
    /// let vec = vec![1i, 2, 3, 4];
S
Steven Fackler 已提交
364
    /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
365 366
    /// assert_eq!(even, vec![2i, 4]);
    /// assert_eq!(odd, vec![1i, 3]);
S
Steven Fackler 已提交
367
    /// ```
A
Alex Crichton 已提交
368
    #[experimental]
369 370 371 372 373 374 375 376 377 378 379 380 381 382
    pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
        let mut lefts = Vec::new();
        let mut rights = Vec::new();

        for elt in self.iter() {
            if f(elt) {
                lefts.push(elt.clone());
            } else {
                rights.push(elt.clone());
            }
        }

        (lefts, rights)
    }
383 384
}

385
#[unstable]
386
impl<T:Clone> Clone for Vec<T> {
387
    fn clone(&self) -> Vec<T> { self.as_slice().to_vec() }
H
Huon Wilson 已提交
388 389 390 391 392

    fn clone_from(&mut self, other: &Vec<T>) {
        // drop anything in self that will not be overwritten
        if self.len() > other.len() {
            self.truncate(other.len())
393
        }
H
Huon Wilson 已提交
394 395

        // reuse the contained values' allocations/resources.
A
Aaron Turon 已提交
396
        for (place, thing) in self.iter_mut().zip(other.iter()) {
H
Huon Wilson 已提交
397 398 399 400 401
            place.clone_from(thing)
        }

        // self.len <= other.len due to the truncate above, so the
        // slice here is always in-bounds.
402
        let slice = other[self.len()..];
403
        self.push_all(slice);
404 405 406
    }
}

A
Alex Crichton 已提交
407
#[experimental = "waiting on Index stability"]
408 409 410
impl<T> Index<uint,T> for Vec<T> {
    #[inline]
    fn index<'a>(&'a self, index: &uint) -> &'a T {
411
        &self.as_slice()[*index]
412 413 414
    }
}

415
impl<T> IndexMut<uint,T> for Vec<T> {
416 417
    #[inline]
    fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
418
        &mut self.as_mut_slice()[*index]
419
    }
420
}
421

N
Nick Cameron 已提交
422 423 424 425 426 427 428 429 430 431
impl<T> ops::Slice<uint, [T]> for Vec<T> {
    #[inline]
    fn as_slice_<'a>(&'a self) -> &'a [T] {
        self.as_slice()
    }

    #[inline]
    fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
        self.as_slice().slice_from_or_fail(start)
    }
N
Nick Cameron 已提交
432

N
Nick Cameron 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    #[inline]
    fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
        self.as_slice().slice_to_or_fail(end)
    }
    #[inline]
    fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
        self.as_slice().slice_or_fail(start, end)
    }
}

impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
    #[inline]
    fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
        self.as_mut_slice()
    }

    #[inline]
    fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
        self.as_mut_slice().slice_from_or_fail_mut(start)
    }

    #[inline]
    fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
        self.as_mut_slice().slice_to_or_fail_mut(end)
    }
    #[inline]
    fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
        self.as_mut_slice().slice_or_fail_mut(start, end)
    }
}
A
Alex Crichton 已提交
463

464 465 466 467 468 469 470 471 472 473
#[experimental = "waiting on Deref stability"]
impl<T> ops::Deref<[T]> for Vec<T> {
    fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
}

#[experimental = "waiting on DerefMut stability"]
impl<T> ops::DerefMut<[T]> for Vec<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
}

A
Alex Crichton 已提交
474
#[experimental = "waiting on FromIterator stability"]
475
impl<T> FromIterator<T> for Vec<T> {
476
    #[inline]
477
    fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
478 479
        let (lower, _) = iterator.size_hint();
        let mut vector = Vec::with_capacity(lower);
480
        for element in iterator {
481 482 483 484 485 486
            vector.push(element)
        }
        vector
    }
}

G
gamazeps 已提交
487 488
#[experimental = "waiting on Extend stability"]
impl<T> Extend<T> for Vec<T> {
489
    #[inline]
490
    fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
491
        let (lower, _) = iterator.size_hint();
492
        self.reserve(lower);
493
        for element in iterator {
494 495 496 497 498
            self.push(element)
        }
    }
}

A
Alex Crichton 已提交
499
#[unstable = "waiting on PartialEq stability"]
500
impl<T: PartialEq> PartialEq for Vec<T> {
501 502 503 504 505 506
    #[inline]
    fn eq(&self, other: &Vec<T>) -> bool {
        self.as_slice() == other.as_slice()
    }
}

A
Alex Crichton 已提交
507
#[unstable = "waiting on PartialOrd stability"]
508
impl<T: PartialOrd> PartialOrd for Vec<T> {
509 510 511 512
    #[inline]
    fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
        self.as_slice().partial_cmp(other.as_slice())
    }
513 514
}

A
Alex Crichton 已提交
515
#[unstable = "waiting on Eq stability"]
516
impl<T: Eq> Eq for Vec<T> {}
517

A
Alex Crichton 已提交
518
#[experimental]
N
Nick Cameron 已提交
519
impl<T: PartialEq, V: AsSlice<T>> Equiv<V> for Vec<T> {
520 521 522 523
    #[inline]
    fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
}

A
Alex Crichton 已提交
524
#[unstable = "waiting on Ord stability"]
525
impl<T: Ord> Ord for Vec<T> {
526 527 528 529
    #[inline]
    fn cmp(&self, other: &Vec<T>) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
530 531
}

D
Daniel Micay 已提交
532 533
// FIXME: #13996: need a way to mark the return value as `noalias`
#[inline(never)]
534
unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
D
Daniel Micay 已提交
535
    if old_size == 0 {
A
Alex Crichton 已提交
536
        allocate(size, mem::min_align_of::<T>()) as *mut T
D
Daniel Micay 已提交
537
    } else {
538
        reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
D
Daniel Micay 已提交
539 540 541
    }
}

542 543
#[inline]
unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
A
Alex Crichton 已提交
544 545 546 547
    if mem::size_of::<T>() != 0 {
        deallocate(ptr as *mut u8,
                   len * mem::size_of::<T>(),
                   mem::min_align_of::<T>())
548 549 550
    }
}

551
impl<T> Vec<T> {
S
Steven Fackler 已提交
552 553 554 555 556
    /// Returns the number of elements the vector can hold without
    /// reallocating.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
557
    /// ```
S
Steven Fackler 已提交
558 559 560
    /// let vec: Vec<int> = Vec::with_capacity(10);
    /// assert_eq!(vec.capacity(), 10);
    /// ```
561
    #[inline]
A
Alex Crichton 已提交
562
    #[stable]
563 564 565 566
    pub fn capacity(&self) -> uint {
        self.cap
    }

567 568
    /// Deprecated: Renamed to `reserve`.
    #[deprecated = "Renamed to `reserve`"]
569
    pub fn reserve_additional(&mut self, extra: uint) {
570
        self.reserve(extra)
571 572
    }

573 574
    /// Reserves capacity for at least `additional` more elements to be inserted in the given
    /// `Vec`. The collection may reserve more space to avoid frequent reallocations.
S
Steven Fackler 已提交
575
    ///
576
    /// # Panics
S
Steven Fackler 已提交
577
    ///
578
    /// Panics if the new capacity overflows `uint`.
S
Steven Fackler 已提交
579 580 581
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
582
    /// ```
583
    /// let mut vec: Vec<int> = vec![1];
S
Steven Fackler 已提交
584
    /// vec.reserve(10);
585
    /// assert!(vec.capacity() >= 11);
S
Steven Fackler 已提交
586
    /// ```
587 588 589
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn reserve(&mut self, additional: uint) {
        if self.cap - self.len < additional {
590
            match self.len.checked_add(additional) {
591 592 593
                None => panic!("Vec::reserve: `uint` overflow"),
                // if the checked_add
                Some(new_cap) => {
594
                    let amort_cap = new_cap.next_power_of_two();
595 596 597 598 599 600 601 602
                    // next_power_of_two will overflow to exactly 0 for really big capacities
                    if amort_cap == 0 {
                        self.grow_capacity(new_cap);
                    } else {
                        self.grow_capacity(amort_cap);
                    }
                }
            }
603 604 605
        }
    }

606 607
    /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
    /// given `Vec`. Does nothing if the capacity is already sufficient.
S
Steven Fackler 已提交
608
    ///
609 610 611 612 613 614 615
    /// Note that the allocator may give the collection more space than it requests. Therefore
    /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
    /// insertions are expected.
    ///
    /// # Panics
    ///
    /// Panics if the new capacity overflows `uint`.
S
Steven Fackler 已提交
616 617 618
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
619
    /// ```
620 621 622
    /// let mut vec: Vec<int> = vec![1];
    /// vec.reserve_exact(10);
    /// assert!(vec.capacity() >= 11);
S
Steven Fackler 已提交
623
    /// ```
624 625 626
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn reserve_exact(&mut self, additional: uint) {
        if self.cap - self.len < additional {
627
            match self.len.checked_add(additional) {
628 629
                None => panic!("Vec::reserve: `uint` overflow"),
                Some(new_cap) => self.grow_capacity(new_cap)
630 631 632 633
            }
        }
    }

634 635 636
    /// Shrinks the capacity of the vector as much as possible. It will drop
    /// down as close as possible to the length but the allocator may still
    /// inform the vector that there is space for a few more elements.
S
Steven Fackler 已提交
637 638 639
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
640
    /// ```
A
areski 已提交
641 642 643
    /// let mut vec: Vec<int> = Vec::with_capacity(10);
    /// vec.push_all([1, 2, 3]);
    /// assert_eq!(vec.capacity(), 10);
S
Steven Fackler 已提交
644
    /// vec.shrink_to_fit();
645
    /// assert!(vec.capacity() >= 3);
S
Steven Fackler 已提交
646
    /// ```
A
Alex Crichton 已提交
647
    #[stable]
648
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
649
    pub fn shrink_to_fit(&mut self) {
A
Alex Crichton 已提交
650 651
        if mem::size_of::<T>() == 0 { return }

652
        if self.len == 0 {
D
Daniel Micay 已提交
653 654
            if self.cap != 0 {
                unsafe {
655
                    dealloc(self.ptr, self.cap)
D
Daniel Micay 已提交
656 657 658
                }
                self.cap = 0;
            }
659 660
        } else {
            unsafe {
A
Alex Crichton 已提交
661 662 663
                // Overflow check is unnecessary as the vector is already at
                // least this large.
                self.ptr = reallocate(self.ptr as *mut u8,
664
                                      self.cap * mem::size_of::<T>(),
A
Alex Crichton 已提交
665
                                      self.len * mem::size_of::<T>(),
666
                                      mem::min_align_of::<T>()) as *mut T;
667
                if self.ptr.is_null() { ::alloc::oom() }
668 669 670 671 672
            }
            self.cap = self.len;
        }
    }

673 674 675 676 677 678 679 680 681 682 683 684 685 686
    /// Convert the vector into Box<[T]>.
    ///
    /// Note that this will drop any excess capacity. Calling this and converting back to a vector
    /// with `into_vec()` is equivalent to calling `shrink_to_fit()`.
    #[experimental]
    pub fn into_boxed_slice(mut self) -> Box<[T]> {
        self.shrink_to_fit();
        unsafe {
            let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
            mem::forget(self);
            xs
        }
    }

S
Steven Fackler 已提交
687 688 689 690 691 692 693
    /// Shorten a vector, dropping excess elements.
    ///
    /// If `len` is greater than the vector's current length, this has no
    /// effect.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
694
    /// ```
695
    /// let mut vec = vec![1i, 2, 3, 4];
S
Steven Fackler 已提交
696
    /// vec.truncate(2);
697
    /// assert_eq!(vec, vec![1, 2]);
S
Steven Fackler 已提交
698
    /// ```
699
    #[unstable = "matches collection reform specification; waiting on panic semantics"]
700 701 702
    pub fn truncate(&mut self, len: uint) {
        unsafe {
            // drop any extra elements
703
            while len < self.len {
S
Steve Klabnik 已提交
704
                // decrement len before the read(), so a panic on Drop doesn't
705 706
                // re-drop the just-failed value.
                self.len -= 1;
707
                ptr::read(self.as_slice().unsafe_get(self.len));
708 709 710 711
            }
        }
    }

P
P1start 已提交
712
    /// Returns a mutable slice of the elements of `self`.
S
Steven Fackler 已提交
713 714 715
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
716
    /// ```
S
Steven Fackler 已提交
717 718
    /// fn foo(slice: &mut [int]) {}
    ///
719
    /// let mut vec = vec![1i, 2];
S
Steven Fackler 已提交
720 721
    /// foo(vec.as_mut_slice());
    /// ```
722
    #[inline]
A
Alex Crichton 已提交
723
    #[stable]
724
    pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
725
        unsafe {
726
            mem::transmute(RawSlice {
727
                data: self.ptr as *const T,
728 729
                len: self.len,
            })
730
        }
731 732
    }

S
Steven Fackler 已提交
733 734 735 736 737 738
    /// Creates a consuming iterator, that is, one that moves each
    /// value out of the vector (from start to end). The vector cannot
    /// be used after calling this.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
739
    /// ```
740
    /// let v = vec!["a".to_string(), "b".to_string()];
A
Aaron Turon 已提交
741
    /// for s in v.into_iter() {
742
    ///     // s has type String, not &String
S
Steven Fackler 已提交
743 744 745
    ///     println!("{}", s);
    /// }
    /// ```
746
    #[inline]
747
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
A
Aaron Turon 已提交
748
    pub fn into_iter(self) -> MoveItems<T> {
749
        unsafe {
750
            let ptr = self.ptr;
D
Daniel Micay 已提交
751
            let cap = self.cap;
752
            let begin = self.ptr as *const T;
753
            let end = if mem::size_of::<T>() == 0 {
D
Dan Schatzberg 已提交
754
                (ptr as uint + self.len()) as *const T
755
            } else {
D
Dan Schatzberg 已提交
756
                ptr.offset(self.len() as int) as *const T
757
            };
A
Alex Crichton 已提交
758
            mem::forget(self);
759
            MoveItems { allocation: ptr, cap: cap, ptr: begin, end: end }
760 761 762
        }
    }

S
Steven Fackler 已提交
763 764 765 766 767
    /// Sets the length of a vector.
    ///
    /// This will explicitly set the size of the vector, without actually
    /// modifying its buffers, so it is up to the caller to ensure that the
    /// vector is actually the specified size.
768 769 770 771 772 773 774 775 776
    ///
    /// # Example
    ///
    /// ```
    /// let mut v = vec![1u, 2, 3, 4];
    /// unsafe {
    ///     v.set_len(1);
    /// }
    /// ```
777
    #[inline]
A
Alex Crichton 已提交
778
    #[stable]
779 780 781
    pub unsafe fn set_len(&mut self, len: uint) {
        self.len = len;
    }
782

P
P1start 已提交
783
    /// Removes an element from anywhere in the vector and return it, replacing
S
Steven Fackler 已提交
784 785 786 787 788
    /// it with the last element. This does not preserve ordering, but is O(1).
    ///
    /// Returns `None` if `index` is out of bounds.
    ///
    /// # Example
J
Jonas Hietala 已提交
789
    /// ```
790
    /// let mut v = vec!["foo", "bar", "baz", "qux"];
S
Steven Fackler 已提交
791
    ///
792 793
    /// assert_eq!(v.swap_remove(1), Some("bar"));
    /// assert_eq!(v, vec!["foo", "qux", "baz"]);
S
Steven Fackler 已提交
794
    ///
795 796
    /// assert_eq!(v.swap_remove(0), Some("foo"));
    /// assert_eq!(v, vec!["baz", "qux"]);
S
Steven Fackler 已提交
797 798 799
    ///
    /// assert_eq!(v.swap_remove(2), None);
    /// ```
800
    #[inline]
A
Alex Crichton 已提交
801
    #[unstable = "the naming of this function may be altered"]
802
    pub fn swap_remove(&mut self, index: uint) -> Option<T> {
803
        let length = self.len();
804
        if length > 0 && index < length - 1 {
805
            self.as_mut_slice().swap(index, length - 1);
806 807
        } else if index >= length {
            return None
808
        }
809
        self.pop()
810 811
    }

P
P1start 已提交
812 813
    /// Inserts an element at position `index` within the vector, shifting all
    /// elements after position `i` one position to the right.
S
Steven Fackler 已提交
814
    ///
S
Steve Klabnik 已提交
815
    /// # Panics
S
Steven Fackler 已提交
816
    ///
S
Steve Klabnik 已提交
817
    /// Panics if `index` is not between `0` and the vector's length (both
818
    /// bounds inclusive).
S
Steven Fackler 已提交
819 820 821
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
822
    /// ```
823
    /// let mut vec = vec![1i, 2, 3];
S
Steven Fackler 已提交
824
    /// vec.insert(1, 4);
825
    /// assert_eq!(vec, vec![1, 4, 2, 3]);
826
    /// vec.insert(4, 5);
827
    /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
S
Steven Fackler 已提交
828
    /// ```
S
Steve Klabnik 已提交
829
    #[unstable = "panic semantics need settling"]
830 831 832 833
    pub fn insert(&mut self, index: uint, element: T) {
        let len = self.len();
        assert!(index <= len);
        // space for the new element
834
        self.reserve(1);
835 836 837 838

        unsafe { // infallible
            // The spot to put the new value
            {
839
                let p = self.as_mut_ptr().offset(index as int);
840 841 842 843 844
                // Shift everything over to make space. (Duplicating the
                // `index`th element into two consecutive places.)
                ptr::copy_memory(p.offset(1), &*p, len - index);
                // Write it in, overwriting the first copy of the `index`th
                // element.
845
                ptr::write(&mut *p, element);
846 847 848 849 850
            }
            self.set_len(len + 1);
        }
    }

P
P1start 已提交
851
    /// Removes and returns the element at position `index` within the vector,
S
Steven Fackler 已提交
852 853 854 855 856
    /// shifting all elements after position `index` one position to the left.
    /// Returns `None` if `i` is out of bounds.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
857
    /// ```
858
    /// let mut v = vec![1i, 2, 3];
S
Steven Fackler 已提交
859
    /// assert_eq!(v.remove(1), Some(2));
860
    /// assert_eq!(v, vec![1, 3]);
S
Steven Fackler 已提交
861 862 863
    ///
    /// assert_eq!(v.remove(4), None);
    /// // v is unchanged:
864
    /// assert_eq!(v, vec![1, 3]);
S
Steven Fackler 已提交
865
    /// ```
S
Steve Klabnik 已提交
866
    #[unstable = "panic semantics need settling"]
867
    pub fn remove(&mut self, index: uint) -> Option<T> {
K
Kiet Tran 已提交
868 869 870 871 872 873
        let len = self.len();
        if index < len {
            unsafe { // infallible
                let ret;
                {
                    // the place we are taking from.
874
                    let ptr = self.as_mut_ptr().offset(index as int);
K
Kiet Tran 已提交
875 876
                    // copy it out, unsafely having a copy of the value on
                    // the stack and in the vector at the same time.
877
                    ret = Some(ptr::read(ptr as *const T));
K
Kiet Tran 已提交
878 879 880 881 882 883 884 885 886 887 888 889

                    // Shift everything down to fill in that spot.
                    ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
                }
                self.set_len(len - 1);
                ret
            }
        } else {
            None
        }
    }

890 891 892
    /// Retains only the elements specified by the predicate.
    ///
    /// In other words, remove all elements `e` such that `f(&e)` returns false.
893
    /// This method operates in place and preserves the order of the retained elements.
894 895 896
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
897
    /// ```
898
    /// let mut vec = vec![1i, 2, 3, 4];
899
    /// vec.retain(|&x| x%2 == 0);
900
    /// assert_eq!(vec, vec![2, 4]);
901
    /// ```
A
Alex Crichton 已提交
902
    #[unstable = "the closure argument may become an unboxed closure"]
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    pub fn retain(&mut self, f: |&T| -> bool) {
        let len = self.len();
        let mut del = 0u;
        {
            let v = self.as_mut_slice();

            for i in range(0u, len) {
                if !f(&v[i]) {
                    del += 1;
                } else if del > 0 {
                    v.swap(i-del, i);
                }
            }
        }
        if del > 0 {
            self.truncate(len - del);
        }
    }

    /// Expands a vector in place, initializing the new elements to the result of a function.
    ///
    /// The vector is grown by `n` elements. The i-th new element are initialized to the value
    /// returned by `f(i)` where `i` is in the range [0, n).
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
929
    /// ```
930
    /// let mut vec = vec![0u, 1];
931
    /// vec.grow_fn(3, |i| i);
932
    /// assert_eq!(vec, vec![0, 1, 0, 1, 2]);
933
    /// ```
A
Alex Crichton 已提交
934
    #[unstable = "this function may be renamed or change to unboxed closures"]
935
    pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
936
        self.reserve(n);
937 938 939 940
        for i in range(0u, n) {
            self.push(f(i));
        }
    }
941

942 943
    /// Appends an element to the back of a collection.
    ///
944
    /// # Panics
945
    ///
946
    /// Panics if the number of elements in the vector overflows a `uint`.
947 948 949 950 951 952 953 954 955 956 957 958 959
    ///
    /// # Example
    ///
    /// ```rust
    /// let mut vec = vec!(1i, 2);
    /// vec.push(3);
    /// assert_eq!(vec, vec!(1, 2, 3));
    /// ```
    #[inline]
    #[stable]
    pub fn push(&mut self, value: T) {
        if mem::size_of::<T>() == 0 {
            // zero-size types consume no memory, so we can't rely on the address space running out
960
            self.len = self.len.checked_add(1).expect("length overflow");
961 962 963 964 965 966 967 968 969
            unsafe { mem::forget(value); }
            return
        }
        if self.len == self.cap {
            let old_size = self.cap * mem::size_of::<T>();
            let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
            if old_size > size { panic!("capacity overflow") }
            unsafe {
                self.ptr = alloc_or_realloc(self.ptr, old_size, size);
970
                if self.ptr.is_null() { ::alloc::oom() }
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
            }
            self.cap = max(self.cap, 2) * 2;
        }

        unsafe {
            let end = (self.ptr as *const T).offset(self.len as int) as *mut T;
            ptr::write(&mut *end, value);
            self.len += 1;
        }
    }

    /// Removes the last element from a vector and returns it, or `None` if
    /// it is empty.
    ///
    /// # Example
    ///
    /// ```rust
    /// let mut vec = vec![1i, 2, 3];
    /// assert_eq!(vec.pop(), Some(3));
    /// assert_eq!(vec, vec![1, 2]);
    /// ```
992
    #[inline]
A
Alex Crichton 已提交
993
    #[stable]
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            None
        } else {
            unsafe {
                self.len -= 1;
                Some(ptr::read(self.as_slice().unsafe_get(self.len())))
            }
        }
    }

    /// Clears the vector, removing all values.
    ///
    /// # Example
    ///
    /// ```
    /// let mut v = vec![1i, 2, 3];
    /// v.clear();
    /// assert!(v.is_empty());
    /// ```
    #[inline]
    #[stable]
    pub fn clear(&mut self) {
1017 1018
        self.truncate(0)
    }
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

    /// Return the number of elements in the vector
    ///
    /// # Example
    ///
    /// ```
    /// let a = vec![1i, 2, 3];
    /// assert_eq!(a.len(), 3);
    /// ```
    #[inline]
    #[stable]
    pub fn len(&self) -> uint { self.len }

    /// Returns true if the vector contains no elements
    ///
    /// # Example
    ///
    /// ```
    /// let mut v = Vec::new();
    /// assert!(v.is_empty());
    /// v.push(1i);
    /// assert!(!v.is_empty());
    /// ```
1042
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
1043
    pub fn is_empty(&self) -> bool { self.len() == 0 }
1044 1045 1046 1047 1048 1049 1050 1051 1052

    /// Reserves capacity for exactly `capacity` elements in the given vector.
    ///
    /// If the capacity for `self` is already equal to or greater than the
    /// requested capacity, then no action is taken.
    fn grow_capacity(&mut self, capacity: uint) {
        if mem::size_of::<T>() == 0 { return }

        if capacity > self.cap {
1053
            let size = capacity.checked_mul(mem::size_of::<T>())
1054 1055 1056 1057 1058 1059 1060 1061
                               .expect("capacity overflow");
            unsafe {
                self.ptr = alloc_or_realloc(self.ptr, self.cap * mem::size_of::<T>(), size);
                if self.ptr.is_null() { ::alloc::oom() }
            }
            self.cap = capacity;
        }
    }
1062 1063
}

P
P1start 已提交
1064 1065
impl<T: PartialEq> Vec<T> {
    /// Removes consecutive repeated elements in the vector.
S
Steven Fackler 已提交
1066 1067 1068 1069 1070
    ///
    /// If the vector is sorted, this removes all duplicates.
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
1071
    /// ```
1072
    /// let mut vec = vec![1i, 2, 2, 3, 2];
S
Steven Fackler 已提交
1073
    /// vec.dedup();
1074
    /// assert_eq!(vec, vec![1i, 2, 3, 2]);
S
Steven Fackler 已提交
1075
    /// ```
A
Alex Crichton 已提交
1076
    #[unstable = "this function may be renamed"]
1077 1078 1079
    pub fn dedup(&mut self) {
        unsafe {
            // Although we have a mutable reference to `self`, we cannot make
S
Steve Klabnik 已提交
1080
            // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
            // must ensure that the vector is in a valid state at all time.
            //
            // The way that we handle this is by using swaps; we iterate
            // over all the elements, swapping as we go so that at the end
            // the elements we wish to keep are in the front, and those we
            // wish to reject are at the back. We can then truncate the
            // vector. This operation is still O(n).
            //
            // Example: We start in this state, where `r` represents "next
            // read" and `w` represents "next_write`.
            //
            //           r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //           w
            //
A
Adolfo Ochagavía 已提交
1098
            // Comparing self[r] against self[w-1], this is not a duplicate, so
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
            // we swap self[r] and self[w] (no effect as r==w) and then increment both
            // r and w, leaving us with:
            //
            //               r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //               w
            //
            // Comparing self[r] against self[w-1], this value is a duplicate,
            // so we increment `r` but leave everything else unchanged:
            //
            //                   r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 1 | 2 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //               w
            //
            // Comparing self[r] against self[w-1], this is not a duplicate,
            // so swap self[r] and self[w] and advance r and w:
            //
            //                       r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 2 | 1 | 3 | 3 |
            //     +---+---+---+---+---+---+
            //                   w
            //
            // Not a duplicate, repeat:
            //
            //                           r
            //     +---+---+---+---+---+---+
            //     | 0 | 1 | 2 | 3 | 1 | 3 |
            //     +---+---+---+---+---+---+
            //                       w
            //
            // Duplicate, advance r. End of vec. Truncate to w.

            let ln = self.len();
            if ln < 1 { return; }

            // Avoid bounds checks by using unsafe pointers.
            let p = self.as_mut_slice().as_mut_ptr();
            let mut r = 1;
            let mut w = 1;

            while r < ln {
                let p_r = p.offset(r as int);
                let p_wm1 = p.offset((w - 1) as int);
                if *p_r != *p_wm1 {
                    if r != w {
                        let p_w = p_wm1.offset(1);
                        mem::swap(&mut *p_r, &mut *p_w);
                    }
                    w += 1;
                }
                r += 1;
            }

            self.truncate(w);
        }
    }
1160 1161
}

N
Nick Cameron 已提交
1162
impl<T> AsSlice<T> for Vec<T> {
P
P1start 已提交
1163
    /// Returns a slice into `self`.
1164 1165 1166
    ///
    /// # Example
    ///
J
Jonas Hietala 已提交
1167
    /// ```
1168 1169
    /// fn foo(slice: &[int]) {}
    ///
1170
    /// let vec = vec![1i, 2];
1171 1172 1173
    /// foo(vec.as_slice());
    /// ```
    #[inline]
A
Alex Crichton 已提交
1174
    #[stable]
1175
    fn as_slice<'a>(&'a self) -> &'a [T] {
1176 1177 1178 1179 1180 1181
        unsafe {
            mem::transmute(RawSlice {
                data: self.ptr as *const T,
                len: self.len
            })
        }
1182 1183 1184
    }
}

N
Nick Cameron 已提交
1185
impl<T: Clone, V: AsSlice<T>> Add<V, Vec<T>> for Vec<T> {
1186 1187 1188 1189 1190 1191 1192 1193 1194
    #[inline]
    fn add(&self, rhs: &V) -> Vec<T> {
        let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
        res.push_all(self.as_slice());
        res.push_all(rhs.as_slice());
        res
    }
}

1195 1196 1197
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
    fn drop(&mut self) {
1198 1199
        // This is (and should always remain) a no-op if the fields are
        // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
D
Daniel Micay 已提交
1200 1201 1202 1203 1204
        if self.cap != 0 {
            unsafe {
                for x in self.as_mut_slice().iter() {
                    ptr::read(x);
                }
1205
                dealloc(self.ptr, self.cap)
1206 1207 1208 1209 1210
            }
        }
    }
}

A
Alex Crichton 已提交
1211
#[stable]
1212 1213 1214 1215 1216 1217
impl<T> Default for Vec<T> {
    fn default() -> Vec<T> {
        Vec::new()
    }
}

A
Alex Crichton 已提交
1218
#[experimental = "waiting on Show stability"]
1219 1220 1221 1222 1223 1224
impl<T:fmt::Show> fmt::Show for Vec<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.as_slice().fmt(f)
    }
}

S
Steven Fackler 已提交
1225
/// An iterator that moves out of a vector.
1226
pub struct MoveItems<T> {
1227
    allocation: *mut T, // the block of memory allocated for the vector
D
Daniel Micay 已提交
1228
    cap: uint, // the capacity of the vector
1229 1230
    ptr: *const T,
    end: *const T
1231 1232
}

J
Julian Orth 已提交
1233 1234 1235 1236 1237 1238
impl<T> MoveItems<T> {
    #[inline]
    /// Drops all items that have not yet been moved and returns the empty vector.
    pub fn unwrap(mut self) -> Vec<T> {
        unsafe {
            for _x in self { }
D
Dan Schatzberg 已提交
1239
            let MoveItems { allocation, cap, ptr: _ptr, end: _end } = self;
J
Julian Orth 已提交
1240 1241 1242 1243 1244 1245
            mem::forget(self);
            Vec { ptr: allocation, cap: cap, len: 0 }
        }
    }
}

1246 1247
impl<T> Iterator<T> for MoveItems<T> {
    #[inline]
1248
    fn next<'a>(&'a mut self) -> Option<T> {
1249
        unsafe {
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
            if self.ptr == self.end {
                None
            } else {
                if mem::size_of::<T>() == 0 {
                    // purposefully don't use 'ptr.offset' because for
                    // vectors with 0-size elements this would return the
                    // same pointer.
                    self.ptr = mem::transmute(self.ptr as uint + 1);

                    // Use a non-null pointer value
                    Some(ptr::read(mem::transmute(1u)))
                } else {
                    let old = self.ptr;
                    self.ptr = self.ptr.offset(1);

                    Some(ptr::read(old))
                }
            }
1268 1269 1270 1271 1272
        }
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
1273 1274 1275 1276
        let diff = (self.end as uint) - (self.ptr as uint);
        let size = mem::size_of::<T>();
        let exact = diff / (if size == 0 {1} else {size});
        (exact, Some(exact))
1277 1278 1279 1280 1281
    }
}

impl<T> DoubleEndedIterator<T> for MoveItems<T> {
    #[inline]
1282
    fn next_back<'a>(&'a mut self) -> Option<T> {
1283
        unsafe {
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
            if self.end == self.ptr {
                None
            } else {
                if mem::size_of::<T>() == 0 {
                    // See above for why 'ptr.offset' isn't used
                    self.end = mem::transmute(self.end as uint - 1);

                    // Use a non-null pointer value
                    Some(ptr::read(mem::transmute(1u)))
                } else {
                    self.end = self.end.offset(-1);

                    Some(ptr::read(mem::transmute(self.end)))
                }
            }
1299 1300 1301 1302
        }
    }
}

1303 1304
impl<T> ExactSize<T> for MoveItems<T> {}

1305 1306 1307 1308
#[unsafe_destructor]
impl<T> Drop for MoveItems<T> {
    fn drop(&mut self) {
        // destroy the remaining elements
D
Daniel Micay 已提交
1309 1310 1311
        if self.cap != 0 {
            for _x in *self {}
            unsafe {
1312
                dealloc(self.allocation, self.cap);
D
Daniel Micay 已提交
1313
            }
1314 1315 1316
        }
    }
}
1317

P
P1start 已提交
1318 1319 1320 1321 1322 1323
/// Converts an iterator of pairs into a pair of vectors.
///
/// Returns a tuple containing two vectors where the i-th element of the first
/// vector contains the first element of the i-th tuple of the input iterator,
/// and the i-th element of the second vector contains the second element
/// of the i-th tuple of the input iterator.
A
Alex Crichton 已提交
1324
#[unstable = "this functionality may become more generic over time"]
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
    let (lo, _) = iter.size_hint();
    let mut ts = Vec::with_capacity(lo);
    let mut us = Vec::with_capacity(lo);
    for (t, u) in iter {
        ts.push(t);
        us.push(u);
    }
    (ts, us)
}

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
/// Wrapper type providing a `&Vec<T>` reference via `Deref`.
#[experimental]
pub struct DerefVec<'a, T> {
    x: Vec<T>,
    l: ContravariantLifetime<'a>
}

impl<'a, T> Deref<Vec<T>> for DerefVec<'a, T> {
    fn deref<'b>(&'b self) -> &'b Vec<T> {
        &self.x
    }
}

// Prevent the inner `Vec<T>` from attempting to deallocate memory.
#[unsafe_destructor]
impl<'a, T> Drop for DerefVec<'a, T> {
    fn drop(&mut self) {
        self.x.len = 0;
        self.x.cap = 0;
    }
}

/// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
#[experimental]
pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
    unsafe {
        DerefVec {
1363
            x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1364 1365 1366 1367 1368
            l: ContravariantLifetime::<'a>
        }
    }
}

P
P1start 已提交
1369
/// Unsafe vector operations.
A
Alex Crichton 已提交
1370
#[unstable]
1371 1372
pub mod raw {
    use super::Vec;
1373
    use core::ptr;
1374
    use core::slice::SlicePrelude;
1375 1376 1377 1378 1379 1380

    /// Constructs a vector from an unsafe pointer to a buffer.
    ///
    /// The elements of the buffer are copied into the vector without cloning,
    /// as if `ptr::read()` were called on them.
    #[inline]
A
Alex Crichton 已提交
1381
    #[unstable]
1382
    pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
1383 1384 1385 1386 1387 1388 1389
        let mut dst = Vec::with_capacity(elts);
        dst.set_len(elts);
        ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
        dst
    }
}

1390
/// An owned, partially type-converted vector of elements with non-zero size.
1391
///
1392 1393
/// `T` and `U` must have the same, non-zero size. They must also have the same
/// alignment.
1394
///
1395 1396 1397 1398
/// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
/// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
/// destructed. Additionally the underlying storage of `vec` will be freed.
struct PartialVecNonZeroSized<T,U> {
1399 1400 1401 1402 1403 1404 1405 1406
    vec: Vec<T>,

    start_u: *mut U,
    end_u: *mut U,
    start_t: *mut T,
    end_t: *mut T,
}

1407 1408 1409 1410 1411 1412 1413 1414 1415
/// An owned, partially type-converted vector of zero-sized elements.
///
/// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
/// are destructed.
struct PartialVecZeroSized<T,U> {
    num_t: uint,
    num_u: uint,
    marker_t: InvariantType<T>,
    marker_u: InvariantType<U>,
1416 1417 1418
}

#[unsafe_destructor]
1419
impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1420 1421
    fn drop(&mut self) {
        unsafe {
1422 1423 1424 1425 1426
            // `vec` hasn't been modified until now. As it has a length
            // currently, this would run destructors of `T`s which might not be
            // there. So at first, set `vec`s length to `0`. This must be done
            // at first to remain memory-safe as the destructors of `U` or `T`
            // might cause unwinding where `vec`s destructor would be executed.
1427 1428
            self.vec.set_len(0);

1429 1430
            // We have instances of `U`s and `T`s in `vec`. Destruct them.
            while self.start_u != self.end_u {
1431 1432 1433
                let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
                self.start_u = self.start_u.offset(1);
            }
1434
            while self.start_t != self.end_t {
1435 1436 1437 1438 1439 1440 1441 1442 1443
                let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
                self.start_t = self.start_t.offset(1);
            }
            // After this destructor ran, the destructor of `vec` will run,
            // deallocating the underlying memory.
        }
    }
}

1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
#[unsafe_destructor]
impl<T,U> Drop for PartialVecZeroSized<T,U> {
    fn drop(&mut self) {
        unsafe {
            // Destruct the instances of `T` and `U` this struct owns.
            while self.num_t != 0 {
                let _: T = mem::uninitialized(); // Run a `T` destructor.
                self.num_t -= 1;
            }
            while self.num_u != 0 {
                let _: U = mem::uninitialized(); // Run a `U` destructor.
                self.num_u -= 1;
            }
        }
    }
}

1461
impl<T> Vec<T> {
1462
    /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
1463
    /// size and in case they are not zero-sized the same minimal alignment.
1464
    ///
1465
    /// # Panics
1466
    ///
1467
    /// Panics if `T` and `U` have differing sizes or are not zero-sized and
1468
    /// have differing minimal alignments.
1469 1470 1471
    ///
    /// # Example
    ///
1472
    /// ```
1473
    /// let v = vec![0u, 1, 2];
1474
    /// let w = v.map_in_place(|i| i + 3);
1475
    /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
1476
    ///
1477 1478 1479 1480 1481
    /// #[deriving(PartialEq, Show)]
    /// struct Newtype(u8);
    /// let bytes = vec![0x11, 0x22];
    /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
    /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
1482
    /// ```
1483
    pub fn map_in_place<U>(self, f: |T| -> U) -> Vec<U> {
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
        // FIXME: Assert statically that the types `T` and `U` have the same
        // size.
        assert!(mem::size_of::<T>() == mem::size_of::<U>());

        let mut vec = self;

        if mem::size_of::<T>() != 0 {
            // FIXME: Assert statically that the types `T` and `U` have the
            // same minimal alignment in case they are not zero-sized.

            // These asserts are necessary because the `min_align_of` of the
            // types are passed to the allocator by `Vec`.
            assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());

            // This `as int` cast is safe, because the size of the elements of the
            // vector is not 0, and:
            //
            // 1) If the size of the elements in the vector is 1, the `int` may
            //    overflow, but it has the correct bit pattern so that the
            //    `.offset()` function will work.
            //
            //    Example:
            //        Address space 0x0-0xF.
            //        `u8` array at: 0x1.
            //        Size of `u8` array: 0x8.
            //        Calculated `offset`: -0x8.
            //        After `array.offset(offset)`: 0x9.
            //        (0x1 + 0x8 = 0x1 - 0x8)
            //
            // 2) If the size of the elements in the vector is >1, the `uint` ->
            //    `int` conversion can't overflow.
            let offset = vec.len() as int;
            let start = vec.as_mut_ptr();

            let mut pv = PartialVecNonZeroSized {
                vec: vec,

                start_t: start,
                // This points inside the vector, as the vector has length
                // `offset`.
                end_t: unsafe { start.offset(offset) },
                start_u: start as *mut U,
                end_u: start as *mut U,
            };
            //  start_t
            //  start_u
            //  |
            // +-+-+-+-+-+-+
            // |T|T|T|...|T|
            // +-+-+-+-+-+-+
            //  |           |
            //  end_u       end_t

            while pv.end_u as *mut T != pv.end_t {
                unsafe {
                    //  start_u start_t
                    //  |       |
                    // +-+-+-+-+-+-+-+-+-+
                    // |U|...|U|T|T|...|T|
                    // +-+-+-+-+-+-+-+-+-+
                    //          |         |
                    //          end_u     end_t

                    let t = ptr::read(pv.start_t as *const T);
                    //  start_u start_t
                    //  |       |
                    // +-+-+-+-+-+-+-+-+-+
                    // |U|...|U|X|T|...|T|
                    // +-+-+-+-+-+-+-+-+-+
                    //          |         |
                    //          end_u     end_t
S
Steve Klabnik 已提交
1555
                    // We must not panic here, one cell is marked as `T`
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
                    // although it is not `T`.

                    pv.start_t = pv.start_t.offset(1);
                    //  start_u   start_t
                    //  |         |
                    // +-+-+-+-+-+-+-+-+-+
                    // |U|...|U|X|T|...|T|
                    // +-+-+-+-+-+-+-+-+-+
                    //          |         |
                    //          end_u     end_t
S
Steve Klabnik 已提交
1566
                    // We may panic again.
1567

S
Steve Klabnik 已提交
1568
                    // The function given by the user might panic.
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                    let u = f(t);

                    ptr::write(pv.end_u, u);
                    //  start_u   start_t
                    //  |         |
                    // +-+-+-+-+-+-+-+-+-+
                    // |U|...|U|U|T|...|T|
                    // +-+-+-+-+-+-+-+-+-+
                    //          |         |
                    //          end_u     end_t
S
Steve Klabnik 已提交
1579
                    // We should not panic here, because that would leak the `U`
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
                    // pointed to by `end_u`.

                    pv.end_u = pv.end_u.offset(1);
                    //  start_u   start_t
                    //  |         |
                    // +-+-+-+-+-+-+-+-+-+
                    // |U|...|U|U|T|...|T|
                    // +-+-+-+-+-+-+-+-+-+
                    //            |       |
                    //            end_u   end_t
S
Steve Klabnik 已提交
1590
                    // We may panic again.
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
                }
            }

            //  start_u     start_t
            //  |           |
            // +-+-+-+-+-+-+
            // |U|...|U|U|U|
            // +-+-+-+-+-+-+
            //              |
            //              end_t
            //              end_u
            // Extract `vec` and prevent the destructor of
            // `PartialVecNonZeroSized` from running. Note that none of the
S
Steve Klabnik 已提交
1604
            // function calls can panic, thus no resources can be leaked (as the
1605 1606
            // `vec` member of `PartialVec` is the only one which holds
            // allocations -- and it is returned from this function. None of
S
Steve Klabnik 已提交
1607
            // this can panic.
1608 1609 1610 1611 1612
            unsafe {
                let vec_len = pv.vec.len();
                let vec_cap = pv.vec.capacity();
                let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
                mem::forget(pv);
1613
                Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
            }
        } else {
            // Put the `Vec` into the `PartialVecZeroSized` structure and
            // prevent the destructor of the `Vec` from running. Since the
            // `Vec` contained zero-sized objects, it did not allocate, so we
            // are not leaking memory here.
            let mut pv = PartialVecZeroSized::<T,U> {
                num_t: vec.len(),
                num_u: 0,
                marker_t: InvariantType,
                marker_u: InvariantType,
1625
            };
1626 1627 1628 1629 1630
            unsafe { mem::forget(vec); }

            while pv.num_t != 0 {
                unsafe {
                    // Create a `T` out of thin air and decrement `num_t`. This
S
Steve Klabnik 已提交
1631
                    // must not panic between these steps, as otherwise a
1632 1633 1634 1635
                    // destructor of `T` which doesn't exist runs.
                    let t = mem::uninitialized();
                    pv.num_t -= 1;

S
Steve Klabnik 已提交
1636
                    // The function given by the user might panic.
1637 1638 1639 1640 1641
                    let u = f(t);

                    // Forget the `U` and increment `num_u`. This increment
                    // cannot overflow the `uint` as we only do this for a
                    // number of times that fits into a `uint` (and start with
S
Steve Klabnik 已提交
1642
                    // `0`). Again, we should not panic between these steps.
1643 1644 1645 1646 1647
                    mem::forget(u);
                    pv.num_u += 1;
                }
            }
            // Create a `Vec` from our `PartialVecZeroSized` and make sure the
S
Steve Klabnik 已提交
1648
            // destructor of the latter will not run. None of this can panic.
1649 1650 1651
            let mut result = Vec::new();
            unsafe { result.set_len(pv.num_u); }
            result
1652 1653 1654 1655
        }
    }
}

1656 1657
#[cfg(test)]
mod tests {
1658 1659
    extern crate test;

1660 1661
    use std::prelude::*;
    use std::mem::size_of;
1662
    use test::Bencher;
1663
    use super::{as_vec, unzip, raw, Vec};
1664

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
    struct DropCounter<'a> {
        count: &'a mut int
    }

    #[unsafe_destructor]
    impl<'a> Drop for DropCounter<'a> {
        fn drop(&mut self) {
            *self.count += 1;
        }
    }

    #[test]
    fn test_as_vec() {
        let xs = [1u8, 2u8, 3u8];
        assert_eq!(as_vec(xs).as_slice(), xs.as_slice());
    }

    #[test]
    fn test_as_vec_dtor() {
        let (mut count_x, mut count_y) = (0, 0);
        {
            let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
            assert_eq!(as_vec(xs).len(), 2);
        }
        assert_eq!(count_x, 1);
        assert_eq!(count_y, 1);
    }

1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
    #[test]
    fn test_small_vec_struct() {
        assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
    }

    #[test]
    fn test_double_drop() {
        struct TwoVec<T> {
            x: Vec<T>,
            y: Vec<T>
        }

1705
        let (mut count_x, mut count_y) = (0, 0);
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
        {
            let mut tv = TwoVec {
                x: Vec::new(),
                y: Vec::new()
            };
            tv.x.push(DropCounter {count: &mut count_x});
            tv.y.push(DropCounter {count: &mut count_y});

            // If Vec had a drop flag, here is where it would be zeroed.
            // Instead, it should rely on its internal state to prevent
            // doing anything significant when dropped multiple times.
            drop(tv.x);

            // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
        }

        assert_eq!(count_x, 1);
        assert_eq!(count_y, 1);
    }
1725 1726

    #[test]
1727
    fn test_reserve() {
1728 1729 1730
        let mut v = Vec::new();
        assert_eq!(v.capacity(), 0);

1731
        v.reserve(2);
1732 1733
        assert!(v.capacity() >= 2);

1734
        for i in range(0i, 16) {
1735 1736 1737 1738
            v.push(i);
        }

        assert!(v.capacity() >= 16);
1739
        v.reserve(16);
1740 1741 1742 1743
        assert!(v.capacity() >= 32);

        v.push(16);

1744
        v.reserve(16);
1745 1746 1747 1748 1749 1750 1751 1752
        assert!(v.capacity() >= 33)
    }

    #[test]
    fn test_extend() {
        let mut v = Vec::new();
        let mut w = Vec::new();

1753 1754
        v.extend(range(0i, 3));
        for i in range(0i, 3) { w.push(i) }
1755 1756 1757

        assert_eq!(v, w);

1758 1759
        v.extend(range(3i, 10));
        for i in range(3i, 10) { w.push(i) }
1760 1761 1762

        assert_eq!(v, w);
    }
1763 1764

    #[test]
N
NODA, Kai 已提交
1765 1766
    fn test_slice_from_mut() {
        let mut values = vec![1u8,2,3,4,5];
1767
        {
A
Aaron Turon 已提交
1768
            let slice = values.slice_from_mut(2);
1769
            assert!(slice == [3, 4, 5]);
A
Aaron Turon 已提交
1770
            for p in slice.iter_mut() {
1771 1772 1773 1774 1775 1776 1777 1778
                *p += 2;
            }
        }

        assert!(values.as_slice() == [1, 2, 5, 6, 7]);
    }

    #[test]
N
NODA, Kai 已提交
1779 1780
    fn test_slice_to_mut() {
        let mut values = vec![1u8,2,3,4,5];
1781
        {
A
Aaron Turon 已提交
1782
            let slice = values.slice_to_mut(2);
1783
            assert!(slice == [1, 2]);
A
Aaron Turon 已提交
1784
            for p in slice.iter_mut() {
1785 1786 1787 1788 1789 1790 1791 1792
                *p += 1;
            }
        }

        assert!(values.as_slice() == [2, 3, 3, 4, 5]);
    }

    #[test]
N
NODA, Kai 已提交
1793 1794
    fn test_split_at_mut() {
        let mut values = vec![1u8,2,3,4,5];
1795
        {
A
Aaron Turon 已提交
1796
            let (left, right) = values.split_at_mut(2);
1797 1798
            {
                let left: &[_] = left;
1799
                assert!(left[0..left.len()] == [1, 2][]);
1800
            }
A
Aaron Turon 已提交
1801
            for p in left.iter_mut() {
1802 1803 1804
                *p += 1;
            }

1805 1806
            {
                let right: &[_] = right;
1807
                assert!(right[0..right.len()] == [3, 4, 5][]);
1808
            }
A
Aaron Turon 已提交
1809
            for p in right.iter_mut() {
1810 1811 1812 1813
                *p += 2;
            }
        }

N
NODA, Kai 已提交
1814
        assert!(values == vec![2u8, 3, 5, 6, 7]);
1815
    }
H
Huon Wilson 已提交
1816 1817 1818 1819

    #[test]
    fn test_clone() {
        let v: Vec<int> = vec!();
1820
        let w = vec!(1i, 2, 3);
H
Huon Wilson 已提交
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

        assert_eq!(v, v.clone());

        let z = w.clone();
        assert_eq!(w, z);
        // they should be disjoint in memory.
        assert!(w.as_ptr() != z.as_ptr())
    }

    #[test]
    fn test_clone_from() {
        let mut v = vec!();
1833 1834
        let three = vec!(box 1i, box 2, box 3);
        let two = vec!(box 4i, box 5);
H
Huon Wilson 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
        // zero, long
        v.clone_from(&three);
        assert_eq!(v, three);

        // equal
        v.clone_from(&three);
        assert_eq!(v, three);

        // long, short
        v.clone_from(&two);
        assert_eq!(v, two);

        // short, long
        v.clone_from(&three);
        assert_eq!(v, three)
    }
1851

A
Alex Crichton 已提交
1852
    #[test]
1853
    fn test_grow_fn() {
N
NODA, Kai 已提交
1854
        let mut v = vec![0u, 1];
1855
        v.grow_fn(3, |i| i);
N
NODA, Kai 已提交
1856
        assert!(v == vec![0u, 1, 0, 1, 2]);
1857 1858 1859 1860
    }

    #[test]
    fn test_retain() {
N
NODA, Kai 已提交
1861
        let mut vec = vec![1u, 2, 3, 4];
1862
        vec.retain(|&x| x % 2 == 0);
N
NODA, Kai 已提交
1863
        assert!(vec == vec![2u, 4]);
1864
    }
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877

    #[test]
    fn zero_sized_values() {
        let mut v = Vec::new();
        assert_eq!(v.len(), 0);
        v.push(());
        assert_eq!(v.len(), 1);
        v.push(());
        assert_eq!(v.len(), 2);
        assert_eq!(v.pop(), Some(()));
        assert_eq!(v.pop(), Some(()));
        assert_eq!(v.pop(), None);

A
Aaron Turon 已提交
1878
        assert_eq!(v.iter().count(), 0);
1879
        v.push(());
A
Aaron Turon 已提交
1880
        assert_eq!(v.iter().count(), 1);
1881
        v.push(());
A
Aaron Turon 已提交
1882
        assert_eq!(v.iter().count(), 2);
1883 1884 1885

        for &() in v.iter() {}

A
Aaron Turon 已提交
1886
        assert_eq!(v.iter_mut().count(), 2);
1887
        v.push(());
A
Aaron Turon 已提交
1888
        assert_eq!(v.iter_mut().count(), 3);
1889
        v.push(());
A
Aaron Turon 已提交
1890
        assert_eq!(v.iter_mut().count(), 4);
1891

A
Aaron Turon 已提交
1892
        for &() in v.iter_mut() {}
1893
        unsafe { v.set_len(0); }
A
Aaron Turon 已提交
1894
        assert_eq!(v.iter_mut().count(), 0);
1895
    }
1896 1897 1898 1899

    #[test]
    fn test_partition() {
        assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
1900 1901 1902
        assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
        assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
        assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1903 1904 1905 1906
    }

    #[test]
    fn test_partitioned() {
1907
        assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
1908 1909 1910
        assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
        assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
        assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1911
    }
1912 1913 1914

    #[test]
    fn test_zip_unzip() {
1915
        let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
1916 1917 1918 1919 1920 1921 1922 1923

        let (left, right) = unzip(z1.iter().map(|&x| x));

        let (left, right) = (left.as_slice(), right.as_slice());
        assert_eq!((1, 4), (left[0], right[0]));
        assert_eq!((2, 5), (left[1], right[1]));
        assert_eq!((3, 6), (left[2], right[2]));
    }
1924 1925 1926 1927 1928

    #[test]
    fn test_unsafe_ptrs() {
        unsafe {
            // Test on-stack copy-from-buf.
1929
            let a = [1i, 2, 3];
1930 1931 1932 1933 1934
            let ptr = a.as_ptr();
            let b = raw::from_buf(ptr, 3u);
            assert_eq!(b, vec![1, 2, 3]);

            // Test on-heap copy-from-buf.
1935
            let c = vec![1i, 2, 3, 4, 5];
1936 1937 1938 1939 1940
            let ptr = c.as_ptr();
            let d = raw::from_buf(ptr, 5u);
            assert_eq!(d, vec![1, 2, 3, 4, 5]);
        }
    }
1941

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
    #[test]
    fn test_vec_truncate_drop() {
        static mut drops: uint = 0;
        struct Elem(int);
        impl Drop for Elem {
            fn drop(&mut self) {
                unsafe { drops += 1; }
            }
        }

        let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
        assert_eq!(unsafe { drops }, 0);
        v.truncate(3);
        assert_eq!(unsafe { drops }, 2);
        v.truncate(0);
        assert_eq!(unsafe { drops }, 5);
    }

    #[test]
    #[should_fail]
    fn test_vec_truncate_fail() {
        struct BadElem(int);
        impl Drop for BadElem {
            fn drop(&mut self) {
                let BadElem(ref mut x) = *self;
                if *x == 0xbadbeef {
S
Steve Klabnik 已提交
1968
                    panic!("BadElem panic: 0xbadbeef")
1969 1970 1971 1972 1973 1974 1975
                }
            }
        }

        let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
        v.truncate(0);
    }
1976

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
    #[test]
    fn test_index() {
        let vec = vec!(1i, 2, 3);
        assert!(vec[1] == 2);
    }

    #[test]
    #[should_fail]
    fn test_index_out_of_bounds() {
        let vec = vec!(1i, 2, 3);
        let _ = vec[3];
    }

N
Nick Cameron 已提交
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
    #[test]
    #[should_fail]
    fn test_slice_out_of_bounds_1() {
        let x: Vec<int> = vec![1, 2, 3, 4, 5];
        x[-1..];
    }

    #[test]
    #[should_fail]
    fn test_slice_out_of_bounds_2() {
        let x: Vec<int> = vec![1, 2, 3, 4, 5];
        x[..6];
    }

    #[test]
    #[should_fail]
    fn test_slice_out_of_bounds_3() {
        let x: Vec<int> = vec![1, 2, 3, 4, 5];
        x[-1..4];
    }

    #[test]
    #[should_fail]
    fn test_slice_out_of_bounds_4() {
        let x: Vec<int> = vec![1, 2, 3, 4, 5];
        x[1..6];
    }

    #[test]
    #[should_fail]
    fn test_slice_out_of_bounds_5() {
        let x: Vec<int> = vec![1, 2, 3, 4, 5];
        x[3..2];
    }

2025 2026 2027 2028 2029 2030
    #[test]
    fn test_swap_remove_empty() {
        let mut vec: Vec<uint> = vec!();
        assert_eq!(vec.swap_remove(0), None);
    }

J
Julian Orth 已提交
2031 2032 2033 2034 2035 2036
    #[test]
    fn test_move_iter_unwrap() {
        let mut vec: Vec<uint> = Vec::with_capacity(7);
        vec.push(1);
        vec.push(2);
        let ptr = vec.as_ptr();
A
Aaron Turon 已提交
2037
        vec = vec.into_iter().unwrap();
J
Julian Orth 已提交
2038 2039 2040
        assert_eq!(vec.as_ptr(), ptr);
        assert_eq!(vec.capacity(), 7);
        assert_eq!(vec.len(), 0);
2041
    }
2042 2043 2044

    #[test]
    #[should_fail]
2045
    fn test_map_in_place_incompatible_types_fail() {
2046
        let v = vec![0u, 1, 2];
2047
        v.map_in_place(|_| ());
2048 2049 2050
    }

    #[test]
2051
    fn test_map_in_place() {
2052
        let v = vec![0u, 1, 2];
2053
        assert_eq!(v.map_in_place(|i: uint| i as int - 1).as_slice(), [-1i, 0, 1].as_slice());
J
Julian Orth 已提交
2054 2055
    }

2056 2057 2058 2059 2060 2061 2062 2063
    #[test]
    fn test_map_in_place_zero_sized() {
        let v = vec![(), ()];
        #[deriving(PartialEq, Show)]
        struct ZeroSized;
        assert_eq!(v.map_in_place(|_| ZeroSized).as_slice(), [ZeroSized, ZeroSized].as_slice());
    }

D
Dan Schatzberg 已提交
2064 2065
    #[test]
    fn test_move_items() {
N
NODA, Kai 已提交
2066 2067
        let vec = vec![1, 2, 3];
        let mut vec2 : Vec<i32> = vec![];
D
Dan Schatzberg 已提交
2068
        for i in vec.into_iter() {
D
Dan Schatzberg 已提交
2069 2070
            vec2.push(i);
        }
N
NODA, Kai 已提交
2071
        assert!(vec2 == vec![1, 2, 3]);
D
Dan Schatzberg 已提交
2072 2073 2074 2075
    }

    #[test]
    fn test_move_items_reverse() {
N
NODA, Kai 已提交
2076 2077
        let vec = vec![1, 2, 3];
        let mut vec2 : Vec<i32> = vec![];
D
Dan Schatzberg 已提交
2078
        for i in vec.into_iter().rev() {
D
Dan Schatzberg 已提交
2079 2080
            vec2.push(i);
        }
N
NODA, Kai 已提交
2081
        assert!(vec2 == vec![3, 2, 1]);
D
Dan Schatzberg 已提交
2082 2083 2084 2085
    }

    #[test]
    fn test_move_items_zero_sized() {
N
NODA, Kai 已提交
2086 2087
        let vec = vec![(), (), ()];
        let mut vec2 : Vec<()> = vec![];
D
Dan Schatzberg 已提交
2088
        for i in vec.into_iter() {
D
Dan Schatzberg 已提交
2089 2090
            vec2.push(i);
        }
N
NODA, Kai 已提交
2091
        assert!(vec2 == vec![(), (), ()]);
D
Dan Schatzberg 已提交
2092 2093
    }

2094 2095 2096 2097
    #[test]
    fn test_into_boxed_slice() {
        let xs = vec![1u, 2, 3];
        let ys = xs.into_boxed_slice();
2098
        assert_eq!(ys.as_slice(), [1u, 2, 3].as_slice());
2099 2100
    }

2101 2102 2103
    #[bench]
    fn bench_new(b: &mut Bencher) {
        b.iter(|| {
2104 2105
            let v: Vec<uint> = Vec::new();
            assert_eq!(v.len(), 0);
2106 2107 2108 2109
            assert_eq!(v.capacity(), 0);
        })
    }

2110 2111 2112
    fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
        b.bytes = src_len as u64;

2113
        b.iter(|| {
2114 2115 2116
            let v: Vec<uint> = Vec::with_capacity(src_len);
            assert_eq!(v.len(), 0);
            assert_eq!(v.capacity(), src_len);
2117 2118 2119
        })
    }

2120 2121 2122 2123
    #[bench]
    fn bench_with_capacity_0000(b: &mut Bencher) {
        do_bench_with_capacity(b, 0)
    }
2124 2125

    #[bench]
2126 2127
    fn bench_with_capacity_0010(b: &mut Bencher) {
        do_bench_with_capacity(b, 10)
2128 2129 2130
    }

    #[bench]
2131 2132
    fn bench_with_capacity_0100(b: &mut Bencher) {
        do_bench_with_capacity(b, 100)
2133 2134 2135
    }

    #[bench]
2136 2137 2138 2139 2140 2141 2142
    fn bench_with_capacity_1000(b: &mut Bencher) {
        do_bench_with_capacity(b, 1000)
    }

    fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
        b.bytes = src_len as u64;

2143
        b.iter(|| {
2144 2145 2146
            let dst = Vec::from_fn(src_len, |i| i);
            assert_eq!(dst.len(), src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2147 2148 2149 2150
        })
    }

    #[bench]
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    fn bench_from_fn_0000(b: &mut Bencher) {
        do_bench_from_fn(b, 0)
    }

    #[bench]
    fn bench_from_fn_0010(b: &mut Bencher) {
        do_bench_from_fn(b, 10)
    }

    #[bench]
    fn bench_from_fn_0100(b: &mut Bencher) {
        do_bench_from_fn(b, 100)
    }

    #[bench]
    fn bench_from_fn_1000(b: &mut Bencher) {
        do_bench_from_fn(b, 1000)
    }

    fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
        b.bytes = src_len as u64;

2173
        b.iter(|| {
2174 2175 2176
            let dst: Vec<uint> = Vec::from_elem(src_len, 5);
            assert_eq!(dst.len(), src_len);
            assert!(dst.iter().all(|x| *x == 5));
2177 2178 2179 2180
        })
    }

    #[bench]
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
    fn bench_from_elem_0000(b: &mut Bencher) {
        do_bench_from_elem(b, 0)
    }

    #[bench]
    fn bench_from_elem_0010(b: &mut Bencher) {
        do_bench_from_elem(b, 10)
    }

    #[bench]
    fn bench_from_elem_0100(b: &mut Bencher) {
        do_bench_from_elem(b, 100)
    }

    #[bench]
    fn bench_from_elem_1000(b: &mut Bencher) {
        do_bench_from_elem(b, 1000)
    }

    fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
        let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));

        b.bytes = src_len as u64;

2205
        b.iter(|| {
N
NODA, Kai 已提交
2206
            let dst = src.clone().as_slice().to_vec();
2207 2208 2209 2210 2211 2212 2213 2214
            assert_eq!(dst.len(), src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
    }

    #[bench]
    fn bench_from_slice_0000(b: &mut Bencher) {
        do_bench_from_slice(b, 0)
2215 2216 2217
    }

    #[bench]
2218 2219 2220 2221 2222 2223 2224
    fn bench_from_slice_0010(b: &mut Bencher) {
        do_bench_from_slice(b, 10)
    }

    #[bench]
    fn bench_from_slice_0100(b: &mut Bencher) {
        do_bench_from_slice(b, 100)
2225 2226 2227
    }

    #[bench]
2228 2229 2230 2231 2232 2233 2234 2235 2236
    fn bench_from_slice_1000(b: &mut Bencher) {
        do_bench_from_slice(b, 1000)
    }

    fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
        let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));

        b.bytes = src_len as u64;

2237
        b.iter(|| {
A
Aaron Turon 已提交
2238
            let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
            assert_eq!(dst.len(), src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
    }

    #[bench]
    fn bench_from_iter_0000(b: &mut Bencher) {
        do_bench_from_iter(b, 0)
    }

    #[bench]
    fn bench_from_iter_0010(b: &mut Bencher) {
        do_bench_from_iter(b, 10)
2252 2253 2254
    }

    #[bench]
2255 2256
    fn bench_from_iter_0100(b: &mut Bencher) {
        do_bench_from_iter(b, 100)
2257 2258 2259
    }

    #[bench]
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    fn bench_from_iter_1000(b: &mut Bencher) {
        do_bench_from_iter(b, 1000)
    }

    fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
        let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
        let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));

        b.bytes = src_len as u64;

2270
        b.iter(|| {
2271
            let mut dst = dst.clone();
A
Aaron Turon 已提交
2272
            dst.extend(src.clone().into_iter());
2273 2274 2275 2276 2277 2278 2279 2280
            assert_eq!(dst.len(), dst_len + src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
    }

    #[bench]
    fn bench_extend_0000_0000(b: &mut Bencher) {
        do_bench_extend(b, 0, 0)
2281 2282 2283
    }

    #[bench]
2284 2285 2286 2287 2288 2289 2290
    fn bench_extend_0000_0010(b: &mut Bencher) {
        do_bench_extend(b, 0, 10)
    }

    #[bench]
    fn bench_extend_0000_0100(b: &mut Bencher) {
        do_bench_extend(b, 0, 100)
2291 2292 2293
    }

    #[bench]
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
    fn bench_extend_0000_1000(b: &mut Bencher) {
        do_bench_extend(b, 0, 1000)
    }

    #[bench]
    fn bench_extend_0010_0010(b: &mut Bencher) {
        do_bench_extend(b, 10, 10)
    }

    #[bench]
    fn bench_extend_0100_0100(b: &mut Bencher) {
        do_bench_extend(b, 100, 100)
    }

    #[bench]
    fn bench_extend_1000_1000(b: &mut Bencher) {
        do_bench_extend(b, 1000, 1000)
    }

    fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
        let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
        let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));

        b.bytes = src_len as u64;

2319
        b.iter(|| {
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
            let mut dst = dst.clone();
            dst.push_all(src.as_slice());
            assert_eq!(dst.len(), dst_len + src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
    }

    #[bench]
    fn bench_push_all_0000_0000(b: &mut Bencher) {
        do_bench_push_all(b, 0, 0)
2330 2331 2332
    }

    #[bench]
2333 2334 2335 2336 2337 2338 2339
    fn bench_push_all_0000_0010(b: &mut Bencher) {
        do_bench_push_all(b, 0, 10)
    }

    #[bench]
    fn bench_push_all_0000_0100(b: &mut Bencher) {
        do_bench_push_all(b, 0, 100)
2340 2341 2342
    }

    #[bench]
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
    fn bench_push_all_0000_1000(b: &mut Bencher) {
        do_bench_push_all(b, 0, 1000)
    }

    #[bench]
    fn bench_push_all_0010_0010(b: &mut Bencher) {
        do_bench_push_all(b, 10, 10)
    }

    #[bench]
    fn bench_push_all_0100_0100(b: &mut Bencher) {
        do_bench_push_all(b, 100, 100)
    }

    #[bench]
    fn bench_push_all_1000_1000(b: &mut Bencher) {
        do_bench_push_all(b, 1000, 1000)
    }

    fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
        let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
        let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));

        b.bytes = src_len as u64;

2368
        b.iter(|| {
2369
            let mut dst = dst.clone();
N
NODA, Kai 已提交
2370
            dst.extend(src.clone().into_iter());
2371 2372 2373 2374 2375 2376 2377 2378
            assert_eq!(dst.len(), dst_len + src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
    }

    #[bench]
    fn bench_push_all_move_0000_0000(b: &mut Bencher) {
        do_bench_push_all_move(b, 0, 0)
2379 2380 2381
    }

    #[bench]
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
    fn bench_push_all_move_0000_0010(b: &mut Bencher) {
        do_bench_push_all_move(b, 0, 10)
    }

    #[bench]
    fn bench_push_all_move_0000_0100(b: &mut Bencher) {
        do_bench_push_all_move(b, 0, 100)
    }

    #[bench]
    fn bench_push_all_move_0000_1000(b: &mut Bencher) {
        do_bench_push_all_move(b, 0, 1000)
2394 2395 2396
    }

    #[bench]
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
    fn bench_push_all_move_0010_0010(b: &mut Bencher) {
        do_bench_push_all_move(b, 10, 10)
    }

    #[bench]
    fn bench_push_all_move_0100_0100(b: &mut Bencher) {
        do_bench_push_all_move(b, 100, 100)
    }

    #[bench]
    fn bench_push_all_move_1000_1000(b: &mut Bencher) {
        do_bench_push_all_move(b, 1000, 1000)
    }

    fn do_bench_clone(b: &mut Bencher, src_len: uint) {
        let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));

        b.bytes = src_len as u64;

2416
        b.iter(|| {
2417 2418 2419 2420
            let dst = src.clone();
            assert_eq!(dst.len(), src_len);
            assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
        });
2421 2422 2423
    }

    #[bench]
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
    fn bench_clone_0000(b: &mut Bencher) {
        do_bench_clone(b, 0)
    }

    #[bench]
    fn bench_clone_0010(b: &mut Bencher) {
        do_bench_clone(b, 10)
    }

    #[bench]
    fn bench_clone_0100(b: &mut Bencher) {
        do_bench_clone(b, 100)
    }

    #[bench]
    fn bench_clone_1000(b: &mut Bencher) {
        do_bench_clone(b, 1000)
    }

2443
    fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2444 2445 2446
        let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
        let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));

2447
        b.bytes = (times * src_len) as u64;
2448

2449
        b.iter(|| {
2450
            let mut dst = dst.clone();
2451 2452 2453 2454 2455 2456 2457

            for _ in range(0, times) {
                dst.clone_from(&src);

                assert_eq!(dst.len(), src_len);
                assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
            }
2458 2459 2460 2461
        });
    }

    #[bench]
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
    fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 0, 0)
    }

    #[bench]
    fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 0, 10)
    }

    #[bench]
    fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 0, 100)
    }

    #[bench]
    fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 0, 1000)
    }

    #[bench]
    fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 10, 10)
    }

    #[bench]
    fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 100, 100)
    }

    #[bench]
    fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 1000, 1000)
    }

    #[bench]
    fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 10, 100)
    }

    #[bench]
    fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 100, 1000)
    }

    #[bench]
    fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 10, 0)
    }

    #[bench]
    fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 100, 10)
    }

    #[bench]
    fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 1, 1000, 100)
    }

    #[bench]
    fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 0, 0)
2524 2525 2526
    }

    #[bench]
2527 2528
    fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 0, 10)
2529 2530 2531
    }

    #[bench]
2532 2533
    fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 0, 100)
2534 2535 2536
    }

    #[bench]
2537 2538
    fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 0, 1000)
2539 2540 2541
    }

    #[bench]
2542 2543
    fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 10, 10)
2544 2545 2546
    }

    #[bench]
2547 2548
    fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 100, 100)
2549 2550 2551
    }

    #[bench]
2552 2553
    fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 1000, 1000)
2554 2555 2556
    }

    #[bench]
2557 2558
    fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 10, 100)
2559 2560 2561
    }

    #[bench]
2562 2563
    fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 100, 1000)
2564 2565 2566
    }

    #[bench]
2567 2568
    fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 10, 0)
2569 2570 2571
    }

    #[bench]
2572 2573
    fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 100, 10)
2574 2575 2576
    }

    #[bench]
2577 2578
    fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
        do_bench_clone_from(b, 10, 1000, 100)
2579
    }
2580
}