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