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