rune_alloc/vec/mod.rs
1//! A contiguous growable array type with heap-allocated contents, written
2//! `Vec<T>`.
3//!
4//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5//! *O*(1) pop (from the end).
6//!
7//! Vectors ensure they never allocate more than `isize::MAX` bytes.
8//!
9//! # Examples
10//!
11//! You can explicitly create a [`Vec`] with [`Vec::new`]:
12//!
13//! ```
14//! use rune::alloc::Vec;
15//!
16//! let v: Vec<i32> = Vec::new();
17//! ```
18//!
19//! ...or by using the [`try_vec!`][crate::try_vec!] macro:
20//!
21//! ```
22//! use rune::alloc::{try_vec, Vec};
23//!
24//! let v: Vec<i32> = try_vec![];
25//! let v = try_vec![1, 2, 3, 4, 5];
26//! let v = try_vec![0; 10]; // ten zeroes
27//! # Ok::<_, rune::alloc::Error>(())
28//! ```
29//!
30//! You can [`try_push`] values onto the end of a vector (which will grow the vector
31//! as needed):
32//!
33//! ```
34//! use rune::alloc::try_vec;
35//! let mut v = try_vec![1, 2];
36//!
37//! v.try_push(3)?;
38//! # Ok::<_, rune::alloc::Error>(())
39//! ```
40//!
41//! Popping values works in much the same way:
42//!
43//! ```
44//! use rune::alloc::try_vec;
45//!
46//! let mut v = try_vec![1, 2];
47//!
48//! let two = v.pop();
49//! # Ok::<_, rune::alloc::Error>(())
50//! ```
51//!
52//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
53//!
54//! ```
55//! use rune::alloc::try_vec;
56//!
57//! let mut v = try_vec![1, 2, 3];
58//! let three = v[2];
59//! v[1] = v[1] + 5;
60//! # Ok::<_, rune::alloc::Error>(())
61//! ```
62//!
63//! [`try_push`]: Vec::try_push
64
65pub use self::drain::Drain;
66
67mod drain;
68pub use self::into_iter::IntoIter;
69
70mod into_iter;
71
72mod partial_eq;
73
74use self::spec_from_elem::SpecFromElem;
75mod spec_from_elem;
76
77use self::spec_extend::SpecExtend;
78mod spec_extend;
79
80use self::set_len_on_drop::SetLenOnDrop;
81mod set_len_on_drop;
82
83mod splice;
84
85#[cfg(rune_nightly)]
86use self::is_zero::IsZero;
87#[cfg(rune_nightly)]
88mod is_zero;
89
90#[cfg(feature = "alloc")]
91use core::alloc::Layout;
92use core::borrow::Borrow;
93use core::cmp;
94use core::cmp::Ordering;
95use core::fmt;
96use core::hash::{Hash, Hasher};
97use core::iter;
98use core::marker::PhantomData;
99use core::mem::{self, ManuallyDrop, MaybeUninit};
100use core::ops::{self, Index, IndexMut, Range, RangeBounds};
101use core::slice::{self, SliceIndex};
102
103use crate::alloc::{Allocator, Global, SizedTypeProperties};
104use crate::clone::TryClone;
105use crate::error::Error;
106use crate::iter::{TryExtend, TryFromIteratorIn};
107use crate::ptr::{self, NonNull};
108use crate::raw_vec::RawVec;
109use crate::slice::range as slice_range;
110use crate::slice::{RawIter, RawIterMut};
111#[cfg(test)]
112use crate::testing::*;
113use crate::Box;
114
115/// Construct a vector from an element that can be cloned.
116#[doc(hidden)]
117pub fn try_from_elem<T: TryClone>(elem: T, n: usize) -> Result<Vec<T>, Error> {
118 <T as SpecFromElem>::from_elem(elem, n, Global)
119}
120
121/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
122///
123/// # Examples
124///
125/// ```
126/// use rune::alloc::Vec;
127/// use rune::alloc::prelude::*;
128///
129/// let mut vec = Vec::new();
130/// vec.try_push(1)?;
131/// vec.try_push(2)?;
132///
133/// assert_eq!(vec.len(), 2);
134/// assert_eq!(vec[0], 1);
135///
136/// assert_eq!(vec.pop(), Some(2));
137/// assert_eq!(vec.len(), 1);
138///
139/// vec[0] = 7;
140/// assert_eq!(vec[0], 7);
141///
142/// vec.try_extend([1, 2, 3])?;
143///
144/// for x in &vec {
145/// println!("{x}");
146/// }
147///
148/// assert_eq!(vec, [7, 1, 2, 3]);
149/// # Ok::<_, rune::alloc::Error>(())
150/// ```
151///
152/// The [`try_vec!`][crate::try_vec!] macro is provided for convenient
153/// initialization:
154///
155/// ```
156/// use rune::alloc::{try_vec, Vec};
157///
158/// let mut vec1 = try_vec![1, 2, 3];
159/// vec1.try_push(4)?;
160/// let vec2 = Vec::try_from([1, 2, 3, 4])?;
161/// assert_eq!(vec1, vec2);
162/// # Ok::<_, rune::alloc::Error>(())
163/// ```
164///
165/// It can also initialize each element of a `Vec<T>` with a given value.
166/// This may be more efficient than performing allocation and initialization
167/// in separate steps, especially when initializing a vector of zeros:
168///
169/// ```
170/// use rune::alloc::{try_vec, Vec};
171///
172/// let vec = try_vec![0; 5];
173/// assert_eq!(vec, [0, 0, 0, 0, 0]);
174///
175/// // The following is equivalent, but potentially slower:
176/// let mut vec = Vec::try_with_capacity(5)?;
177/// vec.try_resize(5, 0)?;
178/// assert_eq!(vec, [0, 0, 0, 0, 0]);
179/// # Ok::<_, rune::alloc::Error>(())
180/// ```
181///
182/// For more information, see
183/// [Capacity and Reallocation](#capacity-and-reallocation).
184///
185/// Use a `Vec<T>` as an efficient stack:
186///
187/// ```
188/// use rune::alloc::Vec;
189///
190/// let mut stack = Vec::new();
191///
192/// stack.try_push(1)?;
193/// stack.try_push(2)?;
194/// stack.try_push(3)?;
195///
196/// while let Some(top) = stack.pop() {
197/// // Prints 3, 2, 1
198/// println!("{top}");
199/// }
200/// # Ok::<_, rune::alloc::Error>(())
201/// ```
202///
203/// # Indexing
204///
205/// The `Vec` type allows to access values by index, because it implements the
206/// [`Index`] trait. An example will be more explicit:
207///
208/// ```
209/// use rune::alloc::try_vec;
210///
211/// let v = try_vec![0, 2, 4, 6];
212/// println!("{}", v[1]); // it will display '2'
213/// # Ok::<_, rune::alloc::Error>(())
214/// ```
215///
216/// However be careful: if you try to access an index which isn't in the `Vec`,
217/// your software will panic! You cannot do this:
218///
219/// ```should_panic
220/// use rune::alloc::try_vec;
221///
222/// let v = try_vec![0, 2, 4, 6];
223/// println!("{}", v[6]); // it will panic!
224/// # Ok::<_, rune::alloc::Error>(())
225/// ```
226///
227/// Use [`get`] and [`get_mut`] if you want to check whether the index is in
228/// the `Vec`.
229///
230/// # Slicing
231///
232/// A `Vec` can be mutable. On the other hand, slices are read-only objects.
233/// To get a [slice][prim@slice], use [`&`]. Example:
234///
235/// ```
236/// use rune::alloc::try_vec;
237///
238/// fn read_slice(slice: &[usize]) {
239/// // ...
240/// }
241///
242/// let v = try_vec![0, 1];
243/// read_slice(&v);
244///
245/// // ... and that's all!
246/// // you can also do it like this:
247/// let u: &[usize] = &v;
248/// // or like this:
249/// let u: &[_] = &v;
250/// # Ok::<_, rune::alloc::Error>(())
251/// ```
252///
253/// In Rust, it's more common to pass slices as arguments rather than vectors
254/// when you just want to provide read access. The same goes for [`String`] and
255/// [`&str`].
256///
257/// # Capacity and reallocation
258///
259/// The capacity of a vector is the amount of space allocated for any future
260/// elements that will be added onto the vector. This is not to be confused with
261/// the *length* of a vector, which specifies the number of actual elements
262/// within the vector. If a vector's length exceeds its capacity, its capacity
263/// will automatically be increased, but its elements will have to be
264/// reallocated.
265///
266/// For example, a vector with capacity 10 and length 0 would be an empty vector
267/// with space for 10 more elements. Pushing 10 or fewer elements onto the
268/// vector will not change its capacity or cause reallocation to occur. However,
269/// if the vector's length is increased to 11, it will have to reallocate, which
270/// can be slow. For this reason, it is recommended to use
271/// [`Vec::try_with_capacity`] whenever possible to specify how big the vector
272/// is expected to get.
273///
274/// # Guarantees
275///
276/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
277/// about its design. This ensures that it's as low-overhead as possible in
278/// the general case, and can be correctly manipulated in primitive ways
279/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
280/// If additional type parameters are added (e.g., to support custom allocators),
281/// overriding their defaults may change the behavior.
282///
283/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
284/// triplet. No more, no less. The order of these fields is completely
285/// unspecified, and you should use the appropriate methods to modify these.
286/// The pointer will never be null, so this type is null-pointer-optimized.
287///
288/// However, the pointer might not actually point to allocated memory. In
289/// particular, if you construct a `Vec` with capacity 0 via [`Vec::new`],
290/// [`try_vec![]`], [`Vec::try_with_capacity(0)`], or by calling
291/// [`try_shrink_to_fit`] on an empty Vec, it will not allocate memory.
292/// Similarly, if you store zero-sized types inside a `Vec`, it will not
293/// allocate space for them. *Note that in this case the `Vec` might not report
294/// a [`capacity`] of 0*. `Vec` will allocate if and only if
295/// <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general,
296/// `Vec`'s allocation details are very subtle --- if you intend to allocate
297/// memory using a `Vec` and use it for something else (either to pass to unsafe
298/// code, or to build your own memory-backed collection), be sure to deallocate
299/// this memory by using `from_raw_parts` to recover the `Vec` and then dropping
300/// it.
301///
302/// [`try_vec![]`]: try_vec!
303/// [`Vec::try_with_capacity(0)`]: Vec::try_with_capacity
304///
305/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
306/// (as defined by the allocator Rust is configured to use by default), and its
307/// pointer points to [`len`] initialized, contiguous elements in order (what
308/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
309/// logically uninitialized, contiguous elements.
310///
311/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
312/// visualized as below. The top part is the `Vec` struct, it contains a
313/// pointer to the head of the allocation in the heap, length and capacity.
314/// The bottom part is the allocation on the heap, a contiguous memory block.
315///
316/// ```text
317/// ptr len capacity
318/// +--------+--------+--------+
319/// | 0x0123 | 2 | 4 |
320/// +--------+--------+--------+
321/// |
322/// v
323/// Heap +--------+--------+--------+--------+
324/// | 'a' | 'b' | uninit | uninit |
325/// +--------+--------+--------+--------+
326/// ```
327///
328/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
329/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
330/// layout (including the order of fields).
331///
332/// `Vec` will never perform a "small optimization" where elements are actually
333/// stored on the stack for two reasons:
334///
335/// * It would make it more difficult for unsafe code to correctly manipulate
336/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
337/// only moved, and it would be more difficult to determine if a `Vec` had
338/// actually allocated memory.
339///
340/// * It would penalize the general case, incurring an additional branch
341/// on every access.
342///
343/// `Vec` will never automatically shrink itself, even if completely empty. This
344/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
345/// and then filling it back up to the same [`len`] should incur no calls to the
346/// allocator. If you wish to free up unused memory, use [`try_shrink_to_fit`]
347/// or [`try_shrink_to`].
348///
349/// [`try_push`] and [`try_insert`] will never (re)allocate if the reported capacity is
350/// sufficient. [`try_push`] and [`try_insert`] *will* (re)allocate if
351/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
352/// accurate, and can be relied on. It can even be used to manually free the memory
353/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
354/// when not necessary.
355///
356/// `Vec` does not guarantee any particular growth strategy when reallocating
357/// when full, nor when [`try_reserve`] is called. The current strategy is basic
358/// and it may prove desirable to use a non-constant growth factor. Whatever
359/// strategy is used will of course guarantee *O*(1) amortized [`try_push`].
360///
361/// `try_vec![x; n]`, `try_vec![a, b, c, d]`, and [`Vec::try_with_capacity(n)`],
362/// will all produce a `Vec` with exactly the requested capacity. If <code>[len]
363/// == [capacity]</code>, (as is the case for the [`try_vec!`] macro), then a
364/// `Vec<T>` can be converted to and from a [`Box<[T]>`][owned slice] without
365/// reallocating or moving the elements.
366///
367/// [`Vec::try_with_capacity(n)`]: Vec::try_with_capacity
368///
369/// `Vec` will not specifically overwrite any data that is removed from it,
370/// but also won't specifically preserve it. Its uninitialized memory is
371/// scratch space that it may use however it wants. It will generally just do
372/// whatever is most efficient or otherwise easy to implement. Do not rely on
373/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
374/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
375/// first, that might not actually happen because the optimizer does not consider
376/// this a side-effect that must be preserved. There is one case which we will
377/// not break, however: using `unsafe` code to write to the excess capacity,
378/// and then increasing the length to match, is always valid.
379///
380/// Currently, `Vec` does not guarantee the order in which elements are dropped.
381/// The order has changed in the past and may change again.
382///
383/// [`get`]: slice::get
384/// [`get_mut`]: slice::get_mut
385/// [`String`]: crate::string::String
386/// [`&str`]: type@str
387/// [`try_shrink_to_fit`]: Vec::try_shrink_to_fit
388/// [`try_shrink_to`]: Vec::try_shrink_to
389/// [capacity]: Vec::capacity
390/// [`capacity`]: Vec::capacity
391/// [mem::size_of::\<T>]: core::mem::size_of
392/// [len]: Vec::len
393/// [`len`]: Vec::len
394/// [`try_push`]: Vec::try_push
395/// [`try_insert`]: Vec::try_insert
396/// [`try_reserve`]: Vec::try_reserve
397/// [`MaybeUninit`]: core::mem::MaybeUninit
398/// [owned slice]: Box
399pub struct Vec<T, A: Allocator = Global> {
400 buf: RawVec<T, A>,
401 len: usize,
402}
403
404////////////////////////////////////////////////////////////////////////////////
405// Inherent methods
406////////////////////////////////////////////////////////////////////////////////
407
408impl<T> Vec<T> {
409 /// Constructs a new, empty `Vec<T>`.
410 ///
411 /// The vector will not allocate until elements are pushed onto it.
412 ///
413 /// # Examples
414 ///
415 /// ```
416 /// # #![allow(unused_mut)]
417 /// let mut vec: Vec<i32> = Vec::new();
418 /// ```
419 #[inline]
420 #[must_use]
421 pub const fn new() -> Self {
422 Vec {
423 buf: RawVec::NEW,
424 len: 0,
425 }
426 }
427
428 /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
429 ///
430 /// The vector will be able to hold at least `capacity` elements without
431 /// reallocating. This method is allowed to allocate for more elements than
432 /// `capacity`. If `capacity` is 0, the vector will not allocate.
433 ///
434 /// It is important to note that although the returned vector has the
435 /// minimum *capacity* specified, the vector will have a zero *length*. For
436 /// an explanation of the difference between length and capacity, see
437 /// *[Capacity and reallocation]*.
438 ///
439 /// If it is important to know the exact allocated capacity of a `Vec`,
440 /// always use the [`capacity`] method after construction.
441 ///
442 /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
443 /// and the capacity will always be `usize::MAX`.
444 ///
445 /// [Capacity and reallocation]: #capacity-and-reallocation
446 /// [`capacity`]: Vec::capacity
447 ///
448 /// # Panics
449 ///
450 /// Panics if the new capacity exceeds `isize::MAX` bytes.
451 ///
452 /// # Examples
453 ///
454 /// ```
455 /// let mut vec = Vec::with_capacity(10);
456 ///
457 /// // The vector contains no items, even though it has capacity for more
458 /// assert_eq!(vec.len(), 0);
459 /// assert!(vec.capacity() >= 10);
460 ///
461 /// // These are all done without reallocating...
462 /// for i in 0..10 {
463 /// vec.push(i);
464 /// }
465 /// assert_eq!(vec.len(), 10);
466 /// assert!(vec.capacity() >= 10);
467 ///
468 /// // ...but this may make the vector reallocate
469 /// vec.push(11);
470 /// assert_eq!(vec.len(), 11);
471 /// assert!(vec.capacity() >= 11);
472 ///
473 /// // A vector of a zero-sized type will always over-allocate, since no
474 /// // allocation is necessary
475 /// let vec_units = Vec::<()>::with_capacity(10);
476 /// assert_eq!(vec_units.capacity(), usize::MAX);
477 /// ```
478 #[inline]
479 pub fn try_with_capacity(capacity: usize) -> Result<Self, Error> {
480 Self::try_with_capacity_in(capacity, Global)
481 }
482
483 /// Convert a [`Vec<T>`] into a std `Vec<T>`.
484 ///
485 /// The result is allocated on the heap, using the default global allocator
486 /// so this is a zero-copy operation.
487 ///
488 /// The memory previously occupied by this vector will be released.
489 #[cfg(feature = "alloc")]
490 pub fn into_std(self) -> ::rust_alloc::vec::Vec<T> {
491 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
492
493 if let Ok(layout) = Layout::array::<T>(cap) {
494 alloc.release(layout);
495 }
496
497 // SAFETY: All the internal invariants of this vector matches what is
498 // needed to construct a rust vector, and the memory has been allocated
499 // using the std `Global` allocator.
500 unsafe { ::rust_alloc::vec::Vec::from_raw_parts(ptr, len, cap) }
501 }
502}
503
504impl<T, A: Allocator> Vec<T, A> {
505 /// Constructs a new, empty `Vec<T, A>`.
506 ///
507 /// The vector will not allocate until elements are pushed onto it.
508 ///
509 /// # Examples
510 ///
511 /// ```
512 /// use rune::alloc::Vec;
513 /// use rune::alloc::alloc::Global;
514 ///
515 /// let mut vec: Vec<i32, Global> = Vec::new_in(Global);
516 /// ```
517 #[inline]
518 pub const fn new_in(alloc: A) -> Self {
519 Vec {
520 buf: RawVec::new_in(alloc),
521 len: 0,
522 }
523 }
524
525 /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
526 /// with the provided allocator.
527 ///
528 /// The vector will be able to hold at least `capacity` elements without
529 /// reallocating. This method is allowed to allocate for more elements than
530 /// `capacity`. If `capacity` is 0, the vector will not allocate.
531 ///
532 /// It is important to note that although the returned vector has the
533 /// minimum *capacity* specified, the vector will have a zero *length*. For
534 /// an explanation of the difference between length and capacity, see
535 /// *[Capacity and reallocation]*.
536 ///
537 /// If it is important to know the exact allocated capacity of a `Vec`,
538 /// always use the [`capacity`] method after construction.
539 ///
540 /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no
541 /// allocation and the capacity will always be `usize::MAX`.
542 ///
543 /// [Capacity and reallocation]: #capacity-and-reallocation
544 /// [`capacity`]: Vec::capacity
545 ///
546 /// # Errors
547 ///
548 /// Errors with [`Error::CapacityOverflow`] if the new capacity exceeds
549 /// `isize::MAX` bytes.
550 ///
551 /// # Examples
552 ///
553 /// ```
554 /// use rune::alloc::Vec;
555 /// use rune::alloc::alloc::Global;
556 ///
557 /// let mut vec = Vec::try_with_capacity_in(10, Global)?;
558 ///
559 /// // The vector contains no items, even though it has capacity for more
560 /// assert_eq!(vec.len(), 0);
561 /// assert!(vec.capacity() >= 10);
562 ///
563 /// // These are all done without reallocating...
564 /// for i in 0..10 {
565 /// vec.try_push(i)?;
566 /// }
567 ///
568 /// assert_eq!(vec.len(), 10);
569 /// assert!(vec.capacity() >= 10);
570 ///
571 /// // ...but this may make the vector reallocate
572 /// vec.try_push(11)?;
573 /// assert_eq!(vec.len(), 11);
574 /// assert!(vec.capacity() >= 11);
575 ///
576 /// // A vector of a zero-sized type will always over-allocate, since no
577 /// // allocation is necessary
578 /// let vec_units = Vec::<(), Global>::try_with_capacity_in(10, Global)?;
579 /// assert_eq!(vec_units.capacity(), usize::MAX);
580 /// # Ok::<_, rune::alloc::Error>(())
581 /// ```
582 #[inline]
583 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, Error> {
584 Ok(Vec {
585 buf: RawVec::try_with_capacity_in(capacity, alloc)?,
586 len: 0,
587 })
588 }
589
590 /// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length, and
591 /// an allocator.
592 ///
593 /// # Safety
594 ///
595 /// This is highly unsafe, due to the number of invariants that aren't
596 /// checked:
597 ///
598 /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
599 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
600 /// (`T` having a less strict alignment is not sufficient, the alignment
601 /// really needs to be equal to satisfy the [`dealloc`] requirement that
602 /// memory must be allocated and deallocated with the same layout.)
603 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes)
604 /// needs to be the same size as the pointer was allocated with. (Because
605 /// similar to alignment, [`dealloc`] must be called with the same layout
606 /// `size`.)
607 /// * `length` needs to be less than or equal to `capacity`.
608 /// * The first `length` values must be properly initialized values of type
609 /// `T`.
610 /// * `capacity` needs to [*fit*] the layout size that the pointer was
611 /// allocated with.
612 /// * The allocated size in bytes must be no larger than `isize::MAX`. See
613 /// the safety documentation of [`pointer::offset`].
614 ///
615 /// These requirements are always upheld by any `ptr` that has been
616 /// allocated via `Vec<T, A>`. Other allocation sources are allowed if the
617 /// invariants are upheld.
618 ///
619 /// Violating these may cause problems like corrupting the allocator's
620 /// internal data structures. For example it is **not** safe to build a
621 /// `Vec<u8>` from a pointer to a C `char` array with length `size_t`. It's
622 /// also not safe to build one from a `Vec<u16>` and its length, because the
623 /// allocator cares about the alignment, and these two types have different
624 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but
625 /// after turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
626 ///
627 /// The ownership of `ptr` is effectively transferred to the `Vec<T>` which
628 /// may then deallocate, reallocate or change the contents of memory pointed
629 /// to by the pointer at will. Ensure that nothing else uses the pointer
630 /// after calling this function.
631 ///
632 /// [`String`]: crate::string::String
633 /// [`dealloc`]: crate::alloc::Allocator::deallocate
634 /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
635 /// [*fit*]: crate::alloc::Allocator#memory-fitting
636 ///
637 /// # Examples
638 ///
639 /// ```
640 /// use std::ptr;
641 /// use std::mem;
642 ///
643 /// use rune::alloc::Vec;
644 /// use rune::alloc::alloc::Global;
645 ///
646 /// let mut v = Vec::try_with_capacity_in(3, Global)?;
647 /// v.try_push(1)?;
648 /// v.try_push(2)?;
649 /// v.try_push(3)?;
650 ///
651 /// // Prevent running `v`'s destructor so we are in complete control
652 /// // of the allocation.
653 /// let mut v = mem::ManuallyDrop::new(v);
654 ///
655 /// // Pull out the various important pieces of information about `v`
656 /// let p = v.as_mut_ptr();
657 /// let len = v.len();
658 /// let cap = v.capacity();
659 /// let alloc = v.allocator();
660 ///
661 /// unsafe {
662 /// // Overwrite memory with 4, 5, 6
663 /// for i in 0..len {
664 /// ptr::write(p.add(i), 4 + i);
665 /// }
666 ///
667 /// // Put everything back together into a Vec
668 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
669 /// assert_eq!(rebuilt, [4, 5, 6]);
670 /// }
671 /// # Ok::<_, rune::alloc::Error>(())
672 /// ```
673 ///
674 /// Using memory that was allocated elsewhere:
675 ///
676 /// ```rust
677 /// use core::alloc::Layout;
678 ///
679 /// use rune::alloc::Vec;
680 /// use rune::alloc::alloc::{Allocator, AllocError, Global};
681 ///
682 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
683 ///
684 /// let vec = unsafe {
685 /// let mem = match Global.allocate(layout) {
686 /// Ok(mem) => mem.cast::<u32>().as_ptr(),
687 /// Err(AllocError) => return,
688 /// };
689 ///
690 /// mem.write(1_000_000);
691 ///
692 /// Vec::from_raw_parts_in(mem, 1, 16, Global)
693 /// };
694 ///
695 /// assert_eq!(vec, &[1_000_000]);
696 /// assert_eq!(vec.capacity(), 16);
697 /// ```
698 ///
699 /// [`pointer::offset`]: primitive@pointer
700 #[inline]
701 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
702 unsafe {
703 Vec {
704 buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
705 len: length,
706 }
707 }
708 }
709
710 /// Returns a reference to the underlying allocator.
711 #[inline]
712 pub fn allocator(&self) -> &A {
713 self.buf.allocator()
714 }
715
716 pub(crate) fn into_raw_vec(self) -> (RawVec<T, A>, usize) {
717 let me = ManuallyDrop::new(self);
718 let buf = unsafe { ptr::read(&me.buf) };
719 (buf, me.len)
720 }
721
722 /// Decomposes a `Vec<T>` into its raw components.
723 ///
724 /// Returns the raw pointer to the underlying data, the length of the vector
725 /// (in elements), the allocated capacity of the data (in elements), and the
726 /// allocator. These are the same arguments in the same order as the
727 /// arguments to [`from_raw_parts_in`].
728 ///
729 /// After calling this function, the caller is responsible for the memory
730 /// previously managed by the `Vec`. The only way to do this is to convert
731 /// the raw pointer, length, and capacity back into a `Vec` with the
732 /// [`from_raw_parts_in`] function, allowing the destructor to perform the
733 /// cleanup.
734 ///
735 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// use rune::alloc::Vec;
741 /// use rune::alloc::alloc::Global;
742 ///
743 /// let mut v: Vec<i32> = Vec::new_in(Global);
744 /// v.try_push(-1)?;
745 /// v.try_push(0)?;
746 /// v.try_push(1)?;
747 ///
748 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
749 ///
750 /// let rebuilt = unsafe {
751 /// // We can now make changes to the components, such as
752 /// // transmuting the raw pointer to a compatible type.
753 /// let ptr = ptr as *mut u32;
754 ///
755 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
756 /// };
757 ///
758 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
759 /// # Ok::<_, rune::alloc::Error>(())
760 /// ```
761 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
762 let mut me = ManuallyDrop::new(self);
763 let len = me.len();
764 let capacity = me.capacity();
765 let ptr = me.as_mut_ptr();
766 let alloc = unsafe { ptr::read(me.allocator()) };
767 (ptr, len, capacity, alloc)
768 }
769
770 /// Returns the total number of elements the vector can hold without
771 /// reallocating.
772 ///
773 /// # Examples
774 ///
775 /// ```
776 /// use rune::alloc::Vec;
777 /// use rune::alloc::alloc::Global;
778 ///
779 /// let mut vec: Vec<i32> = Vec::try_with_capacity_in(10, Global)?;
780 /// vec.try_push(42)?;
781 /// assert!(vec.capacity() >= 10);
782 /// # Ok::<_, rune::alloc::Error>(())
783 /// ```
784 #[inline]
785 pub fn capacity(&self) -> usize {
786 self.buf.capacity()
787 }
788
789 /// Tries to reserve capacity for at least `additional` more elements to be inserted
790 /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
791 /// frequent reallocations. After calling `try_reserve`, capacity will be
792 /// greater than or equal to `self.len() + additional` if it returns
793 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
794 /// preserves the contents even if an error occurs.
795 ///
796 /// # Errors
797 ///
798 /// If the capacity overflows, or the allocator reports a failure, then an error
799 /// is returned.
800 ///
801 /// # Examples
802 ///
803 /// ```
804 /// use rune::alloc::{Vec, Error};
805 ///
806 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, Error> {
807 /// let mut output = Vec::new();
808 ///
809 /// // Pre-reserve the memory, exiting if we can't
810 /// output.try_reserve(data.len())?;
811 ///
812 /// for value in data {
813 /// output.try_push(*value)?;
814 /// }
815 ///
816 /// Ok(output)
817 /// }
818 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
819 /// ```
820 pub fn try_reserve(&mut self, additional: usize) -> Result<(), Error> {
821 self.buf.try_reserve(self.len, additional)
822 }
823
824 /// Tries to reserve the minimum capacity for at least `additional`
825 /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
826 /// this will not deliberately over-allocate to speculatively avoid frequent
827 /// allocations. After calling `try_reserve_exact`, capacity will be greater
828 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
829 /// Does nothing if the capacity is already sufficient.
830 ///
831 /// Note that the allocator may give the collection more space than it
832 /// requests. Therefore, capacity can not be relied upon to be precisely
833 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
834 ///
835 /// [`try_reserve`]: Vec::try_reserve
836 ///
837 /// # Errors
838 ///
839 /// If the capacity overflows, or the allocator reports a failure, then an error
840 /// is returned.
841 ///
842 /// # Examples
843 ///
844 /// ```
845 /// use rune::alloc::{Vec, Error};
846 /// use rune::alloc::prelude::*;
847 ///
848 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, Error> {
849 /// let mut output = Vec::new();
850 ///
851 /// // Pre-reserve the memory, exiting if we can't
852 /// output.try_reserve_exact(data.len())?;
853 ///
854 /// // Now we know this can't OOM in the middle of our complex work
855 /// output.try_extend(data.iter().map(|&val| {
856 /// val * 2 + 5 // very complicated
857 /// }))?;
858 ///
859 /// Ok(output)
860 /// }
861 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
862 /// ```
863 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), Error> {
864 self.buf.try_reserve_exact(self.len, additional)
865 }
866
867 /// Shrinks the capacity of the vector as much as possible.
868 ///
869 /// It will drop down as close as possible to the length but the allocator
870 /// may still inform the vector that there is space for a few more elements.
871 ///
872 /// # Examples
873 ///
874 /// ```
875 /// use rune::alloc::Vec;
876 /// use rune::alloc::prelude::*;
877 ///
878 /// let mut vec = Vec::try_with_capacity(10)?;
879 /// vec.try_extend([1, 2, 3])?;
880 /// assert!(vec.capacity() >= 10);
881 /// vec.try_shrink_to_fit()?;
882 /// assert!(vec.capacity() >= 3);
883 /// # Ok::<_, rune::alloc::Error>(())
884 /// ```
885 pub fn try_shrink_to_fit(&mut self) -> Result<(), Error> {
886 // The capacity is never less than the length, and there's nothing to do when
887 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
888 // by only calling it with a greater capacity.
889 if self.capacity() > self.len {
890 self.buf.try_shrink_to_fit(self.len)?;
891 }
892
893 Ok(())
894 }
895
896 /// Shrinks the capacity of the vector with a lower bound.
897 ///
898 /// The capacity will remain at least as large as both the length
899 /// and the supplied value.
900 ///
901 /// If the current capacity is less than the lower limit, this is a no-op.
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// use rune::alloc::Vec;
907 /// use rune::alloc::prelude::*;
908 ///
909 /// let mut vec = Vec::try_with_capacity(10)?;
910 /// vec.try_extend([1, 2, 3])?;
911 /// assert!(vec.capacity() >= 10);
912 /// vec.try_shrink_to(4)?;
913 /// assert!(vec.capacity() >= 4);
914 /// vec.try_shrink_to(0)?;
915 /// assert!(vec.capacity() >= 3);
916 /// # Ok::<_, rune::alloc::Error>(())
917 /// ```
918 pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), Error> {
919 if self.capacity() > min_capacity {
920 self.buf
921 .try_shrink_to_fit(cmp::max(self.len, min_capacity))?;
922 }
923
924 Ok(())
925 }
926
927 /// Converts the vector into [`Box<[T]>`][owned slice].
928 ///
929 /// If the vector has excess capacity, its items will be moved into a
930 /// newly-allocated buffer with exactly the right capacity.
931 ///
932 /// [owned slice]: Box
933 ///
934 /// # Examples
935 ///
936 /// ```
937 /// use rune::alloc::try_vec;
938 ///
939 /// let v = try_vec![1, 2, 3];
940 /// let slice = v.try_into_boxed_slice()?;
941 /// # Ok::<_, rune::alloc::Error>(())
942 /// ```
943 ///
944 /// Any excess capacity is removed:
945 ///
946 /// ```
947 /// use rune::alloc::Vec;
948 /// use rune::alloc::prelude::*;
949 ///
950 /// let mut vec = Vec::try_with_capacity(10)?;
951 /// vec.try_extend([1, 2, 3])?;
952 ///
953 /// assert!(vec.capacity() >= 10);
954 /// let slice = vec.try_into_boxed_slice()?;
955 /// assert_eq!(Vec::from(slice).capacity(), 3);
956 /// # Ok::<_, rune::alloc::Error>(())
957 /// ```
958 pub fn try_into_boxed_slice(mut self) -> Result<Box<[T], A>, Error> {
959 unsafe {
960 self.try_shrink_to_fit()?;
961 let me = ManuallyDrop::new(self);
962 let buf = ptr::read(&me.buf);
963 let len = me.len();
964 Ok(buf.into_box(len).assume_init())
965 }
966 }
967
968 /// Shortens the vector, keeping the first `len` elements and dropping
969 /// the rest.
970 ///
971 /// If `len` is greater than the vector's current length, this has no
972 /// effect.
973 ///
974 /// The [`drain`] method can emulate `truncate`, but causes the excess
975 /// elements to be returned instead of dropped.
976 ///
977 /// Note that this method has no effect on the allocated capacity
978 /// of the vector.
979 ///
980 /// # Examples
981 ///
982 /// Truncating a five element vector to two elements:
983 ///
984 /// ```
985 /// use rune::alloc::try_vec;
986 ///
987 /// let mut vec = try_vec![1, 2, 3, 4, 5];
988 /// vec.truncate(2);
989 /// assert_eq!(vec, [1, 2]);
990 /// # Ok::<_, rune::alloc::Error>(())
991 /// ```
992 ///
993 /// No truncation occurs when `len` is greater than the vector's current
994 /// length:
995 ///
996 /// ```
997 /// use rune::alloc::try_vec;
998 ///
999 /// let mut vec = try_vec![1, 2, 3];
1000 /// vec.truncate(8);
1001 /// assert_eq!(vec, [1, 2, 3]);
1002 /// # Ok::<_, rune::alloc::Error>(())
1003 /// ```
1004 ///
1005 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1006 /// method.
1007 ///
1008 /// ```
1009 /// use rune::alloc::try_vec;
1010 ///
1011 /// let mut vec = try_vec![1, 2, 3];
1012 /// vec.truncate(0);
1013 /// assert_eq!(vec, []);
1014 /// # Ok::<_, rune::alloc::Error>(())
1015 /// ```
1016 ///
1017 /// [`clear`]: Vec::clear
1018 /// [`drain`]: Vec::drain
1019 pub fn truncate(&mut self, len: usize) {
1020 // This is safe because:
1021 //
1022 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1023 // case avoids creating an invalid slice, and
1024 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1025 // such that no value will be dropped twice in case `drop_in_place`
1026 // were to panic once (if it panics twice, the program aborts).
1027 unsafe {
1028 // Note: It's intentional that this is `>` and not `>=`.
1029 // Changing it to `>=` has negative performance
1030 // implications in some cases. See #78884 for more.
1031 if len > self.len {
1032 return;
1033 }
1034 let remaining_len = self.len - len;
1035 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1036 self.len = len;
1037 ptr::drop_in_place(s);
1038 }
1039 }
1040
1041 /// Extracts a slice containing the entire vector.
1042 ///
1043 /// Equivalent to `&s[..]`.
1044 ///
1045 /// # Examples
1046 ///
1047 /// ```
1048 /// use std::io::{self, Write};
1049 /// use rune::alloc::try_vec;
1050 ///
1051 /// let buffer = try_vec![1, 2, 3, 5, 8];
1052 /// io::sink().write(buffer.as_slice()).unwrap();
1053 /// # Ok::<_, rune::alloc::Error>(())
1054 /// ```
1055 #[inline]
1056 pub fn as_slice(&self) -> &[T] {
1057 self
1058 }
1059
1060 /// Extracts a mutable slice of the entire vector.
1061 ///
1062 /// Equivalent to `&mut s[..]`.
1063 ///
1064 /// # Examples
1065 ///
1066 /// ```
1067 /// use std::io::{self, Read};
1068 /// use rune::alloc::try_vec;
1069 ///
1070 /// let mut buffer = try_vec![0; 3];
1071 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1072 /// # Ok::<_, rune::alloc::Error>(())
1073 /// ```
1074 #[inline]
1075 pub fn as_mut_slice(&mut self) -> &mut [T] {
1076 self
1077 }
1078
1079 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1080 /// valid for zero sized reads if the vector didn't allocate.
1081 ///
1082 /// The caller must ensure that the vector outlives the pointer this
1083 /// function returns, or else it will end up pointing to garbage.
1084 /// Modifying the vector may cause its buffer to be reallocated,
1085 /// which would also make any pointers to it invalid.
1086 ///
1087 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1088 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1089 /// derived from it. If you need to mutate the contents of the slice, use
1090 /// [`as_mut_ptr`].
1091 ///
1092 /// # Examples
1093 ///
1094 /// ```
1095 /// use rune::alloc::try_vec;
1096 ///
1097 /// let x = try_vec![1, 2, 4];
1098 /// let x_ptr = x.as_ptr();
1099 ///
1100 /// unsafe {
1101 /// for i in 0..x.len() {
1102 /// assert_eq!(*x_ptr.add(i), 1 << i);
1103 /// }
1104 /// }
1105 /// # Ok::<_, rune::alloc::Error>(())
1106 /// ```
1107 ///
1108 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1109 #[inline]
1110 pub fn as_ptr(&self) -> *const T {
1111 // We shadow the slice method of the same name to avoid going through
1112 // `deref`, which creates an intermediate reference.
1113 self.buf.ptr()
1114 }
1115
1116 /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
1117 /// raw pointer valid for zero sized reads if the vector didn't allocate.
1118 ///
1119 /// The caller must ensure that the vector outlives the pointer this
1120 /// function returns, or else it will end up pointing to garbage.
1121 /// Modifying the vector may cause its buffer to be reallocated,
1122 /// which would also make any pointers to it invalid.
1123 ///
1124 /// # Examples
1125 ///
1126 /// ```
1127 /// use rune::alloc::Vec;
1128 ///
1129 /// // Allocate vector big enough for 4 elements.
1130 /// let size = 4;
1131 /// let mut x: Vec<i32> = Vec::try_with_capacity(size)?;
1132 /// let x_ptr = x.as_mut_ptr();
1133 ///
1134 /// // Initialize elements via raw pointer writes, then set length.
1135 /// unsafe {
1136 /// for i in 0..size {
1137 /// *x_ptr.add(i) = i as i32;
1138 /// }
1139 /// x.set_len(size);
1140 /// }
1141 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1142 /// # Ok::<_, rune::alloc::Error>(())
1143 /// ```
1144 #[inline]
1145 pub fn as_mut_ptr(&mut self) -> *mut T {
1146 // We shadow the slice method of the same name to avoid going through
1147 // `deref_mut`, which creates an intermediate reference.
1148 self.buf.ptr()
1149 }
1150
1151 /// Forces the length of the vector to `new_len`.
1152 ///
1153 /// This is a low-level operation that maintains none of the normal
1154 /// invariants of the type. Normally changing the length of a vector
1155 /// is done using one of the safe operations instead, such as
1156 /// [`truncate`], [`try_resize`], [`try_extend`], or [`clear`].
1157 ///
1158 /// [`truncate`]: Vec::truncate
1159 /// [`try_resize`]: Vec::try_resize
1160 /// [`try_extend`]: Extend::extend
1161 /// [`clear`]: Vec::clear
1162 ///
1163 /// # Safety
1164 ///
1165 /// - `new_len` must be less than or equal to [`capacity()`].
1166 /// - The elements at `old_len..new_len` must be initialized.
1167 ///
1168 /// [`capacity()`]: Vec::capacity
1169 ///
1170 /// # Examples
1171 ///
1172 /// This method can be useful for situations in which the vector
1173 /// is serving as a buffer for other code, particularly over FFI:
1174 ///
1175 /// ```no_run
1176 /// # #![allow(dead_code)]
1177 /// # // This is just a minimal skeleton for the doc example;
1178 /// # // don't use this as a starting point for a real library.
1179 /// # pub(crate) struct StreamWrapper { strm: *mut std::ffi::c_void }
1180 /// # const Z_OK: i32 = 0;
1181 /// # extern "C" {
1182 /// # fn deflateGetDictionary(
1183 /// # strm: *mut std::ffi::c_void,
1184 /// # dictionary: *mut u8,
1185 /// # dictLength: *mut usize,
1186 /// # ) -> i32;
1187 /// # }
1188 /// # impl StreamWrapper {
1189 /// pub(crate) fn get_dictionary(&self) -> Option<Vec<u8>> {
1190 /// // Per the FFI method's docs, "32768 bytes is always enough".
1191 /// let mut dict = Vec::with_capacity(32_768);
1192 /// let mut dict_length = 0;
1193 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1194 /// // 1. `dict_length` elements were initialized.
1195 /// // 2. `dict_length` <= the capacity (32_768)
1196 /// // which makes `set_len` safe to call.
1197 /// unsafe {
1198 /// // Make the FFI call...
1199 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1200 /// if r == Z_OK {
1201 /// // ...and update the length to what was initialized.
1202 /// dict.set_len(dict_length);
1203 /// Some(dict)
1204 /// } else {
1205 /// None
1206 /// }
1207 /// }
1208 /// }
1209 /// # }
1210 /// ```
1211 ///
1212 /// While the following example is sound, there is a memory leak since
1213 /// the inner vectors were not freed prior to the `set_len` call:
1214 ///
1215 /// ```
1216 /// # #[cfg(not(miri))]
1217 /// # fn main() -> Result<(), rune_alloc::Error> {
1218 /// use rune::alloc::try_vec;
1219 ///
1220 /// let mut vec = try_vec![try_vec![1, 0, 0],
1221 /// try_vec![0, 1, 0],
1222 /// try_vec![0, 0, 1]];
1223 /// // SAFETY:
1224 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1225 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1226 /// unsafe {
1227 /// vec.set_len(0);
1228 /// }
1229 /// # Ok(())
1230 /// # }
1231 /// # #[cfg(miri)] fn main() {}
1232 /// ```
1233 ///
1234 /// Normally, here, one would use [`clear`] instead to correctly drop
1235 /// the contents and thus not leak memory.
1236 #[inline]
1237 pub unsafe fn set_len(&mut self, new_len: usize) {
1238 debug_assert!(new_len <= self.capacity());
1239 self.len = new_len;
1240 }
1241
1242 /// Removes an element from the vector and returns it.
1243 ///
1244 /// The removed element is replaced by the last element of the vector.
1245 ///
1246 /// This does not preserve ordering, but is *O*(1).
1247 /// If you need to preserve the element order, use [`remove`] instead.
1248 ///
1249 /// [`remove`]: Vec::remove
1250 ///
1251 /// # Panics
1252 ///
1253 /// Panics if `index` is out of bounds.
1254 ///
1255 /// # Examples
1256 ///
1257 /// ```
1258 /// use rune::alloc::try_vec;
1259 ///
1260 /// let mut v = try_vec!["foo", "bar", "baz", "qux"];
1261 ///
1262 /// assert_eq!(v.swap_remove(1), "bar");
1263 /// assert_eq!(v, ["foo", "qux", "baz"]);
1264 ///
1265 /// assert_eq!(v.swap_remove(0), "foo");
1266 /// assert_eq!(v, ["baz", "qux"]);
1267 /// # Ok::<_, rune::alloc::Error>(())
1268 /// ```
1269 #[inline]
1270 pub fn swap_remove(&mut self, index: usize) -> T {
1271 #[cold]
1272 #[inline(never)]
1273 fn assert_failed(index: usize, len: usize) -> ! {
1274 panic!("swap_remove index (is {index}) should be < len (is {len})");
1275 }
1276
1277 let len = self.len();
1278 if index >= len {
1279 assert_failed(index, len);
1280 }
1281 unsafe {
1282 // We replace self[index] with the last element. Note that if the
1283 // bounds check above succeeds there must be a last element (which
1284 // can be self[index] itself).
1285 let value = ptr::read(self.as_ptr().add(index));
1286 let base_ptr = self.as_mut_ptr();
1287 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1288 self.set_len(len - 1);
1289 value
1290 }
1291 }
1292
1293 /// Inserts an element at position `index` within the vector, shifting all
1294 /// elements after it to the right.
1295 ///
1296 /// # Panics
1297 ///
1298 /// Panics if `index > len`.
1299 ///
1300 /// # Examples
1301 ///
1302 /// ```
1303 /// use rune::alloc::try_vec;
1304 ///
1305 /// let mut vec = try_vec![1, 2, 3];
1306 /// vec.try_insert(1, 4)?;
1307 /// assert_eq!(vec, [1, 4, 2, 3]);
1308 /// vec.try_insert(4, 5)?;
1309 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1310 /// # Ok::<_, rune::alloc::Error>(())
1311 /// ```
1312 pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), Error> {
1313 #[cold]
1314 #[inline(never)]
1315 fn assert_failed(index: usize, len: usize) -> ! {
1316 panic!("insertion index (is {index}) should be <= len (is {len})");
1317 }
1318
1319 let len = self.len();
1320
1321 // space for the new element
1322 if len == self.buf.capacity() {
1323 self.try_reserve(1)?;
1324 }
1325
1326 unsafe {
1327 // infallible
1328 // The spot to put the new value
1329 {
1330 let p = self.as_mut_ptr().add(index);
1331 if index < len {
1332 // Shift everything over to make space. (Duplicating the
1333 // `index`th element into two consecutive places.)
1334 ptr::copy(p, p.add(1), len - index);
1335 } else if index == len {
1336 // No elements need shifting.
1337 } else {
1338 assert_failed(index, len);
1339 }
1340 // Write it in, overwriting the first copy of the `index`th
1341 // element.
1342 ptr::write(p, element);
1343 }
1344 self.set_len(len + 1);
1345 }
1346
1347 Ok(())
1348 }
1349
1350 /// Removes and returns the element at position `index` within the vector,
1351 /// shifting all elements after it to the left.
1352 ///
1353 /// Note: Because this shifts over the remaining elements, it has a
1354 /// worst-case performance of *O*(*n*). If you don't need the order of
1355 /// elements to be preserved, use [`swap_remove`] instead. If you'd like to
1356 /// remove elements from the beginning of the `Vec`, consider using
1357 /// [`VecDeque::pop_front`] instead.
1358 ///
1359 /// [`swap_remove`]: crate::Vec::swap_remove
1360 /// [`VecDeque::pop_front`]: crate::VecDeque::pop_front
1361 ///
1362 /// # Panics
1363 ///
1364 /// Panics if `index` is out of bounds.
1365 ///
1366 /// # Examples
1367 ///
1368 /// ```
1369 /// use rune::alloc::try_vec;
1370 ///
1371 /// let mut v = try_vec![1, 2, 3];
1372 /// assert_eq!(v.remove(1), 2);
1373 /// assert_eq!(v, [1, 3]);
1374 /// # Ok::<_, rune::alloc::Error>(())
1375 /// ```
1376 #[track_caller]
1377 pub fn remove(&mut self, index: usize) -> T {
1378 #[cold]
1379 #[inline(never)]
1380 #[track_caller]
1381 fn assert_failed(index: usize, len: usize) -> ! {
1382 panic!("removal index (is {index}) should be < len (is {len})");
1383 }
1384
1385 let len = self.len();
1386 if index >= len {
1387 assert_failed(index, len);
1388 }
1389 unsafe {
1390 // infallible
1391 let ret;
1392 {
1393 // the place we are taking from.
1394 let ptr = self.as_mut_ptr().add(index);
1395 // copy it out, unsafely having a copy of the value on
1396 // the stack and in the vector at the same time.
1397 ret = ptr::read(ptr);
1398
1399 // Shift everything down to fill in that spot.
1400 ptr::copy(ptr.add(1), ptr, len - index - 1);
1401 }
1402 self.set_len(len - 1);
1403 ret
1404 }
1405 }
1406
1407 /// Retains only the elements specified by the predicate.
1408 ///
1409 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1410 /// This method operates in place, visiting each element exactly once in the
1411 /// original order, and preserves the order of the retained elements.
1412 ///
1413 /// # Examples
1414 ///
1415 /// ```
1416 /// use rune::alloc::try_vec;
1417 ///
1418 /// let mut vec = try_vec![1, 2, 3, 4];
1419 /// vec.retain(|&x| x % 2 == 0);
1420 /// assert_eq!(vec, [2, 4]);
1421 /// # Ok::<_, rune::alloc::Error>(())
1422 /// ```
1423 ///
1424 /// Because the elements are visited exactly once in the original order,
1425 /// external state may be used to decide which elements to keep.
1426 ///
1427 /// ```
1428 /// use rune::alloc::try_vec;
1429 ///
1430 /// let mut vec = try_vec![1, 2, 3, 4, 5];
1431 /// let keep = [false, true, true, false, true];
1432 /// let mut iter = keep.iter();
1433 /// vec.retain(|_| *iter.next().unwrap());
1434 /// assert_eq!(vec, [2, 3, 5]);
1435 /// # Ok::<_, rune::alloc::Error>(())
1436 /// ```
1437 pub fn retain<F>(&mut self, mut f: F)
1438 where
1439 F: FnMut(&T) -> bool,
1440 {
1441 self.retain_mut(|elem| f(elem));
1442 }
1443
1444 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1445 ///
1446 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1447 /// This method operates in place, visiting each element exactly once in the
1448 /// original order, and preserves the order of the retained elements.
1449 ///
1450 /// # Examples
1451 ///
1452 /// ```
1453 /// use rune::alloc::try_vec;
1454 ///
1455 /// let mut vec = try_vec![1, 2, 3, 4];
1456 /// vec.retain_mut(|x| if *x <= 3 {
1457 /// *x += 1;
1458 /// true
1459 /// } else {
1460 /// false
1461 /// });
1462 /// assert_eq!(vec, [2, 3, 4]);
1463 /// # Ok::<_, rune::alloc::Error>(())
1464 /// ```
1465 pub fn retain_mut<F>(&mut self, mut f: F)
1466 where
1467 F: FnMut(&mut T) -> bool,
1468 {
1469 let original_len = self.len();
1470 // Avoid double drop if the drop guard is not executed,
1471 // since we may make some holes during the process.
1472 unsafe { self.set_len(0) };
1473
1474 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1475 // |<- processed len ->| ^- next to check
1476 // |<- deleted cnt ->|
1477 // |<- original_len ->|
1478 // Kept: Elements which predicate returns true on.
1479 // Hole: Moved or dropped element slot.
1480 // Unchecked: Unchecked valid elements.
1481 //
1482 // This drop guard will be invoked when predicate or `drop` of element panicked.
1483 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1484 // In cases when predicate and `drop` never panick, it will be optimized out.
1485 struct BackshiftOnDrop<'a, T, A: Allocator> {
1486 v: &'a mut Vec<T, A>,
1487 processed_len: usize,
1488 deleted_cnt: usize,
1489 original_len: usize,
1490 }
1491
1492 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1493 fn drop(&mut self) {
1494 if self.deleted_cnt > 0 {
1495 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1496 unsafe {
1497 ptr::copy(
1498 self.v.as_ptr().add(self.processed_len),
1499 self.v
1500 .as_mut_ptr()
1501 .add(self.processed_len - self.deleted_cnt),
1502 self.original_len - self.processed_len,
1503 );
1504 }
1505 }
1506 // SAFETY: After filling holes, all items are in contiguous memory.
1507 unsafe {
1508 self.v.set_len(self.original_len - self.deleted_cnt);
1509 }
1510 }
1511 }
1512
1513 let mut g = BackshiftOnDrop {
1514 v: self,
1515 processed_len: 0,
1516 deleted_cnt: 0,
1517 original_len,
1518 };
1519
1520 fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1521 original_len: usize,
1522 f: &mut F,
1523 g: &mut BackshiftOnDrop<'_, T, A>,
1524 ) where
1525 F: FnMut(&mut T) -> bool,
1526 {
1527 while g.processed_len != original_len {
1528 // SAFETY: Unchecked element must be valid.
1529 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1530 if !f(cur) {
1531 // Advance early to avoid double drop if `drop_in_place` panicked.
1532 g.processed_len += 1;
1533 g.deleted_cnt += 1;
1534 // SAFETY: We never touch this element again after dropped.
1535 unsafe { ptr::drop_in_place(cur) };
1536 // We already advanced the counter.
1537 if DELETED {
1538 continue;
1539 } else {
1540 break;
1541 }
1542 }
1543 if DELETED {
1544 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1545 // We use copy for move, and never touch this element again.
1546 unsafe {
1547 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1548 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1549 }
1550 }
1551 g.processed_len += 1;
1552 }
1553 }
1554
1555 // Stage 1: Nothing was deleted.
1556 process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1557
1558 // Stage 2: Some elements were deleted.
1559 process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1560
1561 // All item are processed. This can be optimized to `set_len` by LLVM.
1562 drop(g);
1563 }
1564
1565 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1566 /// key.
1567 ///
1568 /// If the vector is sorted, this removes all duplicates.
1569 ///
1570 /// # Examples
1571 ///
1572 /// ```
1573 /// use rune::alloc::try_vec;
1574 ///
1575 /// let mut vec = try_vec![10, 20, 21, 30, 20];
1576 /// vec.dedup_by_key(|i| *i / 10);
1577 /// assert_eq!(vec, [10, 20, 30, 20]);
1578 /// # Ok::<_, rune::alloc::Error>(())
1579 /// ```
1580 #[inline]
1581 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1582 where
1583 F: FnMut(&mut T) -> K,
1584 K: PartialEq,
1585 {
1586 self.dedup_by(|a, b| key(a) == key(b))
1587 }
1588
1589 /// Removes all but the first of consecutive elements in the vector
1590 /// satisfying a given equality relation.
1591 ///
1592 /// The `same_bucket` function is passed references to two elements from the
1593 /// vector and must determine if the elements compare equal. The elements
1594 /// are passed in opposite order from their order in the slice, so if
1595 /// `same_bucket(a, b)` returns `true`, `a` is removed.
1596 ///
1597 /// If the vector is sorted, this removes all duplicates.
1598 ///
1599 /// # Examples
1600 ///
1601 /// ```
1602 /// use rune::alloc::try_vec;
1603 ///
1604 /// let mut vec = try_vec!["foo", "bar", "Bar", "baz", "bar"];
1605 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1606 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1607 /// # Ok::<_, rune::alloc::Error>(())
1608 /// ```
1609 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1610 where
1611 F: FnMut(&mut T, &mut T) -> bool,
1612 {
1613 let len = self.len();
1614
1615 if len <= 1 {
1616 return;
1617 }
1618
1619 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1620 struct FillGapOnDrop<'a, T, A: Allocator> {
1621 /* Offset of the element we want to check if it is duplicate */
1622 read: usize,
1623
1624 /* Offset of the place where we want to place the non-duplicate
1625 * when we find it. */
1626 write: usize,
1627
1628 /* The Vec that would need correction if `same_bucket` panicked */
1629 vec: &'a mut Vec<T, A>,
1630 }
1631
1632 impl<T, A: Allocator> Drop for FillGapOnDrop<'_, T, A> {
1633 fn drop(&mut self) {
1634 /* This code gets executed when `same_bucket` panics */
1635
1636 /* SAFETY: invariant guarantees that `read - write`
1637 * and `len - read` never overflow and that the copy is always
1638 * in-bounds. */
1639 unsafe {
1640 let ptr = self.vec.as_mut_ptr();
1641 let len = self.vec.len();
1642
1643 /* How many items were left when `same_bucket` panicked.
1644 * Basically vec[read..].len() */
1645 let items_left = len.wrapping_sub(self.read);
1646
1647 /* Pointer to first item in vec[write..write+items_left] slice */
1648 let dropped_ptr = ptr.add(self.write);
1649 /* Pointer to first item in vec[read..] slice */
1650 let valid_ptr = ptr.add(self.read);
1651
1652 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1653 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1654 ptr::copy(valid_ptr, dropped_ptr, items_left);
1655
1656 /* How many items have been already dropped
1657 * Basically vec[read..write].len() */
1658 let dropped = self.read.wrapping_sub(self.write);
1659
1660 self.vec.set_len(len - dropped);
1661 }
1662 }
1663 }
1664
1665 let mut gap = FillGapOnDrop {
1666 read: 1,
1667 write: 1,
1668 vec: self,
1669 };
1670
1671 let ptr = gap.vec.as_mut_ptr();
1672
1673 /* Drop items while going through Vec, it should be more efficient than
1674 * doing slice partition_dedup + truncate */
1675
1676 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1677 * are always in-bounds and read_ptr never aliases prev_ptr */
1678 unsafe {
1679 while gap.read < len {
1680 let read_ptr = ptr.add(gap.read);
1681 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1682
1683 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1684 // Increase `gap.read` now since the drop may panic.
1685 gap.read += 1;
1686 /* We have found duplicate, drop it in-place */
1687 ptr::drop_in_place(read_ptr);
1688 } else {
1689 let write_ptr = ptr.add(gap.write);
1690
1691 /* Because `read_ptr` can be equal to `write_ptr`, we either
1692 * have to use `copy` or conditional `copy_nonoverlapping`.
1693 * Looks like the first option is faster. */
1694 ptr::copy(read_ptr, write_ptr, 1);
1695
1696 /* We have filled that place, so go further */
1697 gap.write += 1;
1698 gap.read += 1;
1699 }
1700 }
1701
1702 /* Technically we could let `gap` clean up with its Drop, but
1703 * when `same_bucket` is guaranteed to not panic, this bloats a little
1704 * the codegen, so we just do it manually */
1705 gap.vec.set_len(gap.write);
1706 mem::forget(gap);
1707 }
1708 }
1709
1710 /// Appends an element to the back of a collection.
1711 ///
1712 /// # Panics
1713 ///
1714 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1715 ///
1716 /// # Examples
1717 ///
1718 /// ```
1719 /// use rune::alloc::Vec;
1720 /// use rune::alloc::alloc::Global;
1721 ///
1722 /// let mut vec: Vec<i32> = Vec::try_with_capacity_in(2, Global)?;
1723 /// vec.try_push(1)?;
1724 /// vec.try_push(2)?;
1725 /// vec.try_push(3)?;
1726 /// assert_eq!(vec, [1, 2, 3]);
1727 /// # Ok::<_, rune::alloc::Error>(())
1728 /// ```
1729 #[inline]
1730 pub fn try_push(&mut self, value: T) -> Result<(), Error> {
1731 // This will panic or abort if we would allocate > isize::MAX bytes
1732 // or if the length increment would overflow for zero-sized types.
1733 if self.len == self.buf.capacity() {
1734 self.buf.try_reserve_for_push(self.len)?;
1735 }
1736
1737 unsafe {
1738 let end = self.as_mut_ptr().add(self.len);
1739 ptr::write(end, value);
1740 self.len += 1;
1741 }
1742
1743 Ok(())
1744 }
1745
1746 /// Appends an element if there is sufficient spare capacity, otherwise an
1747 /// error is returned with the element.
1748 ///
1749 /// Unlike [`try_push`] this method will not reallocate when there's
1750 /// insufficient capacity. The caller should use [`try_reserve`] to ensure
1751 /// that there is enough capacity.
1752 ///
1753 /// [`try_push`]: Vec::try?push
1754 /// [`try_reserve`]: Vec::try_reserve
1755 ///
1756 /// # Examples
1757 ///
1758 /// A manual, alternative to [`TryFromIteratorIn`]:
1759 ///
1760 /// ```
1761 /// use rune::alloc::{Vec, Error};
1762 /// use rune::alloc::prelude::*;
1763 ///
1764 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, Error> {
1765 /// let mut vec = Vec::new();
1766 ///
1767 /// for value in iter {
1768 /// if let Err(value) = vec.push_within_capacity(value) {
1769 /// vec.try_reserve(1)?;
1770 /// // this cannot fail, the previous line either returned or added at least 1 free slot
1771 /// let _ = vec.push_within_capacity(value);
1772 /// }
1773 /// }
1774 ///
1775 /// Ok(vec)
1776 /// }
1777 ///
1778 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::try_from_iter(0..100)?));
1779 /// # Ok::<_, Error>(())
1780 /// ```
1781 #[inline]
1782 pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
1783 if self.len == self.buf.capacity() {
1784 return Err(value);
1785 }
1786
1787 unsafe {
1788 let end = self.as_mut_ptr().add(self.len);
1789 ptr::write(end, value);
1790 self.len += 1;
1791 }
1792
1793 Ok(())
1794 }
1795
1796 /// Removes the last element from a vector and returns it, or [`None`] if it
1797 /// is empty.
1798 ///
1799 /// # Examples
1800 ///
1801 /// ```
1802 /// use rune::alloc::Vec;
1803 /// use rune::alloc::prelude::*;
1804 ///
1805 /// let mut vec = Vec::try_from_iter([1, 2, 3])?;
1806 /// assert_eq!(vec.pop(), Some(3));
1807 /// assert_eq!(vec, [1, 2]);
1808 /// # Ok::<_, rune::alloc::Error>(())
1809 /// ```
1810 #[inline]
1811 pub fn pop(&mut self) -> Option<T> {
1812 if self.len == 0 {
1813 None
1814 } else {
1815 unsafe {
1816 self.len -= 1;
1817 Some(ptr::read(self.as_ptr().add(self.len())))
1818 }
1819 }
1820 }
1821
1822 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1823 ///
1824 /// # Panics
1825 ///
1826 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1827 ///
1828 /// # Examples
1829 ///
1830 /// ```
1831 /// use rune::alloc::try_vec;
1832 ///
1833 /// let mut vec = try_vec![1, 2, 3];
1834 /// let mut vec2 = try_vec![4, 5, 6];
1835 /// vec.try_append(&mut vec2)?;
1836 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1837 /// assert_eq!(vec2, []);
1838 /// # Ok::<_, rune::alloc::Error>(())
1839 /// ```
1840 #[inline]
1841 pub fn try_append(&mut self, other: &mut Self) -> Result<(), Error> {
1842 unsafe {
1843 self.try_append_elements(other.as_slice() as _)?;
1844 other.set_len(0);
1845 }
1846
1847 Ok(())
1848 }
1849
1850 /// Appends elements to `self` from other buffer.
1851 #[inline]
1852 unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), Error> {
1853 let count = unsafe { (*other).len() };
1854 self.try_reserve(count)?;
1855 let len = self.len();
1856 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1857 self.len += count;
1858 Ok(())
1859 }
1860
1861 /// Construct a raw iterator over the current vector
1862 ///
1863 /// # Safety
1864 ///
1865 /// The caller must ensure that any pointers returned by the iterator are
1866 /// not dereferenced unless the object they were constructed from is still
1867 /// alive.
1868 pub unsafe fn raw_iter(&self) -> RawIter<T> {
1869 RawIter::new(self)
1870 }
1871
1872 /// Construct a raw mutable iterator over the current vector
1873 ///
1874 /// # Safety
1875 ///
1876 /// The caller must ensure that any pointers returned by the iterator are
1877 /// not dereferenced unless the object they were constructed from is still
1878 /// alive.
1879 ///
1880 /// As a mutable iterator, this also implies that *no other* mutable
1881 /// accesses are performed over the collection this was constructed from
1882 /// until the returned iterator has been dropped.
1883 pub unsafe fn raw_iter_mut(&mut self) -> RawIterMut<T> {
1884 RawIterMut::new(self)
1885 }
1886
1887 /// Removes the specified range from the vector in bulk, returning all
1888 /// removed elements as an iterator. If the iterator is dropped before
1889 /// being fully consumed, it drops the remaining removed elements.
1890 ///
1891 /// The returned iterator keeps a mutable borrow on the vector to optimize
1892 /// its implementation.
1893 ///
1894 /// # Panics
1895 ///
1896 /// Panics if the starting point is greater than the end point or if
1897 /// the end point is greater than the length of the vector.
1898 ///
1899 /// # Leaking
1900 ///
1901 /// If the returned iterator goes out of scope without being dropped (due to
1902 /// [`mem::forget`], for example), the vector may have lost and leaked
1903 /// elements arbitrarily, including elements outside the range.
1904 ///
1905 /// # Examples
1906 ///
1907 /// ```
1908 /// use rune::alloc::{try_vec, Vec};
1909 /// use rune::alloc::prelude::*;
1910 ///
1911 /// let mut v = try_vec![1, 2, 3];
1912 /// let u: Vec<_> = v.drain(1..).try_collect()?;
1913 /// assert_eq!(v, &[1]);
1914 /// assert_eq!(u, &[2, 3]);
1915 ///
1916 /// // A full range clears the vector, like `clear()` does
1917 /// v.drain(..);
1918 /// assert_eq!(v, &[]);
1919 /// # Ok::<_, rune::alloc::Error>(())
1920 /// ```
1921 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1922 where
1923 R: RangeBounds<usize>,
1924 {
1925 // Memory safety
1926 //
1927 // When the Drain is first created, it shortens the length of
1928 // the source vector to make sure no uninitialized or moved-from elements
1929 // are accessible at all if the Drain's destructor never gets to run.
1930 //
1931 // Drain will ptr::read out the values to remove.
1932 // When finished, remaining tail of the vec is copied back to cover
1933 // the hole, and the vector length is restored to the new length.
1934 //
1935 let len = self.len();
1936 let Range { start, end } = slice_range(range, ..len);
1937
1938 unsafe {
1939 // set self.vec length's to start, to be safe in case Drain is leaked
1940 self.set_len(start);
1941 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1942 Drain {
1943 tail_start: end,
1944 tail_len: len - end,
1945 iter: range_slice.iter(),
1946 vec: NonNull::from(self),
1947 }
1948 }
1949 }
1950
1951 /// Clears the vector, removing all values.
1952 ///
1953 /// Note that this method has no effect on the allocated capacity
1954 /// of the vector.
1955 ///
1956 /// # Examples
1957 ///
1958 /// ```
1959 /// use rune::alloc::try_vec;
1960 ///
1961 /// let mut v = try_vec![1, 2, 3];
1962 /// v.clear();
1963 /// assert!(v.is_empty());
1964 /// # Ok::<_, rune::alloc::Error>(())
1965 /// ```
1966 #[inline]
1967 pub fn clear(&mut self) {
1968 let elems: *mut [T] = self.as_mut_slice();
1969
1970 // SAFETY:
1971 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
1972 // - Setting `self.len` before calling `drop_in_place` means that,
1973 // if an element's `Drop` impl panics, the vector's `Drop` impl will
1974 // do nothing (leaking the rest of the elements) instead of dropping
1975 // some twice.
1976 unsafe {
1977 self.len = 0;
1978 ptr::drop_in_place(elems);
1979 }
1980 }
1981
1982 /// Returns the number of elements in the vector, also referred to as its
1983 /// 'length'.
1984 ///
1985 /// # Examples
1986 ///
1987 /// ```
1988 /// use rune::alloc::Vec;
1989 /// use rune::alloc::alloc::Global;
1990 ///
1991 /// let mut a = Vec::new_in(Global);
1992 ///
1993 /// for value in 0..3 {
1994 /// a.try_push(value)?;
1995 /// }
1996 ///
1997 /// assert_eq!(a.len(), 3);
1998 /// # Ok::<_, rune::alloc::Error>(())
1999 /// ```
2000 #[inline]
2001 pub const fn len(&self) -> usize {
2002 self.len
2003 }
2004
2005 /// Returns `true` if the vector contains no elements.
2006 ///
2007 /// # Examples
2008 ///
2009 /// ```
2010 /// use rune::alloc::Vec;
2011 ///
2012 /// let mut v = Vec::new();
2013 /// assert!(v.is_empty());
2014 ///
2015 /// v.try_push(1)?;
2016 /// assert!(!v.is_empty());
2017 /// # Ok::<_, rune::alloc::Error>(())
2018 /// ```
2019 pub fn is_empty(&self) -> bool {
2020 self.len() == 0
2021 }
2022
2023 /// Splits the collection into two at the given index.
2024 ///
2025 /// Returns a newly allocated vector containing the elements in the range
2026 /// `[at, len)`. After the call, the original vector will be left containing
2027 /// the elements `[0, at)` with its previous capacity unchanged.
2028 ///
2029 /// # Panics
2030 ///
2031 /// Panics if `at > len`.
2032 ///
2033 /// # Examples
2034 ///
2035 /// ```
2036 /// use rune::alloc::try_vec;
2037 ///
2038 /// let mut vec = try_vec![1, 2, 3];
2039 /// let vec2 = vec.try_split_off(1)?;
2040 /// assert_eq!(vec, [1]);
2041 /// assert_eq!(vec2, [2, 3]);
2042 /// # Ok::<_, rune::alloc::Error>(())
2043 /// ```
2044 #[inline]
2045 #[must_use = "use `.truncate()` if you don't need the other half"]
2046 pub fn try_split_off(&mut self, at: usize) -> Result<Self, Error>
2047 where
2048 A: Clone,
2049 {
2050 #[cold]
2051 #[inline(never)]
2052 fn assert_failed(at: usize, len: usize) -> ! {
2053 panic!("`at` split index (is {at}) should be <= len (is {len})");
2054 }
2055
2056 if at > self.len() {
2057 assert_failed(at, self.len());
2058 }
2059
2060 if at == 0 {
2061 let new = Vec::try_with_capacity_in(self.capacity(), self.allocator().clone())?;
2062 // the new vector can take over the original buffer and avoid the copy
2063 return Ok(mem::replace(self, new));
2064 }
2065
2066 let other_len = self.len - at;
2067 let mut other = Vec::try_with_capacity_in(other_len, self.allocator().clone())?;
2068
2069 // Unsafely `set_len` and copy items to `other`.
2070 unsafe {
2071 self.set_len(at);
2072 other.set_len(other_len);
2073 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2074 }
2075
2076 Ok(other)
2077 }
2078
2079 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2080 ///
2081 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2082 /// difference, with each additional slot filled with the result of
2083 /// calling the closure `f`. The return values from `f` will end up
2084 /// in the `Vec` in the order they have been generated.
2085 ///
2086 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2087 ///
2088 /// This method uses a closure to create new values on every push. If
2089 /// you'd rather [`Clone`] a given value, use [`Vec::try_resize`]. If you
2090 /// want to use the [`Default`] trait to generate values, you can
2091 /// pass [`Default::default`] as the second argument.
2092 ///
2093 /// # Examples
2094 ///
2095 /// ```
2096 /// use rune::alloc::try_vec;
2097 ///
2098 /// let mut vec = try_vec![1, 2, 3];
2099 /// vec.try_resize_with(5, Default::default)?;
2100 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2101 ///
2102 /// let mut vec = try_vec![];
2103 /// let mut p = 1;
2104 /// vec.try_resize_with(4, || { p *= 2; p })?;
2105 /// assert_eq!(vec, [2, 4, 8, 16]);
2106 /// # Ok::<_, rune::alloc::Error>(())
2107 /// ```
2108 pub fn try_resize_with<F>(&mut self, new_len: usize, f: F) -> Result<(), Error>
2109 where
2110 F: FnMut() -> T,
2111 {
2112 let len = self.len();
2113
2114 if new_len > len {
2115 self.try_extend_trusted(iter::repeat_with(f).take(new_len - len))?;
2116 } else {
2117 self.truncate(new_len);
2118 }
2119
2120 Ok(())
2121 }
2122
2123 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2124 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2125 /// `'a`. If the type has only static references, or none at all, then this
2126 /// may be chosen to be `'static`.
2127 ///
2128 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2129 /// so the leaked allocation may include unused capacity that is not part
2130 /// of the returned slice.
2131 ///
2132 /// This function is mainly useful for data that lives for the remainder of
2133 /// the program's life. Dropping the returned reference will cause a memory
2134 /// leak.
2135 ///
2136 /// # Examples
2137 ///
2138 /// Simple usage:
2139 ///
2140 /// ```
2141 /// use rune::alloc::try_vec;
2142 ///
2143 /// # #[cfg(not(miri))]
2144 /// # fn main() -> Result<(), rune_alloc::Error> {
2145 /// let x = try_vec![1, 2, 3];
2146 /// let static_ref: &'static mut [usize] = x.leak();
2147 /// static_ref[0] += 1;
2148 /// assert_eq!(static_ref, &[2, 2, 3]);
2149 /// # Ok(())
2150 /// # }
2151 /// # #[cfg(miri)] fn main() {}
2152 /// ```
2153 #[inline]
2154 pub fn leak<'a>(self) -> &'a mut [T]
2155 where
2156 A: 'a,
2157 {
2158 let mut me = ManuallyDrop::new(self);
2159 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2160 }
2161
2162 /// Returns the remaining spare capacity of the vector as a slice of
2163 /// `MaybeUninit<T>`.
2164 ///
2165 /// The returned slice can be used to fill the vector with data (e.g. by
2166 /// reading from a file) before marking the data as initialized using the
2167 /// [`set_len`] method.
2168 ///
2169 /// [`set_len`]: Vec::set_len
2170 ///
2171 /// # Examples
2172 ///
2173 /// ```
2174 /// use rune::alloc::Vec;
2175 ///
2176 /// // Allocate vector big enough for 10 elements.
2177 /// let mut v = Vec::try_with_capacity(10)?;
2178 ///
2179 /// // Fill in the first 3 elements.
2180 /// let uninit = v.spare_capacity_mut();
2181 /// uninit[0].write(0);
2182 /// uninit[1].write(1);
2183 /// uninit[2].write(2);
2184 ///
2185 /// // Mark the first 3 elements of the vector as being initialized.
2186 /// unsafe {
2187 /// v.set_len(3);
2188 /// }
2189 ///
2190 /// assert_eq!(&v, &[0, 1, 2]);
2191 /// # Ok::<_, rune::alloc::Error>(())
2192 /// ```
2193 #[inline]
2194 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2195 // Note:
2196 // This method is not implemented in terms of `split_at_spare_mut`,
2197 // to prevent invalidation of pointers to the buffer.
2198 unsafe {
2199 slice::from_raw_parts_mut(
2200 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2201 self.buf.capacity() - self.len,
2202 )
2203 }
2204 }
2205
2206 /// Returns vector content as a slice of `T`, along with the remaining spare
2207 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2208 ///
2209 /// The returned spare capacity slice can be used to fill the vector with data
2210 /// (e.g. by reading from a file) before marking the data as initialized using
2211 /// the [`set_len`] method.
2212 ///
2213 /// [`set_len`]: Vec::set_len
2214 ///
2215 /// Note that this is a low-level API, which should be used with care for
2216 /// optimization purposes. If you need to append data to a `Vec` you can use
2217 /// [`try_push`], [`try_extend`], [`try_extend_from_slice`],
2218 /// [`try_extend_from_within`], [`try_insert`], [`try_append`],
2219 /// [`try_resize`] or [`try_resize_with`], depending on your exact needs.
2220 ///
2221 /// [`try_push`]: Vec::try_push
2222 /// [`try_extend`]: Vec::try_extend
2223 /// [`try_extend_from_slice`]: Vec::try_extend_from_slice
2224 /// [`try_extend_from_within`]: Vec::try_extend_from_within
2225 /// [`try_insert`]: Vec::try_insert
2226 /// [`try_append`]: Vec::try_append
2227 /// [`try_resize`]: Vec::try_resize
2228 /// [`try_resize_with`]: Vec::try_resize_with
2229 ///
2230 /// # Examples
2231 ///
2232 /// ```
2233 /// use rune::alloc::try_vec;
2234 ///
2235 /// let mut v = try_vec![1, 1, 2];
2236 ///
2237 /// // Reserve additional space big enough for 10 elements.
2238 /// v.try_reserve(10)?;
2239 ///
2240 /// let (init, uninit) = v.split_at_spare_mut();
2241 /// let sum = init.iter().copied().sum::<u32>();
2242 ///
2243 /// // Fill in the next 4 elements.
2244 /// uninit[0].write(sum);
2245 /// uninit[1].write(sum * 2);
2246 /// uninit[2].write(sum * 3);
2247 /// uninit[3].write(sum * 4);
2248 ///
2249 /// // Mark the 4 elements of the vector as being initialized.
2250 /// unsafe {
2251 /// let len = v.len();
2252 /// v.set_len(len + 4);
2253 /// }
2254 ///
2255 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2256 /// # Ok::<_, rune::alloc::Error>(())
2257 /// ```
2258 #[inline]
2259 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2260 // SAFETY:
2261 // - len is ignored and so never changed
2262 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2263 (init, spare)
2264 }
2265
2266 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2267 ///
2268 /// This method provides unique access to all vec parts at once in `try_extend_from_within`.
2269 unsafe fn split_at_spare_mut_with_len(
2270 &mut self,
2271 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2272 let ptr = self.as_mut_ptr();
2273 // SAFETY:
2274 // - `ptr` is guaranteed to be valid for `self.len` elements
2275 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2276 // uninitialized
2277 let spare_ptr = unsafe { ptr.add(self.len) };
2278 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2279 let spare_len = self.buf.capacity() - self.len;
2280
2281 // SAFETY:
2282 // - `ptr` is guaranteed to be valid for `self.len` elements
2283 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2284 unsafe {
2285 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2286 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2287
2288 (initialized, spare, &mut self.len)
2289 }
2290 }
2291
2292 #[inline]
2293 pub(crate) fn try_splice_in_place<R, I>(
2294 &mut self,
2295 range: R,
2296 replace_with: I,
2297 ) -> Result<(), Error>
2298 where
2299 R: RangeBounds<usize>,
2300 I: IntoIterator<Item = T>,
2301 {
2302 let mut drain = self.drain(range);
2303 let mut iter = replace_with.into_iter();
2304 self::splice::splice(&mut drain, &mut iter)
2305 }
2306
2307 // specific extend for `TrustedLen` iterators, called both by the specializations
2308 // and internal places where resolving specialization makes compilation slower
2309 fn try_extend_trusted(&mut self, iterator: impl iter::Iterator<Item = T>) -> Result<(), Error> {
2310 let (low, high) = iterator.size_hint();
2311
2312 if let Some(additional) = high {
2313 debug_assert_eq!(
2314 low,
2315 additional,
2316 "TrustedLen iterator's size hint is not exact: {:?}",
2317 (low, high)
2318 );
2319
2320 self.try_reserve(additional)?;
2321
2322 unsafe {
2323 let ptr = self.as_mut_ptr();
2324 let mut local_len = SetLenOnDrop::new(&mut self.len);
2325
2326 for element in iterator {
2327 ptr::write(ptr.add(local_len.current_len()), element);
2328 // Since the loop executes user code which can panic we have to update
2329 // the length every step to correctly drop what we've written.
2330 // NB can't overflow since we would have had to alloc the address space
2331 local_len.increment_len(1);
2332 }
2333 }
2334
2335 Ok(())
2336 } else {
2337 // Per TrustedLen contract a `None` upper bound means that the iterator length
2338 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
2339 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
2340 // This avoids additional codegen for a fallback code path which would eventually
2341 // panic anyway.
2342 Err(Error::CapacityOverflow)
2343 }
2344 }
2345}
2346
2347impl<T, A: Allocator> Vec<T, A>
2348where
2349 T: TryClone,
2350{
2351 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2352 ///
2353 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2354 /// difference, with each additional slot filled with `value`. If `new_len`
2355 /// is less than `len`, the `Vec` is simply truncated.
2356 ///
2357 /// This method requires `T` to implement [`Clone`], in order to be able to
2358 /// clone the passed value. If you need more flexibility (or want to rely on
2359 /// [`Default`] instead of [`Clone`]), use [`Vec::try_resize_with`]. If you
2360 /// only need to resize to a smaller size, use [`Vec::truncate`].
2361 ///
2362 /// # Examples
2363 ///
2364 /// ```
2365 /// use rune::alloc::try_vec;
2366 ///
2367 /// let mut vec = try_vec!["hello"];
2368 /// vec.try_resize(3, "world")?;
2369 /// assert_eq!(vec, ["hello", "world", "world"]);
2370 ///
2371 /// let mut vec = try_vec![1, 2, 3, 4];
2372 /// vec.try_resize(2, 0)?;
2373 /// assert_eq!(vec, [1, 2]);
2374 /// # Ok::<_, rune::alloc::Error>(())
2375 /// ```
2376 pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), Error> {
2377 let len = self.len();
2378
2379 if new_len > len {
2380 self.try_extend_with(new_len - len, value)?;
2381 } else {
2382 self.truncate(new_len);
2383 }
2384
2385 Ok(())
2386 }
2387
2388 /// Clones and appends all elements in a slice to the `Vec`.
2389 ///
2390 /// Iterates over the slice `other`, clones each element, and then appends
2391 /// it to this `Vec`. The `other` slice is traversed in-order.
2392 ///
2393 /// Note that this function is same as [`try_extend`] except that it is
2394 /// specialized to work with slices instead. If and when Rust gets
2395 /// specialization this function will likely be deprecated (but still
2396 /// available).
2397 ///
2398 /// # Examples
2399 ///
2400 /// ```
2401 /// use rune::alloc::try_vec;
2402 ///
2403 /// let mut vec = try_vec![1];
2404 /// vec.try_extend_from_slice(&[2, 3, 4]);
2405 /// assert_eq!(vec, [1, 2, 3, 4]);
2406 /// # Ok::<_, rune::alloc::Error>(())
2407 /// ```
2408 ///
2409 /// [`try_extend`]: Vec::try_extend
2410 pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), Error> {
2411 try_extend_desugared(self, other.iter())
2412 }
2413
2414 /// Copies elements from `src` range to the end of the vector.
2415 ///
2416 /// # Panics
2417 ///
2418 /// Panics if the starting point is greater than the end point or if the end
2419 /// point is greater than the length of the vector.
2420 ///
2421 /// # Examples
2422 ///
2423 /// ```
2424 /// use rune::alloc::try_vec;
2425 ///
2426 /// let mut vec = try_vec![0, 1, 2, 3, 4];
2427 ///
2428 /// vec.try_extend_from_within(2..);
2429 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2430 ///
2431 /// vec.try_extend_from_within(..2);
2432 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2433 ///
2434 /// vec.try_extend_from_within(4..8);
2435 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2436 /// # Ok::<_, rune::alloc::Error>(())
2437 /// ```
2438 pub fn try_extend_from_within<R>(&mut self, src: R) -> Result<(), Error>
2439 where
2440 R: RangeBounds<usize>,
2441 {
2442 let range = slice_range(src, ..self.len());
2443 self.try_reserve(range.len())?;
2444
2445 // SAFETY:
2446 // - `slice::range` guarantees that the given range is valid for indexing self
2447 unsafe {
2448 // SAFETY:
2449 // - len is increased only after initializing elements
2450 let (this, spare, len) = self.split_at_spare_mut_with_len();
2451
2452 // SAFETY:
2453 // - caller guarantees that src is a valid index
2454 let to_clone = this.get_unchecked(range);
2455
2456 for (src, dst) in iter::zip(to_clone, spare) {
2457 dst.write(src.try_clone()?);
2458 *len += 1
2459 }
2460 }
2461
2462 Ok(())
2463 }
2464}
2465
2466impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2467 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2468 ///
2469 /// # Panics
2470 ///
2471 /// Panics if the length of the resulting vector would overflow a `usize`.
2472 ///
2473 /// This is only possible when flattening a vector of arrays of zero-sized
2474 /// types, and thus tends to be irrelevant in practice. If
2475 /// `size_of::<T>() > 0`, this will never panic.
2476 ///
2477 /// # Examples
2478 ///
2479 /// ```
2480 /// use rune::alloc::try_vec;
2481 ///
2482 /// let mut vec = try_vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2483 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2484 ///
2485 /// let mut flattened = vec.into_flattened();
2486 /// assert_eq!(flattened.pop(), Some(6));
2487 /// # Ok::<_, rune::alloc::Error>(())
2488 /// ```
2489 pub fn into_flattened(self) -> Vec<T, A> {
2490 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2491 let (new_len, new_cap) = if T::IS_ZST {
2492 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2493 } else {
2494 // SAFETY:
2495 // - `cap * N` cannot overflow because the allocation is already in
2496 // the address space.
2497 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2498 // valid elements in the allocation.
2499 (len.wrapping_mul(N), cap.wrapping_mul(N))
2500 };
2501 // SAFETY:
2502 // - `ptr` was allocated by `self`
2503 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2504 // - `new_cap` refers to the same sized allocation as `cap` because
2505 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2506 // - `len` <= `cap`, so `len * N` <= `cap * N`.
2507 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2508 }
2509}
2510
2511impl<T, A: Allocator> Vec<T, A>
2512where
2513 T: TryClone,
2514{
2515 /// Extend the vector by `n` clones of value.
2516 fn try_extend_with(&mut self, n: usize, value: T) -> Result<(), Error> {
2517 self.try_reserve(n)?;
2518
2519 unsafe {
2520 let mut ptr = self.as_mut_ptr().add(self.len());
2521 // Use SetLenOnDrop to work around bug where compiler
2522 // might not realize the store through `ptr` through self.set_len()
2523 // don't alias.
2524 let mut local_len = SetLenOnDrop::new(&mut self.len);
2525
2526 // Write all elements except the last one
2527 for _ in 1..n {
2528 ptr::write(ptr, value.try_clone()?);
2529 ptr = ptr.add(1);
2530 // Increment the length in every step in case clone() panics
2531 local_len.increment_len(1);
2532 }
2533
2534 if n > 0 {
2535 // We can write the last element directly without cloning needlessly
2536 ptr::write(ptr, value);
2537 local_len.increment_len(1);
2538 }
2539
2540 // len set by scope guard
2541 }
2542
2543 Ok(())
2544 }
2545}
2546
2547impl<T, A: Allocator> Vec<T, A>
2548where
2549 T: PartialEq,
2550{
2551 /// Removes consecutive repeated elements in the vector according to the
2552 /// [`PartialEq`] trait implementation.
2553 ///
2554 /// If the vector is sorted, this removes all duplicates.
2555 ///
2556 /// # Examples
2557 ///
2558 /// ```
2559 /// use rune::alloc::try_vec;
2560 ///
2561 /// let mut vec = try_vec![1, 2, 2, 3, 2];
2562 /// vec.dedup();
2563 /// assert_eq!(vec, [1, 2, 3, 2]);
2564 /// # Ok::<_, rune::alloc::Error>(())
2565 /// ```
2566 #[inline]
2567 pub fn dedup(&mut self) {
2568 self.dedup_by(|a, b| a == b)
2569 }
2570}
2571
2572////////////////////////////////////////////////////////////////////////////////
2573// Common trait implementations for Vec
2574////////////////////////////////////////////////////////////////////////////////
2575
2576impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2577 type Target = [T];
2578
2579 #[inline]
2580 fn deref(&self) -> &[T] {
2581 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2582 }
2583}
2584
2585impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2586 #[inline]
2587 fn deref_mut(&mut self) -> &mut [T] {
2588 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2589 }
2590}
2591
2592impl<T, A: Allocator + Clone> TryClone for Vec<T, A>
2593where
2594 T: TryClone,
2595{
2596 fn try_clone(&self) -> Result<Self, Error> {
2597 let alloc = self.allocator().clone();
2598 crate::slice::to_vec(self, alloc)
2599 }
2600}
2601
2602#[cfg(test)]
2603impl<T, A: Allocator + Clone> Clone for Vec<T, A>
2604where
2605 T: TryClone,
2606{
2607 fn clone(&self) -> Self {
2608 self.try_clone().abort()
2609 }
2610}
2611
2612/// The hash of a vector is the same as that of the corresponding slice,
2613/// as required by the `core::borrow::Borrow` implementation.
2614///
2615/// ```
2616/// use std::hash::BuildHasher;
2617/// use rune::alloc::{try_vec, Vec};
2618///
2619/// let b = std::collections::hash_map::RandomState::new();
2620/// let v: Vec<u8> = try_vec![0xa8, 0x3c, 0x09];
2621/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2622/// assert_eq!(b.hash_one(v), b.hash_one(s));
2623/// # Ok::<_, rune::alloc::Error>(())
2624/// ```
2625impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2626 #[inline]
2627 fn hash<H: Hasher>(&self, state: &mut H) {
2628 Hash::hash(&**self, state)
2629 }
2630}
2631
2632impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2633 type Output = I::Output;
2634
2635 #[inline]
2636 fn index(&self, index: I) -> &Self::Output {
2637 Index::index(&**self, index)
2638 }
2639}
2640
2641impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2642 #[inline]
2643 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2644 IndexMut::index_mut(&mut **self, index)
2645 }
2646}
2647
2648impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2649 type Item = T;
2650 type IntoIter = IntoIter<T, A>;
2651
2652 /// Creates a consuming iterator, that is, one that moves each value out of
2653 /// the vector (from start to end). The vector cannot be used after calling
2654 /// this.
2655 ///
2656 /// # Examples
2657 ///
2658 /// ```
2659 /// use rune::alloc::try_vec;
2660 ///
2661 /// let v = try_vec!["a".to_string(), "b".to_string()];
2662 /// let mut v_iter = v.into_iter();
2663 ///
2664 /// let first_element: Option<String> = v_iter.next();
2665 ///
2666 /// assert_eq!(first_element, Some("a".to_string()));
2667 /// assert_eq!(v_iter.next(), Some("b".to_string()));
2668 /// assert_eq!(v_iter.next(), None);
2669 /// # Ok::<_, rune::alloc::Error>(())
2670 /// ```
2671 #[inline]
2672 fn into_iter(self) -> Self::IntoIter {
2673 const fn wrapping_byte_add<T>(this: *mut T, count: usize) -> *mut T {
2674 this.cast::<u8>().wrapping_add(count) as *mut T
2675 }
2676
2677 unsafe {
2678 let mut me = ManuallyDrop::new(self);
2679 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2680 let begin = me.as_mut_ptr();
2681 let end = if T::IS_ZST {
2682 wrapping_byte_add(begin, me.len())
2683 } else {
2684 begin.add(me.len()) as *const T
2685 };
2686 let cap = me.buf.capacity();
2687 IntoIter {
2688 buf: NonNull::new_unchecked(begin),
2689 phantom: PhantomData,
2690 cap,
2691 alloc,
2692 ptr: begin,
2693 end,
2694 }
2695 }
2696 }
2697}
2698
2699impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2700 type Item = &'a T;
2701 type IntoIter = slice::Iter<'a, T>;
2702
2703 fn into_iter(self) -> Self::IntoIter {
2704 self.iter()
2705 }
2706}
2707
2708impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2709 type Item = &'a mut T;
2710 type IntoIter = slice::IterMut<'a, T>;
2711
2712 fn into_iter(self) -> Self::IntoIter {
2713 self.iter_mut()
2714 }
2715}
2716
2717// leaf method to which various SpecFrom/SpecExtend implementations delegate when
2718// they have no further optimizations to apply
2719fn try_extend_desugared<'a, T, A: Allocator>(
2720 this: &mut Vec<T, A>,
2721 mut iterator: impl Iterator<Item = &'a T>,
2722) -> Result<(), Error>
2723where
2724 T: 'a + TryClone,
2725{
2726 // This is the case for a general iterator.
2727 //
2728 // This function should be the moral equivalent of:
2729 //
2730 // for item in iterator {
2731 // self.push(item);
2732 // }
2733 while let Some(element) = iterator.next() {
2734 let len = this.len();
2735 if len == this.capacity() {
2736 let (lower, _) = iterator.size_hint();
2737 this.try_reserve(lower.saturating_add(1))?;
2738 }
2739 unsafe {
2740 ptr::write(this.as_mut_ptr().add(len), element.try_clone()?);
2741 // Since next() executes user code which can panic we have to bump the length
2742 // after each step.
2743 // NB can't overflow since we would have had to alloc the address space
2744 this.set_len(len + 1);
2745 }
2746 }
2747
2748 Ok(())
2749}
2750
2751/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
2752impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
2753where
2754 T: PartialOrd,
2755 A1: Allocator,
2756 A2: Allocator,
2757{
2758 #[inline]
2759 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
2760 PartialOrd::partial_cmp(&**self, &**other)
2761 }
2762}
2763
2764impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2765
2766/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
2767impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2768 #[inline]
2769 fn cmp(&self, other: &Self) -> Ordering {
2770 Ord::cmp(&**self, &**other)
2771 }
2772}
2773
2774#[cfg(rune_nightly)]
2775unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2776 fn drop(&mut self) {
2777 unsafe {
2778 // use drop for [T]
2779 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2780 // could avoid questions of validity in certain cases
2781 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2782 }
2783 // RawVec handles deallocation
2784 }
2785}
2786
2787#[cfg(not(rune_nightly))]
2788impl<T, A: Allocator> Drop for Vec<T, A> {
2789 fn drop(&mut self) {
2790 unsafe {
2791 // use drop for [T]
2792 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2793 // could avoid questions of validity in certain cases
2794 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2795 }
2796 // RawVec handles deallocation
2797 }
2798}
2799
2800impl<T> Default for Vec<T> {
2801 /// Creates an empty `Vec<T>`.
2802 ///
2803 /// The vector will not allocate until elements are pushed onto it.
2804 fn default() -> Vec<T> {
2805 Vec::new()
2806 }
2807}
2808
2809impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2810 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2811 fmt::Debug::fmt(&**self, f)
2812 }
2813}
2814
2815impl<T, A: Allocator> Borrow<[T]> for Vec<T, A> {
2816 #[inline]
2817 fn borrow(&self) -> &[T] {
2818 self
2819 }
2820}
2821
2822impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2823 fn as_ref(&self) -> &Vec<T, A> {
2824 self
2825 }
2826}
2827
2828impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2829 fn as_mut(&mut self) -> &mut Vec<T, A> {
2830 self
2831 }
2832}
2833
2834impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2835 fn as_ref(&self) -> &[T] {
2836 self
2837 }
2838}
2839
2840impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2841 fn as_mut(&mut self) -> &mut [T] {
2842 self
2843 }
2844}
2845
2846impl<T> TryFrom<&[T]> for Vec<T>
2847where
2848 T: TryClone,
2849{
2850 type Error = Error;
2851
2852 /// Converts a `&[T]` into a [`Vec<T>`].
2853 ///
2854 /// The result is fallibly allocated on the heap.
2855 fn try_from(values: &[T]) -> Result<Self, Error> {
2856 let mut out = Vec::try_with_capacity(values.len())?;
2857
2858 for value in values {
2859 out.try_push(value.try_clone()?)?;
2860 }
2861
2862 Ok(out)
2863 }
2864}
2865
2866impl<T, const N: usize> TryFrom<[T; N]> for Vec<T> {
2867 type Error = Error;
2868
2869 /// Converts a `[T; N]` into a [`Vec<T>`].
2870 ///
2871 /// The result is fallibly allocated on the heap.
2872 ///
2873 /// ```
2874 /// use rune::alloc::{vec, Vec};
2875 ///
2876 /// let a = Vec::try_from([1, 2, 3])?;
2877 /// let b: Vec<_> = [1, 2, 3].try_into()?;
2878 /// assert_eq!(a, b);
2879 /// # Ok::<_, rune::alloc::Error>(())
2880 /// ```
2881 fn try_from(arr: [T; N]) -> Result<Self, Error> {
2882 let mut out = Vec::try_with_capacity(arr.len())?;
2883 let arr = ManuallyDrop::new(arr);
2884
2885 if !<T>::IS_ZST {
2886 // SAFETY: Vec::try_with_capacity ensures that there is enough capacity.
2887 unsafe {
2888 ptr::copy_nonoverlapping(arr.as_ptr(), out.as_mut_ptr(), N);
2889 }
2890 }
2891
2892 unsafe {
2893 out.set_len(N);
2894 }
2895
2896 Ok(out)
2897 }
2898}
2899
2900#[cfg(feature = "alloc")]
2901impl<T> TryFrom<::rust_alloc::vec::Vec<T>> for Vec<T, Global> {
2902 type Error = Error;
2903
2904 /// Converts a std `Vec<T>` into a [`Vec<T>`].
2905 ///
2906 /// The result is allocated on the heap.
2907 fn try_from(vec: ::rust_alloc::vec::Vec<T>) -> Result<Self, Error> {
2908 let mut vec = ManuallyDrop::new(vec);
2909
2910 let ptr = vec.as_mut_ptr();
2911 let length = vec.len();
2912 let capacity = vec.capacity();
2913
2914 if let Ok(layout) = Layout::array::<T>(capacity) {
2915 Global.take(layout)?;
2916 }
2917
2918 // SAFETY: The layout of the vector is identical to the std vector and
2919 // it uses the same underlying allocator.
2920 unsafe { Ok(Self::from_raw_parts_in(ptr, length, capacity, Global)) }
2921 }
2922}
2923
2924impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2925 type Error = Vec<T, A>;
2926
2927 /// Gets the entire contents of the `Vec<T>` as an array,
2928 /// if its size exactly matches that of the requested array.
2929 ///
2930 /// # Examples
2931 ///
2932 /// ```
2933 /// use rune::alloc::try_vec;
2934 ///
2935 /// assert_eq!(try_vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2936 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2937 /// # Ok::<_, rune::alloc::Error>(())
2938 /// ```
2939 ///
2940 /// If the length doesn't match, the input comes back in `Err`:
2941 /// ```
2942 /// use rune::alloc::{try_vec, Vec};
2943 /// use rune::alloc::prelude::*;
2944 ///
2945 /// let r: Result<[i32; 4], _> = (0..10).try_collect::<Vec<_>>()?.try_into();
2946 /// assert_eq!(r, Err(try_vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2947 /// # Ok::<_, rune::alloc::Error>(())
2948 /// ```
2949 ///
2950 /// If you're fine with just getting a prefix of the `Vec<T>`,
2951 /// you can call [`.truncate(N)`](Vec::truncate) first.
2952 /// ```
2953 /// use rune::alloc::String;
2954 ///
2955 /// let mut v = String::try_from("hello world")?.into_bytes();
2956 /// v.sort();
2957 /// v.truncate(2);
2958 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2959 /// assert_eq!(a, b' ');
2960 /// assert_eq!(b, b'd');
2961 /// # Ok::<_, rune::alloc::Error>(())
2962 /// ```
2963 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2964 if vec.len() != N {
2965 return Err(vec);
2966 }
2967
2968 // SAFETY: `.set_len(0)` is always sound.
2969 unsafe { vec.set_len(0) };
2970
2971 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2972 // the alignment the array needs is the same as the items.
2973 // We checked earlier that we have sufficient items.
2974 // The items will not double-drop as the `set_len`
2975 // tells the `Vec` not to also drop them.
2976 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
2977 Ok(array)
2978 }
2979}
2980
2981impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2982 /// Convert a boxed slice into a vector by transferring ownership of the
2983 /// existing heap allocation.
2984 ///
2985 /// # Examples
2986 ///
2987 /// ```
2988 /// use rune::alloc::{Box, Vec};
2989 /// use rune::alloc::try_vec;
2990 ///
2991 /// let s: Box<[i32]> = Box::try_from([10, 40, 30])?;
2992 /// let x: Vec<i32> = Vec::from(s);
2993 ///
2994 /// assert_eq!(x, [10, 40, 30]);
2995 ///
2996 /// let s: Box<[i32]> = try_vec![10, 40, 30].try_into_boxed_slice()?;
2997 /// let x: Vec<i32> = Vec::from(s);
2998 ///
2999 /// assert_eq!(x, [10, 40, 30]);
3000 /// # Ok::<_, rune::alloc::Error>(())
3001 /// ```
3002 fn from(s: Box<[T], A>) -> Self {
3003 crate::slice::into_vec(s)
3004 }
3005}
3006
3007impl<T, A: Allocator> TryFromIteratorIn<T, A> for Vec<T, A> {
3008 fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<Self, Error>
3009 where
3010 I: IntoIterator<Item = T>,
3011 {
3012 let mut this = Vec::new_in(alloc);
3013
3014 for value in iter {
3015 this.try_push(value)?;
3016 }
3017
3018 Ok(this)
3019 }
3020}
3021
3022#[cfg(test)]
3023impl<T> FromIterator<T> for Vec<T> {
3024 fn from_iter<I>(iter: I) -> Self
3025 where
3026 I: IntoIterator<Item = T>,
3027 {
3028 Self::try_from_iter_in(iter, Global).abort()
3029 }
3030}
3031
3032impl<T, A: Allocator> TryExtend<T> for Vec<T, A> {
3033 #[inline]
3034 fn try_extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> Result<(), Error> {
3035 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
3036 }
3037}
3038
3039#[cfg(feature = "std")]
3040fn io_err(error: Error) -> std::io::Error {
3041 std::io::Error::other(error)
3042}
3043
3044#[cfg(feature = "std")]
3045impl std::io::Write for Vec<u8> {
3046 #[inline]
3047 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
3048 self.try_extend_from_slice(buf).map_err(io_err)?;
3049 Ok(buf.len())
3050 }
3051
3052 #[inline]
3053 fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
3054 let len = bufs.iter().map(|b| b.len()).sum();
3055 self.try_reserve(len).map_err(io_err)?;
3056
3057 for buf in bufs {
3058 self.try_extend_from_slice(buf).map_err(io_err)?;
3059 }
3060
3061 Ok(len)
3062 }
3063
3064 #[inline]
3065 fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
3066 self.try_extend_from_slice(buf).map_err(io_err)?;
3067 Ok(())
3068 }
3069
3070 #[inline]
3071 fn flush(&mut self) -> std::io::Result<()> {
3072 Ok(())
3073 }
3074}