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