]> git.proxmox.com Git - rustc.git/blob - src/libcollections/vec.rs
New upstream version 1.13.0+dfsg1
[rustc.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, FusedIterator};
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 #[cfg_attr(stage0, 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 mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1050 // Use SetLenOnDrop to work around bug where compiler
1051 // may not realize the store through `ptr` trough self.set_len()
1052 // don't alias.
1053 let mut local_len = SetLenOnDrop::new(&mut self.len);
1054
1055 // Write all elements except the last one
1056 for _ in 1..n {
1057 ptr::write(ptr, value.clone());
1058 ptr = ptr.offset(1);
1059 // Increment the length in every step in case clone() panics
1060 local_len.increment_len(1);
1061 }
1062
1063 if n > 0 {
1064 // We can write the last element directly without cloning needlessly
1065 ptr::write(ptr, value);
1066 local_len.increment_len(1);
1067 }
1068
1069 // len set by scope guard
1070 }
1071 }
1072
1073 /// Clones and appends all elements in a slice to the `Vec`.
1074 ///
1075 /// Iterates over the slice `other`, clones each element, and then appends
1076 /// it to this `Vec`. The `other` vector is traversed in-order.
1077 ///
1078 /// Note that this function is same as `extend` except that it is
1079 /// specialized to work with slices instead. If and when Rust gets
1080 /// specialization this function will likely be deprecated (but still
1081 /// available).
1082 ///
1083 /// # Examples
1084 ///
1085 /// ```
1086 /// let mut vec = vec![1];
1087 /// vec.extend_from_slice(&[2, 3, 4]);
1088 /// assert_eq!(vec, [1, 2, 3, 4]);
1089 /// ```
1090 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1091 pub fn extend_from_slice(&mut self, other: &[T]) {
1092 self.reserve(other.len());
1093
1094 // Unsafe code so this can be optimised to a memcpy (or something
1095 // similarly fast) when T is Copy. LLVM is easily confused, so any
1096 // extra operations during the loop can prevent this optimisation.
1097 unsafe {
1098 let len = self.len();
1099 let ptr = self.get_unchecked_mut(len) as *mut T;
1100 // Use SetLenOnDrop to work around bug where compiler
1101 // may not realize the store through `ptr` trough self.set_len()
1102 // don't alias.
1103 let mut local_len = SetLenOnDrop::new(&mut self.len);
1104
1105 for i in 0..other.len() {
1106 ptr::write(ptr.offset(i as isize), other.get_unchecked(i).clone());
1107 local_len.increment_len(1);
1108 }
1109
1110 // len set by scope guard
1111 }
1112 }
1113 }
1114
1115 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1116 //
1117 // The idea is: The length field in SetLenOnDrop is a local variable
1118 // that the optimizer will see does not alias with any stores through the Vec's data
1119 // pointer. This is a workaround for alias analysis issue #32155
1120 struct SetLenOnDrop<'a> {
1121 len: &'a mut usize,
1122 local_len: usize,
1123 }
1124
1125 impl<'a> SetLenOnDrop<'a> {
1126 #[inline]
1127 fn new(len: &'a mut usize) -> Self {
1128 SetLenOnDrop { local_len: *len, len: len }
1129 }
1130
1131 #[inline]
1132 fn increment_len(&mut self, increment: usize) {
1133 self.local_len += increment;
1134 }
1135 }
1136
1137 impl<'a> Drop for SetLenOnDrop<'a> {
1138 #[inline]
1139 fn drop(&mut self) {
1140 *self.len = self.local_len;
1141 }
1142 }
1143
1144 impl<T: PartialEq> Vec<T> {
1145 /// Removes consecutive repeated elements in the vector.
1146 ///
1147 /// If the vector is sorted, this removes all duplicates.
1148 ///
1149 /// # Examples
1150 ///
1151 /// ```
1152 /// let mut vec = vec![1, 2, 2, 3, 2];
1153 ///
1154 /// vec.dedup();
1155 ///
1156 /// assert_eq!(vec, [1, 2, 3, 2]);
1157 /// ```
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 pub fn dedup(&mut self) {
1160 unsafe {
1161 // Although we have a mutable reference to `self`, we cannot make
1162 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1163 // must ensure that the vector is in a valid state at all time.
1164 //
1165 // The way that we handle this is by using swaps; we iterate
1166 // over all the elements, swapping as we go so that at the end
1167 // the elements we wish to keep are in the front, and those we
1168 // wish to reject are at the back. We can then truncate the
1169 // vector. This operation is still O(n).
1170 //
1171 // Example: We start in this state, where `r` represents "next
1172 // read" and `w` represents "next_write`.
1173 //
1174 // r
1175 // +---+---+---+---+---+---+
1176 // | 0 | 1 | 1 | 2 | 3 | 3 |
1177 // +---+---+---+---+---+---+
1178 // w
1179 //
1180 // Comparing self[r] against self[w-1], this is not a duplicate, so
1181 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1182 // r and w, leaving us with:
1183 //
1184 // r
1185 // +---+---+---+---+---+---+
1186 // | 0 | 1 | 1 | 2 | 3 | 3 |
1187 // +---+---+---+---+---+---+
1188 // w
1189 //
1190 // Comparing self[r] against self[w-1], this value is a duplicate,
1191 // so we increment `r` but leave everything else unchanged:
1192 //
1193 // r
1194 // +---+---+---+---+---+---+
1195 // | 0 | 1 | 1 | 2 | 3 | 3 |
1196 // +---+---+---+---+---+---+
1197 // w
1198 //
1199 // Comparing self[r] against self[w-1], this is not a duplicate,
1200 // so swap self[r] and self[w] and advance r and w:
1201 //
1202 // r
1203 // +---+---+---+---+---+---+
1204 // | 0 | 1 | 2 | 1 | 3 | 3 |
1205 // +---+---+---+---+---+---+
1206 // w
1207 //
1208 // Not a duplicate, repeat:
1209 //
1210 // r
1211 // +---+---+---+---+---+---+
1212 // | 0 | 1 | 2 | 3 | 1 | 3 |
1213 // +---+---+---+---+---+---+
1214 // w
1215 //
1216 // Duplicate, advance r. End of vec. Truncate to w.
1217
1218 let ln = self.len();
1219 if ln <= 1 {
1220 return;
1221 }
1222
1223 // Avoid bounds checks by using raw pointers.
1224 let p = self.as_mut_ptr();
1225 let mut r: usize = 1;
1226 let mut w: usize = 1;
1227
1228 while r < ln {
1229 let p_r = p.offset(r as isize);
1230 let p_wm1 = p.offset((w - 1) as isize);
1231 if *p_r != *p_wm1 {
1232 if r != w {
1233 let p_w = p_wm1.offset(1);
1234 mem::swap(&mut *p_r, &mut *p_w);
1235 }
1236 w += 1;
1237 }
1238 r += 1;
1239 }
1240
1241 self.truncate(w);
1242 }
1243 }
1244 }
1245
1246 ////////////////////////////////////////////////////////////////////////////////
1247 // Internal methods and functions
1248 ////////////////////////////////////////////////////////////////////////////////
1249
1250 #[doc(hidden)]
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1253 let mut v = Vec::with_capacity(n);
1254 v.extend_with_element(n, elem);
1255 v
1256 }
1257
1258 ////////////////////////////////////////////////////////////////////////////////
1259 // Common trait implementations for Vec
1260 ////////////////////////////////////////////////////////////////////////////////
1261
1262 #[stable(feature = "rust1", since = "1.0.0")]
1263 impl<T: Clone> Clone for Vec<T> {
1264 #[cfg(not(test))]
1265 fn clone(&self) -> Vec<T> {
1266 <[T]>::to_vec(&**self)
1267 }
1268
1269 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1270 // required for this method definition, is not available. Instead use the
1271 // `slice::to_vec` function which is only available with cfg(test)
1272 // NB see the slice::hack module in slice.rs for more information
1273 #[cfg(test)]
1274 fn clone(&self) -> Vec<T> {
1275 ::slice::to_vec(&**self)
1276 }
1277
1278 fn clone_from(&mut self, other: &Vec<T>) {
1279 // drop anything in self that will not be overwritten
1280 self.truncate(other.len());
1281 let len = self.len();
1282
1283 // reuse the contained values' allocations/resources.
1284 self.clone_from_slice(&other[..len]);
1285
1286 // self.len <= other.len due to the truncate above, so the
1287 // slice here is always in-bounds.
1288 self.extend_from_slice(&other[len..]);
1289 }
1290 }
1291
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<T: Hash> Hash for Vec<T> {
1294 #[inline]
1295 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1296 Hash::hash(&**self, state)
1297 }
1298 }
1299
1300 #[stable(feature = "rust1", since = "1.0.0")]
1301 impl<T> Index<usize> for Vec<T> {
1302 type Output = T;
1303
1304 #[inline]
1305 fn index(&self, index: usize) -> &T {
1306 // NB built-in indexing via `&[T]`
1307 &(**self)[index]
1308 }
1309 }
1310
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T> IndexMut<usize> for Vec<T> {
1313 #[inline]
1314 fn index_mut(&mut self, index: usize) -> &mut T {
1315 // NB built-in indexing via `&mut [T]`
1316 &mut (**self)[index]
1317 }
1318 }
1319
1320
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1323 type Output = [T];
1324
1325 #[inline]
1326 fn index(&self, index: ops::Range<usize>) -> &[T] {
1327 Index::index(&**self, index)
1328 }
1329 }
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1332 type Output = [T];
1333
1334 #[inline]
1335 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1336 Index::index(&**self, index)
1337 }
1338 }
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1341 type Output = [T];
1342
1343 #[inline]
1344 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1345 Index::index(&**self, index)
1346 }
1347 }
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1350 type Output = [T];
1351
1352 #[inline]
1353 fn index(&self, _index: ops::RangeFull) -> &[T] {
1354 self
1355 }
1356 }
1357 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1358 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1359 type Output = [T];
1360
1361 #[inline]
1362 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1363 Index::index(&**self, index)
1364 }
1365 }
1366 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1367 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1368 type Output = [T];
1369
1370 #[inline]
1371 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1372 Index::index(&**self, index)
1373 }
1374 }
1375
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1378 #[inline]
1379 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1380 IndexMut::index_mut(&mut **self, index)
1381 }
1382 }
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1385 #[inline]
1386 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1387 IndexMut::index_mut(&mut **self, index)
1388 }
1389 }
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1392 #[inline]
1393 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1394 IndexMut::index_mut(&mut **self, index)
1395 }
1396 }
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1399 #[inline]
1400 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1401 self
1402 }
1403 }
1404 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1405 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1406 #[inline]
1407 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1408 IndexMut::index_mut(&mut **self, index)
1409 }
1410 }
1411 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1412 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1413 #[inline]
1414 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1415 IndexMut::index_mut(&mut **self, index)
1416 }
1417 }
1418
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<T> ops::Deref for Vec<T> {
1421 type Target = [T];
1422
1423 fn deref(&self) -> &[T] {
1424 unsafe {
1425 let p = self.buf.ptr();
1426 assume(!p.is_null());
1427 slice::from_raw_parts(p, self.len)
1428 }
1429 }
1430 }
1431
1432 #[stable(feature = "rust1", since = "1.0.0")]
1433 impl<T> ops::DerefMut for Vec<T> {
1434 fn deref_mut(&mut self) -> &mut [T] {
1435 unsafe {
1436 let ptr = self.buf.ptr();
1437 assume(!ptr.is_null());
1438 slice::from_raw_parts_mut(ptr, self.len)
1439 }
1440 }
1441 }
1442
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<T> FromIterator<T> for Vec<T> {
1445 #[inline]
1446 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1447 // Unroll the first iteration, as the vector is going to be
1448 // expanded on this iteration in every case when the iterable is not
1449 // empty, but the loop in extend_desugared() is not going to see the
1450 // vector being full in the few subsequent loop iterations.
1451 // So we get better branch prediction.
1452 let mut iterator = iter.into_iter();
1453 let mut vector = match iterator.next() {
1454 None => return Vec::new(),
1455 Some(element) => {
1456 let (lower, _) = iterator.size_hint();
1457 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1458 unsafe {
1459 ptr::write(vector.get_unchecked_mut(0), element);
1460 vector.set_len(1);
1461 }
1462 vector
1463 }
1464 };
1465 vector.extend_desugared(iterator);
1466 vector
1467 }
1468 }
1469
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 impl<T> IntoIterator for Vec<T> {
1472 type Item = T;
1473 type IntoIter = IntoIter<T>;
1474
1475 /// Creates a consuming iterator, that is, one that moves each value out of
1476 /// the vector (from start to end). The vector cannot be used after calling
1477 /// this.
1478 ///
1479 /// # Examples
1480 ///
1481 /// ```
1482 /// let v = vec!["a".to_string(), "b".to_string()];
1483 /// for s in v.into_iter() {
1484 /// // s has type String, not &String
1485 /// println!("{}", s);
1486 /// }
1487 /// ```
1488 #[inline]
1489 fn into_iter(mut self) -> IntoIter<T> {
1490 unsafe {
1491 let begin = self.as_mut_ptr();
1492 assume(!begin.is_null());
1493 let end = if mem::size_of::<T>() == 0 {
1494 arith_offset(begin as *const i8, self.len() as isize) as *const T
1495 } else {
1496 begin.offset(self.len() as isize) as *const T
1497 };
1498 let cap = self.buf.cap();
1499 mem::forget(self);
1500 IntoIter {
1501 buf: Shared::new(begin),
1502 cap: cap,
1503 ptr: begin,
1504 end: end,
1505 }
1506 }
1507 }
1508 }
1509
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 impl<'a, T> IntoIterator for &'a Vec<T> {
1512 type Item = &'a T;
1513 type IntoIter = slice::Iter<'a, T>;
1514
1515 fn into_iter(self) -> slice::Iter<'a, T> {
1516 self.iter()
1517 }
1518 }
1519
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1522 type Item = &'a mut T;
1523 type IntoIter = slice::IterMut<'a, T>;
1524
1525 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1526 self.iter_mut()
1527 }
1528 }
1529
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 impl<T> Extend<T> for Vec<T> {
1532 #[inline]
1533 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1534 <Self as SpecExtend<I>>::spec_extend(self, iter);
1535 }
1536 }
1537
1538 impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
1539 default fn spec_extend(&mut self, iter: I) {
1540 self.extend_desugared(iter.into_iter())
1541 }
1542 }
1543
1544 impl<T> SpecExtend<Vec<T>> for Vec<T> {
1545 fn spec_extend(&mut self, ref mut other: Vec<T>) {
1546 self.append(other);
1547 }
1548 }
1549
1550 impl<T> Vec<T> {
1551 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1552 // This function should be the moral equivalent of:
1553 //
1554 // for item in iterator {
1555 // self.push(item);
1556 // }
1557 while let Some(element) = iterator.next() {
1558 let len = self.len();
1559 if len == self.capacity() {
1560 let (lower, _) = iterator.size_hint();
1561 self.reserve(lower.saturating_add(1));
1562 }
1563 unsafe {
1564 ptr::write(self.get_unchecked_mut(len), element);
1565 // NB can't overflow since we would have had to alloc the address space
1566 self.set_len(len + 1);
1567 }
1568 }
1569 }
1570 }
1571
1572 #[stable(feature = "extend_ref", since = "1.2.0")]
1573 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1574 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1575 self.extend(iter.into_iter().cloned());
1576 }
1577 }
1578
1579 macro_rules! __impl_slice_eq1 {
1580 ($Lhs: ty, $Rhs: ty) => {
1581 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1582 };
1583 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1586 #[inline]
1587 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1588 #[inline]
1589 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1590 }
1591 }
1592 }
1593
1594 __impl_slice_eq1! { Vec<A>, Vec<B> }
1595 __impl_slice_eq1! { Vec<A>, &'b [B] }
1596 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1597 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1598 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1599 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1600
1601 macro_rules! array_impls {
1602 ($($N: expr)+) => {
1603 $(
1604 // NOTE: some less important impls are omitted to reduce code bloat
1605 __impl_slice_eq1! { Vec<A>, [B; $N] }
1606 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1607 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1608 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1609 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1610 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1611 )+
1612 }
1613 }
1614
1615 array_impls! {
1616 0 1 2 3 4 5 6 7 8 9
1617 10 11 12 13 14 15 16 17 18 19
1618 20 21 22 23 24 25 26 27 28 29
1619 30 31 32
1620 }
1621
1622 #[stable(feature = "rust1", since = "1.0.0")]
1623 impl<T: PartialOrd> PartialOrd for Vec<T> {
1624 #[inline]
1625 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1626 PartialOrd::partial_cmp(&**self, &**other)
1627 }
1628 }
1629
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<T: Eq> Eq for Vec<T> {}
1632
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 impl<T: Ord> Ord for Vec<T> {
1635 #[inline]
1636 fn cmp(&self, other: &Vec<T>) -> Ordering {
1637 Ord::cmp(&**self, &**other)
1638 }
1639 }
1640
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<T> Drop for Vec<T> {
1643 #[unsafe_destructor_blind_to_params]
1644 fn drop(&mut self) {
1645 unsafe {
1646 // use drop for [T]
1647 ptr::drop_in_place(&mut self[..]);
1648 }
1649 // RawVec handles deallocation
1650 }
1651 }
1652
1653 #[stable(feature = "rust1", since = "1.0.0")]
1654 impl<T> Default for Vec<T> {
1655 /// Creates an empty `Vec<T>`.
1656 fn default() -> Vec<T> {
1657 Vec::new()
1658 }
1659 }
1660
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1663 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1664 fmt::Debug::fmt(&**self, f)
1665 }
1666 }
1667
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<T> AsRef<Vec<T>> for Vec<T> {
1670 fn as_ref(&self) -> &Vec<T> {
1671 self
1672 }
1673 }
1674
1675 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1676 impl<T> AsMut<Vec<T>> for Vec<T> {
1677 fn as_mut(&mut self) -> &mut Vec<T> {
1678 self
1679 }
1680 }
1681
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 impl<T> AsRef<[T]> for Vec<T> {
1684 fn as_ref(&self) -> &[T] {
1685 self
1686 }
1687 }
1688
1689 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1690 impl<T> AsMut<[T]> for Vec<T> {
1691 fn as_mut(&mut self) -> &mut [T] {
1692 self
1693 }
1694 }
1695
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1698 #[cfg(not(test))]
1699 fn from(s: &'a [T]) -> Vec<T> {
1700 s.to_vec()
1701 }
1702 #[cfg(test)]
1703 fn from(s: &'a [T]) -> Vec<T> {
1704 ::slice::to_vec(s)
1705 }
1706 }
1707
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<'a> From<&'a str> for Vec<u8> {
1710 fn from(s: &'a str) -> Vec<u8> {
1711 From::from(s.as_bytes())
1712 }
1713 }
1714
1715 ////////////////////////////////////////////////////////////////////////////////
1716 // Clone-on-write
1717 ////////////////////////////////////////////////////////////////////////////////
1718
1719 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1720 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1721 fn from(s: &'a [T]) -> Cow<'a, [T]> {
1722 Cow::Borrowed(s)
1723 }
1724 }
1725
1726 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1727 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1728 fn from(v: Vec<T>) -> Cow<'a, [T]> {
1729 Cow::Owned(v)
1730 }
1731 }
1732
1733 #[stable(feature = "rust1", since = "1.0.0")]
1734 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1735 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1736 Cow::Owned(FromIterator::from_iter(it))
1737 }
1738 }
1739
1740 ////////////////////////////////////////////////////////////////////////////////
1741 // Iterators
1742 ////////////////////////////////////////////////////////////////////////////////
1743
1744 /// An iterator that moves out of a vector.
1745 ///
1746 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
1747 /// by the [`IntoIterator`] trait).
1748 ///
1749 /// [`Vec`]: struct.Vec.html
1750 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub struct IntoIter<T> {
1753 buf: Shared<T>,
1754 cap: usize,
1755 ptr: *const T,
1756 end: *const T,
1757 }
1758
1759 #[stable(feature = "vec_intoiter_debug", since = "")]
1760 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1762 f.debug_tuple("IntoIter")
1763 .field(&self.as_slice())
1764 .finish()
1765 }
1766 }
1767
1768 impl<T> IntoIter<T> {
1769 /// Returns the remaining items of this iterator as a slice.
1770 ///
1771 /// # Examples
1772 ///
1773 /// ```rust
1774 /// # #![feature(vec_into_iter_as_slice)]
1775 /// let vec = vec!['a', 'b', 'c'];
1776 /// let mut into_iter = vec.into_iter();
1777 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1778 /// let _ = into_iter.next().unwrap();
1779 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
1780 /// ```
1781 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1782 pub fn as_slice(&self) -> &[T] {
1783 unsafe {
1784 slice::from_raw_parts(self.ptr, self.len())
1785 }
1786 }
1787
1788 /// Returns the remaining items of this iterator as a mutable slice.
1789 ///
1790 /// # Examples
1791 ///
1792 /// ```rust
1793 /// # #![feature(vec_into_iter_as_slice)]
1794 /// let vec = vec!['a', 'b', 'c'];
1795 /// let mut into_iter = vec.into_iter();
1796 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1797 /// into_iter.as_mut_slice()[2] = 'z';
1798 /// assert_eq!(into_iter.next().unwrap(), 'a');
1799 /// assert_eq!(into_iter.next().unwrap(), 'b');
1800 /// assert_eq!(into_iter.next().unwrap(), 'z');
1801 /// ```
1802 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1803 pub fn as_mut_slice(&self) -> &mut [T] {
1804 unsafe {
1805 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
1806 }
1807 }
1808 }
1809
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 unsafe impl<T: Send> Send for IntoIter<T> {}
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1814
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<T> Iterator for IntoIter<T> {
1817 type Item = T;
1818
1819 #[inline]
1820 fn next(&mut self) -> Option<T> {
1821 unsafe {
1822 if self.ptr as *const _ == self.end {
1823 None
1824 } else {
1825 if mem::size_of::<T>() == 0 {
1826 // purposefully don't use 'ptr.offset' because for
1827 // vectors with 0-size elements this would return the
1828 // same pointer.
1829 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
1830
1831 // Use a non-null pointer value
1832 Some(ptr::read(EMPTY as *mut T))
1833 } else {
1834 let old = self.ptr;
1835 self.ptr = self.ptr.offset(1);
1836
1837 Some(ptr::read(old))
1838 }
1839 }
1840 }
1841 }
1842
1843 #[inline]
1844 fn size_hint(&self) -> (usize, Option<usize>) {
1845 let diff = (self.end as usize) - (self.ptr as usize);
1846 let size = mem::size_of::<T>();
1847 let exact = diff /
1848 (if size == 0 {
1849 1
1850 } else {
1851 size
1852 });
1853 (exact, Some(exact))
1854 }
1855
1856 #[inline]
1857 fn count(self) -> usize {
1858 self.len()
1859 }
1860 }
1861
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<T> DoubleEndedIterator for IntoIter<T> {
1864 #[inline]
1865 fn next_back(&mut self) -> Option<T> {
1866 unsafe {
1867 if self.end == self.ptr {
1868 None
1869 } else {
1870 if mem::size_of::<T>() == 0 {
1871 // See above for why 'ptr.offset' isn't used
1872 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
1873
1874 // Use a non-null pointer value
1875 Some(ptr::read(EMPTY as *mut T))
1876 } else {
1877 self.end = self.end.offset(-1);
1878
1879 Some(ptr::read(self.end))
1880 }
1881 }
1882 }
1883 }
1884 }
1885
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<T> ExactSizeIterator for IntoIter<T> {}
1888
1889 #[unstable(feature = "fused", issue = "35602")]
1890 impl<T> FusedIterator for IntoIter<T> {}
1891
1892 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1893 impl<T: Clone> Clone for IntoIter<T> {
1894 fn clone(&self) -> IntoIter<T> {
1895 self.as_slice().to_owned().into_iter()
1896 }
1897 }
1898
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<T> Drop for IntoIter<T> {
1901 #[unsafe_destructor_blind_to_params]
1902 fn drop(&mut self) {
1903 // destroy the remaining elements
1904 for _x in self.by_ref() {}
1905
1906 // RawVec handles deallocation
1907 let _ = unsafe { RawVec::from_raw_parts(*self.buf, self.cap) };
1908 }
1909 }
1910
1911 /// A draining iterator for `Vec<T>`.
1912 ///
1913 /// This `struct` is created by the [`drain`] method on [`Vec`].
1914 ///
1915 /// [`drain`]: struct.Vec.html#method.drain
1916 /// [`Vec`]: struct.Vec.html
1917 #[stable(feature = "drain", since = "1.6.0")]
1918 pub struct Drain<'a, T: 'a> {
1919 /// Index of tail to preserve
1920 tail_start: usize,
1921 /// Length of tail
1922 tail_len: usize,
1923 /// Current remaining range to remove
1924 iter: slice::Iter<'a, T>,
1925 vec: Shared<Vec<T>>,
1926 }
1927
1928 #[stable(feature = "drain", since = "1.6.0")]
1929 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1930 #[stable(feature = "drain", since = "1.6.0")]
1931 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1932
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<'a, T> Iterator for Drain<'a, T> {
1935 type Item = T;
1936
1937 #[inline]
1938 fn next(&mut self) -> Option<T> {
1939 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1940 }
1941
1942 fn size_hint(&self) -> (usize, Option<usize>) {
1943 self.iter.size_hint()
1944 }
1945 }
1946
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1949 #[inline]
1950 fn next_back(&mut self) -> Option<T> {
1951 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1952 }
1953 }
1954
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<'a, T> Drop for Drain<'a, T> {
1957 fn drop(&mut self) {
1958 // exhaust self first
1959 while let Some(_) = self.next() {}
1960
1961 if self.tail_len > 0 {
1962 unsafe {
1963 let source_vec = &mut **self.vec;
1964 // memmove back untouched tail, update to new length
1965 let start = source_vec.len();
1966 let tail = self.tail_start;
1967 let src = source_vec.as_ptr().offset(tail as isize);
1968 let dst = source_vec.as_mut_ptr().offset(start as isize);
1969 ptr::copy(src, dst, self.tail_len);
1970 source_vec.set_len(start + self.tail_len);
1971 }
1972 }
1973 }
1974 }
1975
1976
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1979
1980 #[unstable(feature = "fused", issue = "35602")]
1981 impl<'a, T> FusedIterator for Drain<'a, T> {}