]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
Rollup merge of #34930 - frewsxcv:vec-as-slice, r=steveklabnik
[rust.git] / src / libcollections / vec.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but pronounced 'vector.'
13 //!
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
16 //!
17 //! # Examples
18 //!
19 //! You can explicitly create a `Vec<T>` with `new()`:
20 //!
21 //! ```
22 //! let v: Vec<i32> = Vec::new();
23 //! ```
24 //!
25 //! ...or by using the `vec!` macro:
26 //!
27 //! ```
28 //! let v: Vec<i32> = vec![];
29 //!
30 //! let v = vec![1, 2, 3, 4, 5];
31 //!
32 //! let v = vec![0; 10]; // ten zeroes
33 //! ```
34 //!
35 //! You can `push` values onto the end of a vector (which will grow the vector
36 //! as needed):
37 //!
38 //! ```
39 //! let mut v = vec![1, 2];
40 //!
41 //! v.push(3);
42 //! ```
43 //!
44 //! Popping values works in much the same way:
45 //!
46 //! ```
47 //! let mut v = vec![1, 2];
48 //!
49 //! let two = v.pop();
50 //! ```
51 //!
52 //! Vectors also support indexing (through the `Index` and `IndexMut` traits):
53 //!
54 //! ```
55 //! let mut v = vec![1, 2, 3];
56 //! let three = v[2];
57 //! v[1] = v[1] + 5;
58 //! ```
59
60 #![stable(feature = "rust1", since = "1.0.0")]
61
62 use alloc::boxed::Box;
63 use alloc::heap::EMPTY;
64 use alloc::raw_vec::RawVec;
65 use borrow::ToOwned;
66 use borrow::Cow;
67 use core::cmp::Ordering;
68 use core::fmt;
69 use core::hash::{self, Hash};
70 use core::intrinsics::{arith_offset, assume};
71 use core::iter::FromIterator;
72 use core::mem;
73 use core::ops::{Index, IndexMut};
74 use core::ops;
75 use core::ptr;
76 use core::slice;
77
78 use super::SpecExtend;
79 use super::range::RangeArgument;
80
81 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
82 ///
83 /// # Examples
84 ///
85 /// ```
86 /// let mut vec = Vec::new();
87 /// vec.push(1);
88 /// vec.push(2);
89 ///
90 /// assert_eq!(vec.len(), 2);
91 /// assert_eq!(vec[0], 1);
92 ///
93 /// assert_eq!(vec.pop(), Some(2));
94 /// assert_eq!(vec.len(), 1);
95 ///
96 /// vec[0] = 7;
97 /// assert_eq!(vec[0], 7);
98 ///
99 /// vec.extend([1, 2, 3].iter().cloned());
100 ///
101 /// for x in &vec {
102 ///     println!("{}", x);
103 /// }
104 /// assert_eq!(vec, [7, 1, 2, 3]);
105 /// ```
106 ///
107 /// The `vec!` macro is provided to make initialization more convenient:
108 ///
109 /// ```
110 /// let mut vec = vec![1, 2, 3];
111 /// vec.push(4);
112 /// assert_eq!(vec, [1, 2, 3, 4]);
113 /// ```
114 ///
115 /// It can also initialize each element of a `Vec<T>` with a given value:
116 ///
117 /// ```
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
120 /// ```
121 ///
122 /// Use a `Vec<T>` as an efficient stack:
123 ///
124 /// ```
125 /// let mut stack = Vec::new();
126 ///
127 /// stack.push(1);
128 /// stack.push(2);
129 /// stack.push(3);
130 ///
131 /// while let Some(top) = stack.pop() {
132 ///     // Prints 3, 2, 1
133 ///     println!("{}", top);
134 /// }
135 /// ```
136 ///
137 /// # Indexing
138 ///
139 /// The Vec type allows to access values by index, because it implements the
140 /// `Index` trait. An example will be more explicit:
141 ///
142 /// ```
143 /// let v = vec!(0, 2, 4, 6);
144 /// println!("{}", v[1]); // it will display '2'
145 /// ```
146 ///
147 /// However be careful: if you try to access an index which isn't in the Vec,
148 /// your software will panic! You cannot do this:
149 ///
150 /// ```ignore
151 /// let v = vec!(0, 2, 4, 6);
152 /// println!("{}", v[6]); // it will panic!
153 /// ```
154 ///
155 /// In conclusion: always check if the index you want to get really exists
156 /// before doing it.
157 ///
158 /// # Slicing
159 ///
160 /// A Vec can be mutable. Slices, on the other hand, are read-only objects.
161 /// To get a slice, use "&". Example:
162 ///
163 /// ```
164 /// fn read_slice(slice: &[usize]) {
165 ///     // ...
166 /// }
167 ///
168 /// let v = vec!(0, 1);
169 /// read_slice(&v);
170 ///
171 /// // ... and that's all!
172 /// // you can also do it like this:
173 /// let x : &[usize] = &v;
174 /// ```
175 ///
176 /// In Rust, it's more common to pass slices as arguments rather than vectors
177 /// when you just want to provide a read access. The same goes for String and
178 /// &str.
179 ///
180 /// # Capacity and reallocation
181 ///
182 /// The capacity of a vector is the amount of space allocated for any future
183 /// elements that will be added onto the vector. This is not to be confused with
184 /// the *length* of a vector, which specifies the number of actual elements
185 /// within the vector. If a vector's length exceeds its capacity, its capacity
186 /// will automatically be increased, but its elements will have to be
187 /// reallocated.
188 ///
189 /// For example, a vector with capacity 10 and length 0 would be an empty vector
190 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
191 /// vector will not change its capacity or cause reallocation to occur. However,
192 /// if the vector's length is increased to 11, it will have to reallocate, which
193 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
194 /// whenever possible to specify how big the vector is expected to get.
195 ///
196 /// # Guarantees
197 ///
198 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
199 /// about its design. This ensures that it's as low-overhead as possible in
200 /// the general case, and can be correctly manipulated in primitive ways
201 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
202 /// If additional type parameters are added (e.g. to support custom allocators),
203 /// overriding their defaults may change the behavior.
204 ///
205 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
206 /// triplet. No more, no less. The order of these fields is completely
207 /// unspecified, and you should use the appropriate methods to modify these.
208 /// The pointer will never be null, so this type is null-pointer-optimized.
209 ///
210 /// However, the pointer may not actually point to allocated memory. In particular,
211 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
212 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
213 /// will not allocate memory. Similarly, if you store zero-sized types inside
214 /// a Vec, it will not allocate space for them. *Note that in this case the
215 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
216 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
217 /// details are subtle enough that it is strongly recommended that you only
218 /// free memory allocated by a Vec by creating a new Vec and dropping it.
219 ///
220 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
221 /// (as defined by the allocator Rust is configured to use by default), and its
222 /// pointer points to `len()` initialized elements in order (what you would see
223 /// if you coerced it to a slice), followed by `capacity() - len()` logically
224 /// uninitialized elements.
225 ///
226 /// Vec will never perform a "small optimization" where elements are actually
227 /// stored on the stack for two reasons:
228 ///
229 /// * It would make it more difficult for unsafe code to correctly manipulate
230 ///   a Vec. The contents of a Vec wouldn't have a stable address if it were
231 ///   only moved, and it would be more difficult to determine if a Vec had
232 ///   actually allocated memory.
233 ///
234 /// * It would penalize the general case, incurring an additional branch
235 ///   on every access.
236 ///
237 /// Vec will never automatically shrink itself, even if completely empty. This
238 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
239 /// and then filling it back up to the same `len()` should incur no calls to
240 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
241 ///
242 /// `push` and `insert` will never (re)allocate if the reported capacity is
243 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
244 /// That is, the reported capacity is completely accurate, and can be relied on.
245 /// It can even be used to manually free the memory allocated by a Vec if
246 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
247 ///
248 /// Vec does not guarantee any particular growth strategy when reallocating
249 /// when full, nor when `reserve` is called. The current strategy is basic
250 /// and it may prove desirable to use a non-constant growth factor. Whatever
251 /// strategy is used will of course guarantee `O(1)` amortized `push`.
252 ///
253 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
254 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
255 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
256 /// to and from a `Box<[T]>` without reallocating or moving the elements.
257 ///
258 /// Vec will not specifically overwrite any data that is removed from it,
259 /// but also won't specifically preserve it. Its uninitialized memory is
260 /// scratch space that it may use however it wants. It will generally just do
261 /// whatever is most efficient or otherwise easy to implement. Do not rely on
262 /// removed data to be erased for security purposes. Even if you drop a Vec, its
263 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
264 /// first, that may not actually happen because the optimizer does not consider
265 /// this a side-effect that must be preserved.
266 ///
267 /// Vec does not currently guarantee the order in which elements are dropped
268 /// (the order has changed in the past, and may change again).
269 ///
270 #[unsafe_no_drop_flag]
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub struct Vec<T> {
273     buf: RawVec<T>,
274     len: usize,
275 }
276
277 ////////////////////////////////////////////////////////////////////////////////
278 // Inherent methods
279 ////////////////////////////////////////////////////////////////////////////////
280
281 impl<T> Vec<T> {
282     /// Constructs a new, empty `Vec<T>`.
283     ///
284     /// The vector will not allocate until elements are pushed onto it.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// # #![allow(unused_mut)]
290     /// let mut vec: Vec<i32> = Vec::new();
291     /// ```
292     #[inline]
293     #[stable(feature = "rust1", since = "1.0.0")]
294     pub fn new() -> Vec<T> {
295         Vec {
296             buf: RawVec::new(),
297             len: 0,
298         }
299     }
300
301     /// Constructs a new, empty `Vec<T>` with the specified capacity.
302     ///
303     /// The vector will be able to hold exactly `capacity` elements without
304     /// reallocating. If `capacity` is 0, the vector will not allocate.
305     ///
306     /// It is important to note that this function does not specify the *length*
307     /// of the returned vector, but only the *capacity*. (For an explanation of
308     /// the difference between length and capacity, see the main `Vec<T>` docs
309     /// above, 'Capacity and reallocation'.)
310     ///
311     /// # Examples
312     ///
313     /// ```
314     /// let mut vec = Vec::with_capacity(10);
315     ///
316     /// // The vector contains no items, even though it has capacity for more
317     /// assert_eq!(vec.len(), 0);
318     ///
319     /// // These are all done without reallocating...
320     /// for i in 0..10 {
321     ///     vec.push(i);
322     /// }
323     ///
324     /// // ...but this may make the vector reallocate
325     /// vec.push(11);
326     /// ```
327     #[inline]
328     #[stable(feature = "rust1", since = "1.0.0")]
329     pub fn with_capacity(capacity: usize) -> Vec<T> {
330         Vec {
331             buf: RawVec::with_capacity(capacity),
332             len: 0,
333         }
334     }
335
336     /// Creates a `Vec<T>` directly from the raw components of another vector.
337     ///
338     /// # Safety
339     ///
340     /// This is highly unsafe, due to the number of invariants that aren't
341     /// checked:
342     ///
343     /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
344     ///   (at least, it's highly likely to be incorrect if it wasn't).
345     /// * `length` needs to be less than or equal to `capacity`.
346     /// * `capacity` needs to be the capacity that the pointer was allocated with.
347     ///
348     /// Violating these may cause problems like corrupting the allocator's
349     /// internal datastructures.
350     ///
351     /// The ownership of `ptr` is effectively transferred to the
352     /// `Vec<T>` which may then deallocate, reallocate or change the
353     /// contents of memory pointed to by the pointer at will. Ensure
354     /// that nothing else uses the pointer after calling this
355     /// function.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::ptr;
361     /// use std::mem;
362     ///
363     /// fn main() {
364     ///     let mut v = vec![1, 2, 3];
365     ///
366     ///     // Pull out the various important pieces of information about `v`
367     ///     let p = v.as_mut_ptr();
368     ///     let len = v.len();
369     ///     let cap = v.capacity();
370     ///
371     ///     unsafe {
372     ///         // Cast `v` into the void: no destructor run, so we are in
373     ///         // complete control of the allocation to which `p` points.
374     ///         mem::forget(v);
375     ///
376     ///         // Overwrite memory with 4, 5, 6
377     ///         for i in 0..len as isize {
378     ///             ptr::write(p.offset(i), 4 + i);
379     ///         }
380     ///
381     ///         // Put everything back together into a Vec
382     ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
383     ///         assert_eq!(rebuilt, [4, 5, 6]);
384     ///     }
385     /// }
386     /// ```
387     #[stable(feature = "rust1", since = "1.0.0")]
388     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
389         Vec {
390             buf: RawVec::from_raw_parts(ptr, capacity),
391             len: length,
392         }
393     }
394
395     /// Returns the number of elements the vector can hold without
396     /// reallocating.
397     ///
398     /// # Examples
399     ///
400     /// ```
401     /// let vec: Vec<i32> = Vec::with_capacity(10);
402     /// assert_eq!(vec.capacity(), 10);
403     /// ```
404     #[inline]
405     #[stable(feature = "rust1", since = "1.0.0")]
406     pub fn capacity(&self) -> usize {
407         self.buf.cap()
408     }
409
410     /// Reserves capacity for at least `additional` more elements to be inserted
411     /// in the given `Vec<T>`. The collection may reserve more space to avoid
412     /// frequent reallocations.
413     ///
414     /// # Panics
415     ///
416     /// Panics if the new capacity overflows `usize`.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// let mut vec = vec![1];
422     /// vec.reserve(10);
423     /// assert!(vec.capacity() >= 11);
424     /// ```
425     #[stable(feature = "rust1", since = "1.0.0")]
426     pub fn reserve(&mut self, additional: usize) {
427         self.buf.reserve(self.len, additional);
428     }
429
430     /// Reserves the minimum capacity for exactly `additional` more elements to
431     /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
432     /// sufficient.
433     ///
434     /// Note that the allocator may give the collection more space than it
435     /// requests. Therefore capacity can not be relied upon to be precisely
436     /// minimal. Prefer `reserve` if future insertions are expected.
437     ///
438     /// # Panics
439     ///
440     /// Panics if the new capacity overflows `usize`.
441     ///
442     /// # Examples
443     ///
444     /// ```
445     /// let mut vec = vec![1];
446     /// vec.reserve_exact(10);
447     /// assert!(vec.capacity() >= 11);
448     /// ```
449     #[stable(feature = "rust1", since = "1.0.0")]
450     pub fn reserve_exact(&mut self, additional: usize) {
451         self.buf.reserve_exact(self.len, additional);
452     }
453
454     /// Shrinks the capacity of the vector as much as possible.
455     ///
456     /// It will drop down as close as possible to the length but the allocator
457     /// may still inform the vector that there is space for a few more elements.
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// let mut vec = Vec::with_capacity(10);
463     /// vec.extend([1, 2, 3].iter().cloned());
464     /// assert_eq!(vec.capacity(), 10);
465     /// vec.shrink_to_fit();
466     /// assert!(vec.capacity() >= 3);
467     /// ```
468     #[stable(feature = "rust1", since = "1.0.0")]
469     pub fn shrink_to_fit(&mut self) {
470         self.buf.shrink_to_fit(self.len);
471     }
472
473     /// Converts the vector into Box<[T]>.
474     ///
475     /// Note that this will drop any excess capacity. Calling this and
476     /// converting back to a vector with `into_vec()` is equivalent to calling
477     /// `shrink_to_fit()`.
478     #[stable(feature = "rust1", since = "1.0.0")]
479     pub fn into_boxed_slice(mut self) -> Box<[T]> {
480         unsafe {
481             self.shrink_to_fit();
482             let buf = ptr::read(&self.buf);
483             mem::forget(self);
484             buf.into_box()
485         }
486     }
487
488     /// Shortens the vector, keeping the first `len` elements and dropping
489     /// the rest.
490     ///
491     /// If `len` is greater than the vector's current length, this has no
492     /// effect.
493     ///
494     /// The [`drain`] method can emulate `truncate`, but causes the excess
495     /// elements to be returned instead of dropped.
496     ///
497     /// # Examples
498     ///
499     /// Truncating a five element vector to two elements:
500     ///
501     /// ```
502     /// let mut vec = vec![1, 2, 3, 4, 5];
503     /// vec.truncate(2);
504     /// assert_eq!(vec, [1, 2]);
505     /// ```
506     ///
507     /// No truncation occurs when `len` is greater than the vector's current
508     /// length:
509     ///
510     /// ```
511     /// let mut vec = vec![1, 2, 3];
512     /// vec.truncate(8);
513     /// assert_eq!(vec, [1, 2, 3]);
514     /// ```
515     ///
516     /// Truncating when `len == 0` is equivalent to calling the [`clear`]
517     /// method.
518     ///
519     /// ```
520     /// let mut vec = vec![1, 2, 3];
521     /// vec.truncate(0);
522     /// assert_eq!(vec, []);
523     /// ```
524     ///
525     /// [`clear`]: #method.clear
526     /// [`drain`]: #method.drain
527     #[stable(feature = "rust1", since = "1.0.0")]
528     pub fn truncate(&mut self, len: usize) {
529         unsafe {
530             // drop any extra elements
531             while len < self.len {
532                 // decrement len before the drop_in_place(), so a panic on Drop
533                 // doesn't re-drop the just-failed value.
534                 self.len -= 1;
535                 let len = self.len;
536                 ptr::drop_in_place(self.get_unchecked_mut(len));
537             }
538         }
539     }
540
541     /// Extracts a slice containing the entire vector.
542     ///
543     /// Equivalent to `&s[..]`.
544     ///
545     /// # Examples
546     ///
547     /// ```
548     /// use std::io::{self, Write};
549     /// let buffer = vec![1, 2, 3, 5, 8];
550     /// io::sink().write(buffer.as_slice()).unwrap();
551     /// ```
552     #[inline]
553     #[stable(feature = "vec_as_slice", since = "1.7.0")]
554     pub fn as_slice(&self) -> &[T] {
555         self
556     }
557
558     /// Extracts a mutable slice of the entire vector.
559     ///
560     /// Equivalent to `&mut s[..]`.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// use std::io::{self, Read};
566     /// let mut buffer = vec![0; 3];
567     /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
568     /// ```
569     #[inline]
570     #[stable(feature = "vec_as_slice", since = "1.7.0")]
571     pub fn as_mut_slice(&mut self) -> &mut [T] {
572         self
573     }
574
575     /// Sets the length of a vector.
576     ///
577     /// This will explicitly set the size of the vector, without actually
578     /// modifying its buffers, so it is up to the caller to ensure that the
579     /// vector is actually the specified size.
580     ///
581     /// # Examples
582     ///
583     /// ```
584     /// use std::ptr;
585     ///
586     /// let mut vec = vec!['r', 'u', 's', 't'];
587     ///
588     /// unsafe {
589     ///     ptr::drop_in_place(&mut vec[3]);
590     ///     vec.set_len(3);
591     /// }
592     /// assert_eq!(vec, ['r', 'u', 's']);
593     /// ```
594     ///
595     /// In this example, there is a memory leak since the memory locations
596     /// owned by the vector were not freed prior to the `set_len` call:
597     ///
598     /// ```
599     /// let mut vec = vec!['r', 'u', 's', 't'];
600     ///
601     /// unsafe {
602     ///     vec.set_len(0);
603     /// }
604     /// ```
605     ///
606     /// In this example, the vector gets expanded from zero to four items
607     /// without any memory allocations occurring, resulting in vector
608     /// values of unallocated memory:
609     ///
610     /// ```
611     /// let mut vec: Vec<char> = Vec::new();
612     ///
613     /// unsafe {
614     ///     vec.set_len(4);
615     /// }
616     /// ```
617     #[inline]
618     #[stable(feature = "rust1", since = "1.0.0")]
619     pub unsafe fn set_len(&mut self, len: usize) {
620         self.len = len;
621     }
622
623     /// Removes an element from anywhere in the vector and return it, replacing
624     /// it with the last element.
625     ///
626     /// This does not preserve ordering, but is O(1).
627     ///
628     /// # Panics
629     ///
630     /// Panics if `index` is out of bounds.
631     ///
632     /// # Examples
633     ///
634     /// ```
635     /// let mut v = vec!["foo", "bar", "baz", "qux"];
636     ///
637     /// assert_eq!(v.swap_remove(1), "bar");
638     /// assert_eq!(v, ["foo", "qux", "baz"]);
639     ///
640     /// assert_eq!(v.swap_remove(0), "foo");
641     /// assert_eq!(v, ["baz", "qux"]);
642     /// ```
643     #[inline]
644     #[stable(feature = "rust1", since = "1.0.0")]
645     pub fn swap_remove(&mut self, index: usize) -> T {
646         let length = self.len();
647         self.swap(index, length - 1);
648         self.pop().unwrap()
649     }
650
651     /// Inserts an element at position `index` within the vector, shifting all
652     /// elements after it to the right.
653     ///
654     /// # Panics
655     ///
656     /// Panics if `index` is greater than the vector's length.
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// let mut vec = vec![1, 2, 3];
662     /// vec.insert(1, 4);
663     /// assert_eq!(vec, [1, 4, 2, 3]);
664     /// vec.insert(4, 5);
665     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
666     /// ```
667     #[stable(feature = "rust1", since = "1.0.0")]
668     pub fn insert(&mut self, index: usize, element: T) {
669         let len = self.len();
670         assert!(index <= len);
671
672         // space for the new element
673         if len == self.buf.cap() {
674             self.buf.double();
675         }
676
677         unsafe {
678             // infallible
679             // The spot to put the new value
680             {
681                 let p = self.as_mut_ptr().offset(index as isize);
682                 // Shift everything over to make space. (Duplicating the
683                 // `index`th element into two consecutive places.)
684                 ptr::copy(p, p.offset(1), len - index);
685                 // Write it in, overwriting the first copy of the `index`th
686                 // element.
687                 ptr::write(p, element);
688             }
689             self.set_len(len + 1);
690         }
691     }
692
693     /// Removes and returns the element at position `index` within the vector,
694     /// shifting all elements after it to the left.
695     ///
696     /// # Panics
697     ///
698     /// Panics if `index` is out of bounds.
699     ///
700     /// # Examples
701     ///
702     /// ```
703     /// let mut v = vec![1, 2, 3];
704     /// assert_eq!(v.remove(1), 2);
705     /// assert_eq!(v, [1, 3]);
706     /// ```
707     #[stable(feature = "rust1", since = "1.0.0")]
708     pub fn remove(&mut self, index: usize) -> T {
709         let len = self.len();
710         assert!(index < len);
711         unsafe {
712             // infallible
713             let ret;
714             {
715                 // the place we are taking from.
716                 let ptr = self.as_mut_ptr().offset(index as isize);
717                 // copy it out, unsafely having a copy of the value on
718                 // the stack and in the vector at the same time.
719                 ret = ptr::read(ptr);
720
721                 // Shift everything down to fill in that spot.
722                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
723             }
724             self.set_len(len - 1);
725             ret
726         }
727     }
728
729     /// Retains only the elements specified by the predicate.
730     ///
731     /// In other words, remove all elements `e` such that `f(&e)` returns false.
732     /// This method operates in place and preserves the order of the retained
733     /// elements.
734     ///
735     /// # Examples
736     ///
737     /// ```
738     /// let mut vec = vec![1, 2, 3, 4];
739     /// vec.retain(|&x| x%2 == 0);
740     /// assert_eq!(vec, [2, 4]);
741     /// ```
742     #[stable(feature = "rust1", since = "1.0.0")]
743     pub fn retain<F>(&mut self, mut f: F)
744         where F: FnMut(&T) -> bool
745     {
746         let len = self.len();
747         let mut del = 0;
748         {
749             let v = &mut **self;
750
751             for i in 0..len {
752                 if !f(&v[i]) {
753                     del += 1;
754                 } else if del > 0 {
755                     v.swap(i - del, i);
756                 }
757             }
758         }
759         if del > 0 {
760             self.truncate(len - del);
761         }
762     }
763
764     /// Appends an element to the back of a collection.
765     ///
766     /// # Panics
767     ///
768     /// Panics if the number of elements in the vector overflows a `usize`.
769     ///
770     /// # Examples
771     ///
772     /// ```
773     /// let mut vec = vec![1, 2];
774     /// vec.push(3);
775     /// assert_eq!(vec, [1, 2, 3]);
776     /// ```
777     #[inline]
778     #[stable(feature = "rust1", since = "1.0.0")]
779     pub fn push(&mut self, value: T) {
780         // This will panic or abort if we would allocate > isize::MAX bytes
781         // or if the length increment would overflow for zero-sized types.
782         if self.len == self.buf.cap() {
783             self.buf.double();
784         }
785         unsafe {
786             let end = self.as_mut_ptr().offset(self.len as isize);
787             ptr::write(end, value);
788             self.len += 1;
789         }
790     }
791
792     /// Removes the last element from a vector and returns it, or `None` if it
793     /// is empty.
794     ///
795     /// # Examples
796     ///
797     /// ```
798     /// let mut vec = vec![1, 2, 3];
799     /// assert_eq!(vec.pop(), Some(3));
800     /// assert_eq!(vec, [1, 2]);
801     /// ```
802     #[inline]
803     #[stable(feature = "rust1", since = "1.0.0")]
804     pub fn pop(&mut self) -> Option<T> {
805         if self.len == 0 {
806             None
807         } else {
808             unsafe {
809                 self.len -= 1;
810                 Some(ptr::read(self.get_unchecked(self.len())))
811             }
812         }
813     }
814
815     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
816     ///
817     /// # Panics
818     ///
819     /// Panics if the number of elements in the vector overflows a `usize`.
820     ///
821     /// # Examples
822     ///
823     /// ```
824     /// let mut vec = vec![1, 2, 3];
825     /// let mut vec2 = vec![4, 5, 6];
826     /// vec.append(&mut vec2);
827     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
828     /// assert_eq!(vec2, []);
829     /// ```
830     #[inline]
831     #[stable(feature = "append", since = "1.4.0")]
832     pub fn append(&mut self, other: &mut Self) {
833         self.reserve(other.len());
834         let len = self.len();
835         unsafe {
836             ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
837         }
838
839         self.len += other.len();
840         unsafe {
841             other.set_len(0);
842         }
843     }
844
845     /// Create a draining iterator that removes the specified range in the vector
846     /// and yields the removed items.
847     ///
848     /// Note 1: The element range is removed even if the iterator is not
849     /// consumed until the end.
850     ///
851     /// Note 2: It is unspecified how many elements are removed from the vector,
852     /// if the `Drain` value is leaked.
853     ///
854     /// # Panics
855     ///
856     /// Panics if the starting point is greater than the end point or if
857     /// the end point is greater than the length of the vector.
858     ///
859     /// # Examples
860     ///
861     /// ```
862     /// let mut v = vec![1, 2, 3];
863     /// let u: Vec<_> = v.drain(1..).collect();
864     /// assert_eq!(v, &[1]);
865     /// assert_eq!(u, &[2, 3]);
866     ///
867     /// // A full range clears the vector
868     /// v.drain(..);
869     /// assert_eq!(v, &[]);
870     /// ```
871     #[stable(feature = "drain", since = "1.6.0")]
872     pub fn drain<R>(&mut self, range: R) -> Drain<T>
873         where R: RangeArgument<usize>
874     {
875         // Memory safety
876         //
877         // When the Drain is first created, it shortens the length of
878         // the source vector to make sure no uninitalized or moved-from elements
879         // are accessible at all if the Drain's destructor never gets to run.
880         //
881         // Drain will ptr::read out the values to remove.
882         // When finished, remaining tail of the vec is copied back to cover
883         // the hole, and the vector length is restored to the new length.
884         //
885         let len = self.len();
886         let start = *range.start().unwrap_or(&0);
887         let end = *range.end().unwrap_or(&len);
888         assert!(start <= end);
889         assert!(end <= len);
890
891         unsafe {
892             // set self.vec length's to start, to be safe in case Drain is leaked
893             self.set_len(start);
894             // Use the borrow in the IterMut to indicate borrowing behavior of the
895             // whole Drain iterator (like &mut T).
896             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
897                                                         end - start);
898             Drain {
899                 tail_start: end,
900                 tail_len: len - end,
901                 iter: range_slice.iter_mut(),
902                 vec: self as *mut _,
903             }
904         }
905     }
906
907     /// Clears the vector, removing all values.
908     ///
909     /// # Examples
910     ///
911     /// ```
912     /// let mut v = vec![1, 2, 3];
913     ///
914     /// v.clear();
915     ///
916     /// assert!(v.is_empty());
917     /// ```
918     #[inline]
919     #[stable(feature = "rust1", since = "1.0.0")]
920     pub fn clear(&mut self) {
921         self.truncate(0)
922     }
923
924     /// Returns the number of elements in the vector.
925     ///
926     /// # Examples
927     ///
928     /// ```
929     /// let a = vec![1, 2, 3];
930     /// assert_eq!(a.len(), 3);
931     /// ```
932     #[inline]
933     #[stable(feature = "rust1", since = "1.0.0")]
934     pub fn len(&self) -> usize {
935         self.len
936     }
937
938     /// Returns `true` if the vector contains no elements.
939     ///
940     /// # Examples
941     ///
942     /// ```
943     /// let mut v = Vec::new();
944     /// assert!(v.is_empty());
945     ///
946     /// v.push(1);
947     /// assert!(!v.is_empty());
948     /// ```
949     #[stable(feature = "rust1", since = "1.0.0")]
950     pub fn is_empty(&self) -> bool {
951         self.len() == 0
952     }
953
954     /// Splits the collection into two at the given index.
955     ///
956     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
957     /// and the returned `Self` contains elements `[at, len)`.
958     ///
959     /// Note that the capacity of `self` does not change.
960     ///
961     /// # Panics
962     ///
963     /// Panics if `at > len`.
964     ///
965     /// # Examples
966     ///
967     /// ```
968     /// let mut vec = vec![1,2,3];
969     /// let vec2 = vec.split_off(1);
970     /// assert_eq!(vec, [1]);
971     /// assert_eq!(vec2, [2, 3]);
972     /// ```
973     #[inline]
974     #[stable(feature = "split_off", since = "1.4.0")]
975     pub fn split_off(&mut self, at: usize) -> Self {
976         assert!(at <= self.len(), "`at` out of bounds");
977
978         let other_len = self.len - at;
979         let mut other = Vec::with_capacity(other_len);
980
981         // Unsafely `set_len` and copy items to `other`.
982         unsafe {
983             self.set_len(at);
984             other.set_len(other_len);
985
986             ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
987                                      other.as_mut_ptr(),
988                                      other.len());
989         }
990         other
991     }
992 }
993
994 impl<T: Clone> Vec<T> {
995     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
996     ///
997     /// If `new_len` is greater than `len()`, the `Vec` is extended by the
998     /// difference, with each additional slot filled with `value`.
999     /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
1000     ///
1001     /// # Examples
1002     ///
1003     /// ```
1004     /// let mut vec = vec!["hello"];
1005     /// vec.resize(3, "world");
1006     /// assert_eq!(vec, ["hello", "world", "world"]);
1007     ///
1008     /// let mut vec = vec![1, 2, 3, 4];
1009     /// vec.resize(2, 0);
1010     /// assert_eq!(vec, [1, 2]);
1011     /// ```
1012     #[stable(feature = "vec_resize", since = "1.5.0")]
1013     pub fn resize(&mut self, new_len: usize, value: T) {
1014         let len = self.len();
1015
1016         if new_len > len {
1017             self.extend_with_element(new_len - len, value);
1018         } else {
1019             self.truncate(new_len);
1020         }
1021     }
1022
1023     /// Extend the vector by `n` additional clones of `value`.
1024     fn extend_with_element(&mut self, n: usize, value: T) {
1025         self.reserve(n);
1026
1027         unsafe {
1028             let len = self.len();
1029             let mut ptr = self.as_mut_ptr().offset(len as isize);
1030             // Write all elements except the last one
1031             for i in 1..n {
1032                 ptr::write(ptr, value.clone());
1033                 ptr = ptr.offset(1);
1034                 // Increment the length in every step in case clone() panics
1035                 self.set_len(len + i);
1036             }
1037
1038             if n > 0 {
1039                 // We can write the last element directly without cloning needlessly
1040                 ptr::write(ptr, value);
1041                 self.set_len(len + n);
1042             }
1043         }
1044     }
1045
1046     /// Clones and appends all elements in a slice to the `Vec`.
1047     ///
1048     /// Iterates over the slice `other`, clones each element, and then appends
1049     /// it to this `Vec`. The `other` vector is traversed in-order.
1050     ///
1051     /// Note that this function is same as `extend` except that it is
1052     /// specialized to work with slices instead. If and when Rust gets
1053     /// specialization this function will likely be deprecated (but still
1054     /// available).
1055     ///
1056     /// # Examples
1057     ///
1058     /// ```
1059     /// let mut vec = vec![1];
1060     /// vec.extend_from_slice(&[2, 3, 4]);
1061     /// assert_eq!(vec, [1, 2, 3, 4]);
1062     /// ```
1063     #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1064     pub fn extend_from_slice(&mut self, other: &[T]) {
1065         self.reserve(other.len());
1066
1067         for i in 0..other.len() {
1068             let len = self.len();
1069
1070             // Unsafe code so this can be optimised to a memcpy (or something
1071             // similarly fast) when T is Copy. LLVM is easily confused, so any
1072             // extra operations during the loop can prevent this optimisation.
1073             unsafe {
1074                 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
1075                 self.set_len(len + 1);
1076             }
1077         }
1078     }
1079 }
1080
1081 impl<T: PartialEq> Vec<T> {
1082     /// Removes consecutive repeated elements in the vector.
1083     ///
1084     /// If the vector is sorted, this removes all duplicates.
1085     ///
1086     /// # Examples
1087     ///
1088     /// ```
1089     /// let mut vec = vec![1, 2, 2, 3, 2];
1090     ///
1091     /// vec.dedup();
1092     ///
1093     /// assert_eq!(vec, [1, 2, 3, 2]);
1094     /// ```
1095     #[stable(feature = "rust1", since = "1.0.0")]
1096     pub fn dedup(&mut self) {
1097         unsafe {
1098             // Although we have a mutable reference to `self`, we cannot make
1099             // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1100             // must ensure that the vector is in a valid state at all time.
1101             //
1102             // The way that we handle this is by using swaps; we iterate
1103             // over all the elements, swapping as we go so that at the end
1104             // the elements we wish to keep are in the front, and those we
1105             // wish to reject are at the back. We can then truncate the
1106             // vector. This operation is still O(n).
1107             //
1108             // Example: We start in this state, where `r` represents "next
1109             // read" and `w` represents "next_write`.
1110             //
1111             //           r
1112             //     +---+---+---+---+---+---+
1113             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1114             //     +---+---+---+---+---+---+
1115             //           w
1116             //
1117             // Comparing self[r] against self[w-1], this is not a duplicate, so
1118             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1119             // r and w, leaving us with:
1120             //
1121             //               r
1122             //     +---+---+---+---+---+---+
1123             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1124             //     +---+---+---+---+---+---+
1125             //               w
1126             //
1127             // Comparing self[r] against self[w-1], this value is a duplicate,
1128             // so we increment `r` but leave everything else unchanged:
1129             //
1130             //                   r
1131             //     +---+---+---+---+---+---+
1132             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1133             //     +---+---+---+---+---+---+
1134             //               w
1135             //
1136             // Comparing self[r] against self[w-1], this is not a duplicate,
1137             // so swap self[r] and self[w] and advance r and w:
1138             //
1139             //                       r
1140             //     +---+---+---+---+---+---+
1141             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1142             //     +---+---+---+---+---+---+
1143             //                   w
1144             //
1145             // Not a duplicate, repeat:
1146             //
1147             //                           r
1148             //     +---+---+---+---+---+---+
1149             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1150             //     +---+---+---+---+---+---+
1151             //                       w
1152             //
1153             // Duplicate, advance r. End of vec. Truncate to w.
1154
1155             let ln = self.len();
1156             if ln <= 1 {
1157                 return;
1158             }
1159
1160             // Avoid bounds checks by using raw pointers.
1161             let p = self.as_mut_ptr();
1162             let mut r: usize = 1;
1163             let mut w: usize = 1;
1164
1165             while r < ln {
1166                 let p_r = p.offset(r as isize);
1167                 let p_wm1 = p.offset((w - 1) as isize);
1168                 if *p_r != *p_wm1 {
1169                     if r != w {
1170                         let p_w = p_wm1.offset(1);
1171                         mem::swap(&mut *p_r, &mut *p_w);
1172                     }
1173                     w += 1;
1174                 }
1175                 r += 1;
1176             }
1177
1178             self.truncate(w);
1179         }
1180     }
1181 }
1182
1183 ////////////////////////////////////////////////////////////////////////////////
1184 // Internal methods and functions
1185 ////////////////////////////////////////////////////////////////////////////////
1186
1187 #[doc(hidden)]
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1190     let mut v = Vec::with_capacity(n);
1191     v.extend_with_element(n, elem);
1192     v
1193 }
1194
1195 ////////////////////////////////////////////////////////////////////////////////
1196 // Common trait implementations for Vec
1197 ////////////////////////////////////////////////////////////////////////////////
1198
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T: Clone> Clone for Vec<T> {
1201     #[cfg(not(test))]
1202     fn clone(&self) -> Vec<T> {
1203         <[T]>::to_vec(&**self)
1204     }
1205
1206     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1207     // required for this method definition, is not available. Instead use the
1208     // `slice::to_vec`  function which is only available with cfg(test)
1209     // NB see the slice::hack module in slice.rs for more information
1210     #[cfg(test)]
1211     fn clone(&self) -> Vec<T> {
1212         ::slice::to_vec(&**self)
1213     }
1214
1215     fn clone_from(&mut self, other: &Vec<T>) {
1216         // drop anything in self that will not be overwritten
1217         self.truncate(other.len());
1218         let len = self.len();
1219
1220         // reuse the contained values' allocations/resources.
1221         self.clone_from_slice(&other[..len]);
1222
1223         // self.len <= other.len due to the truncate above, so the
1224         // slice here is always in-bounds.
1225         self.extend_from_slice(&other[len..]);
1226     }
1227 }
1228
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<T: Hash> Hash for Vec<T> {
1231     #[inline]
1232     fn hash<H: hash::Hasher>(&self, state: &mut H) {
1233         Hash::hash(&**self, state)
1234     }
1235 }
1236
1237 #[stable(feature = "rust1", since = "1.0.0")]
1238 impl<T> Index<usize> for Vec<T> {
1239     type Output = T;
1240
1241     #[inline]
1242     fn index(&self, index: usize) -> &T {
1243         // NB built-in indexing via `&[T]`
1244         &(**self)[index]
1245     }
1246 }
1247
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 impl<T> IndexMut<usize> for Vec<T> {
1250     #[inline]
1251     fn index_mut(&mut self, index: usize) -> &mut T {
1252         // NB built-in indexing via `&mut [T]`
1253         &mut (**self)[index]
1254     }
1255 }
1256
1257
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1260     type Output = [T];
1261
1262     #[inline]
1263     fn index(&self, index: ops::Range<usize>) -> &[T] {
1264         Index::index(&**self, index)
1265     }
1266 }
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1269     type Output = [T];
1270
1271     #[inline]
1272     fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1273         Index::index(&**self, index)
1274     }
1275 }
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1278     type Output = [T];
1279
1280     #[inline]
1281     fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1282         Index::index(&**self, index)
1283     }
1284 }
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1287     type Output = [T];
1288
1289     #[inline]
1290     fn index(&self, _index: ops::RangeFull) -> &[T] {
1291         self
1292     }
1293 }
1294 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1295 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1296     type Output = [T];
1297
1298     #[inline]
1299     fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1300         Index::index(&**self, index)
1301     }
1302 }
1303 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1304 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1305     type Output = [T];
1306
1307     #[inline]
1308     fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1309         Index::index(&**self, index)
1310     }
1311 }
1312
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1315     #[inline]
1316     fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1317         IndexMut::index_mut(&mut **self, index)
1318     }
1319 }
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1322     #[inline]
1323     fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1324         IndexMut::index_mut(&mut **self, index)
1325     }
1326 }
1327 #[stable(feature = "rust1", since = "1.0.0")]
1328 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1329     #[inline]
1330     fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1331         IndexMut::index_mut(&mut **self, index)
1332     }
1333 }
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1336     #[inline]
1337     fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1338         self
1339     }
1340 }
1341 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1342 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1343     #[inline]
1344     fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1345         IndexMut::index_mut(&mut **self, index)
1346     }
1347 }
1348 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1349 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1350     #[inline]
1351     fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1352         IndexMut::index_mut(&mut **self, index)
1353     }
1354 }
1355
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<T> ops::Deref for Vec<T> {
1358     type Target = [T];
1359
1360     fn deref(&self) -> &[T] {
1361         unsafe {
1362             let p = self.buf.ptr();
1363             assume(!p.is_null());
1364             slice::from_raw_parts(p, self.len)
1365         }
1366     }
1367 }
1368
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<T> ops::DerefMut for Vec<T> {
1371     fn deref_mut(&mut self) -> &mut [T] {
1372         unsafe {
1373             let ptr = self.buf.ptr();
1374             assume(!ptr.is_null());
1375             slice::from_raw_parts_mut(ptr, self.len)
1376         }
1377     }
1378 }
1379
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<T> FromIterator<T> for Vec<T> {
1382     #[inline]
1383     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1384         // Unroll the first iteration, as the vector is going to be
1385         // expanded on this iteration in every case when the iterable is not
1386         // empty, but the loop in extend_desugared() is not going to see the
1387         // vector being full in the few subsequent loop iterations.
1388         // So we get better branch prediction.
1389         let mut iterator = iter.into_iter();
1390         let mut vector = match iterator.next() {
1391             None => return Vec::new(),
1392             Some(element) => {
1393                 let (lower, _) = iterator.size_hint();
1394                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1395                 unsafe {
1396                     ptr::write(vector.get_unchecked_mut(0), element);
1397                     vector.set_len(1);
1398                 }
1399                 vector
1400             }
1401         };
1402         vector.extend_desugared(iterator);
1403         vector
1404     }
1405 }
1406
1407 #[stable(feature = "rust1", since = "1.0.0")]
1408 impl<T> IntoIterator for Vec<T> {
1409     type Item = T;
1410     type IntoIter = IntoIter<T>;
1411
1412     /// Creates a consuming iterator, that is, one that moves each value out of
1413     /// the vector (from start to end). The vector cannot be used after calling
1414     /// this.
1415     ///
1416     /// # Examples
1417     ///
1418     /// ```
1419     /// let v = vec!["a".to_string(), "b".to_string()];
1420     /// for s in v.into_iter() {
1421     ///     // s has type String, not &String
1422     ///     println!("{}", s);
1423     /// }
1424     /// ```
1425     #[inline]
1426     fn into_iter(mut self) -> IntoIter<T> {
1427         unsafe {
1428             let ptr = self.as_mut_ptr();
1429             assume(!ptr.is_null());
1430             let begin = ptr as *const T;
1431             let end = if mem::size_of::<T>() == 0 {
1432                 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1433             } else {
1434                 ptr.offset(self.len() as isize) as *const T
1435             };
1436             let buf = ptr::read(&self.buf);
1437             mem::forget(self);
1438             IntoIter {
1439                 _buf: buf,
1440                 ptr: begin,
1441                 end: end,
1442             }
1443         }
1444     }
1445 }
1446
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<'a, T> IntoIterator for &'a Vec<T> {
1449     type Item = &'a T;
1450     type IntoIter = slice::Iter<'a, T>;
1451
1452     fn into_iter(self) -> slice::Iter<'a, T> {
1453         self.iter()
1454     }
1455 }
1456
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1459     type Item = &'a mut T;
1460     type IntoIter = slice::IterMut<'a, T>;
1461
1462     fn into_iter(mut self) -> slice::IterMut<'a, T> {
1463         self.iter_mut()
1464     }
1465 }
1466
1467 #[stable(feature = "rust1", since = "1.0.0")]
1468 impl<T> Extend<T> for Vec<T> {
1469     #[inline]
1470     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1471         <Self as SpecExtend<I>>::spec_extend(self, iter);
1472     }
1473 }
1474
1475 impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
1476     default fn spec_extend(&mut self, iter: I) {
1477         self.extend_desugared(iter.into_iter())
1478     }
1479 }
1480
1481 impl<T> SpecExtend<Vec<T>> for Vec<T> {
1482     fn spec_extend(&mut self, ref mut other: Vec<T>) {
1483         self.append(other);
1484     }
1485 }
1486
1487 impl<T> Vec<T> {
1488     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1489         // This function should be the moral equivalent of:
1490         //
1491         //      for item in iterator {
1492         //          self.push(item);
1493         //      }
1494         while let Some(element) = iterator.next() {
1495             let len = self.len();
1496             if len == self.capacity() {
1497                 let (lower, _) = iterator.size_hint();
1498                 self.reserve(lower.saturating_add(1));
1499             }
1500             unsafe {
1501                 ptr::write(self.get_unchecked_mut(len), element);
1502                 // NB can't overflow since we would have had to alloc the address space
1503                 self.set_len(len + 1);
1504             }
1505         }
1506     }
1507 }
1508
1509 #[stable(feature = "extend_ref", since = "1.2.0")]
1510 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1511     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1512         self.extend(iter.into_iter().cloned());
1513     }
1514 }
1515
1516 macro_rules! __impl_slice_eq1 {
1517     ($Lhs: ty, $Rhs: ty) => {
1518         __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1519     };
1520     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1521         #[stable(feature = "rust1", since = "1.0.0")]
1522         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1523             #[inline]
1524             fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1525             #[inline]
1526             fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1527         }
1528     }
1529 }
1530
1531 __impl_slice_eq1! { Vec<A>, Vec<B> }
1532 __impl_slice_eq1! { Vec<A>, &'b [B] }
1533 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1534 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1535 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1536 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1537
1538 macro_rules! array_impls {
1539     ($($N: expr)+) => {
1540         $(
1541             // NOTE: some less important impls are omitted to reduce code bloat
1542             __impl_slice_eq1! { Vec<A>, [B; $N] }
1543             __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1544             // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1545             // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1546             // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1547             // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1548         )+
1549     }
1550 }
1551
1552 array_impls! {
1553      0  1  2  3  4  5  6  7  8  9
1554     10 11 12 13 14 15 16 17 18 19
1555     20 21 22 23 24 25 26 27 28 29
1556     30 31 32
1557 }
1558
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<T: PartialOrd> PartialOrd for Vec<T> {
1561     #[inline]
1562     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1563         PartialOrd::partial_cmp(&**self, &**other)
1564     }
1565 }
1566
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<T: Eq> Eq for Vec<T> {}
1569
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<T: Ord> Ord for Vec<T> {
1572     #[inline]
1573     fn cmp(&self, other: &Vec<T>) -> Ordering {
1574         Ord::cmp(&**self, &**other)
1575     }
1576 }
1577
1578 #[stable(feature = "rust1", since = "1.0.0")]
1579 impl<T> Drop for Vec<T> {
1580     #[unsafe_destructor_blind_to_params]
1581     fn drop(&mut self) {
1582         if self.buf.unsafe_no_drop_flag_needs_drop() {
1583             unsafe {
1584                 // use drop for [T]
1585                 ptr::drop_in_place(&mut self[..]);
1586             }
1587         }
1588         // RawVec handles deallocation
1589     }
1590 }
1591
1592 #[stable(feature = "rust1", since = "1.0.0")]
1593 impl<T> Default for Vec<T> {
1594     fn default() -> Vec<T> {
1595         Vec::new()
1596     }
1597 }
1598
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1601     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1602         fmt::Debug::fmt(&**self, f)
1603     }
1604 }
1605
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl<T> AsRef<Vec<T>> for Vec<T> {
1608     fn as_ref(&self) -> &Vec<T> {
1609         self
1610     }
1611 }
1612
1613 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1614 impl<T> AsMut<Vec<T>> for Vec<T> {
1615     fn as_mut(&mut self) -> &mut Vec<T> {
1616         self
1617     }
1618 }
1619
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<T> AsRef<[T]> for Vec<T> {
1622     fn as_ref(&self) -> &[T] {
1623         self
1624     }
1625 }
1626
1627 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1628 impl<T> AsMut<[T]> for Vec<T> {
1629     fn as_mut(&mut self) -> &mut [T] {
1630         self
1631     }
1632 }
1633
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1636     #[cfg(not(test))]
1637     fn from(s: &'a [T]) -> Vec<T> {
1638         s.to_vec()
1639     }
1640     #[cfg(test)]
1641     fn from(s: &'a [T]) -> Vec<T> {
1642         ::slice::to_vec(s)
1643     }
1644 }
1645
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<'a> From<&'a str> for Vec<u8> {
1648     fn from(s: &'a str) -> Vec<u8> {
1649         From::from(s.as_bytes())
1650     }
1651 }
1652
1653 ////////////////////////////////////////////////////////////////////////////////
1654 // Clone-on-write
1655 ////////////////////////////////////////////////////////////////////////////////
1656
1657 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1658 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1659     fn from(s: &'a [T]) -> Cow<'a, [T]> {
1660         Cow::Borrowed(s)
1661     }
1662 }
1663
1664 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1665 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1666     fn from(v: Vec<T>) -> Cow<'a, [T]> {
1667         Cow::Owned(v)
1668     }
1669 }
1670
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1673     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1674         Cow::Owned(FromIterator::from_iter(it))
1675     }
1676 }
1677
1678 ////////////////////////////////////////////////////////////////////////////////
1679 // Iterators
1680 ////////////////////////////////////////////////////////////////////////////////
1681
1682 /// An iterator that moves out of a vector.
1683 ///
1684 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
1685 /// by the [`IntoIterator`] trait).
1686 ///
1687 /// [`Vec`]: struct.Vec.html
1688 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 pub struct IntoIter<T> {
1691     _buf: RawVec<T>,
1692     ptr: *const T,
1693     end: *const T,
1694 }
1695
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 unsafe impl<T: Send> Send for IntoIter<T> {}
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1700
1701 #[stable(feature = "rust1", since = "1.0.0")]
1702 impl<T> Iterator for IntoIter<T> {
1703     type Item = T;
1704
1705     #[inline]
1706     fn next(&mut self) -> Option<T> {
1707         unsafe {
1708             if self.ptr == self.end {
1709                 None
1710             } else {
1711                 if mem::size_of::<T>() == 0 {
1712                     // purposefully don't use 'ptr.offset' because for
1713                     // vectors with 0-size elements this would return the
1714                     // same pointer.
1715                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1716
1717                     // Use a non-null pointer value
1718                     Some(ptr::read(EMPTY as *mut T))
1719                 } else {
1720                     let old = self.ptr;
1721                     self.ptr = self.ptr.offset(1);
1722
1723                     Some(ptr::read(old))
1724                 }
1725             }
1726         }
1727     }
1728
1729     #[inline]
1730     fn size_hint(&self) -> (usize, Option<usize>) {
1731         let diff = (self.end as usize) - (self.ptr as usize);
1732         let size = mem::size_of::<T>();
1733         let exact = diff /
1734                     (if size == 0 {
1735                          1
1736                      } else {
1737                          size
1738                      });
1739         (exact, Some(exact))
1740     }
1741
1742     #[inline]
1743     fn count(self) -> usize {
1744         self.len()
1745     }
1746 }
1747
1748 #[stable(feature = "rust1", since = "1.0.0")]
1749 impl<T> DoubleEndedIterator for IntoIter<T> {
1750     #[inline]
1751     fn next_back(&mut self) -> Option<T> {
1752         unsafe {
1753             if self.end == self.ptr {
1754                 None
1755             } else {
1756                 if mem::size_of::<T>() == 0 {
1757                     // See above for why 'ptr.offset' isn't used
1758                     self.end = arith_offset(self.end as *const i8, -1) as *const T;
1759
1760                     // Use a non-null pointer value
1761                     Some(ptr::read(EMPTY as *mut T))
1762                 } else {
1763                     self.end = self.end.offset(-1);
1764
1765                     Some(ptr::read(self.end))
1766                 }
1767             }
1768         }
1769     }
1770 }
1771
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl<T> ExactSizeIterator for IntoIter<T> {}
1774
1775 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1776 impl<T: Clone> Clone for IntoIter<T> {
1777     fn clone(&self) -> IntoIter<T> {
1778         unsafe {
1779             slice::from_raw_parts(self.ptr, self.len()).to_owned().into_iter()
1780         }
1781     }
1782 }
1783
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<T> Drop for IntoIter<T> {
1786     #[unsafe_destructor_blind_to_params]
1787     fn drop(&mut self) {
1788         // destroy the remaining elements
1789         for _x in self {}
1790
1791         // RawVec handles deallocation
1792     }
1793 }
1794
1795 /// A draining iterator for `Vec<T>`.
1796 ///
1797 /// This `struct` is created by the [`drain`] method on [`Vec`].
1798 ///
1799 /// [`drain`]: struct.Vec.html#method.drain
1800 /// [`Vec`]: struct.Vec.html
1801 #[stable(feature = "drain", since = "1.6.0")]
1802 pub struct Drain<'a, T: 'a> {
1803     /// Index of tail to preserve
1804     tail_start: usize,
1805     /// Length of tail
1806     tail_len: usize,
1807     /// Current remaining range to remove
1808     iter: slice::IterMut<'a, T>,
1809     vec: *mut Vec<T>,
1810 }
1811
1812 #[stable(feature = "drain", since = "1.6.0")]
1813 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1814 #[stable(feature = "drain", since = "1.6.0")]
1815 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1816
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a, T> Iterator for Drain<'a, T> {
1819     type Item = T;
1820
1821     #[inline]
1822     fn next(&mut self) -> Option<T> {
1823         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1824     }
1825
1826     fn size_hint(&self) -> (usize, Option<usize>) {
1827         self.iter.size_hint()
1828     }
1829 }
1830
1831 #[stable(feature = "rust1", since = "1.0.0")]
1832 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1833     #[inline]
1834     fn next_back(&mut self) -> Option<T> {
1835         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1836     }
1837 }
1838
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 impl<'a, T> Drop for Drain<'a, T> {
1841     fn drop(&mut self) {
1842         // exhaust self first
1843         while let Some(_) = self.next() {}
1844
1845         if self.tail_len > 0 {
1846             unsafe {
1847                 let source_vec = &mut *self.vec;
1848                 // memmove back untouched tail, update to new length
1849                 let start = source_vec.len();
1850                 let tail = self.tail_start;
1851                 let src = source_vec.as_ptr().offset(tail as isize);
1852                 let dst = source_vec.as_mut_ptr().offset(start as isize);
1853                 ptr::copy(src, dst, self.tail_len);
1854                 source_vec.set_len(start + self.tail_len);
1855             }
1856         }
1857     }
1858 }
1859
1860
1861 #[stable(feature = "rust1", since = "1.0.0")]
1862 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}