]> git.proxmox.com Git - rustc.git/blob - src/libcollections/vec.rs
3ef8438bc0bd23c6cea5bd2a0fe41b42f3da0a4a
[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 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
61 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
62 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
63 //! [`Index`]: ../../std/ops/trait.Index.html
64 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
65 //! [`vec!`]: ../../std/macro.vec.html
66
67 #![stable(feature = "rust1", since = "1.0.0")]
68
69 use alloc::boxed::Box;
70 use alloc::raw_vec::RawVec;
71 use borrow::ToOwned;
72 use borrow::Cow;
73 use core::cmp::Ordering;
74 use core::fmt;
75 use core::hash::{self, Hash};
76 use core::intrinsics::{arith_offset, assume};
77 use core::iter::{FromIterator, FusedIterator, TrustedLen};
78 use core::mem;
79 #[cfg(not(test))]
80 use core::num::Float;
81 use core::ops::{InPlace, Index, IndexMut, Place, Placer};
82 use core::ops;
83 use core::ptr;
84 use core::ptr::Shared;
85 use core::slice;
86
87 use super::range::RangeArgument;
88 use Bound::{Excluded, Included, Unbounded};
89
90 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
91 ///
92 /// # Examples
93 ///
94 /// ```
95 /// let mut vec = Vec::new();
96 /// vec.push(1);
97 /// vec.push(2);
98 ///
99 /// assert_eq!(vec.len(), 2);
100 /// assert_eq!(vec[0], 1);
101 ///
102 /// assert_eq!(vec.pop(), Some(2));
103 /// assert_eq!(vec.len(), 1);
104 ///
105 /// vec[0] = 7;
106 /// assert_eq!(vec[0], 7);
107 ///
108 /// vec.extend([1, 2, 3].iter().cloned());
109 ///
110 /// for x in &vec {
111 /// println!("{}", x);
112 /// }
113 /// assert_eq!(vec, [7, 1, 2, 3]);
114 /// ```
115 ///
116 /// The [`vec!`] macro is provided to make initialization more convenient:
117 ///
118 /// ```
119 /// let mut vec = vec![1, 2, 3];
120 /// vec.push(4);
121 /// assert_eq!(vec, [1, 2, 3, 4]);
122 /// ```
123 ///
124 /// It can also initialize each element of a `Vec<T>` with a given value:
125 ///
126 /// ```
127 /// let vec = vec![0; 5];
128 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
129 /// ```
130 ///
131 /// Use a `Vec<T>` as an efficient stack:
132 ///
133 /// ```
134 /// let mut stack = Vec::new();
135 ///
136 /// stack.push(1);
137 /// stack.push(2);
138 /// stack.push(3);
139 ///
140 /// while let Some(top) = stack.pop() {
141 /// // Prints 3, 2, 1
142 /// println!("{}", top);
143 /// }
144 /// ```
145 ///
146 /// # Indexing
147 ///
148 /// The `Vec` type allows to access values by index, because it implements the
149 /// [`Index`] trait. An example will be more explicit:
150 ///
151 /// ```
152 /// let v = vec![0, 2, 4, 6];
153 /// println!("{}", v[1]); // it will display '2'
154 /// ```
155 ///
156 /// However be careful: if you try to access an index which isn't in the `Vec`,
157 /// your software will panic! You cannot do this:
158 ///
159 /// ```ignore
160 /// let v = vec![0, 2, 4, 6];
161 /// println!("{}", v[6]); // it will panic!
162 /// ```
163 ///
164 /// In conclusion: always check if the index you want to get really exists
165 /// before doing it.
166 ///
167 /// # Slicing
168 ///
169 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
170 /// To get a slice, use `&`. Example:
171 ///
172 /// ```
173 /// fn read_slice(slice: &[usize]) {
174 /// // ...
175 /// }
176 ///
177 /// let v = vec![0, 1];
178 /// read_slice(&v);
179 ///
180 /// // ... and that's all!
181 /// // you can also do it like this:
182 /// let x : &[usize] = &v;
183 /// ```
184 ///
185 /// In Rust, it's more common to pass slices as arguments rather than vectors
186 /// when you just want to provide a read access. The same goes for [`String`] and
187 /// [`&str`].
188 ///
189 /// # Capacity and reallocation
190 ///
191 /// The capacity of a vector is the amount of space allocated for any future
192 /// elements that will be added onto the vector. This is not to be confused with
193 /// the *length* of a vector, which specifies the number of actual elements
194 /// within the vector. If a vector's length exceeds its capacity, its capacity
195 /// will automatically be increased, but its elements will have to be
196 /// reallocated.
197 ///
198 /// For example, a vector with capacity 10 and length 0 would be an empty vector
199 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
200 /// vector will not change its capacity or cause reallocation to occur. However,
201 /// if the vector's length is increased to 11, it will have to reallocate, which
202 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
203 /// whenever possible to specify how big the vector is expected to get.
204 ///
205 /// # Guarantees
206 ///
207 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
208 /// about its design. This ensures that it's as low-overhead as possible in
209 /// the general case, and can be correctly manipulated in primitive ways
210 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
211 /// If additional type parameters are added (e.g. to support custom allocators),
212 /// overriding their defaults may change the behavior.
213 ///
214 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
215 /// triplet. No more, no less. The order of these fields is completely
216 /// unspecified, and you should use the appropriate methods to modify these.
217 /// The pointer will never be null, so this type is null-pointer-optimized.
218 ///
219 /// However, the pointer may not actually point to allocated memory. In particular,
220 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
221 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
222 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
223 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
224 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
225 /// if [`mem::size_of::<T>`]` * capacity() > 0`. In general, `Vec`'s allocation
226 /// details are subtle enough that it is strongly recommended that you only
227 /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it.
228 ///
229 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
230 /// (as defined by the allocator Rust is configured to use by default), and its
231 /// pointer points to [`len`] initialized elements in order (what you would see
232 /// if you coerced it to a slice), followed by [`capacity`]` - `[`len`]
233 /// logically uninitialized elements.
234 ///
235 /// `Vec` will never perform a "small optimization" where elements are actually
236 /// stored on the stack for two reasons:
237 ///
238 /// * It would make it more difficult for unsafe code to correctly manipulate
239 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
240 /// only moved, and it would be more difficult to determine if a `Vec` had
241 /// actually allocated memory.
242 ///
243 /// * It would penalize the general case, incurring an additional branch
244 /// on every access.
245 ///
246 /// `Vec` will never automatically shrink itself, even if completely empty. This
247 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
248 /// and then filling it back up to the same [`len`] should incur no calls to
249 /// the allocator. If you wish to free up unused memory, use
250 /// [`shrink_to_fit`][`shrink_to_fit`].
251 ///
252 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
253 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
254 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
255 /// accurate, and can be relied on. It can even be used to manually free the memory
256 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
257 /// when not necessary.
258 ///
259 /// `Vec` does not guarantee any particular growth strategy when reallocating
260 /// when full, nor when [`reserve`] is called. The current strategy is basic
261 /// and it may prove desirable to use a non-constant growth factor. Whatever
262 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
263 ///
264 /// `vec![x; n]`, `vec![a, b, c, d]`, and
265 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
266 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
267 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
268 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
269 ///
270 /// `Vec` will not specifically overwrite any data that is removed from it,
271 /// but also won't specifically preserve it. Its uninitialized memory is
272 /// scratch space that it may use however it wants. It will generally just do
273 /// whatever is most efficient or otherwise easy to implement. Do not rely on
274 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
275 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
276 /// first, that may not actually happen because the optimizer does not consider
277 /// this a side-effect that must be preserved. There is one case which we will
278 /// not break, however: using `unsafe` code to write to the excess capacity,
279 /// and then increasing the length to match, is always valid.
280 ///
281 /// `Vec` does not currently guarantee the order in which elements are dropped
282 /// (the order has changed in the past, and may change again).
283 ///
284 /// [`vec!`]: ../../std/macro.vec.html
285 /// [`Index`]: ../../std/ops/trait.Index.html
286 /// [`String`]: ../../std/string/struct.String.html
287 /// [`&str`]: ../../std/primitive.str.html
288 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
289 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
290 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
291 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
292 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
293 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
294 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
295 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
296 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
297 /// [owned slice]: ../../std/boxed/struct.Box.html
298 #[stable(feature = "rust1", since = "1.0.0")]
299 pub struct Vec<T> {
300 buf: RawVec<T>,
301 len: usize,
302 }
303
304 ////////////////////////////////////////////////////////////////////////////////
305 // Inherent methods
306 ////////////////////////////////////////////////////////////////////////////////
307
308 impl<T> Vec<T> {
309 /// Constructs a new, empty `Vec<T>`.
310 ///
311 /// The vector will not allocate until elements are pushed onto it.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// # #![allow(unused_mut)]
317 /// let mut vec: Vec<i32> = Vec::new();
318 /// ```
319 #[inline]
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn new() -> Vec<T> {
322 Vec {
323 buf: RawVec::new(),
324 len: 0,
325 }
326 }
327
328 /// Constructs a new, empty `Vec<T>` with the specified capacity.
329 ///
330 /// The vector will be able to hold exactly `capacity` elements without
331 /// reallocating. If `capacity` is 0, the vector will not allocate.
332 ///
333 /// It is important to note that this function does not specify the *length*
334 /// of the returned vector, but only the *capacity*. For an explanation of
335 /// the difference between length and capacity, see *[Capacity and reallocation]*.
336 ///
337 /// [Capacity and reallocation]: #capacity-and-reallocation
338 ///
339 /// # Examples
340 ///
341 /// ```
342 /// let mut vec = Vec::with_capacity(10);
343 ///
344 /// // The vector contains no items, even though it has capacity for more
345 /// assert_eq!(vec.len(), 0);
346 ///
347 /// // These are all done without reallocating...
348 /// for i in 0..10 {
349 /// vec.push(i);
350 /// }
351 ///
352 /// // ...but this may make the vector reallocate
353 /// vec.push(11);
354 /// ```
355 #[inline]
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn with_capacity(capacity: usize) -> Vec<T> {
358 Vec {
359 buf: RawVec::with_capacity(capacity),
360 len: 0,
361 }
362 }
363
364 /// Creates a `Vec<T>` directly from the raw components of another vector.
365 ///
366 /// # Safety
367 ///
368 /// This is highly unsafe, due to the number of invariants that aren't
369 /// checked:
370 ///
371 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
372 /// (at least, it's highly likely to be incorrect if it wasn't).
373 /// * `length` needs to be less than or equal to `capacity`.
374 /// * `capacity` needs to be the capacity that the pointer was allocated with.
375 ///
376 /// Violating these may cause problems like corrupting the allocator's
377 /// internal datastructures. For example it is **not** safe
378 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
379 ///
380 /// The ownership of `ptr` is effectively transferred to the
381 /// `Vec<T>` which may then deallocate, reallocate or change the
382 /// contents of memory pointed to by the pointer at will. Ensure
383 /// that nothing else uses the pointer after calling this
384 /// function.
385 ///
386 /// [`String`]: ../../std/string/struct.String.html
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use std::ptr;
392 /// use std::mem;
393 ///
394 /// fn main() {
395 /// let mut v = vec![1, 2, 3];
396 ///
397 /// // Pull out the various important pieces of information about `v`
398 /// let p = v.as_mut_ptr();
399 /// let len = v.len();
400 /// let cap = v.capacity();
401 ///
402 /// unsafe {
403 /// // Cast `v` into the void: no destructor run, so we are in
404 /// // complete control of the allocation to which `p` points.
405 /// mem::forget(v);
406 ///
407 /// // Overwrite memory with 4, 5, 6
408 /// for i in 0..len as isize {
409 /// ptr::write(p.offset(i), 4 + i);
410 /// }
411 ///
412 /// // Put everything back together into a Vec
413 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
414 /// assert_eq!(rebuilt, [4, 5, 6]);
415 /// }
416 /// }
417 /// ```
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
420 Vec {
421 buf: RawVec::from_raw_parts(ptr, capacity),
422 len: length,
423 }
424 }
425
426 /// Returns the number of elements the vector can hold without
427 /// reallocating.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// let vec: Vec<i32> = Vec::with_capacity(10);
433 /// assert_eq!(vec.capacity(), 10);
434 /// ```
435 #[inline]
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn capacity(&self) -> usize {
438 self.buf.cap()
439 }
440
441 /// Reserves capacity for at least `additional` more elements to be inserted
442 /// in the given `Vec<T>`. The collection may reserve more space to avoid
443 /// frequent reallocations. After calling `reserve`, capacity will be
444 /// greater than or equal to `self.len() + additional`. Does nothing if
445 /// capacity is already sufficient.
446 ///
447 /// # Panics
448 ///
449 /// Panics if the new capacity overflows `usize`.
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// let mut vec = vec![1];
455 /// vec.reserve(10);
456 /// assert!(vec.capacity() >= 11);
457 /// ```
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn reserve(&mut self, additional: usize) {
460 self.buf.reserve(self.len, additional);
461 }
462
463 /// Reserves the minimum capacity for exactly `additional` more elements to
464 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
465 /// capacity will be greater than or equal to `self.len() + additional`.
466 /// Does nothing if the capacity is already sufficient.
467 ///
468 /// Note that the allocator may give the collection more space than it
469 /// requests. Therefore capacity can not be relied upon to be precisely
470 /// minimal. Prefer `reserve` if future insertions are expected.
471 ///
472 /// # Panics
473 ///
474 /// Panics if the new capacity overflows `usize`.
475 ///
476 /// # Examples
477 ///
478 /// ```
479 /// let mut vec = vec![1];
480 /// vec.reserve_exact(10);
481 /// assert!(vec.capacity() >= 11);
482 /// ```
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn reserve_exact(&mut self, additional: usize) {
485 self.buf.reserve_exact(self.len, additional);
486 }
487
488 /// Shrinks the capacity of the vector as much as possible.
489 ///
490 /// It will drop down as close as possible to the length but the allocator
491 /// may still inform the vector that there is space for a few more elements.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// let mut vec = Vec::with_capacity(10);
497 /// vec.extend([1, 2, 3].iter().cloned());
498 /// assert_eq!(vec.capacity(), 10);
499 /// vec.shrink_to_fit();
500 /// assert!(vec.capacity() >= 3);
501 /// ```
502 #[stable(feature = "rust1", since = "1.0.0")]
503 pub fn shrink_to_fit(&mut self) {
504 self.buf.shrink_to_fit(self.len);
505 }
506
507 /// Converts the vector into [`Box<[T]>`][owned slice].
508 ///
509 /// Note that this will drop any excess capacity. Calling this and
510 /// converting back to a vector with [`into_vec`] is equivalent to calling
511 /// [`shrink_to_fit`].
512 ///
513 /// [owned slice]: ../../std/boxed/struct.Box.html
514 /// [`into_vec`]: ../../std/primitive.slice.html#method.into_vec
515 /// [`shrink_to_fit`]: #method.shrink_to_fit
516 ///
517 /// # Examples
518 ///
519 /// ```
520 /// let v = vec![1, 2, 3];
521 ///
522 /// let slice = v.into_boxed_slice();
523 /// ```
524 ///
525 /// Any excess capacity is removed:
526 ///
527 /// ```
528 /// let mut vec = Vec::with_capacity(10);
529 /// vec.extend([1, 2, 3].iter().cloned());
530 ///
531 /// assert_eq!(vec.capacity(), 10);
532 /// let slice = vec.into_boxed_slice();
533 /// assert_eq!(slice.into_vec().capacity(), 3);
534 /// ```
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn into_boxed_slice(mut self) -> Box<[T]> {
537 unsafe {
538 self.shrink_to_fit();
539 let buf = ptr::read(&self.buf);
540 mem::forget(self);
541 buf.into_box()
542 }
543 }
544
545 /// Shortens the vector, keeping the first `len` elements and dropping
546 /// the rest.
547 ///
548 /// If `len` is greater than the vector's current length, this has no
549 /// effect.
550 ///
551 /// The [`drain`] method can emulate `truncate`, but causes the excess
552 /// elements to be returned instead of dropped.
553 ///
554 /// Note that this method has no effect on the allocated capacity
555 /// of the vector.
556 ///
557 /// # Examples
558 ///
559 /// Truncating a five element vector to two elements:
560 ///
561 /// ```
562 /// let mut vec = vec![1, 2, 3, 4, 5];
563 /// vec.truncate(2);
564 /// assert_eq!(vec, [1, 2]);
565 /// ```
566 ///
567 /// No truncation occurs when `len` is greater than the vector's current
568 /// length:
569 ///
570 /// ```
571 /// let mut vec = vec![1, 2, 3];
572 /// vec.truncate(8);
573 /// assert_eq!(vec, [1, 2, 3]);
574 /// ```
575 ///
576 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
577 /// method.
578 ///
579 /// ```
580 /// let mut vec = vec![1, 2, 3];
581 /// vec.truncate(0);
582 /// assert_eq!(vec, []);
583 /// ```
584 ///
585 /// [`clear`]: #method.clear
586 /// [`drain`]: #method.drain
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn truncate(&mut self, len: usize) {
589 unsafe {
590 // drop any extra elements
591 while len < self.len {
592 // decrement len before the drop_in_place(), so a panic on Drop
593 // doesn't re-drop the just-failed value.
594 self.len -= 1;
595 let len = self.len;
596 ptr::drop_in_place(self.get_unchecked_mut(len));
597 }
598 }
599 }
600
601 /// Extracts a slice containing the entire vector.
602 ///
603 /// Equivalent to `&s[..]`.
604 ///
605 /// # Examples
606 ///
607 /// ```
608 /// use std::io::{self, Write};
609 /// let buffer = vec![1, 2, 3, 5, 8];
610 /// io::sink().write(buffer.as_slice()).unwrap();
611 /// ```
612 #[inline]
613 #[stable(feature = "vec_as_slice", since = "1.7.0")]
614 pub fn as_slice(&self) -> &[T] {
615 self
616 }
617
618 /// Extracts a mutable slice of the entire vector.
619 ///
620 /// Equivalent to `&mut s[..]`.
621 ///
622 /// # Examples
623 ///
624 /// ```
625 /// use std::io::{self, Read};
626 /// let mut buffer = vec![0; 3];
627 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
628 /// ```
629 #[inline]
630 #[stable(feature = "vec_as_slice", since = "1.7.0")]
631 pub fn as_mut_slice(&mut self) -> &mut [T] {
632 self
633 }
634
635 /// Sets the length of a vector.
636 ///
637 /// This will explicitly set the size of the vector, without actually
638 /// modifying its buffers, so it is up to the caller to ensure that the
639 /// vector is actually the specified size.
640 ///
641 /// # Examples
642 ///
643 /// ```
644 /// use std::ptr;
645 ///
646 /// let mut vec = vec!['r', 'u', 's', 't'];
647 ///
648 /// unsafe {
649 /// ptr::drop_in_place(&mut vec[3]);
650 /// vec.set_len(3);
651 /// }
652 /// assert_eq!(vec, ['r', 'u', 's']);
653 /// ```
654 ///
655 /// In this example, there is a memory leak since the memory locations
656 /// owned by the inner vectors were not freed prior to the `set_len` call:
657 ///
658 /// ```
659 /// let mut vec = vec![vec![1, 0, 0],
660 /// vec![0, 1, 0],
661 /// vec![0, 0, 1]];
662 /// unsafe {
663 /// vec.set_len(0);
664 /// }
665 /// ```
666 ///
667 /// In this example, the vector gets expanded from zero to four items
668 /// without any memory allocations occurring, resulting in vector
669 /// values of unallocated memory:
670 ///
671 /// ```
672 /// let mut vec: Vec<char> = Vec::new();
673 ///
674 /// unsafe {
675 /// vec.set_len(4);
676 /// }
677 /// ```
678 #[inline]
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub unsafe fn set_len(&mut self, len: usize) {
681 self.len = len;
682 }
683
684 /// Removes an element from the vector and returns it.
685 ///
686 /// The removed element is replaced by the last element of the vector.
687 ///
688 /// This does not preserve ordering, but is O(1).
689 ///
690 /// # Panics
691 ///
692 /// Panics if `index` is out of bounds.
693 ///
694 /// # Examples
695 ///
696 /// ```
697 /// let mut v = vec!["foo", "bar", "baz", "qux"];
698 ///
699 /// assert_eq!(v.swap_remove(1), "bar");
700 /// assert_eq!(v, ["foo", "qux", "baz"]);
701 ///
702 /// assert_eq!(v.swap_remove(0), "foo");
703 /// assert_eq!(v, ["baz", "qux"]);
704 /// ```
705 #[inline]
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn swap_remove(&mut self, index: usize) -> T {
708 let length = self.len();
709 self.swap(index, length - 1);
710 self.pop().unwrap()
711 }
712
713 /// Inserts an element at position `index` within the vector, shifting all
714 /// elements after it to the right.
715 ///
716 /// # Panics
717 ///
718 /// Panics if `index` is out of bounds.
719 ///
720 /// # Examples
721 ///
722 /// ```
723 /// let mut vec = vec![1, 2, 3];
724 /// vec.insert(1, 4);
725 /// assert_eq!(vec, [1, 4, 2, 3]);
726 /// vec.insert(4, 5);
727 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
728 /// ```
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn insert(&mut self, index: usize, element: T) {
731 let len = self.len();
732 assert!(index <= len);
733
734 // space for the new element
735 if len == self.buf.cap() {
736 self.buf.double();
737 }
738
739 unsafe {
740 // infallible
741 // The spot to put the new value
742 {
743 let p = self.as_mut_ptr().offset(index as isize);
744 // Shift everything over to make space. (Duplicating the
745 // `index`th element into two consecutive places.)
746 ptr::copy(p, p.offset(1), len - index);
747 // Write it in, overwriting the first copy of the `index`th
748 // element.
749 ptr::write(p, element);
750 }
751 self.set_len(len + 1);
752 }
753 }
754
755 /// Removes and returns the element at position `index` within the vector,
756 /// shifting all elements after it to the left.
757 ///
758 /// # Panics
759 ///
760 /// Panics if `index` is out of bounds.
761 ///
762 /// # Examples
763 ///
764 /// ```
765 /// let mut v = vec![1, 2, 3];
766 /// assert_eq!(v.remove(1), 2);
767 /// assert_eq!(v, [1, 3]);
768 /// ```
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn remove(&mut self, index: usize) -> T {
771 let len = self.len();
772 assert!(index < len);
773 unsafe {
774 // infallible
775 let ret;
776 {
777 // the place we are taking from.
778 let ptr = self.as_mut_ptr().offset(index as isize);
779 // copy it out, unsafely having a copy of the value on
780 // the stack and in the vector at the same time.
781 ret = ptr::read(ptr);
782
783 // Shift everything down to fill in that spot.
784 ptr::copy(ptr.offset(1), ptr, len - index - 1);
785 }
786 self.set_len(len - 1);
787 ret
788 }
789 }
790
791 /// Retains only the elements specified by the predicate.
792 ///
793 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
794 /// This method operates in place and preserves the order of the retained
795 /// elements.
796 ///
797 /// # Examples
798 ///
799 /// ```
800 /// let mut vec = vec![1, 2, 3, 4];
801 /// vec.retain(|&x| x%2 == 0);
802 /// assert_eq!(vec, [2, 4]);
803 /// ```
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn retain<F>(&mut self, mut f: F)
806 where F: FnMut(&T) -> bool
807 {
808 let len = self.len();
809 let mut del = 0;
810 {
811 let v = &mut **self;
812
813 for i in 0..len {
814 if !f(&v[i]) {
815 del += 1;
816 } else if del > 0 {
817 v.swap(i - del, i);
818 }
819 }
820 }
821 if del > 0 {
822 self.truncate(len - del);
823 }
824 }
825
826 /// Removes consecutive elements in the vector that resolve to the same key.
827 ///
828 /// If the vector is sorted, this removes all duplicates.
829 ///
830 /// # Examples
831 ///
832 /// ```
833 /// let mut vec = vec![10, 20, 21, 30, 20];
834 ///
835 /// vec.dedup_by_key(|i| *i / 10);
836 ///
837 /// assert_eq!(vec, [10, 20, 30, 20]);
838 /// ```
839 #[stable(feature = "dedup_by", since = "1.16.0")]
840 #[inline]
841 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
842 self.dedup_by(|a, b| key(a) == key(b))
843 }
844
845 /// Removes consecutive elements in the vector according to a predicate.
846 ///
847 /// The `same_bucket` function is passed references to two elements from the vector, and
848 /// returns `true` if the elements compare equal, or `false` if they do not. Only the first
849 /// of adjacent equal items is kept.
850 ///
851 /// If the vector is sorted, this removes all duplicates.
852 ///
853 /// # Examples
854 ///
855 /// ```
856 /// use std::ascii::AsciiExt;
857 ///
858 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
859 ///
860 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
861 ///
862 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
863 /// ```
864 #[stable(feature = "dedup_by", since = "1.16.0")]
865 pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
866 unsafe {
867 // Although we have a mutable reference to `self`, we cannot make
868 // *arbitrary* changes. The `same_bucket` calls could panic, so we
869 // must ensure that the vector is in a valid state at all time.
870 //
871 // The way that we handle this is by using swaps; we iterate
872 // over all the elements, swapping as we go so that at the end
873 // the elements we wish to keep are in the front, and those we
874 // wish to reject are at the back. We can then truncate the
875 // vector. This operation is still O(n).
876 //
877 // Example: We start in this state, where `r` represents "next
878 // read" and `w` represents "next_write`.
879 //
880 // r
881 // +---+---+---+---+---+---+
882 // | 0 | 1 | 1 | 2 | 3 | 3 |
883 // +---+---+---+---+---+---+
884 // w
885 //
886 // Comparing self[r] against self[w-1], this is not a duplicate, so
887 // we swap self[r] and self[w] (no effect as r==w) and then increment both
888 // r and w, leaving us with:
889 //
890 // r
891 // +---+---+---+---+---+---+
892 // | 0 | 1 | 1 | 2 | 3 | 3 |
893 // +---+---+---+---+---+---+
894 // w
895 //
896 // Comparing self[r] against self[w-1], this value is a duplicate,
897 // so we increment `r` but leave everything else unchanged:
898 //
899 // r
900 // +---+---+---+---+---+---+
901 // | 0 | 1 | 1 | 2 | 3 | 3 |
902 // +---+---+---+---+---+---+
903 // w
904 //
905 // Comparing self[r] against self[w-1], this is not a duplicate,
906 // so swap self[r] and self[w] and advance r and w:
907 //
908 // r
909 // +---+---+---+---+---+---+
910 // | 0 | 1 | 2 | 1 | 3 | 3 |
911 // +---+---+---+---+---+---+
912 // w
913 //
914 // Not a duplicate, repeat:
915 //
916 // r
917 // +---+---+---+---+---+---+
918 // | 0 | 1 | 2 | 3 | 1 | 3 |
919 // +---+---+---+---+---+---+
920 // w
921 //
922 // Duplicate, advance r. End of vec. Truncate to w.
923
924 let ln = self.len();
925 if ln <= 1 {
926 return;
927 }
928
929 // Avoid bounds checks by using raw pointers.
930 let p = self.as_mut_ptr();
931 let mut r: usize = 1;
932 let mut w: usize = 1;
933
934 while r < ln {
935 let p_r = p.offset(r as isize);
936 let p_wm1 = p.offset((w - 1) as isize);
937 if !same_bucket(&mut *p_r, &mut *p_wm1) {
938 if r != w {
939 let p_w = p_wm1.offset(1);
940 mem::swap(&mut *p_r, &mut *p_w);
941 }
942 w += 1;
943 }
944 r += 1;
945 }
946
947 self.truncate(w);
948 }
949 }
950
951 /// Appends an element to the back of a collection.
952 ///
953 /// # Panics
954 ///
955 /// Panics if the number of elements in the vector overflows a `usize`.
956 ///
957 /// # Examples
958 ///
959 /// ```
960 /// let mut vec = vec![1, 2];
961 /// vec.push(3);
962 /// assert_eq!(vec, [1, 2, 3]);
963 /// ```
964 #[inline]
965 #[stable(feature = "rust1", since = "1.0.0")]
966 pub fn push(&mut self, value: T) {
967 // This will panic or abort if we would allocate > isize::MAX bytes
968 // or if the length increment would overflow for zero-sized types.
969 if self.len == self.buf.cap() {
970 self.buf.double();
971 }
972 unsafe {
973 let end = self.as_mut_ptr().offset(self.len as isize);
974 ptr::write(end, value);
975 self.len += 1;
976 }
977 }
978
979 /// Returns a place for insertion at the back of the `Vec`.
980 ///
981 /// Using this method with placement syntax is equivalent to [`push`](#method.push),
982 /// but may be more efficient.
983 ///
984 /// # Examples
985 ///
986 /// ```
987 /// #![feature(collection_placement)]
988 /// #![feature(placement_in_syntax)]
989 ///
990 /// let mut vec = vec![1, 2];
991 /// vec.place_back() <- 3;
992 /// vec.place_back() <- 4;
993 /// assert_eq!(&vec, &[1, 2, 3, 4]);
994 /// ```
995 #[unstable(feature = "collection_placement",
996 reason = "placement protocol is subject to change",
997 issue = "30172")]
998 pub fn place_back(&mut self) -> PlaceBack<T> {
999 PlaceBack { vec: self }
1000 }
1001
1002 /// Removes the last element from a vector and returns it, or [`None`] if it
1003 /// is empty.
1004 ///
1005 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1006 ///
1007 /// # Examples
1008 ///
1009 /// ```
1010 /// let mut vec = vec![1, 2, 3];
1011 /// assert_eq!(vec.pop(), Some(3));
1012 /// assert_eq!(vec, [1, 2]);
1013 /// ```
1014 #[inline]
1015 #[stable(feature = "rust1", since = "1.0.0")]
1016 pub fn pop(&mut self) -> Option<T> {
1017 if self.len == 0 {
1018 None
1019 } else {
1020 unsafe {
1021 self.len -= 1;
1022 Some(ptr::read(self.get_unchecked(self.len())))
1023 }
1024 }
1025 }
1026
1027 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1028 ///
1029 /// # Panics
1030 ///
1031 /// Panics if the number of elements in the vector overflows a `usize`.
1032 ///
1033 /// # Examples
1034 ///
1035 /// ```
1036 /// let mut vec = vec![1, 2, 3];
1037 /// let mut vec2 = vec![4, 5, 6];
1038 /// vec.append(&mut vec2);
1039 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1040 /// assert_eq!(vec2, []);
1041 /// ```
1042 #[inline]
1043 #[stable(feature = "append", since = "1.4.0")]
1044 pub fn append(&mut self, other: &mut Self) {
1045 unsafe {
1046 self.append_elements(other.as_slice() as _);
1047 other.set_len(0);
1048 }
1049 }
1050
1051 /// Appends elements to `Self` from other buffer.
1052 #[inline]
1053 unsafe fn append_elements(&mut self, other: *const [T]) {
1054 let count = (*other).len();
1055 self.reserve(count);
1056 let len = self.len();
1057 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1058 self.len += count;
1059 }
1060
1061 /// Creates a draining iterator that removes the specified range in the vector
1062 /// and yields the removed items.
1063 ///
1064 /// Note 1: The element range is removed even if the iterator is only
1065 /// partially consumed or not consumed at all.
1066 ///
1067 /// Note 2: It is unspecified how many elements are removed from the vector
1068 /// if the `Drain` value is leaked.
1069 ///
1070 /// # Panics
1071 ///
1072 /// Panics if the starting point is greater than the end point or if
1073 /// the end point is greater than the length of the vector.
1074 ///
1075 /// # Examples
1076 ///
1077 /// ```
1078 /// let mut v = vec![1, 2, 3];
1079 /// let u: Vec<_> = v.drain(1..).collect();
1080 /// assert_eq!(v, &[1]);
1081 /// assert_eq!(u, &[2, 3]);
1082 ///
1083 /// // A full range clears the vector
1084 /// v.drain(..);
1085 /// assert_eq!(v, &[]);
1086 /// ```
1087 #[stable(feature = "drain", since = "1.6.0")]
1088 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1089 where R: RangeArgument<usize>
1090 {
1091 // Memory safety
1092 //
1093 // When the Drain is first created, it shortens the length of
1094 // the source vector to make sure no uninitalized or moved-from elements
1095 // are accessible at all if the Drain's destructor never gets to run.
1096 //
1097 // Drain will ptr::read out the values to remove.
1098 // When finished, remaining tail of the vec is copied back to cover
1099 // the hole, and the vector length is restored to the new length.
1100 //
1101 let len = self.len();
1102 let start = match range.start() {
1103 Included(&n) => n,
1104 Excluded(&n) => n + 1,
1105 Unbounded => 0,
1106 };
1107 let end = match range.end() {
1108 Included(&n) => n + 1,
1109 Excluded(&n) => n,
1110 Unbounded => len,
1111 };
1112 assert!(start <= end);
1113 assert!(end <= len);
1114
1115 unsafe {
1116 // set self.vec length's to start, to be safe in case Drain is leaked
1117 self.set_len(start);
1118 // Use the borrow in the IterMut to indicate borrowing behavior of the
1119 // whole Drain iterator (like &mut T).
1120 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1121 end - start);
1122 Drain {
1123 tail_start: end,
1124 tail_len: len - end,
1125 iter: range_slice.iter(),
1126 vec: Shared::new(self as *mut _),
1127 }
1128 }
1129 }
1130
1131 /// Clears the vector, removing all values.
1132 ///
1133 /// Note that this method has no effect on the allocated capacity
1134 /// of the vector.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// let mut v = vec![1, 2, 3];
1140 ///
1141 /// v.clear();
1142 ///
1143 /// assert!(v.is_empty());
1144 /// ```
1145 #[inline]
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 pub fn clear(&mut self) {
1148 self.truncate(0)
1149 }
1150
1151 /// Returns the number of elements in the vector, also referred to
1152 /// as its 'length'.
1153 ///
1154 /// # Examples
1155 ///
1156 /// ```
1157 /// let a = vec![1, 2, 3];
1158 /// assert_eq!(a.len(), 3);
1159 /// ```
1160 #[inline]
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 pub fn len(&self) -> usize {
1163 self.len
1164 }
1165
1166 /// Returns `true` if the vector contains no elements.
1167 ///
1168 /// # Examples
1169 ///
1170 /// ```
1171 /// let mut v = Vec::new();
1172 /// assert!(v.is_empty());
1173 ///
1174 /// v.push(1);
1175 /// assert!(!v.is_empty());
1176 /// ```
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub fn is_empty(&self) -> bool {
1179 self.len() == 0
1180 }
1181
1182 /// Splits the collection into two at the given index.
1183 ///
1184 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1185 /// and the returned `Self` contains elements `[at, len)`.
1186 ///
1187 /// Note that the capacity of `self` does not change.
1188 ///
1189 /// # Panics
1190 ///
1191 /// Panics if `at > len`.
1192 ///
1193 /// # Examples
1194 ///
1195 /// ```
1196 /// let mut vec = vec![1,2,3];
1197 /// let vec2 = vec.split_off(1);
1198 /// assert_eq!(vec, [1]);
1199 /// assert_eq!(vec2, [2, 3]);
1200 /// ```
1201 #[inline]
1202 #[stable(feature = "split_off", since = "1.4.0")]
1203 pub fn split_off(&mut self, at: usize) -> Self {
1204 assert!(at <= self.len(), "`at` out of bounds");
1205
1206 let other_len = self.len - at;
1207 let mut other = Vec::with_capacity(other_len);
1208
1209 // Unsafely `set_len` and copy items to `other`.
1210 unsafe {
1211 self.set_len(at);
1212 other.set_len(other_len);
1213
1214 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1215 other.as_mut_ptr(),
1216 other.len());
1217 }
1218 other
1219 }
1220 }
1221
1222 impl<T: Clone> Vec<T> {
1223 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1224 ///
1225 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1226 /// difference, with each additional slot filled with `value`.
1227 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1228 ///
1229 /// This method requires `Clone` to clone the passed value. If you'd
1230 /// rather create a value with `Default` instead, see [`resize_default`].
1231 ///
1232 /// # Examples
1233 ///
1234 /// ```
1235 /// let mut vec = vec!["hello"];
1236 /// vec.resize(3, "world");
1237 /// assert_eq!(vec, ["hello", "world", "world"]);
1238 ///
1239 /// let mut vec = vec![1, 2, 3, 4];
1240 /// vec.resize(2, 0);
1241 /// assert_eq!(vec, [1, 2]);
1242 /// ```
1243 ///
1244 /// [`resize_default`]: #method.resize_default
1245 #[stable(feature = "vec_resize", since = "1.5.0")]
1246 pub fn resize(&mut self, new_len: usize, value: T) {
1247 let len = self.len();
1248
1249 if new_len > len {
1250 self.extend_with(new_len - len, ExtendElement(value))
1251 } else {
1252 self.truncate(new_len);
1253 }
1254 }
1255
1256 /// Clones and appends all elements in a slice to the `Vec`.
1257 ///
1258 /// Iterates over the slice `other`, clones each element, and then appends
1259 /// it to this `Vec`. The `other` vector is traversed in-order.
1260 ///
1261 /// Note that this function is same as `extend` except that it is
1262 /// specialized to work with slices instead. If and when Rust gets
1263 /// specialization this function will likely be deprecated (but still
1264 /// available).
1265 ///
1266 /// # Examples
1267 ///
1268 /// ```
1269 /// let mut vec = vec![1];
1270 /// vec.extend_from_slice(&[2, 3, 4]);
1271 /// assert_eq!(vec, [1, 2, 3, 4]);
1272 /// ```
1273 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1274 pub fn extend_from_slice(&mut self, other: &[T]) {
1275 self.spec_extend(other.iter())
1276 }
1277 }
1278
1279 impl<T: Default> Vec<T> {
1280 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1281 ///
1282 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1283 /// difference, with each additional slot filled with `Default::default()`.
1284 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1285 ///
1286 /// This method uses `Default` to create new values on every push. If
1287 /// you'd rather `Clone` a given value, use [`resize`].
1288 ///
1289 ///
1290 /// # Examples
1291 ///
1292 /// ```
1293 /// #![feature(vec_resize_default)]
1294 ///
1295 /// let mut vec = vec![1, 2, 3];
1296 /// vec.resize_default(5);
1297 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1298 ///
1299 /// let mut vec = vec![1, 2, 3, 4];
1300 /// vec.resize_default(2);
1301 /// assert_eq!(vec, [1, 2]);
1302 /// ```
1303 ///
1304 /// [`resize`]: #method.resize
1305 #[unstable(feature = "vec_resize_default", issue = "41758")]
1306 pub fn resize_default(&mut self, new_len: usize) {
1307 let len = self.len();
1308
1309 if new_len > len {
1310 self.extend_with(new_len - len, ExtendDefault);
1311 } else {
1312 self.truncate(new_len);
1313 }
1314 }
1315 }
1316
1317 // This code generalises `extend_with_{element,default}`.
1318 trait ExtendWith<T> {
1319 fn next(&self) -> T;
1320 fn last(self) -> T;
1321 }
1322
1323 struct ExtendElement<T>(T);
1324 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1325 fn next(&self) -> T { self.0.clone() }
1326 fn last(self) -> T { self.0 }
1327 }
1328
1329 struct ExtendDefault;
1330 impl<T: Default> ExtendWith<T> for ExtendDefault {
1331 fn next(&self) -> T { Default::default() }
1332 fn last(self) -> T { Default::default() }
1333 }
1334 impl<T> Vec<T> {
1335 /// Extend the vector by `n` values, using the given generator.
1336 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, value: E) {
1337 self.reserve(n);
1338
1339 unsafe {
1340 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1341 // Use SetLenOnDrop to work around bug where compiler
1342 // may not realize the store through `ptr` through self.set_len()
1343 // don't alias.
1344 let mut local_len = SetLenOnDrop::new(&mut self.len);
1345
1346 // Write all elements except the last one
1347 for _ in 1..n {
1348 ptr::write(ptr, value.next());
1349 ptr = ptr.offset(1);
1350 // Increment the length in every step in case next() panics
1351 local_len.increment_len(1);
1352 }
1353
1354 if n > 0 {
1355 // We can write the last element directly without cloning needlessly
1356 ptr::write(ptr, value.last());
1357 local_len.increment_len(1);
1358 }
1359
1360 // len set by scope guard
1361 }
1362 }
1363 }
1364
1365 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1366 //
1367 // The idea is: The length field in SetLenOnDrop is a local variable
1368 // that the optimizer will see does not alias with any stores through the Vec's data
1369 // pointer. This is a workaround for alias analysis issue #32155
1370 struct SetLenOnDrop<'a> {
1371 len: &'a mut usize,
1372 local_len: usize,
1373 }
1374
1375 impl<'a> SetLenOnDrop<'a> {
1376 #[inline]
1377 fn new(len: &'a mut usize) -> Self {
1378 SetLenOnDrop { local_len: *len, len: len }
1379 }
1380
1381 #[inline]
1382 fn increment_len(&mut self, increment: usize) {
1383 self.local_len += increment;
1384 }
1385 }
1386
1387 impl<'a> Drop for SetLenOnDrop<'a> {
1388 #[inline]
1389 fn drop(&mut self) {
1390 *self.len = self.local_len;
1391 }
1392 }
1393
1394 impl<T: PartialEq> Vec<T> {
1395 /// Removes consecutive repeated elements in the vector.
1396 ///
1397 /// If the vector is sorted, this removes all duplicates.
1398 ///
1399 /// # Examples
1400 ///
1401 /// ```
1402 /// let mut vec = vec![1, 2, 2, 3, 2];
1403 ///
1404 /// vec.dedup();
1405 ///
1406 /// assert_eq!(vec, [1, 2, 3, 2]);
1407 /// ```
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 #[inline]
1410 pub fn dedup(&mut self) {
1411 self.dedup_by(|a, b| a == b)
1412 }
1413
1414 /// Removes the first instance of `item` from the vector if the item exists.
1415 ///
1416 /// # Examples
1417 ///
1418 /// ```
1419 /// # #![feature(vec_remove_item)]
1420 /// let mut vec = vec![1, 2, 3, 1];
1421 ///
1422 /// vec.remove_item(&1);
1423 ///
1424 /// assert_eq!(vec, vec![2, 3, 1]);
1425 /// ```
1426 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1427 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1428 let pos = match self.iter().position(|x| *x == *item) {
1429 Some(x) => x,
1430 None => return None,
1431 };
1432 Some(self.remove(pos))
1433 }
1434 }
1435
1436 ////////////////////////////////////////////////////////////////////////////////
1437 // Internal methods and functions
1438 ////////////////////////////////////////////////////////////////////////////////
1439
1440 #[doc(hidden)]
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1443 <T as SpecFromElem>::from_elem(elem, n)
1444 }
1445
1446 // Specialization trait used for Vec::from_elem
1447 trait SpecFromElem: Sized {
1448 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1449 }
1450
1451 impl<T: Clone> SpecFromElem for T {
1452 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1453 let mut v = Vec::with_capacity(n);
1454 v.extend_with(n, ExtendElement(elem));
1455 v
1456 }
1457 }
1458
1459 impl SpecFromElem for u8 {
1460 #[inline]
1461 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1462 if elem == 0 {
1463 return Vec {
1464 buf: RawVec::with_capacity_zeroed(n),
1465 len: n,
1466 }
1467 }
1468 unsafe {
1469 let mut v = Vec::with_capacity(n);
1470 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1471 v.set_len(n);
1472 v
1473 }
1474 }
1475 }
1476
1477 macro_rules! impl_spec_from_elem {
1478 ($t: ty, $is_zero: expr) => {
1479 impl SpecFromElem for $t {
1480 #[inline]
1481 fn from_elem(elem: $t, n: usize) -> Vec<$t> {
1482 if $is_zero(elem) {
1483 return Vec {
1484 buf: RawVec::with_capacity_zeroed(n),
1485 len: n,
1486 }
1487 }
1488 let mut v = Vec::with_capacity(n);
1489 v.extend_with(n, ExtendElement(elem));
1490 v
1491 }
1492 }
1493 };
1494 }
1495
1496 impl_spec_from_elem!(i8, |x| x == 0);
1497 impl_spec_from_elem!(i16, |x| x == 0);
1498 impl_spec_from_elem!(i32, |x| x == 0);
1499 impl_spec_from_elem!(i64, |x| x == 0);
1500 impl_spec_from_elem!(i128, |x| x == 0);
1501 impl_spec_from_elem!(isize, |x| x == 0);
1502
1503 impl_spec_from_elem!(u16, |x| x == 0);
1504 impl_spec_from_elem!(u32, |x| x == 0);
1505 impl_spec_from_elem!(u64, |x| x == 0);
1506 impl_spec_from_elem!(u128, |x| x == 0);
1507 impl_spec_from_elem!(usize, |x| x == 0);
1508
1509 impl_spec_from_elem!(f32, |x: f32| x == 0. && x.is_sign_positive());
1510 impl_spec_from_elem!(f64, |x: f64| x == 0. && x.is_sign_positive());
1511
1512 ////////////////////////////////////////////////////////////////////////////////
1513 // Common trait implementations for Vec
1514 ////////////////////////////////////////////////////////////////////////////////
1515
1516 #[stable(feature = "rust1", since = "1.0.0")]
1517 impl<T: Clone> Clone for Vec<T> {
1518 #[cfg(not(test))]
1519 fn clone(&self) -> Vec<T> {
1520 <[T]>::to_vec(&**self)
1521 }
1522
1523 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1524 // required for this method definition, is not available. Instead use the
1525 // `slice::to_vec` function which is only available with cfg(test)
1526 // NB see the slice::hack module in slice.rs for more information
1527 #[cfg(test)]
1528 fn clone(&self) -> Vec<T> {
1529 ::slice::to_vec(&**self)
1530 }
1531
1532 fn clone_from(&mut self, other: &Vec<T>) {
1533 other.as_slice().clone_into(self);
1534 }
1535 }
1536
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<T: Hash> Hash for Vec<T> {
1539 #[inline]
1540 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1541 Hash::hash(&**self, state)
1542 }
1543 }
1544
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<T> Index<usize> for Vec<T> {
1547 type Output = T;
1548
1549 #[inline]
1550 fn index(&self, index: usize) -> &T {
1551 // NB built-in indexing via `&[T]`
1552 &(**self)[index]
1553 }
1554 }
1555
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 impl<T> IndexMut<usize> for Vec<T> {
1558 #[inline]
1559 fn index_mut(&mut self, index: usize) -> &mut T {
1560 // NB built-in indexing via `&mut [T]`
1561 &mut (**self)[index]
1562 }
1563 }
1564
1565
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1568 type Output = [T];
1569
1570 #[inline]
1571 fn index(&self, index: ops::Range<usize>) -> &[T] {
1572 Index::index(&**self, index)
1573 }
1574 }
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1577 type Output = [T];
1578
1579 #[inline]
1580 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1581 Index::index(&**self, index)
1582 }
1583 }
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1586 type Output = [T];
1587
1588 #[inline]
1589 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1590 Index::index(&**self, index)
1591 }
1592 }
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1595 type Output = [T];
1596
1597 #[inline]
1598 fn index(&self, _index: ops::RangeFull) -> &[T] {
1599 self
1600 }
1601 }
1602 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1603 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1604 type Output = [T];
1605
1606 #[inline]
1607 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1608 Index::index(&**self, index)
1609 }
1610 }
1611 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1612 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1613 type Output = [T];
1614
1615 #[inline]
1616 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1617 Index::index(&**self, index)
1618 }
1619 }
1620
1621 #[stable(feature = "rust1", since = "1.0.0")]
1622 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1623 #[inline]
1624 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1625 IndexMut::index_mut(&mut **self, index)
1626 }
1627 }
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1630 #[inline]
1631 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1632 IndexMut::index_mut(&mut **self, index)
1633 }
1634 }
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1637 #[inline]
1638 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1639 IndexMut::index_mut(&mut **self, index)
1640 }
1641 }
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1644 #[inline]
1645 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1646 self
1647 }
1648 }
1649 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1650 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1651 #[inline]
1652 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1653 IndexMut::index_mut(&mut **self, index)
1654 }
1655 }
1656 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1657 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1658 #[inline]
1659 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1660 IndexMut::index_mut(&mut **self, index)
1661 }
1662 }
1663
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl<T> ops::Deref for Vec<T> {
1666 type Target = [T];
1667
1668 fn deref(&self) -> &[T] {
1669 unsafe {
1670 let p = self.buf.ptr();
1671 assume(!p.is_null());
1672 slice::from_raw_parts(p, self.len)
1673 }
1674 }
1675 }
1676
1677 #[stable(feature = "rust1", since = "1.0.0")]
1678 impl<T> ops::DerefMut for Vec<T> {
1679 fn deref_mut(&mut self) -> &mut [T] {
1680 unsafe {
1681 let ptr = self.buf.ptr();
1682 assume(!ptr.is_null());
1683 slice::from_raw_parts_mut(ptr, self.len)
1684 }
1685 }
1686 }
1687
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<T> FromIterator<T> for Vec<T> {
1690 #[inline]
1691 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1692 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1693 }
1694 }
1695
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<T> IntoIterator for Vec<T> {
1698 type Item = T;
1699 type IntoIter = IntoIter<T>;
1700
1701 /// Creates a consuming iterator, that is, one that moves each value out of
1702 /// the vector (from start to end). The vector cannot be used after calling
1703 /// this.
1704 ///
1705 /// # Examples
1706 ///
1707 /// ```
1708 /// let v = vec!["a".to_string(), "b".to_string()];
1709 /// for s in v.into_iter() {
1710 /// // s has type String, not &String
1711 /// println!("{}", s);
1712 /// }
1713 /// ```
1714 #[inline]
1715 fn into_iter(mut self) -> IntoIter<T> {
1716 unsafe {
1717 let begin = self.as_mut_ptr();
1718 assume(!begin.is_null());
1719 let end = if mem::size_of::<T>() == 0 {
1720 arith_offset(begin as *const i8, self.len() as isize) as *const T
1721 } else {
1722 begin.offset(self.len() as isize) as *const T
1723 };
1724 let cap = self.buf.cap();
1725 mem::forget(self);
1726 IntoIter {
1727 buf: Shared::new(begin),
1728 cap: cap,
1729 ptr: begin,
1730 end: end,
1731 }
1732 }
1733 }
1734 }
1735
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 impl<'a, T> IntoIterator for &'a Vec<T> {
1738 type Item = &'a T;
1739 type IntoIter = slice::Iter<'a, T>;
1740
1741 fn into_iter(self) -> slice::Iter<'a, T> {
1742 self.iter()
1743 }
1744 }
1745
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1748 type Item = &'a mut T;
1749 type IntoIter = slice::IterMut<'a, T>;
1750
1751 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1752 self.iter_mut()
1753 }
1754 }
1755
1756 #[stable(feature = "rust1", since = "1.0.0")]
1757 impl<T> Extend<T> for Vec<T> {
1758 #[inline]
1759 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1760 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1761 }
1762 }
1763
1764 // Specialization trait used for Vec::from_iter and Vec::extend
1765 trait SpecExtend<T, I> {
1766 fn from_iter(iter: I) -> Self;
1767 fn spec_extend(&mut self, iter: I);
1768 }
1769
1770 impl<T, I> SpecExtend<T, I> for Vec<T>
1771 where I: Iterator<Item=T>,
1772 {
1773 default fn from_iter(mut iterator: I) -> Self {
1774 // Unroll the first iteration, as the vector is going to be
1775 // expanded on this iteration in every case when the iterable is not
1776 // empty, but the loop in extend_desugared() is not going to see the
1777 // vector being full in the few subsequent loop iterations.
1778 // So we get better branch prediction.
1779 let mut vector = match iterator.next() {
1780 None => return Vec::new(),
1781 Some(element) => {
1782 let (lower, _) = iterator.size_hint();
1783 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1784 unsafe {
1785 ptr::write(vector.get_unchecked_mut(0), element);
1786 vector.set_len(1);
1787 }
1788 vector
1789 }
1790 };
1791 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1792 vector
1793 }
1794
1795 default fn spec_extend(&mut self, iter: I) {
1796 self.extend_desugared(iter)
1797 }
1798 }
1799
1800 impl<T, I> SpecExtend<T, I> for Vec<T>
1801 where I: TrustedLen<Item=T>,
1802 {
1803 default fn from_iter(iterator: I) -> Self {
1804 let mut vector = Vec::new();
1805 vector.spec_extend(iterator);
1806 vector
1807 }
1808
1809 default fn spec_extend(&mut self, iterator: I) {
1810 // This is the case for a TrustedLen iterator.
1811 let (low, high) = iterator.size_hint();
1812 if let Some(high_value) = high {
1813 debug_assert_eq!(low, high_value,
1814 "TrustedLen iterator's size hint is not exact: {:?}",
1815 (low, high));
1816 }
1817 if let Some(additional) = high {
1818 self.reserve(additional);
1819 unsafe {
1820 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1821 let mut local_len = SetLenOnDrop::new(&mut self.len);
1822 for element in iterator {
1823 ptr::write(ptr, element);
1824 ptr = ptr.offset(1);
1825 // NB can't overflow since we would have had to alloc the address space
1826 local_len.increment_len(1);
1827 }
1828 }
1829 } else {
1830 self.extend_desugared(iterator)
1831 }
1832 }
1833 }
1834
1835 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1836 fn from_iter(iterator: IntoIter<T>) -> Self {
1837 // A common case is passing a vector into a function which immediately
1838 // re-collects into a vector. We can short circuit this if the IntoIter
1839 // has not been advanced at all.
1840 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1841 unsafe {
1842 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1843 iterator.len(),
1844 iterator.cap);
1845 mem::forget(iterator);
1846 vec
1847 }
1848 } else {
1849 let mut vector = Vec::new();
1850 vector.spec_extend(iterator);
1851 vector
1852 }
1853 }
1854
1855 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1856 unsafe {
1857 self.append_elements(iterator.as_slice() as _);
1858 }
1859 iterator.ptr = iterator.end;
1860 }
1861 }
1862
1863 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1864 where I: Iterator<Item=&'a T>,
1865 T: Clone,
1866 {
1867 default fn from_iter(iterator: I) -> Self {
1868 SpecExtend::from_iter(iterator.cloned())
1869 }
1870
1871 default fn spec_extend(&mut self, iterator: I) {
1872 self.spec_extend(iterator.cloned())
1873 }
1874 }
1875
1876 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1877 where T: Copy,
1878 {
1879 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1880 let slice = iterator.as_slice();
1881 self.reserve(slice.len());
1882 unsafe {
1883 let len = self.len();
1884 self.set_len(len + slice.len());
1885 self.get_unchecked_mut(len..).copy_from_slice(slice);
1886 }
1887 }
1888 }
1889
1890 impl<T> Vec<T> {
1891 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1892 // This is the case for a general iterator.
1893 //
1894 // This function should be the moral equivalent of:
1895 //
1896 // for item in iterator {
1897 // self.push(item);
1898 // }
1899 while let Some(element) = iterator.next() {
1900 let len = self.len();
1901 if len == self.capacity() {
1902 let (lower, _) = iterator.size_hint();
1903 self.reserve(lower.saturating_add(1));
1904 }
1905 unsafe {
1906 ptr::write(self.get_unchecked_mut(len), element);
1907 // NB can't overflow since we would have had to alloc the address space
1908 self.set_len(len + 1);
1909 }
1910 }
1911 }
1912
1913 /// Creates a splicing iterator that replaces the specified range in the vector
1914 /// with the given `replace_with` iterator and yields the removed items.
1915 /// `replace_with` does not need to be the same length as `range`.
1916 ///
1917 /// Note 1: The element range is removed even if the iterator is not
1918 /// consumed until the end.
1919 ///
1920 /// Note 2: It is unspecified how many elements are removed from the vector,
1921 /// if the `Splice` value is leaked.
1922 ///
1923 /// Note 3: The input iterator `replace_with` is only consumed
1924 /// when the `Splice` value is dropped.
1925 ///
1926 /// Note 4: This is optimal if:
1927 ///
1928 /// * The tail (elements in the vector after `range`) is empty,
1929 /// * or `replace_with` yields fewer elements than `range`’s length
1930 /// * or the lower bound of its `size_hint()` is exact.
1931 ///
1932 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1933 ///
1934 /// # Panics
1935 ///
1936 /// Panics if the starting point is greater than the end point or if
1937 /// the end point is greater than the length of the vector.
1938 ///
1939 /// # Examples
1940 ///
1941 /// ```
1942 /// #![feature(splice)]
1943 /// let mut v = vec![1, 2, 3];
1944 /// let new = [7, 8];
1945 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
1946 /// assert_eq!(v, &[7, 8, 3]);
1947 /// assert_eq!(u, &[1, 2]);
1948 /// ```
1949 #[inline]
1950 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1951 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1952 where R: RangeArgument<usize>, I: IntoIterator<Item=T>
1953 {
1954 Splice {
1955 drain: self.drain(range),
1956 replace_with: replace_with.into_iter(),
1957 }
1958 }
1959
1960 }
1961
1962 #[stable(feature = "extend_ref", since = "1.2.0")]
1963 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1964 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1965 self.spec_extend(iter.into_iter())
1966 }
1967 }
1968
1969 macro_rules! __impl_slice_eq1 {
1970 ($Lhs: ty, $Rhs: ty) => {
1971 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1972 };
1973 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1974 #[stable(feature = "rust1", since = "1.0.0")]
1975 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1976 #[inline]
1977 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1978 #[inline]
1979 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1980 }
1981 }
1982 }
1983
1984 __impl_slice_eq1! { Vec<A>, Vec<B> }
1985 __impl_slice_eq1! { Vec<A>, &'b [B] }
1986 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1987 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1988 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1989 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1990
1991 macro_rules! array_impls {
1992 ($($N: expr)+) => {
1993 $(
1994 // NOTE: some less important impls are omitted to reduce code bloat
1995 __impl_slice_eq1! { Vec<A>, [B; $N] }
1996 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1997 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1998 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1999 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2000 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2001 )+
2002 }
2003 }
2004
2005 array_impls! {
2006 0 1 2 3 4 5 6 7 8 9
2007 10 11 12 13 14 15 16 17 18 19
2008 20 21 22 23 24 25 26 27 28 29
2009 30 31 32
2010 }
2011
2012 /// Implements comparison of vectors, lexicographically.
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<T: PartialOrd> PartialOrd for Vec<T> {
2015 #[inline]
2016 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2017 PartialOrd::partial_cmp(&**self, &**other)
2018 }
2019 }
2020
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<T: Eq> Eq for Vec<T> {}
2023
2024 /// Implements ordering of vectors, lexicographically.
2025 #[stable(feature = "rust1", since = "1.0.0")]
2026 impl<T: Ord> Ord for Vec<T> {
2027 #[inline]
2028 fn cmp(&self, other: &Vec<T>) -> Ordering {
2029 Ord::cmp(&**self, &**other)
2030 }
2031 }
2032
2033 #[stable(feature = "rust1", since = "1.0.0")]
2034 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2035 fn drop(&mut self) {
2036 unsafe {
2037 // use drop for [T]
2038 ptr::drop_in_place(&mut self[..]);
2039 }
2040 // RawVec handles deallocation
2041 }
2042 }
2043
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<T> Default for Vec<T> {
2046 /// Creates an empty `Vec<T>`.
2047 fn default() -> Vec<T> {
2048 Vec::new()
2049 }
2050 }
2051
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2055 fmt::Debug::fmt(&**self, f)
2056 }
2057 }
2058
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 impl<T> AsRef<Vec<T>> for Vec<T> {
2061 fn as_ref(&self) -> &Vec<T> {
2062 self
2063 }
2064 }
2065
2066 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2067 impl<T> AsMut<Vec<T>> for Vec<T> {
2068 fn as_mut(&mut self) -> &mut Vec<T> {
2069 self
2070 }
2071 }
2072
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl<T> AsRef<[T]> for Vec<T> {
2075 fn as_ref(&self) -> &[T] {
2076 self
2077 }
2078 }
2079
2080 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2081 impl<T> AsMut<[T]> for Vec<T> {
2082 fn as_mut(&mut self) -> &mut [T] {
2083 self
2084 }
2085 }
2086
2087 #[stable(feature = "rust1", since = "1.0.0")]
2088 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2089 #[cfg(not(test))]
2090 fn from(s: &'a [T]) -> Vec<T> {
2091 s.to_vec()
2092 }
2093 #[cfg(test)]
2094 fn from(s: &'a [T]) -> Vec<T> {
2095 ::slice::to_vec(s)
2096 }
2097 }
2098
2099 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2100 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2101 #[cfg(not(test))]
2102 fn from(s: &'a mut [T]) -> Vec<T> {
2103 s.to_vec()
2104 }
2105 #[cfg(test)]
2106 fn from(s: &'a mut [T]) -> Vec<T> {
2107 ::slice::to_vec(s)
2108 }
2109 }
2110
2111 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2112 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2113 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2114 s.into_owned()
2115 }
2116 }
2117
2118 // note: test pulls in libstd, which causes errors here
2119 #[cfg(not(test))]
2120 #[stable(feature = "vec_from_box", since = "1.18.0")]
2121 impl<T> From<Box<[T]>> for Vec<T> {
2122 fn from(s: Box<[T]>) -> Vec<T> {
2123 s.into_vec()
2124 }
2125 }
2126
2127 #[stable(feature = "box_from_vec", since = "1.18.0")]
2128 impl<T> Into<Box<[T]>> for Vec<T> {
2129 fn into(self) -> Box<[T]> {
2130 self.into_boxed_slice()
2131 }
2132 }
2133
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 impl<'a> From<&'a str> for Vec<u8> {
2136 fn from(s: &'a str) -> Vec<u8> {
2137 From::from(s.as_bytes())
2138 }
2139 }
2140
2141 ////////////////////////////////////////////////////////////////////////////////
2142 // Clone-on-write
2143 ////////////////////////////////////////////////////////////////////////////////
2144
2145 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2146 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2147 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2148 Cow::Borrowed(s)
2149 }
2150 }
2151
2152 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2153 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2154 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2155 Cow::Owned(v)
2156 }
2157 }
2158
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2161 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2162 Cow::Owned(FromIterator::from_iter(it))
2163 }
2164 }
2165
2166 ////////////////////////////////////////////////////////////////////////////////
2167 // Iterators
2168 ////////////////////////////////////////////////////////////////////////////////
2169
2170 /// An iterator that moves out of a vector.
2171 ///
2172 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2173 /// by the [`IntoIterator`] trait).
2174 ///
2175 /// [`Vec`]: struct.Vec.html
2176 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 pub struct IntoIter<T> {
2179 buf: Shared<T>,
2180 cap: usize,
2181 ptr: *const T,
2182 end: *const T,
2183 }
2184
2185 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2186 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2188 f.debug_tuple("IntoIter")
2189 .field(&self.as_slice())
2190 .finish()
2191 }
2192 }
2193
2194 impl<T> IntoIter<T> {
2195 /// Returns the remaining items of this iterator as a slice.
2196 ///
2197 /// # Examples
2198 ///
2199 /// ```
2200 /// let vec = vec!['a', 'b', 'c'];
2201 /// let mut into_iter = vec.into_iter();
2202 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2203 /// let _ = into_iter.next().unwrap();
2204 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2205 /// ```
2206 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2207 pub fn as_slice(&self) -> &[T] {
2208 unsafe {
2209 slice::from_raw_parts(self.ptr, self.len())
2210 }
2211 }
2212
2213 /// Returns the remaining items of this iterator as a mutable slice.
2214 ///
2215 /// # Examples
2216 ///
2217 /// ```
2218 /// let vec = vec!['a', 'b', 'c'];
2219 /// let mut into_iter = vec.into_iter();
2220 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2221 /// into_iter.as_mut_slice()[2] = 'z';
2222 /// assert_eq!(into_iter.next().unwrap(), 'a');
2223 /// assert_eq!(into_iter.next().unwrap(), 'b');
2224 /// assert_eq!(into_iter.next().unwrap(), 'z');
2225 /// ```
2226 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2227 pub fn as_mut_slice(&mut self) -> &mut [T] {
2228 unsafe {
2229 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2230 }
2231 }
2232 }
2233
2234 #[stable(feature = "rust1", since = "1.0.0")]
2235 unsafe impl<T: Send> Send for IntoIter<T> {}
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2238
2239 #[stable(feature = "rust1", since = "1.0.0")]
2240 impl<T> Iterator for IntoIter<T> {
2241 type Item = T;
2242
2243 #[inline]
2244 fn next(&mut self) -> Option<T> {
2245 unsafe {
2246 if self.ptr as *const _ == self.end {
2247 None
2248 } else {
2249 if mem::size_of::<T>() == 0 {
2250 // purposefully don't use 'ptr.offset' because for
2251 // vectors with 0-size elements this would return the
2252 // same pointer.
2253 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2254
2255 // Use a non-null pointer value
2256 // (self.ptr might be null because of wrapping)
2257 Some(ptr::read(1 as *mut T))
2258 } else {
2259 let old = self.ptr;
2260 self.ptr = self.ptr.offset(1);
2261
2262 Some(ptr::read(old))
2263 }
2264 }
2265 }
2266 }
2267
2268 #[inline]
2269 fn size_hint(&self) -> (usize, Option<usize>) {
2270 let exact = match self.ptr.offset_to(self.end) {
2271 Some(x) => x as usize,
2272 None => (self.end as usize).wrapping_sub(self.ptr as usize),
2273 };
2274 (exact, Some(exact))
2275 }
2276
2277 #[inline]
2278 fn count(self) -> usize {
2279 self.len()
2280 }
2281 }
2282
2283 #[stable(feature = "rust1", since = "1.0.0")]
2284 impl<T> DoubleEndedIterator for IntoIter<T> {
2285 #[inline]
2286 fn next_back(&mut self) -> Option<T> {
2287 unsafe {
2288 if self.end == self.ptr {
2289 None
2290 } else {
2291 if mem::size_of::<T>() == 0 {
2292 // See above for why 'ptr.offset' isn't used
2293 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2294
2295 // Use a non-null pointer value
2296 // (self.end might be null because of wrapping)
2297 Some(ptr::read(1 as *mut T))
2298 } else {
2299 self.end = self.end.offset(-1);
2300
2301 Some(ptr::read(self.end))
2302 }
2303 }
2304 }
2305 }
2306 }
2307
2308 #[stable(feature = "rust1", since = "1.0.0")]
2309 impl<T> ExactSizeIterator for IntoIter<T> {
2310 fn is_empty(&self) -> bool {
2311 self.ptr == self.end
2312 }
2313 }
2314
2315 #[unstable(feature = "fused", issue = "35602")]
2316 impl<T> FusedIterator for IntoIter<T> {}
2317
2318 #[unstable(feature = "trusted_len", issue = "37572")]
2319 unsafe impl<T> TrustedLen for IntoIter<T> {}
2320
2321 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2322 impl<T: Clone> Clone for IntoIter<T> {
2323 fn clone(&self) -> IntoIter<T> {
2324 self.as_slice().to_owned().into_iter()
2325 }
2326 }
2327
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2330 fn drop(&mut self) {
2331 // destroy the remaining elements
2332 for _x in self.by_ref() {}
2333
2334 // RawVec handles deallocation
2335 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2336 }
2337 }
2338
2339 /// A draining iterator for `Vec<T>`.
2340 ///
2341 /// This `struct` is created by the [`drain`] method on [`Vec`].
2342 ///
2343 /// [`drain`]: struct.Vec.html#method.drain
2344 /// [`Vec`]: struct.Vec.html
2345 #[stable(feature = "drain", since = "1.6.0")]
2346 pub struct Drain<'a, T: 'a> {
2347 /// Index of tail to preserve
2348 tail_start: usize,
2349 /// Length of tail
2350 tail_len: usize,
2351 /// Current remaining range to remove
2352 iter: slice::Iter<'a, T>,
2353 vec: Shared<Vec<T>>,
2354 }
2355
2356 #[stable(feature = "collection_debug", since = "1.17.0")]
2357 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2358 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2359 f.debug_tuple("Drain")
2360 .field(&self.iter.as_slice())
2361 .finish()
2362 }
2363 }
2364
2365 #[stable(feature = "drain", since = "1.6.0")]
2366 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2367 #[stable(feature = "drain", since = "1.6.0")]
2368 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2369
2370 #[stable(feature = "drain", since = "1.6.0")]
2371 impl<'a, T> Iterator for Drain<'a, T> {
2372 type Item = T;
2373
2374 #[inline]
2375 fn next(&mut self) -> Option<T> {
2376 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2377 }
2378
2379 fn size_hint(&self) -> (usize, Option<usize>) {
2380 self.iter.size_hint()
2381 }
2382 }
2383
2384 #[stable(feature = "drain", since = "1.6.0")]
2385 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2386 #[inline]
2387 fn next_back(&mut self) -> Option<T> {
2388 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2389 }
2390 }
2391
2392 #[stable(feature = "drain", since = "1.6.0")]
2393 impl<'a, T> Drop for Drain<'a, T> {
2394 fn drop(&mut self) {
2395 // exhaust self first
2396 while let Some(_) = self.next() {}
2397
2398 if self.tail_len > 0 {
2399 unsafe {
2400 let source_vec = self.vec.as_mut();
2401 // memmove back untouched tail, update to new length
2402 let start = source_vec.len();
2403 let tail = self.tail_start;
2404 let src = source_vec.as_ptr().offset(tail as isize);
2405 let dst = source_vec.as_mut_ptr().offset(start as isize);
2406 ptr::copy(src, dst, self.tail_len);
2407 source_vec.set_len(start + self.tail_len);
2408 }
2409 }
2410 }
2411 }
2412
2413
2414 #[stable(feature = "drain", since = "1.6.0")]
2415 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2416 fn is_empty(&self) -> bool {
2417 self.iter.is_empty()
2418 }
2419 }
2420
2421 #[unstable(feature = "fused", issue = "35602")]
2422 impl<'a, T> FusedIterator for Drain<'a, T> {}
2423
2424 /// A place for insertion at the back of a `Vec`.
2425 ///
2426 /// See [`Vec::place_back`](struct.Vec.html#method.place_back) for details.
2427 #[must_use = "places do nothing unless written to with `<-` syntax"]
2428 #[unstable(feature = "collection_placement",
2429 reason = "struct name and placement protocol are subject to change",
2430 issue = "30172")]
2431 #[derive(Debug)]
2432 pub struct PlaceBack<'a, T: 'a> {
2433 vec: &'a mut Vec<T>,
2434 }
2435
2436 #[unstable(feature = "collection_placement",
2437 reason = "placement protocol is subject to change",
2438 issue = "30172")]
2439 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2440 type Place = PlaceBack<'a, T>;
2441
2442 fn make_place(self) -> Self {
2443 // This will panic or abort if we would allocate > isize::MAX bytes
2444 // or if the length increment would overflow for zero-sized types.
2445 if self.vec.len == self.vec.buf.cap() {
2446 self.vec.buf.double();
2447 }
2448 self
2449 }
2450 }
2451
2452 #[unstable(feature = "collection_placement",
2453 reason = "placement protocol is subject to change",
2454 issue = "30172")]
2455 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2456 fn pointer(&mut self) -> *mut T {
2457 unsafe { self.vec.as_mut_ptr().offset(self.vec.len as isize) }
2458 }
2459 }
2460
2461 #[unstable(feature = "collection_placement",
2462 reason = "placement protocol is subject to change",
2463 issue = "30172")]
2464 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2465 type Owner = &'a mut T;
2466
2467 unsafe fn finalize(mut self) -> &'a mut T {
2468 let ptr = self.pointer();
2469 self.vec.len += 1;
2470 &mut *ptr
2471 }
2472 }
2473
2474
2475 /// A splicing iterator for `Vec`.
2476 ///
2477 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2478 /// documentation for more.
2479 ///
2480 /// [`splice()`]: struct.Vec.html#method.splice
2481 /// [`Vec`]: struct.Vec.html
2482 #[derive(Debug)]
2483 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2484 pub struct Splice<'a, I: Iterator + 'a> {
2485 drain: Drain<'a, I::Item>,
2486 replace_with: I,
2487 }
2488
2489 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2490 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2491 type Item = I::Item;
2492
2493 fn next(&mut self) -> Option<Self::Item> {
2494 self.drain.next()
2495 }
2496
2497 fn size_hint(&self) -> (usize, Option<usize>) {
2498 self.drain.size_hint()
2499 }
2500 }
2501
2502 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2503 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2504 fn next_back(&mut self) -> Option<Self::Item> {
2505 self.drain.next_back()
2506 }
2507 }
2508
2509 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2510 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2511
2512
2513 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2514 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2515 fn drop(&mut self) {
2516 // exhaust drain first
2517 while let Some(_) = self.drain.next() {}
2518
2519
2520 unsafe {
2521 if self.drain.tail_len == 0 {
2522 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2523 return
2524 }
2525
2526 // First fill the range left by drain().
2527 if !self.drain.fill(&mut self.replace_with) {
2528 return
2529 }
2530
2531 // There may be more elements. Use the lower bound as an estimate.
2532 // FIXME: Is the upper bound a better guess? Or something else?
2533 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2534 if lower_bound > 0 {
2535 self.drain.move_tail(lower_bound);
2536 if !self.drain.fill(&mut self.replace_with) {
2537 return
2538 }
2539 }
2540
2541 // Collect any remaining elements.
2542 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2543 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2544 // Now we have an exact count.
2545 if collected.len() > 0 {
2546 self.drain.move_tail(collected.len());
2547 let filled = self.drain.fill(&mut collected);
2548 debug_assert!(filled);
2549 debug_assert_eq!(collected.len(), 0);
2550 }
2551 }
2552 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2553 }
2554 }
2555
2556 /// Private helper methods for `Splice::drop`
2557 impl<'a, T> Drain<'a, T> {
2558 /// The range from `self.vec.len` to `self.tail_start` contains elements
2559 /// that have been moved out.
2560 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2561 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2562 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2563 let vec = self.vec.as_mut();
2564 let range_start = vec.len;
2565 let range_end = self.tail_start;
2566 let range_slice = slice::from_raw_parts_mut(
2567 vec.as_mut_ptr().offset(range_start as isize),
2568 range_end - range_start);
2569
2570 for place in range_slice {
2571 if let Some(new_item) = replace_with.next() {
2572 ptr::write(place, new_item);
2573 vec.len += 1;
2574 } else {
2575 return false
2576 }
2577 }
2578 true
2579 }
2580
2581 /// Make room for inserting more elements before the tail.
2582 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2583 let vec = self.vec.as_mut();
2584 let used_capacity = self.tail_start + self.tail_len;
2585 vec.buf.reserve(used_capacity, extra_capacity);
2586
2587 let new_tail_start = self.tail_start + extra_capacity;
2588 let src = vec.as_ptr().offset(self.tail_start as isize);
2589 let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2590 ptr::copy(src, dst, self.tail_len);
2591 self.tail_start = new_tail_start;
2592 }
2593 }