diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index b22b051c9697a..e26198c487306 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -214,6 +214,7 @@ #![feature(min_specialization)] #![feature(multiple_supertrait_upcastable)] #![feature(negative_impls)] +#![feature(proc_macro_hygiene)] #![feature(rustc_attrs)] #![feature(slice_internals)] #![feature(staged_api)] diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 1bdec5a74c9e6..d6bb6c303febe 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -104,6 +104,8 @@ use core::cmp::Ordering; use core::hash::{Hash, Hasher}; #[cfg(not(no_global_oom_handling))] use core::iter; +#[cfg(kani)] +use core::kani; use core::marker::{Destruct, Freeze, PhantomData}; use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom}; use core::ops::{self, Index, IndexMut, Range, RangeBounds}; @@ -111,6 +113,8 @@ use core::ptr::{self, NonNull}; use core::slice::{self, SliceIndex}; use core::{cmp, fmt, hint, intrinsics, ub_checks}; +use safety::{ensures, requires}; + #[stable(feature = "extract_if", since = "1.87.0")] pub use self::extract_if::ExtractIf; use crate::alloc::{Allocator, AllocatorNightly, Global}; @@ -165,6 +169,38 @@ use self::spec_from_elem::SpecFromElem; #[cfg(not(no_global_oom_handling))] mod spec_from_elem; +#[cfg(all(kani, not(no_global_oom_handling)))] +#[unstable(feature = "kani", issue = "none")] +mod verify_ch23; + +/// Kani-only: partial check of documented `Vec` raw-parts layout invariants (see module docs). +/// Checks `length <= capacity`, non-null and alignment of `ptr`, `Layout::array::(capacity)` +/// fitting within `isize::MAX` bytes, `can_write`, base-offset-0 (rejecting interior pointers +/// via `!same_allocation(ptr, ptr - 1)`), and in-bounds byte extent of at least +/// `capacity * size_of::()` (permitting legal over-allocated custom-allocator blocks). +/// Remaining caller safety obligations NOT machine-checked by this predicate (due to Kani/CBMC +/// limitations) remain documented caller preconditions: (1) `ptr` was allocated via the matching +/// `Allocator` instance, (2) `ptr` was allocated with `T`'s exact alignment and a fitting layout +/// (`requested_size <= capacity * size_of::() <= actual_size`), and (3) the first `length` +/// elements are initialized to valid values of `T`. +#[cfg(kani)] +fn vec_parts_valid(ptr: *mut T, length: usize, capacity: usize) -> bool { + length <= capacity + && !ptr.is_null() + && ptr.is_aligned() + && (T::IS_ZST || crate::alloc::Layout::array::(capacity).is_ok()) + && ub_checks::can_write(ptr::slice_from_raw_parts_mut(ptr, capacity)) + && (T::IS_ZST + || capacity == 0 + || (kani::mem::is_inbounds(ptr::slice_from_raw_parts( + ptr as *const u8, + capacity * mem::size_of::(), + )) && !kani::mem::same_allocation( + ptr as *const u8, + (ptr as *const u8).wrapping_byte_sub(1), + ))) +} + #[cfg(not(no_global_oom_handling))] use self::set_len_on_drop::SetLenOnDrop; @@ -629,6 +665,8 @@ impl Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr, length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { // SAFETY: Upheld by caller. unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } @@ -709,6 +747,8 @@ impl Vec { #[inline] #[stable(feature = "box_vec_non_null", since = "1.99.0")] #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] pub const unsafe fn from_parts(ptr: NonNull, length: usize, capacity: usize) -> Self { // SAFETY: Upheld by caller. unsafe { Self::from_parts_in(ptr, length, capacity, Global) } @@ -1222,6 +1262,8 @@ impl Vec { #[inline] #[stable(feature = "allocator_api", since = "1.100.0")] #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] pub const unsafe fn from_parts_in( ptr: NonNull, length: usize, @@ -2142,6 +2184,16 @@ impl Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(new_len <= self.capacity())] + #[requires( + new_len <= self.len + || ub_checks::can_dereference(ptr::slice_from_raw_parts( + self.as_ptr().wrapping_add(self.len), + new_len - self.len, + )) + )] + #[cfg_attr(kani, kani::modifies(&self.len))] + #[ensures(|_| self.len() == new_len)] pub const unsafe fn set_len(&mut self, new_len: usize) { ub_checks::assert_unsafe_precondition!( check_library_ub, @@ -3442,6 +3494,8 @@ impl Vec { /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`. /// /// This method provides unique access to all vec parts at once in `extend_from_within`. + #[requires(self.len <= self.buf.capacity())] + #[ensures(|result| result.0.len() == *result.2 && result.0.len() + result.1.len() == old(self.capacity()))] const unsafe fn split_at_spare_mut_with_len( &mut self, ) -> (&mut [T], &mut [MaybeUninit], &mut usize) { @@ -4051,6 +4105,18 @@ impl ExtendFromWithinSpec for Vec { #[cfg(not(no_global_oom_handling))] impl ExtendFromWithinSpec for Vec { + #[requires(src.start <= src.end && src.end <= self.len())] + #[requires(src.end - src.start <= self.capacity() - self.len())] + #[ensures(|_| self.len() == old(self.len()) + old(src.end - src.start))] + #[ensures(|_| self.capacity() == old(self.capacity()))] + #[ensures(|_| self.as_ptr() == old(self.as_ptr()))] + #[cfg_attr( + kani, + kani::modifies( + &self.len, + ptr::slice_from_raw_parts(self.as_ptr().wrapping_add(self.len()), src.end - src.start), + ) + )] unsafe fn spec_extend_from_within(&mut self, src: Range) { let count = src.len(); { diff --git a/library/alloc/src/vec/set_len_on_drop.rs b/library/alloc/src/vec/set_len_on_drop.rs index 6ce5a3a9f54eb..e79a79f388e94 100644 --- a/library/alloc/src/vec/set_len_on_drop.rs +++ b/library/alloc/src/vec/set_len_on_drop.rs @@ -23,6 +23,18 @@ impl<'a> SetLenOnDrop<'a> { pub(super) fn current_len(&self) -> usize { self.local_len } + + #[cfg(all(kani, not(no_global_oom_handling)))] + pub(super) fn kani_trace_increment_len(&mut self, increment: usize) { + self.local_len += increment; + // SAFETY: Kani verification harnesses are single-threaded; record the + // stack address of `self.local_len` once on the peeled iteration so + // `extend_trusted`'s loop invariant can observe the closure's exact + // `SetLenOnDrop` counter without modifying shipped code. + unsafe { + crate::vec::verify_ch23::record_extend_trusted_len_ptr(&raw mut self.local_len); + } + } } impl Drop for SetLenOnDrop<'_> { diff --git a/library/alloc/src/vec/spec_extend_with.rs b/library/alloc/src/vec/spec_extend_with.rs index 846d77bc1956c..9059f79fb2329 100644 --- a/library/alloc/src/vec/spec_extend_with.rs +++ b/library/alloc/src/vec/spec_extend_with.rs @@ -1,4 +1,6 @@ use core::clone::TrivialClone; +#[cfg(kani)] +use core::kani; use core::{mem, ptr}; use crate::alloc::Allocator; @@ -83,6 +85,8 @@ impl SpecExtendWith for Vec { // We use an incrementing index here instead of incrementing pointer because the former // has been observed to have less register pressure in the loop initialization. // https://llvm.org/docs/Vectorizers.html#inductions + #[cfg_attr(kani, kani::loop_invariant(i <= n))] + #[cfg_attr(kani, kani::loop_modifies(&i, ptr::slice_from_raw_parts_mut(ptr, n)))] while i < n { // SAFETY: `TrivialClone` indicates that copying `value` is equivalent to // calling `Clone::clone` for `T`. As per the safety comment for `ptr`, this pointer diff --git a/library/alloc/src/vec/verify_ch23.rs b/library/alloc/src/vec/verify_ch23.rs new file mode 100644 index 0000000000000..c8db6e07921bc --- /dev/null +++ b/library/alloc/src/vec/verify_ch23.rs @@ -0,0 +1,4286 @@ +//! Unbounded Kani verification harnesses for Challenge 23 (`Vec` part 1, +//! `library/alloc/src/vec/mod.rs`). +//! +//! All harnesses allocate symbolic capacities up to the CBMC object-model bound +//! (`MAX_ALLOCATION_BYTES = (1 << 51) - 1` under `--object-bits 12`) with zero +//! `#[kani::unwind]` annotations on data loops, and instantiate targets across +//! representative element types (`u8`, `OverAligned`, `()`, `DropTracker`, +//! `NonZero`, plus `LargeElem`, `PaddedNiche`, `(char, u8)`, `NonPow2`, +//! and `AlignedZst` per issue #734). The four polymorphic user-callback / +//! arbitrary-`Drop` loops (`Vec::extend_desugared`, the default `T: Clone` impl +//! of `SpecExtendWith::spec_extend_with` with `SetLenOnDrop`, `Vec::retain_mut`, +//! and `Vec::dedup_by` / `dedup_tail`) are verified unboundedly for arbitrary +//! generic `T`, arbitrary `Iterator` / stateful `FnMut`, and arbitrary `Drop` in +//! the unified real-`alloc` VeriFast 26.10 crate at +//! `verifast-proofs/alloc/vec/mod.rs/` (with zero `kani::loop_modifies` +//! annotations in `library/alloc/src/vec/mod.rs`). + +use core::alloc::{AllocError, Allocator, Layout}; +use core::clone::TrivialClone; +use core::mem::{self, MaybeUninit, SizedTypeProperties}; +use core::num::NonZero; +use core::ops::{Bound, Deref, DerefMut}; +use core::ptr::NonNull; +use core::{iter, kani, ptr, slice}; + +use super::{ExtendFromWithinSpec, SetLenOnDrop}; +use crate::alloc::Global; +use crate::boxed::Box; +use crate::vec::Vec; + +/// Largest object CBMC can represent under `--object-bits 12`. +const MAX_ALLOCATION_BYTES: usize = (1 << 51) - 1; + +/// Cover witnesses cap buffer capacity (and total bytes) so CBMC does not +/// exhaust memory while formatting witness traces (`kani#4905`); proofs +/// themselves remain completely unbounded. +const WITNESS_CAP: usize = (1 << 13) + 256; +const WITNESS_MAX_BYTES: usize = 1 << 18; + +/// Over-aligned element: size and stride 16, alignment 16 (15 padding bytes). +#[repr(align(16))] +#[derive(Clone, Copy)] +pub struct OverAligned(pub u8); + +// SAFETY: `OverAligned` is `Copy` with derived trivial `Clone`. +unsafe impl TrivialClone for OverAligned {} + +/// Large element (`size_of == 2048 > 1024`, `align_of == 2048`): exercises the +/// third branch of `RawVecInner::min_non_zero_cap` (`MIN_NON_ZERO_CAP == 1`) +/// per issue #734 while keeping typed writes scalar (2047 padding bytes). +#[repr(align(2048))] +#[derive(Clone, Copy)] +pub struct LargeElem(pub u8); + +// SAFETY: `LargeElem` is `Copy` with derived trivial `Clone`. +unsafe impl TrivialClone for LargeElem {} + +/// Padded + niche multi-field element: size 8, align 4, 3 interior padding bytes +/// between `NonZero` (offset 0) and `u32` (offset 4). +#[repr(C)] +#[derive(Clone, Copy)] +pub struct PaddedNiche(pub NonZero, pub u32); + +// SAFETY: `PaddedNiche` is `Copy` with derived trivial `Clone`. +unsafe impl TrivialClone for PaddedNiche {} + +/// Non-power-of-two sized element: size 3, alignment 1. +#[derive(Clone, Copy)] +pub struct NonPow2(pub [u8; 3]); + +// SAFETY: `NonPow2` is `Copy` with derived trivial `Clone`. +unsafe impl TrivialClone for NonPow2 {} + +/// Over-aligned ZST: size 0, alignment 16. +#[repr(align(16))] +#[derive(Clone, Copy)] +pub struct AlignedZst; + +// SAFETY: `AlignedZst` is a `Copy` ZST. +unsafe impl TrivialClone for AlignedZst {} + +/// Number of `DropTracker` values dropped so far. +/// Non-zero sentinel avoids Kani's zero-byte static aliasing bug (`kani#5088`). +static mut DROPS: usize = 0x5A5A_5A5A_5A5A_5A5A; + +/// Element with drop glue (non-`Copy`, non-`TrivialClone`) that counts drops. +pub struct DropTracker(pub u8); + +impl Clone for DropTracker { + fn clone(&self) -> Self { + DropTracker(self.0) + } +} + +impl Drop for DropTracker { + fn drop(&mut self) { + unsafe { DROPS += 1 }; + } +} + +fn reset_drops() { + unsafe { DROPS = 0 }; +} + +fn drops() -> usize { + unsafe { DROPS } +} + +/// Number of `DropAlloc` instances dropped so far. +static mut ALLOC_DROPS: usize = 0x5A5A_5A5A_5A5A_5A5B; + +/// Constructs `NonZero` directly via `#[repr(transparent)]` layout without +/// calling `NonZero::new` (which transmutes `u8 -> Option>` and +/// triggers a false enum-niche layout warning under `-Z uninit-checks`). +fn nonzero_u8(b: u8) -> NonZero { + // SAFETY: Callers pass `b != 0` and `NonZero` is `#[repr(transparent)]`. + unsafe { mem::transmute::>(b) } +} + +/// Non-ZST allocator with a niche (`NonZero`) and drop glue, delegating to `Global`. +pub struct DropAlloc(pub NonZero); + +impl Drop for DropAlloc { + fn drop(&mut self) { + unsafe { ALLOC_DROPS += 1 }; + } +} + +unsafe impl Allocator for DropAlloc { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + Global.allocate(layout) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + unsafe { Global.deallocate(ptr, layout) } + } +} + +/// Custom allocator that legally returns a block with `extra` trailing bytes +/// beyond the requested layout (`Allocator::allocate` explicitly permits excess +/// capacity). Records the exact underlying `(ptr, requested_size, actual_layout)` +/// so `deallocate` upholds Rust's fitting-layout contract for *every* legal +/// caller-supplied size (`requested_size <= layout.size() <= actual_layout.size()`), +/// asserting fitting bounds before forwarding `actual_layout` to `Global`. +pub struct OverAlloc { + pub extra: usize, + allocated: core::cell::Cell, usize, Layout)>>, +} + +impl OverAlloc { + fn new(extra: usize) -> Self { + Self { extra, allocated: core::cell::Cell::new(None) } + } +} + +unsafe impl Allocator for OverAlloc { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + if layout.size() == 0 { + return Global.allocate(layout); + } + let total = layout.size().checked_add(self.extra).ok_or(AllocError)?; + let actual = Layout::from_size_align(total, layout.align()).map_err(|_| AllocError)?; + let slice = Global.allocate(actual)?; + assert!(self.allocated.get().is_none(), "OverAlloc models one live allocation"); + self.allocated.set(Some((slice.cast::(), layout.size(), actual))); + Ok(slice) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + if layout.size() == 0 { + return; + } + let Some((orig_ptr, req_size, actual)) = self.allocated.take() else { + panic!("OverAlloc::deallocate called without live allocation"); + }; + assert!(ptr == orig_ptr, "deallocate ptr must match allocated base"); + assert!(layout.align() == actual.align(), "deallocate align must match allocation"); + assert!( + req_size <= layout.size() && layout.size() <= actual.size(), + "deallocate layout must fit the allocated block" + ); + // SAFETY: `orig_ptr` and `actual` are the exact allocation handed out by `Global`. + unsafe { Global.deallocate(orig_ptr, actual) }; + } +} + +fn reset_alloc_drops() { + unsafe { ALLOC_DROPS = 0 }; +} + +fn alloc_drops() -> usize { + unsafe { ALLOC_DROPS } +} + +/// Uniform typed element construction and observation across all representative +/// types. Every non-ZST type defines a valid `bulk_init_byte(fill)` so 100% of +/// `0..cap` (hence every slot in `0..len` for arbitrary symbolic `len`) holds a +/// valid Rust `T` value before `Vec` construction; padded types then overwrite +/// witness slots via typed `ptr::write` so fresh uninitialized padding bytes +/// remain exercised at witness positions. +trait Elem: Sized { + /// True for element types containing padding bytes (`OverAligned`, + /// `LargeElem`, `PaddedNiche`, `(char, u8)`). + const HAS_PADDING: bool = false; + /// Byte value whose repetition across `size_of::()` bytes forms a + /// mathematically valid Rust `T` value: + /// - `fill` (`1..=255`) for `u8`, `NonZero`, `DropTracker`, `NonPow2`, + /// `OverAligned`, `LargeElem`, and `PaddedNiche` (yielding + /// `T::from_tag(fill)`). + /// - `0u8` for `(char, u8)` (yielding `('\0', 0u8)`, a valid `char` + `u8`). + fn bulk_init_byte(fill: u8) -> u8 { + fill + } + fn from_tag(b: u8) -> Self; + fn tag(&self) -> u8; + fn when_non_zst(f: impl FnOnce()) { + f(); + } + fn when_zst(_f: impl FnOnce()) {} + fn when_needs_drop(_f: impl FnOnce()) {} +} + +impl Elem for u8 { + fn from_tag(b: u8) -> Self { + b + } + fn tag(&self) -> u8 { + *self + } +} + +impl Elem for OverAligned { + const HAS_PADDING: bool = true; + fn from_tag(b: u8) -> Self { + OverAligned(b) + } + fn tag(&self) -> u8 { + self.0 + } +} + +impl Elem for LargeElem { + const HAS_PADDING: bool = true; + fn from_tag(b: u8) -> Self { + LargeElem(b) + } + fn tag(&self) -> u8 { + self.0 + } +} + +impl Elem for PaddedNiche { + const HAS_PADDING: bool = true; + fn from_tag(b: u8) -> Self { + PaddedNiche(nonzero_u8(b), u32::from_ne_bytes([b; 4])) + } + fn tag(&self) -> u8 { + self.0.get() + } +} + +impl Elem for (char, u8) { + const HAS_PADDING: bool = true; + fn bulk_init_byte(_fill: u8) -> u8 { + 0 + } + fn from_tag(b: u8) -> Self { + (char::from(b), b) + } + fn tag(&self) -> u8 { + self.1 + } +} + +impl Elem for NonPow2 { + fn from_tag(b: u8) -> Self { + NonPow2([b; 3]) + } + fn tag(&self) -> u8 { + self.0[0] + } +} + +impl Elem for () { + fn from_tag(_b: u8) -> Self {} + fn tag(&self) -> u8 { + 0 + } + fn when_non_zst(_f: impl FnOnce()) {} + fn when_zst(f: impl FnOnce()) { + f(); + } +} + +impl Elem for AlignedZst { + fn from_tag(_b: u8) -> Self { + AlignedZst + } + fn tag(&self) -> u8 { + 0 + } + fn when_non_zst(_f: impl FnOnce()) {} + fn when_zst(f: impl FnOnce()) { + f(); + } +} + +impl Elem for DropTracker { + fn from_tag(b: u8) -> Self { + DropTracker(b) + } + fn tag(&self) -> u8 { + self.0 + } + fn when_needs_drop(f: impl FnOnce()) { + f(); + } +} + +impl Elem for NonZero { + fn from_tag(b: u8) -> Self { + nonzero_u8(b) + } + fn tag(&self) -> u8 { + self.get() + } +} + +/// A nonzero byte tag valid for all representative types (including `NonZero`). +fn any_tag() -> u8 { + kani::any_where(|&b: &u8| b != 0) +} + +/// A symbolic value in `0..=max`, biased toward small witnesses under CaDiCaL. +fn down_from(max: usize) -> usize { + let x: usize = kani::any_where(|&x: &usize| x <= max); + max - x +} + +/// A symbolic value in `0..=max`, biased toward small witnesses under MiniSat +/// (avoids `kani#4905` 2^51-byte witness blowups when MiniSat defaults bits to 0). +fn any_up_to(max: usize) -> usize { + kani::any_where(|&x: &usize| x <= max) +} + +fn pick_bound(max: usize) -> usize { + if UP { any_up_to(max) } else { down_from(max) } +} + +/// Byte-capped cover witness guard (`<= WITNESS_CAP` elements and +/// `<= 16` elements for `LargeElem` > 1 KiB) so witness traces stay tiny. +fn witness_ok(cap: usize) -> bool { + if T::IS_ZST { + true + } else if mem::size_of::() > 1024 { + cap <= 16 + } else { + cap <= WITNESS_CAP && cap.saturating_mul(mem::size_of::()) <= WITNESS_MAX_BYTES + } +} + +/// Deep-position cover threshold: `4096` for regular types, `4` for `LargeElem` +/// (> 1 KiB) so witness traces fit comfortably within 32 KiB. +fn deep_min() -> usize { + if mem::size_of::() > 1024 { 4 } else { 4096 } +} + +/// Live 16-byte-aligned static anchor providing a provenance-bearing, +/// non-canonical aligned pointer for ZST and zero-capacity `Vec` harnesses. +#[repr(align(16))] +struct ZstAnchor([u8; 16]); + +static ZST_ANCHOR: ZstAnchor = ZstAnchor([0xAA; 16]); + +/// Returns an arbitrary aligned non-null pointer permitted for ZSTs and +/// zero-capacity `Vec`s: exercises provenance-bearing live pointers +/// (`&raw const ZST_ANCHOR`), canonical `NonNull::dangling()`, and arbitrary +/// non-canonical aligned addresses (`without_provenance_mut`). +fn any_aligned_non_null_ptr() -> NonNull { + if mem::align_of::() <= 16 && kani::any() { + // SAFETY: `&raw const ZST_ANCHOR` is non-null, 16-byte aligned, and `'static`. + unsafe { NonNull::new_unchecked((&raw const ZST_ANCHOR) as *mut T) } + } else { + let addr: usize = + kani::any_where(|&a: &usize| a != 0 && a.is_multiple_of(mem::align_of::())); + // SAFETY: `addr != 0` and aligned to `align_of::()`; ZST and zero-capacity + // pointers are never dereferenced. + unsafe { NonNull::new_unchecked(ptr::without_provenance_mut(addr)) } + } +} + +fn any_zst_ptr() -> NonNull { + assert!(T::IS_ZST); + any_aligned_non_null_ptr::() +} + +fn allocate_vec_buffer_mode( + cap: usize, + fill_byte: u8, + alloc: &A, +) -> NonNull { + if T::IS_ZST { + any_zst_ptr::() + } else if cap == 0 { + if NON_CANONICAL_ZERO { any_aligned_non_null_ptr::() } else { NonNull::dangling() } + } else { + unsafe extern "C" { + fn __CPROVER_array_set(dst: *mut u8, value: u8); + } + let layout = Layout::array::(cap).unwrap(); + let raw = alloc.allocate(layout).expect("allocation failed").cast::(); + // SAFETY: `raw` is the base of a live allocation of `cap * size_of::()` + // bytes and repeating `fill_byte` (`T::bulk_init_byte(fill)`) forms a valid + // Rust `T` value at every slot in `0..cap` (padding bytes are legally + // initialized). Initializing on `*mut u8` before casting to `NonNull` + // also avoids an extra `*mut T -> *mut u8` mutable cast under + // `-Z valid-value-checks`. + unsafe { __CPROVER_array_set(raw.as_ptr(), fill_byte) }; + raw.cast::() + } +} + +fn allocate_vec_buffer(cap: usize, fill_byte: u8, alloc: &A) -> NonNull { + allocate_vec_buffer_mode::(cap, fill_byte, alloc) +} + +/// Allocates raw parts `(ptr, len, cap, k, j)` via `alloc` without calling +/// `Vec::from_*`. Initializes 100% of `0..cap` (hence every slot in `0..len` +/// for arbitrary symbolic `len`) with `T::bulk_init_byte(fill)` via +/// `__CPROVER_array_set` so every element satisfies Rust's type-validity +/// invariant before `Vec` construction; then writes typed witness values at +/// arbitrary symbolic indices `k < len` (`marker`) and `j < len, j != k` +/// (`fill`), refreshing uninitialized padding bytes on padded types at witness +/// positions. +fn alloc_raw_parts_in_mode< + T: Elem, + A: Allocator, + const UP: bool, + const NON_CANONICAL_ZERO: bool, +>( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: &A, +) -> (NonNull, usize, usize, usize, usize) { + let cap: usize = + if T::IS_ZST { kani::any() } else { pick_bound::(max_bytes / mem::size_of::()) }; + let len: usize = pick_bound::(cap); + let ptr = + allocate_vec_buffer_mode::(cap, T::bulk_init_byte(fill), alloc); + let k: usize = kani::any_where(|&k: &usize| k < len || (len == 0 && k == 0)); + let j: usize = kani::any(); + if !T::IS_ZST && len > 0 { + if j < len && j != k { + unsafe { ptr::write(ptr.as_ptr().add(j), T::from_tag(fill)) }; + } + unsafe { ptr::write(ptr.as_ptr().add(k), T::from_tag(marker)) }; + } + (ptr, len, cap, k, j) +} + +fn alloc_raw_parts_in( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: &A, +) -> (NonNull, usize, usize, usize, usize) { + alloc_raw_parts_in_mode::(max_bytes, fill, marker, alloc) +} + +fn alloc_raw_parts_in_up( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: &A, +) -> (NonNull, usize, usize, usize, usize) { + alloc_raw_parts_in_mode::(max_bytes, fill, marker, alloc) +} + +/// Builds a `Vec` with symbolic capacity (at most `max_bytes` bytes) and +/// symbolic length `len <= cap`, writing typed values at arbitrary symbolic +/// indices `k < len` (`marker`) and `j < len, j != k` (`fill`). Constructed via +/// `alloc_raw_parts_in` + `Vec::from_parts_in` to avoid `RawVec::try_allocate_in` +/// overhead and `Vec::set_len` calls during harness setup. +fn any_vec_in_mode( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: A, +) -> (Vec, usize, usize) { + let (ptr, len, cap, k, j) = + alloc_raw_parts_in_mode::(max_bytes, fill, marker, &alloc); + let v = unsafe { Vec::from_parts_in(ptr, len, cap, alloc) }; + (v, k, j) +} + +fn any_vec_in( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: A, +) -> (Vec, usize, usize) { + any_vec_in_mode::(max_bytes, fill, marker, alloc) +} + +fn any_vec_in_up( + max_bytes: usize, + fill: u8, + marker: u8, + alloc: A, +) -> (Vec, usize, usize) { + any_vec_in_mode::(max_bytes, fill, marker, alloc) +} + +/// Checks typed element contents at arbitrary symbolic indices `k` (`marker`) +/// and `j` (`fill`), plus deep-position cover. Guards are hoisted into +/// unconditional assertions so CBMC reachability traces can pick `len == 0` +/// without constructing huge witness arrays (`kani#4905`). +fn check_elements( + ptr: *const T, + len: usize, + k: usize, + j: usize, + fill: u8, + marker: u8, + small: bool, +) { + let k_ok = T::IS_ZST || len == 0 || unsafe { (&*ptr.add(k)).tag() } == marker; + assert!(k_ok); + let j_ok = + T::IS_ZST || len == 0 || !(j < len && j != k) || unsafe { (&*ptr.add(j)).tag() } == fill; + assert!(j_ok); + kani::cover( + small && len > 0 && j < len && j != k && j > deep_min::(), + "deep element checked", + ); +} + +/// Covers standard `Vec` capacity/length regimes for raw parts (`cap == 0` +/// is reachable for both sized types and ZSTs). +fn cover_parts_regimes(len: usize, cap: usize, small: bool) { + kani::cover(small && cap == 0, "zero capacity"); + kani::cover(small && len == 0 && cap > 0, "empty with nonzero capacity"); + kani::cover(small && len > 0 && len < cap, "partially filled"); + kani::cover(small && len == cap && cap > 0, "full buffer"); + kani::cover(small && len > deep_min::(), "deep length > 4096"); +} + +/// Covers `Vec` regimes for an already-constructed `Vec` (where ZSTs +/// always have `capacity() == usize::MAX`). +fn cover_vec_regimes(len: usize, cap: usize, small: bool) { + kani::cover( + small && if T::IS_ZST { len == usize::MAX } else { cap == 0 }, + "zero capacity (or ZST max length)", + ); + kani::cover(small && len == 0 && cap > 0, "empty with nonzero capacity"); + kani::cover(small && len > 0 && len < cap, "partially filled"); + kani::cover(small && len == cap && cap > 0, "full buffer"); + kani::cover(small && len > deep_min::(), "deep length > 4096"); +} + +/// Deallocates `v`'s backing buffer without running an unbounded element-drop +/// loop for `DropTracker` and without calling `Vec::set_len`. +fn release_vec_buffer(v: Vec) { + if mem::needs_drop::() { + let (ptr, _len, cap, alloc) = v.into_raw_parts_with_allocator(); + if !T::IS_ZST && cap > 0 { + let layout = Layout::array::(cap).unwrap(); + unsafe { alloc.deallocate(NonNull::new_unchecked(ptr).cast::(), layout) }; + } + } else { + drop(v); + } +} + +// ============================================================================ +// 1. Vec::from_raw_parts +// ============================================================================ + +fn verify_from_raw_parts() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (ptr, len, cap, k, j) = + alloc_raw_parts_in_mode::(MAX_ALLOCATION_BYTES, fill, marker, &Global); + let small = witness_ok::(cap); + + reset_drops(); + let v = unsafe { Vec::from_raw_parts(ptr.as_ptr(), len, cap) }; + + assert!(drops() == 0); + assert!(v.len() == len); + assert!(v.capacity() == if T::IS_ZST { usize::MAX } else { cap }); + assert!(v.as_ptr() == ptr.as_ptr() as *const T); + check_elements(v.as_ptr(), len, k, j, fill, marker, small); + cover_parts_regimes::(len, cap, small); + T::when_zst(|| { + kani::cover( + ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical aligned ZST pointer", + ); + kani::cover( + ptr.as_ptr() == (&raw const ZST_ANCHOR) as *mut T, + "raw-parts constructor accepts provenance-bearing aligned ZST pointer", + ); + }); + T::when_non_zst(|| { + kani::cover( + small && cap == 0 && ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical zero-capacity pointer", + ); + }); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +fn check_from_raw_parts_u8() { + verify_from_raw_parts::(); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +fn check_from_raw_parts_overaligned() { + verify_from_raw_parts::(); +} + +#[kani::proof_for_contract(Vec::<()>::from_raw_parts)] +fn check_from_raw_parts_zst() { + verify_from_raw_parts::<(), false>(); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +fn check_from_raw_parts_drop_tracker() { + verify_from_raw_parts::(); +} + +#[kani::proof_for_contract(Vec::>::from_raw_parts)] +fn check_from_raw_parts_nonzero() { + verify_from_raw_parts::, false>(); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +#[kani::solver(minisat)] +fn check_from_raw_parts_padded_niche() { + verify_from_raw_parts::(); +} + +#[kani::proof_for_contract(Vec::<(char, u8)>::from_raw_parts)] +#[kani::solver(minisat)] +fn check_from_raw_parts_char_u8() { + verify_from_raw_parts::<(char, u8), true>(); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +#[kani::solver(minisat)] +fn check_from_raw_parts_nonpow2() { + verify_from_raw_parts::(); +} + +#[kani::proof_for_contract(Vec::::from_raw_parts)] +#[kani::solver(minisat)] +fn check_from_raw_parts_aligned_zst() { + verify_from_raw_parts::(); +} + +// ============================================================================ +// 2. Vec::from_parts (Challenge 23: Vec::from_nonnull) +// ============================================================================ + +fn verify_from_parts() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (ptr, len, cap, k, j) = + alloc_raw_parts_in::(MAX_ALLOCATION_BYTES, fill, marker, &Global); + let small = witness_ok::(cap); + + reset_drops(); + let v = unsafe { Vec::from_parts(ptr, len, cap) }; + + assert!(drops() == 0); + assert!(v.len() == len); + assert!(v.capacity() == if T::IS_ZST { usize::MAX } else { cap }); + assert!(v.as_ptr() == ptr.as_ptr() as *const T); + check_elements(v.as_ptr(), len, k, j, fill, marker, small); + cover_parts_regimes::(len, cap, small); + T::when_zst(|| { + kani::cover( + ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical aligned ZST pointer", + ); + kani::cover( + ptr.as_ptr() == (&raw const ZST_ANCHOR) as *mut T, + "raw-parts constructor accepts provenance-bearing aligned ZST pointer", + ); + }); + T::when_non_zst(|| { + kani::cover( + small && cap == 0 && ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical zero-capacity pointer", + ); + }); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::from_parts)] +fn check_from_parts_u8() { + verify_from_parts::(); +} + +#[kani::proof_for_contract(Vec::::from_parts)] +fn check_from_parts_overaligned() { + verify_from_parts::(); +} + +#[kani::proof_for_contract(Vec::<()>::from_parts)] +fn check_from_parts_zst() { + verify_from_parts::<()>(); +} + +#[kani::proof_for_contract(Vec::::from_parts)] +fn check_from_parts_drop_tracker() { + verify_from_parts::(); +} + +#[kani::proof_for_contract(Vec::>::from_parts)] +fn check_from_parts_nonzero() { + verify_from_parts::>(); +} + +// ============================================================================ +// 3. Vec::from_parts_in (Challenge 23: Vec::from_nonnull_in) +// ============================================================================ + +fn verify_from_parts_in_global() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (ptr, len, cap, k, j) = + alloc_raw_parts_in::(MAX_ALLOCATION_BYTES, fill, marker, &Global); + let small = witness_ok::(cap); + + reset_drops(); + let v = unsafe { Vec::from_parts_in(ptr, len, cap, Global) }; + + assert!(drops() == 0); + assert!(v.len() == len); + assert!(v.capacity() == if T::IS_ZST { usize::MAX } else { cap }); + assert!(v.as_ptr() == ptr.as_ptr() as *const T); + check_elements(v.as_ptr(), len, k, j, fill, marker, small); + cover_parts_regimes::(len, cap, small); + T::when_zst(|| { + kani::cover( + ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical aligned ZST pointer", + ); + kani::cover( + ptr.as_ptr() == (&raw const ZST_ANCHOR) as *mut T, + "raw-parts constructor accepts provenance-bearing aligned ZST pointer", + ); + }); + T::when_non_zst(|| { + kani::cover( + small && cap == 0 && ptr != NonNull::::dangling(), + "raw-parts constructor accepts non-canonical zero-capacity pointer", + ); + }); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +fn check_from_parts_in_u8() { + verify_from_parts_in_global::(); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +fn check_from_parts_in_overaligned() { + verify_from_parts_in_global::(); +} + +#[kani::proof_for_contract(Vec::<(), Global>::from_parts_in)] +fn check_from_parts_in_zst() { + verify_from_parts_in_global::<()>(); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +fn check_from_parts_in_drop_tracker() { + verify_from_parts_in_global::(); +} + +#[kani::proof_for_contract(Vec::, Global>::from_parts_in)] +fn check_from_parts_in_nonzero() { + verify_from_parts_in_global::>(); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +fn check_from_parts_in_drop_alloc() { + let tag_val: NonZero = kani::any(); + let alloc = DropAlloc(tag_val); + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (ptr, len, cap, k, j) = + alloc_raw_parts_in::(MAX_ALLOCATION_BYTES, fill, marker, &alloc); + let small = witness_ok::(cap); + + reset_alloc_drops(); + let v = unsafe { Vec::from_parts_in(ptr, len, cap, alloc) }; + + assert!(alloc_drops() == 0); + assert!(v.allocator().0 == tag_val); + assert!(v.len() == len); + assert!(v.capacity() == cap); + assert!(v.as_ptr() == ptr.as_ptr() as *const u8); + check_elements(v.as_ptr(), len, k, j, fill, marker, small); + kani::cover(small && len > 4096, "deep length > 4096 with stateful allocator"); + + release_vec_buffer(v); + assert!(alloc_drops() == 1); +} + +fn verify_from_parts_in_overallocated() { + let elem_size = mem::size_of::(); + let extra_elems: usize = any_up_to(8); + let extra_rem: usize = any_up_to(elem_size - 1); + let extra = extra_elems * elem_size + extra_rem; + let max_extra = 9 * elem_size; + let alloc = OverAlloc::new(extra); + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let req_cap = any_up_to((MAX_ALLOCATION_BYTES - max_extra) / elem_size); + let ptr = allocate_vec_buffer::(req_cap, T::bulk_init_byte(fill), &alloc); + let max_fitting_cap = if req_cap == 0 { 0 } else { req_cap + extra_elems }; + let used_cap: usize = kani::any_where(|&c: &usize| req_cap <= c && c <= max_fitting_cap); + let len = any_up_to(used_cap); + let k: usize = kani::any_where(|&k: &usize| k < len || (len == 0 && k == 0)); + let j: usize = kani::any(); + if len > 0 { + if j < len && j != k { + unsafe { ptr::write(ptr.as_ptr().add(j), T::from_tag(fill)) }; + } + unsafe { ptr::write(ptr.as_ptr().add(k), T::from_tag(marker)) }; + } + let small = witness_ok::(used_cap); + + if used_cap > 1 { + // Interior pointer into the live allocation must be rejected by `vec_parts_valid` + // (base-offset-0 check), even while trailing allocator slack is accepted. + assert!(!super::vec_parts_valid(unsafe { ptr.as_ptr().add(1) }, 0, used_cap - 1)); + } + + let v = unsafe { Vec::from_parts_in(ptr, len, used_cap, alloc) }; + + assert!(v.len() == len); + assert!(v.capacity() == used_cap); + assert!(v.as_ptr() == ptr.as_ptr() as *const T); + check_elements(v.as_ptr(), len, k, j, fill, marker, small); + kani::cover( + small && req_cap > 0 && used_cap == req_cap && extra > 0, + "from_parts_in accepts legal over-allocated custom-allocator block", + ); + kani::cover( + small && req_cap > 0 && used_cap > req_cap, + "from_parts_in accepts and deallocates larger fitting capacity", + ); + kani::cover( + small && req_cap > 0 && used_cap * elem_size < req_cap * elem_size + extra && len > 4096, + "from_parts_in accepts deep over-allocated block with trailing slack", + ); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +#[kani::solver(minisat)] +fn check_from_parts_in_overallocated_u8() { + verify_from_parts_in_overallocated::(); +} + +#[kani::proof_for_contract(Vec::::from_parts_in)] +#[kani::solver(minisat)] +fn check_from_parts_in_overallocated_overaligned() { + verify_from_parts_in_overallocated::(); +} + +// ============================================================================ +// 4. Vec::into_raw_parts_with_allocator (Challenge 23: Vec::into_raw_parts_with_alloc) +// ============================================================================ + +fn verify_into_raw_parts_with_allocator_global() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_drops(); + let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + + assert!(drops() == 0); + assert!(ptr as *const T == expected_ptr); + assert!(len == expected_len); + assert!(cap == expected_cap); + check_elements(ptr as *const T, len, k, j, fill, marker, small); + cover_vec_regimes::(len, cap, small); + + if !T::IS_ZST && cap > 0 { + let layout = Layout::array::(cap).unwrap(); + unsafe { alloc.deallocate(NonNull::new_unchecked(ptr).cast::(), layout) }; + } +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_u8() { + verify_into_raw_parts_with_allocator_global::(); +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_overaligned() { + verify_into_raw_parts_with_allocator_global::(); +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_zst() { + verify_into_raw_parts_with_allocator_global::<()>(); +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_drop_tracker() { + verify_into_raw_parts_with_allocator_global::(); +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_nonzero() { + verify_into_raw_parts_with_allocator_global::>(); +} + +#[kani::proof] +fn check_into_raw_parts_with_allocator_drop_alloc() { + let tag_val: NonZero = kani::any(); + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = + any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, DropAlloc(tag_val)); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_alloc_drops(); + let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + + assert!(alloc_drops() == 0); + assert!(alloc.0 == tag_val); + assert!(ptr as *const u8 == expected_ptr); + assert!(len == expected_len); + assert!(cap == expected_cap); + check_elements(ptr as *const u8, len, k, j, fill, marker, small); + kani::cover(small && len > 4096, "deep length > 4096 with stateful allocator"); + + if cap > 0 { + let layout = Layout::array::(cap).unwrap(); + unsafe { alloc.deallocate(NonNull::new_unchecked(ptr).cast::(), layout) }; + } + drop(alloc); + assert!(alloc_drops() == 1); +} + +// ============================================================================ +// 5. Vec::set_len +// ============================================================================ + +fn verify_set_len() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let cap: usize = + if T::IS_ZST { kani::any() } else { down_from(MAX_ALLOCATION_BYTES / mem::size_of::()) }; + let old_len: usize = down_from(cap); + // Allocate and initialize 100% of `0..cap` BEFORE constructing `Vec` via `from_parts`. + let ptr: NonNull = allocate_vec_buffer::(cap, T::bulk_init_byte(fill), &Global); + let actual_cap = if T::IS_ZST { usize::MAX } else { cap }; + let new_len: usize = down_from(actual_cap); + let k: usize = kani::any_where(|&k: &usize| k < new_len || (new_len == 0 && k == 0)); + let j: usize = kani::any(); + if !T::IS_ZST && new_len > 0 { + if j < new_len && j != k { + unsafe { ptr::write(ptr.as_ptr().add(j), T::from_tag(fill)) }; + } + unsafe { ptr::write(ptr.as_ptr().add(k), T::from_tag(marker)) }; + } + // Construct Vec without calling `set_len`. + let mut v = unsafe { Vec::from_parts(ptr, old_len, cap) }; + assert!(v.capacity() == actual_cap); + let small = witness_ok::(actual_cap); + let old_ptr = v.as_ptr(); + + reset_drops(); + unsafe { v.set_len(new_len) }; + + assert!(drops() == 0); + assert!(v.len() == new_len); + assert!(v.capacity() == actual_cap); + assert!(v.as_ptr() == old_ptr); + check_elements(v.as_ptr(), new_len, k, j, fill, marker, small); + + kani::cover(small && new_len == 0, "set_len to zero"); + kani::cover(small && new_len < old_len, "set_len shrinks length"); + kani::cover(small && new_len == old_len && old_len > 0, "set_len unchanged nonzero"); + kani::cover(small && new_len > old_len, "set_len grows into initialized spare capacity"); + kani::cover(small && new_len == actual_cap && actual_cap > 0, "set_len fills full capacity"); + kani::cover(small && new_len > 4096, "set_len deep length > 4096"); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::set_len)] +fn check_set_len_u8() { + verify_set_len::(); +} + +#[kani::proof_for_contract(Vec::::set_len)] +fn check_set_len_overaligned() { + verify_set_len::(); +} + +#[kani::proof_for_contract(Vec::<(), Global>::set_len)] +fn check_set_len_zst() { + verify_set_len::<()>(); +} + +#[kani::proof_for_contract(Vec::::set_len)] +fn check_set_len_drop_tracker() { + verify_set_len::(); +} + +#[kani::proof_for_contract(Vec::, Global>::set_len)] +fn check_set_len_nonzero() { + verify_set_len::>(); +} + +// ============================================================================ +// 6. Vec::deref +// ============================================================================ + +fn verify_deref() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_drops(); + let slice: &[T] = Deref::deref(&v); + + assert!(drops() == 0); + assert!(slice.len() == expected_len); + assert!(slice.as_ptr() == expected_ptr); + if expected_len > 0 { + if !T::IS_ZST { + assert!(slice[k].tag() == marker); + } + if j < expected_len && j != k { + if !T::IS_ZST { + assert!(slice[j].tag() == fill); + } + kani::cover(small && j > 4096, "deep slice index deref"); + } + } + cover_vec_regimes::(expected_len, expected_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_deref_u8() { + verify_deref::(); +} + +#[kani::proof] +fn check_deref_overaligned() { + verify_deref::(); +} + +#[kani::proof] +fn check_deref_zst() { + verify_deref::<()>(); +} + +#[kani::proof] +fn check_deref_drop_tracker() { + verify_deref::(); +} + +#[kani::proof] +fn check_deref_nonzero() { + verify_deref::>(); +} + +// ============================================================================ +// 7. Vec::deref_mut +// ============================================================================ + +fn verify_deref_mut() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let new_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_drops(); + { + let slice: &mut [T] = DerefMut::deref_mut(&mut v); + assert!(drops() == 0); + assert!(slice.len() == expected_len); + assert!(slice.as_ptr() == expected_ptr); + if expected_len > 0 { + if !T::IS_ZST { + assert!(slice[k].tag() == marker); + } + slice[k] = T::from_tag(new_val); + assert!(drops() == usize::from(mem::needs_drop::())); + if !T::IS_ZST { + assert!(slice[k].tag() == new_val); + } + if j < expected_len && j != k { + if !T::IS_ZST { + assert!(slice[j].tag() == fill); + } + kani::cover(small && j > 4096, "deep slice index deref_mut"); + } + } + } + assert!(v.len() == expected_len); + assert!(v.capacity() == expected_cap); + if expected_len > 0 && !T::IS_ZST { + assert!(unsafe { (&*v.as_ptr().add(k)).tag() } == new_val); + } + cover_vec_regimes::(expected_len, expected_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_deref_mut_u8() { + verify_deref_mut::(); +} + +#[kani::proof] +fn check_deref_mut_overaligned() { + verify_deref_mut::(); +} + +#[kani::proof] +fn check_deref_mut_zst() { + verify_deref_mut::<()>(); +} + +#[kani::proof] +fn check_deref_mut_drop_tracker() { + verify_deref_mut::(); +} + +#[kani::proof] +fn check_deref_mut_nonzero() { + verify_deref_mut::>(); +} + +// ============================================================================ +// 8. Vec::spare_capacity_mut +// ============================================================================ + +fn verify_spare_capacity_mut() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let spare_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_drops(); + { + let spare = v.spare_capacity_mut(); + assert!(drops() == 0); + assert!(spare.len() == expected_cap - expected_len); + assert!(spare.as_ptr() as *const T == unsafe { expected_ptr.add(expected_len) }); + if !spare.is_empty() { + let s_idx = down_from(spare.len() - 1); + spare[s_idx].write(T::from_tag(spare_val)); + assert!(drops() == 0); + if !T::IS_ZST { + assert!(unsafe { spare[s_idx].assume_init_ref().tag() } == spare_val); + } + kani::cover(small && s_idx > 4096, "deep spare index written"); + } + } + assert!(drops() == 0); + assert!(v.len() == expected_len); + assert!(v.capacity() == expected_cap); + check_elements(v.as_ptr(), expected_len, k, j, fill, marker, small); + cover_vec_regimes::(expected_len, expected_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_spare_capacity_mut_u8() { + verify_spare_capacity_mut::(); +} + +#[kani::proof] +fn check_spare_capacity_mut_overaligned() { + verify_spare_capacity_mut::(); +} + +#[kani::proof] +fn check_spare_capacity_mut_zst() { + verify_spare_capacity_mut::<()>(); +} + +#[kani::proof] +fn check_spare_capacity_mut_drop_tracker() { + verify_spare_capacity_mut::(); +} + +#[kani::proof] +fn check_spare_capacity_mut_nonzero() { + verify_spare_capacity_mut::>(); +} + +// ============================================================================ +// 9. Vec::split_at_spare_mut +// ============================================================================ + +fn verify_split_at_spare_mut() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let spare_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + + reset_drops(); + { + let (init, spare) = v.split_at_spare_mut(); + assert!(drops() == 0); + assert!(init.len() == expected_len); + assert!(spare.len() == expected_cap - expected_len); + assert!(init.as_ptr() == expected_ptr); + assert!(spare.as_ptr() as *const T == unsafe { expected_ptr.add(expected_len) }); + if !spare.is_empty() { + let s_idx = down_from(spare.len() - 1); + spare[s_idx].write(T::from_tag(spare_val)); + assert!(drops() == 0); + if !T::IS_ZST { + assert!(unsafe { spare[s_idx].assume_init_ref().tag() } == spare_val); + } + kani::cover(small && s_idx > 4096, "deep spare index written"); + } + if expected_len > 0 { + if !T::IS_ZST { + assert!(init[k].tag() == marker); + } + if j < expected_len && j != k { + if !T::IS_ZST { + assert!(init[j].tag() == fill); + } + kani::cover(small && j > 4096, "deep init index verified after spare write"); + } + } + } + assert!(drops() == 0); + assert!(v.len() == expected_len); + assert!(v.capacity() == expected_cap); + cover_vec_regimes::(expected_len, expected_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_split_at_spare_mut_u8() { + verify_split_at_spare_mut::(); +} + +#[kani::proof] +fn check_split_at_spare_mut_overaligned() { + verify_split_at_spare_mut::(); +} + +#[kani::proof] +fn check_split_at_spare_mut_zst() { + verify_split_at_spare_mut::<()>(); +} + +#[kani::proof] +fn check_split_at_spare_mut_drop_tracker() { + verify_split_at_spare_mut::(); +} + +#[kani::proof] +fn check_split_at_spare_mut_nonzero() { + verify_split_at_spare_mut::>(); +} + +// ============================================================================ +// 10. Vec::split_at_spare_mut_with_len +// ============================================================================ + +fn verify_split_at_spare_mut_with_len() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let spare_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = + any_vec_in_mode::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let expected_ptr = v.as_ptr(); + let expected_len = v.len(); + let expected_cap = v.capacity(); + let small = witness_ok::(expected_cap); + let mut grew = false; + + reset_drops(); + { + let (init, spare, len_ref) = unsafe { v.split_at_spare_mut_with_len() }; + assert!(drops() == 0); + assert!(init.len() == expected_len); + assert!(*len_ref == expected_len); + assert!(spare.len() == expected_cap - expected_len); + assert!(init.as_ptr() == expected_ptr); + assert!(spare.as_ptr() as *const T == unsafe { expected_ptr.add(expected_len) }); + if !spare.is_empty() { + let s_idx = pick_bound::(spare.len() - 1); + spare[0].write(T::from_tag(spare_val)); + if s_idx > 0 { + spare[s_idx].write(T::from_tag(spare_val)); + if !T::IS_ZST { + assert!(unsafe { spare[s_idx].assume_init_ref().tag() } == spare_val); + } + } + *len_ref += 1; + grew = true; + kani::cover(small && s_idx > 4096, "deep spare index written"); + } + if expected_len > 0 { + if !T::IS_ZST { + assert!(init[k].tag() == marker); + } + if j < expected_len && j != k { + if !T::IS_ZST { + assert!(init[j].tag() == fill); + } + kani::cover(small && j > 4096, "deep init index verified"); + } + } + } + assert!(drops() == 0); + assert!(v.len() == expected_len + usize::from(grew)); + assert!(v.capacity() == expected_cap); + if grew && !T::IS_ZST { + assert!(unsafe { (&*v.as_ptr().add(expected_len)).tag() } == spare_val); + } + cover_vec_regimes::(expected_len, expected_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract(Vec::::split_at_spare_mut_with_len)] +fn check_split_at_spare_mut_with_len_u8() { + verify_split_at_spare_mut_with_len::(); +} + +#[kani::proof_for_contract(Vec::::split_at_spare_mut_with_len)] +#[kani::solver(minisat)] +fn check_split_at_spare_mut_with_len_overaligned() { + verify_split_at_spare_mut_with_len::(); +} + +#[kani::proof_for_contract(Vec::<(), Global>::split_at_spare_mut_with_len)] +fn check_split_at_spare_mut_with_len_zst() { + verify_split_at_spare_mut_with_len::<(), false>(); +} + +#[kani::proof_for_contract(Vec::::split_at_spare_mut_with_len)] +fn check_split_at_spare_mut_with_len_drop_tracker() { + verify_split_at_spare_mut_with_len::(); +} + +#[kani::proof_for_contract(Vec::, Global>::split_at_spare_mut_with_len)] +fn check_split_at_spare_mut_with_len_nonzero() { + verify_split_at_spare_mut_with_len::, false>(); +} + +// ============================================================================ +// 11. Vec::push_within_capacity and Vec::push +// ============================================================================ + +fn verify_push_within_capacity() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let new_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + + reset_drops(); + let full = old_len == old_cap; + match v.push_within_capacity(T::from_tag(new_val)) { + Ok(r) => { + assert!(!full); + assert!(r as *mut T as *const T == old_ptr.wrapping_add(old_len)); + if !T::IS_ZST { + assert!(r.tag() == new_val); + } + kani::cover(small && old_len > 4096, "push_within_capacity Ok at deep position"); + } + Err(e) => { + assert!(full); + if !T::IS_ZST { + assert!(e.tag() == new_val); + } + drop(e); + assert!(drops() == usize::from(mem::needs_drop::())); + kani::cover(small && old_len > 0, "push_within_capacity Err on full nonempty buffer"); + } + } + if !full { + assert!(drops() == 0); + } + assert!(v.len() == old_len + usize::from(!full)); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + check_elements(v.as_ptr(), old_len, k, j, fill, marker, small); + if !full && !T::IS_ZST { + assert!(unsafe { (&*v.as_ptr().add(old_len)).tag() } == new_val); + } + kani::cover(small && old_len == 0 && !full, "push_within_capacity into empty vec"); + cover_vec_regimes::(old_len, old_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_push_within_capacity_u8() { + verify_push_within_capacity::(); +} + +#[kani::proof] +fn check_push_within_capacity_overaligned() { + verify_push_within_capacity::(); +} + +#[kani::proof] +fn check_push_within_capacity_zst() { + verify_push_within_capacity::<()>(); +} + +#[kani::proof] +fn check_push_within_capacity_drop_tracker() { + verify_push_within_capacity::(); +} + +#[kani::proof] +fn check_push_within_capacity_nonzero() { + verify_push_within_capacity::>(); +} + +fn verify_sized_push() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let new_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = + any_vec_in_mode::(MAX_ALLOCATION_BYTES / 2, fill, marker, Global); + let old_len = v.len(); + let old_cap = v.capacity(); + let old_ptr = v.as_ptr(); + let small = witness_ok::(old_cap); + let deep = deep_min::(); + reset_drops(); + v.push(T::from_tag(new_val)); + + assert!(drops() == 0); + assert!(v.len() == old_len + 1); + let grew = old_len == old_cap; + assert!(!grew || v.capacity() > old_cap); + assert!(grew || (v.capacity() == old_cap && v.as_ptr() == old_ptr)); + kani::cover(small && grew && old_cap == 0, "push allocates for an empty buffer"); + kani::cover(small && grew && old_len > deep, "push grows a full buffer at a deep index"); + kani::cover(small && !grew && old_len == 0, "push into empty buffer with spare capacity"); + kani::cover(small && !grew && old_len > deep, "push at a deep index with spare capacity"); + assert!(unsafe { (&*v.as_ptr().add(old_len)).tag() } == new_val); + check_elements(v.as_ptr(), old_len, k, j, fill, marker, small); + release_vec_buffer(v); +} + +// Both allocator models allocate a new block, copy the old bytes and free the +// old block on success. CBMC's C realloc uses a whole-array copy, avoiding the +// symbolic stack array in Kani's memcpy-based model that breaks trace output. +unsafe fn model_growing_realloc( + old: NonNull, + old_size: usize, + align: core::mem::Alignment, + new_size: usize, +) -> *mut u8 { + unsafe extern "C" { + fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8; + } + assert!(0 < old_size && old_size < new_size); + assert!(Layout::from_size_align(old_size, align.as_usize()).is_ok()); + assert!(Layout::from_size_align(new_size, align.as_usize()).is_ok()); + assert!(old.as_ptr().addr().is_multiple_of(align.as_usize())); + assert!(kani::mem::is_inbounds(ptr::slice_from_raw_parts(old.as_ptr(), old_size))); + assert!(!kani::mem::is_inbounds(ptr::slice_from_raw_parts(old.as_ptr(), old_size + 1))); + let new_ptr = unsafe { realloc(old.as_ptr(), new_size) }; + assert!(new_ptr.is_null() || new_ptr.addr().is_multiple_of(align.as_usize())); + new_ptr +} + +#[kani::proof] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_u8() { + verify_sized_push::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_overaligned() { + verify_sized_push::(); +} + +#[kani::proof] +fn check_push_zst() { + let old_len = down_from(usize::MAX - 1); + // A Vec of units needs no storage or per-element initialization. + let mut v = Vec::new(); + v.len = old_len; + let old_ptr = v.as_ptr(); + + v.push(()); + + assert!(v.len() == old_len + 1); + assert!(v.capacity() == usize::MAX); + assert!(v.as_ptr() == old_ptr); + kani::cover(old_len == 0, "first push into a ZST vector"); + kani::cover(old_len > 4096, "push at a deep ZST index"); + kani::cover(old_len == usize::MAX - 1, "push reaches the maximum ZST length"); +} + +#[kani::proof] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_drop_tracker() { + verify_sized_push::(); +} + +#[kani::proof] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_nonzero() { + verify_sized_push::, false>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_padded_niche() { + verify_sized_push::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_push_nonpow2() { + verify_sized_push::(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_push_zst_capacity_overflow() { + // All `()` elements exist without any backing storage. + let mut v = Vec::new(); + v.len = usize::MAX; + kani::cover(v.len() == usize::MAX, "push would overflow ZST length"); + v.push(()); +} + +// ============================================================================ +// 12. Vec::pop +// ============================================================================ + +fn verify_pop() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (ptr, old_len, cap, k, j) = + alloc_raw_parts_in::(MAX_ALLOCATION_BYTES, fill, marker, &Global); + // Ensure the tail slot `old_len - 1` read by `pop` is always initialized even + // for padded types, without restricting `k` or `j` via `kani::assume`. + if !T::IS_ZST && old_len > 0 && k != old_len - 1 { + unsafe { ptr::write(ptr.as_ptr().add(old_len - 1), T::from_tag(fill)) }; + } + let mut v = unsafe { Vec::from_parts(ptr, old_len, cap) }; + let old_ptr = v.as_ptr(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + + reset_drops(); + match v.pop() { + Some(x) => { + assert!(old_len > 0); + if !T::IS_ZST { + let expected = if k == old_len - 1 { marker } else { fill }; + assert!(x.tag() == expected); + } + drop(x); + assert!(drops() == usize::from(mem::needs_drop::())); + kani::cover(small && old_len > 4096, "pop from deep position"); + } + None => { + assert!(old_len == 0); + assert!(drops() == 0); + kani::cover(small && old_cap > 0, "pop on empty vec with capacity"); + } + } + let new_len = old_len.saturating_sub(1); + assert!(v.len() == new_len); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + if !T::IS_ZST && k < new_len { + assert!(unsafe { (&*v.as_ptr().add(k)).tag() } == marker); + } + if !T::IS_ZST && j < new_len && j != k { + assert!(unsafe { (&*v.as_ptr().add(j)).tag() } == fill); + } + cover_vec_regimes::(old_len, old_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_pop_u8() { + verify_pop::(); +} + +#[kani::proof] +fn check_pop_overaligned() { + verify_pop::(); +} + +#[kani::proof] +fn check_pop_zst() { + verify_pop::<()>(); +} + +#[kani::proof] +fn check_pop_drop_tracker() { + verify_pop::(); +} + +#[kani::proof] +fn check_pop_nonzero() { + verify_pop::>(); +} + +// ============================================================================ +// 13. Vec::swap_remove +// ============================================================================ + +fn verify_swap_remove() { + let retained_tag = any_tag(); + let last_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != retained_tag); + let removed_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != last_tag && b != retained_tag); + let (mut v, k, _) = + any_vec_in_mode::(MAX_ALLOCATION_BYTES, retained_tag, retained_tag, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + kani::assume(old_len > 0); + let index: usize = kani::any_where(|&i: &usize| i < old_len); + let last = old_len - 1; + // Materialize both slots the implementation reads independently of the + // arbitrary index `k`, which samples an element that may be retained. + if !T::IS_ZST { + let base = v.as_mut_ptr(); + unsafe { + base.add(last).write(T::from_tag(last_tag)); + if index != last { + base.add(index).write(T::from_tag(removed_tag)); + } + } + } + + reset_drops(); + let x = v.swap_remove(index); + + assert!(drops() == 0); + assert!(v.len() == last); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + if !T::IS_ZST { + assert!(x.tag() == if index == last { last_tag } else { removed_tag }); + // The old last element moved into the hole. + if index < last { + assert!(unsafe { (&*v.as_ptr().add(index)).tag() } == last_tag); + } + if k != index && k < last { + assert!(unsafe { (&*v.as_ptr().add(k)).tag() } == retained_tag); + } + } + drop(x); + assert!(drops() == usize::from(mem::needs_drop::())); + kani::cover(small && index == last, "swap_remove last element"); + kani::cover(small && index < last, "swap_remove moves last into hole"); + kani::cover(small && index < last && k < last && k != index, "retained element checked"); + kani::cover(small && index > 4096, "swap_remove deep index"); + kani::cover(small && old_len == 1, "swap_remove only element"); + kani::cover(small && old_len < old_cap, "swap_remove partially filled"); + kani::cover(small && old_len == old_cap, "swap_remove full buffer"); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_swap_remove_u8() { + verify_swap_remove::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_swap_remove_overaligned() { + verify_swap_remove::(); +} + +#[kani::proof] +fn check_swap_remove_zst() { + verify_swap_remove::<(), false>(); +} + +#[kani::proof] +fn check_swap_remove_drop_tracker() { + verify_swap_remove::(); +} + +#[kani::proof] +fn check_swap_remove_nonzero() { + verify_swap_remove::, false>(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_swap_remove_out_of_bounds() { + let (mut v, _, _) = any_vec_in::(MAX_ALLOCATION_BYTES, 1, 2, Global); + let index = kani::any_where(|&i: &usize| i >= v.len()); + kani::cover(v.len() == 0, "out-of-bounds swap_remove on an empty vector"); + kani::cover( + witness_ok::(v.capacity()) && v.len() > 4096 && index == v.len(), + "out-of-bounds swap_remove after a deep initialized prefix", + ); + let _ = v.swap_remove(index); +} + +// ============================================================================ +// 14. Vec::leak +// ============================================================================ + +fn verify_leak() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + + reset_drops(); + let s: &mut [T] = v.leak(); + + assert!(drops() == 0); + assert!(s.len() == old_len); + assert!(s.as_ptr() == old_ptr); + check_elements(s.as_ptr(), old_len, k, j, fill, marker, small); + if old_len > 0 { + // The leaked slice is writable for the rest of the program. + s[k] = T::from_tag(fill); + if !T::IS_ZST { + assert!(s[k].tag() == fill); + } + } + cover_vec_regimes::(old_len, old_cap, small); + // Release the leaked buffer so the harness itself does not leak. + if !T::IS_ZST && old_cap > 0 { + let layout = Layout::array::(old_cap).unwrap(); + unsafe { Global.deallocate(NonNull::new_unchecked(s.as_mut_ptr()).cast::(), layout) }; + } +} + +#[kani::proof] +fn check_leak_u8() { + verify_leak::(); +} + +#[kani::proof] +fn check_leak_overaligned() { + verify_leak::(); +} + +#[kani::proof] +fn check_leak_zst() { + verify_leak::<()>(); +} + +#[kani::proof] +fn check_leak_drop_tracker() { + verify_leak::(); +} + +#[kani::proof] +fn check_leak_nonzero() { + verify_leak::>(); +} + +// ============================================================================ +// 15. Vec::insert +// ============================================================================ + +/// Verifies `Vec::insert` for sized element types up to `MAX_ALLOCATION_BYTES / 2` +/// initial bytes (so a doubled allocation stays within `MAX_ALLOCATION_BYTES`). +/// Memory safety of the in-place shift (`ptr::copy`) — bounds, alignment, and +/// liveness of both source and destination ranges — is checked by Kani's +/// instrumentation of `ptr::copy`. Element contents are not read after the +/// overlapping shift because reading through CBMC's symbolic `memmove` model +/// causes its array decision procedure to diverge. +fn verify_sized_insert() { + let fill = any_tag(); + let new_val: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + // Keep initial buffer <= MAX_ALLOCATION_BYTES / 2 so grown buffer (2 * cap) + // and every byte offset up to new_len * size_of::() stay inside + // MAX_ALLOCATION_BYTES = (1 << 51) - 1. + let (mut v, _, _) = any_vec_in_up::(MAX_ALLOCATION_BYTES / 2, fill, fill, Global); + let old_len = v.len(); + let old_cap = v.capacity(); + let old_ptr = v.as_ptr(); + let small = witness_ok::(old_cap); + let deep = deep_min::(); + let index = any_up_to(old_len); + + reset_drops(); + v.insert(index, T::from_tag(new_val)); + + assert!(drops() == 0); + assert!(v.len() == old_len + 1); + if old_len == old_cap { + assert!(v.capacity() > old_cap); + kani::cover(small && old_cap == 0, "insert allocates for an empty buffer"); + kani::cover( + small && old_cap > 0 && index < old_len, + "insert grows a full buffer and shifts tail", + ); + } else { + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + kani::cover(small && old_len == 0, "insert into empty buffer with spare capacity"); + kani::cover(small && index < old_len, "insert shifts tail in place"); + } + kani::cover(small && index == 0 && old_len > 0, "insert at front shifts all elements"); + kani::cover(small && index == old_len && old_len > 0, "insert at end without shift"); + kani::cover( + small && index > deep && old_len - index > deep, + "insert at deep index with deep shifted tail", + ); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_u8() { + verify_sized_insert::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_overaligned() { + verify_sized_insert::(); +} + +#[kani::proof] +fn check_insert_zst() { + let old_len = down_from(usize::MAX - 1); + let index = down_from(old_len); + let mut v = Vec::new(); + v.len = old_len; + let old_ptr = v.as_ptr(); + + v.insert(index, ()); + + assert!(v.len() == old_len + 1); + assert!(v.capacity() == usize::MAX); + assert!(v.as_ptr() == old_ptr); + kani::cover(old_len == 0 && index == 0, "insert into empty ZST vector"); + kani::cover(index == 0 && old_len > 4096, "insert at front of deep ZST vector"); + kani::cover(index > 4096 && index < old_len, "insert in middle of deep ZST vector"); + kani::cover(old_len == usize::MAX - 1 && index == old_len, "insert reaches ZST max len"); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_drop_tracker() { + verify_sized_insert::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_nonzero() { + verify_sized_insert::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_large() { + verify_sized_insert::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_insert_char_u8() { + verify_sized_insert::<(char, u8)>(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_insert_out_of_bounds() { + let (mut v, _, _) = any_vec_in::(MAX_ALLOCATION_BYTES, 1, 2, Global); + let index = kani::any_where(|&i: &usize| i > v.len()); + kani::cover(v.len() == 0 && index == 1, "out-of-bounds insert on an empty vector"); + kani::cover( + witness_ok::(v.capacity()) && v.len() > 4096 && index == v.len() + 1, + "out-of-bounds insert right past deep initialized prefix", + ); + v.insert(index, 7); +} + +#[kani::proof] +#[kani::should_panic] +fn check_insert_zst_capacity_overflow() { + let mut v = Vec::new(); + v.len = usize::MAX; + let index: usize = kani::any(); + kani::cover(index == usize::MAX, "insert at end would overflow ZST length"); + kani::cover(index == 0, "insert at front would overflow ZST length"); + v.insert(index, ()); +} + +// ============================================================================ +// 16. Vec::remove +// ============================================================================ + +/// Verifies `Vec::remove` across arbitrary unbounded buffers and in-bounds +/// indices. `ptr::read` of the removed element precedes `ptr::copy`, so the +/// returned element value and drop behavior are verified directly while Kani's +/// instrumentation of `ptr::copy` checks full memory safety of the left shift. +fn verify_remove() { + let fill = any_tag(); + let removed_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (mut v, _, _) = any_vec_in_up::(MAX_ALLOCATION_BYTES, fill, fill, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + kani::assume(old_len > 0); + let index = any_up_to(old_len - 1); + if !T::IS_ZST { + unsafe { v.as_mut_ptr().add(index).write(T::from_tag(removed_tag)) }; + } + + reset_drops(); + let x = v.remove(index); + + assert!(drops() == 0); + assert!(v.len() == old_len - 1); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + if !T::IS_ZST { + assert!(x.tag() == removed_tag); + } + drop(x); + assert!(drops() == usize::from(mem::needs_drop::())); + + kani::cover(small && old_len == 1 && index == 0, "remove only element"); + kani::cover(small && index == 0 && old_len > 1, "remove first element shifts all left"); + kani::cover(small && index > 0 && index < old_len - 1, "remove middle element"); + kani::cover(small && index == old_len - 1 && old_len > 1, "remove last element without shift"); + kani::cover(small && old_len < old_cap, "remove from partially filled buffer"); + kani::cover(small && old_len == old_cap, "remove from full buffer"); + kani::cover( + small && index > 4096 && old_len - 1 - index > 4096, + "remove at deep index with deep shifted tail", + ); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_remove_u8() { + verify_remove::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_remove_overaligned() { + verify_remove::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_remove_zst() { + verify_remove::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_remove_drop_tracker() { + verify_remove::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_remove_nonzero() { + verify_remove::>(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_remove_out_of_bounds() { + let (mut v, _, _) = any_vec_in::(MAX_ALLOCATION_BYTES, 1, 2, Global); + let index = kani::any_where(|&i: &usize| i >= v.len()); + kani::cover(v.len() == 0, "out-of-bounds remove on an empty vector"); + kani::cover( + witness_ok::(v.capacity()) && v.len() > 4096 && index == v.len(), + "out-of-bounds remove right past deep initialized prefix", + ); + let _ = v.remove(index); +} + +// ============================================================================ +// 17. Vec::truncate and 18. Vec::clear +// ============================================================================ + +static mut LAST_DROP_PTR: usize = 0x5A5A_5A5A_5A5A_5A5C; +static mut LAST_DROP_LEN: usize = 0x5A5A_5A5A_5A5A_5A5D; + +fn reset_drop_trace() { + reset_drops(); + unsafe { + LAST_DROP_PTR = 0; + LAST_DROP_LEN = 0; + } +} + +/// Modular verification summary for `core::ptr::drop_in_place::<[DropTracker]>`. +/// +/// The compiler synthesizes an unannotatable loop inside the drop glue for +/// `[DropTracker]`. For `DropTracker`, whose `Drop::drop` only increments +/// `DROPS` by 1 without mutating `self` or panicking, checking full slice +/// read/write validity and a symbolic element read plus `DROPS += count` is an +/// exact sound summary for arbitrary slice lengths. +unsafe fn drop_tracker_slice_stub(to_drop: *mut T) { + assert!(kani::mem::can_write(to_drop)); + assert!(kani::mem::can_dereference(to_drop as *const T)); + let sz = kani::mem::checked_size_of_raw(to_drop as *const T).unwrap(); + assert!(sz % mem::size_of::() == 0); + let count = sz / mem::size_of::(); + let base_u8 = (to_drop as *mut ()).cast::(); + let base_addr = base_u8.addr(); + assert!(base_addr.is_multiple_of(mem::align_of::())); + if count > 0 { + let k: usize = kani::any_where(|&k: &usize| k < count); + let _ = unsafe { *base_u8.add(k * mem::size_of::()) }; + } + unsafe { + LAST_DROP_PTR = base_addr; + LAST_DROP_LEN = count; + DROPS += count; + } +} + +fn verify_truncate(expect_drops: bool) { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (mut v, k, j) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let new_len: usize = kani::any(); + let expected_len = old_len.min(new_len); + let dropped = old_len.saturating_sub(new_len); + + reset_drop_trace(); + v.truncate(new_len); + + assert!(v.len() == expected_len); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + if expect_drops { + assert!(drops() == dropped); + assert!(unsafe { LAST_DROP_LEN } == dropped); + if dropped > 0 { + assert!(unsafe { LAST_DROP_PTR } == unsafe { old_ptr.add(new_len) }.addr()); + } else { + assert!(unsafe { LAST_DROP_PTR } == 0); + } + } else { + assert!(drops() == 0); + } + if !T::IS_ZST && expected_len > 0 { + if k < expected_len { + assert!(unsafe { (&*v.as_ptr().add(k)).tag() } == marker); + } + if j < expected_len && j != k { + assert!(unsafe { (&*v.as_ptr().add(j)).tag() } == fill); + } + } + kani::cover(small && old_len == 0, "truncate empty vec"); + kani::cover(small && old_len > 0 && new_len == 0, "truncate all elements"); + kani::cover(small && new_len > 0 && new_len < old_len, "partial truncate"); + kani::cover(small && old_len > 0 && new_len == old_len, "truncate equal len no-op"); + kani::cover(small && new_len > old_len, "truncate greater len no-op"); + kani::cover( + small && new_len > 4096 && dropped > 4096, + "truncate deep surviving prefix and deep dropped tail", + ); + kani::cover(small && k < expected_len && k > 4096, "deep surviving element verified"); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_truncate_u8() { + verify_truncate::(false); +} + +#[kani::proof] +fn check_truncate_overaligned() { + verify_truncate::(false); +} + +#[kani::proof] +fn check_truncate_zst() { + verify_truncate::<()>(false); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_truncate_drop_tracker() { + verify_truncate::(true); +} + +#[kani::proof] +fn check_truncate_nonzero() { + verify_truncate::>(false); +} + +fn verify_clear(expect_drops: bool) { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (mut v, _, _) = any_vec_in::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + + reset_drop_trace(); + v.clear(); + + assert!(v.len() == 0); + assert!(v.is_empty()); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + if expect_drops { + assert!(drops() == old_len); + assert!(unsafe { LAST_DROP_LEN } == old_len); + assert!(unsafe { LAST_DROP_PTR } == old_ptr.addr()); + } else { + assert!(drops() == 0); + } + cover_vec_regimes::(old_len, old_cap, small); + + release_vec_buffer(v); +} + +#[kani::proof] +fn check_clear_u8() { + verify_clear::(false); +} + +#[kani::proof] +fn check_clear_overaligned() { + verify_clear::(false); +} + +#[kani::proof] +fn check_clear_zst() { + verify_clear::<()>(false); +} + +#[kani::proof] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_clear_drop_tracker() { + verify_clear::(true); +} + +#[kani::proof] +fn check_clear_nonzero() { + verify_clear::>(false); +} + +// ============================================================================ +// 19. Vec::split_off +// ============================================================================ + +fn verify_split_off() { + let prefix_tag = any_tag(); + let suffix_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != prefix_tag); + let (mut v, _, _) = + any_vec_in_up::(MAX_ALLOCATION_BYTES, prefix_tag, prefix_tag, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let at = any_up_to(old_len); + let other_len = old_len - at; + + let prefix_idx: usize = kani::any(); + let has_prefix = prefix_idx < at; + let suffix_idx: usize = kani::any(); + let has_suffix = suffix_idx < other_len; + if !T::IS_ZST { + if has_prefix { + unsafe { v.as_mut_ptr().add(prefix_idx).write(T::from_tag(prefix_tag)) }; + } + if has_suffix { + unsafe { v.as_mut_ptr().add(at + suffix_idx).write(T::from_tag(suffix_tag)) }; + } + } + + reset_drops(); + let other = v.split_off(at); + + assert!(drops() == 0); + assert!(v.len() == at); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + assert!(other.len() == other_len); + assert!(other.capacity() == if T::IS_ZST { usize::MAX } else { other_len }); + if !T::IS_ZST { + if other_len > 0 { + assert!(other.as_ptr() != v.as_ptr()); + } + if has_prefix { + assert!(unsafe { (&*v.as_ptr().add(prefix_idx)).tag() } == prefix_tag); + } + if has_suffix { + assert!(unsafe { (&*other.as_ptr().add(suffix_idx)).tag() } == suffix_tag); + } + } + kani::cover(small && old_len == 0 && at == 0, "split_off empty vec"); + kani::cover(small && old_len > 0 && at == 0, "split_off all elements"); + kani::cover(small && at > 0 && at < old_len, "split_off in middle"); + kani::cover(small && old_len > 0 && at == old_len, "split_off empty tail"); + kani::cover(small && old_len == old_cap && old_cap > 0, "split_off full buffer"); + kani::cover(small && at > 4096 && other_len > 4096, "split_off deep prefix and deep tail"); + + release_vec_buffer(other); + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_split_off_u8() { + verify_split_off::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_split_off_overaligned() { + verify_split_off::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_split_off_zst() { + verify_split_off::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_split_off_drop_tracker() { + verify_split_off::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_split_off_nonzero() { + verify_split_off::>(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_split_off_out_of_bounds() { + let (mut v, _, _) = any_vec_in::(MAX_ALLOCATION_BYTES, 1, 2, Global); + let at = kani::any_where(|&i: &usize| i > v.len()); + kani::cover(v.len() == 0 && at == 1, "out-of-bounds split_off on an empty vector"); + kani::cover( + witness_ok::(v.capacity()) && v.len() > 4096 && at == v.len() + 1, + "out-of-bounds split_off right past deep initialized prefix", + ); + let _ = v.split_off(at); +} + +// ============================================================================ +// 20. Vec::append and 21. Vec::append_elements +// ============================================================================ + +/// Builds a second, independent symbolic vector whose elements are all +/// considered to carry `tag` at the symbolic index `s` (if `s < len`). +fn any_source_vec(tag: u8) -> (Vec, usize) { + let (v, s, _) = any_vec_in_up::(MAX_ALLOCATION_BYTES / 2, tag, tag, Global); + (v, s) +} + +/// Shared postconditions for `append`/`append_elements`: `self` keeps its +/// prefix, gains `count` elements copied from `src_ptr`, and only reallocates +/// when spare capacity was insufficient. +fn check_appended( + v: &Vec, + old_ptr: *const T, + old_len: usize, + old_cap: usize, + count: usize, + k: usize, + j: usize, + fill: u8, + marker: u8, + s: usize, + src_tag: u8, + small: bool, +) { + let deep = deep_min::(); + assert!(v.len() == old_len + count); + assert!(v.capacity() >= old_len + count); + let in_place = count <= old_cap - old_len; + assert!(!in_place || (v.capacity() == old_cap && v.as_ptr() == old_ptr)); + assert!(in_place || v.capacity() > old_cap); + kani::cover( + small && in_place && count > 0 && old_len > deep, + "append into deep spare capacity", + ); + T::when_non_zst(|| { + kani::cover(small && !in_place && old_cap == 0, "append allocates for an empty buffer"); + kani::cover( + small && !in_place && old_len > deep && count > deep, + "append grows deep buffer", + ); + }); + let s_ok = + T::IS_ZST || s >= count || unsafe { (&*v.as_ptr().add(old_len + s)).tag() } == src_tag; + assert!(s_ok); + T::when_non_zst(|| { + kani::cover(small && s < count && s > deep, "deep appended element checked"); + }); + check_elements(v.as_ptr(), old_len, k, j, fill, marker, small); + kani::cover(small && count == 0, "append empty source"); + kani::cover(small && old_len == 0 && count > 0, "append into empty vector"); +} + +fn verify_append() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let src_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in_up::(MAX_ALLOCATION_BYTES / 2, fill, marker, Global); + let (mut other, s) = any_source_vec::(src_tag); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let other_ptr = other.as_ptr(); + let other_cap = other.capacity(); + let count = other.len(); + // Only the ZST length sum can overflow `usize` (covered by a should_panic harness). + kani::assume(old_len.checked_add(count).is_some()); + let small = witness_ok::(old_cap) && witness_ok::(other_cap); + + reset_drops(); + v.append(&mut other); + + assert!(drops() == 0); + assert!(other.len() == 0); + assert!(other.capacity() == other_cap); + assert!(other.as_ptr() == other_ptr); + check_appended(&v, old_ptr, old_len, old_cap, count, k, j, fill, marker, s, src_tag, small); + + release_vec_buffer(other); + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_u8() { + verify_append::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_overaligned() { + verify_append::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_append_zst() { + verify_append::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_drop_tracker() { + verify_append::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_nonzero() { + verify_append::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_padded_niche() { + verify_append::(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_append_zst_capacity_overflow() { + let (mut v, _, _) = any_vec_in::<(), Global>(MAX_ALLOCATION_BYTES, 1, 1, Global); + let (mut other, _, _) = any_vec_in::<(), Global>(MAX_ALLOCATION_BYTES, 1, 1, Global); + kani::assume(v.len().checked_add(other.len()).is_none()); + kani::cover(v.len() == usize::MAX && other.len() == 1, "append one past ZST length limit"); + v.append(&mut other); +} + +fn verify_append_elements() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let src_tag: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill && b != marker); + let (mut v, k, j) = any_vec_in_up::(MAX_ALLOCATION_BYTES / 2, fill, marker, Global); + let (other, s) = any_source_vec::(src_tag); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let count = other.len(); + kani::assume(old_len.checked_add(count).is_some()); + let small = witness_ok::(old_cap) && witness_ok::(other.capacity()); + + reset_drops(); + // `other`'s elements are bitwise-moved; its buffer is released below + // without dropping them. + unsafe { v.append_elements(other.as_slice() as *const [T]) }; + + assert!(drops() == 0); + assert!(other.len() == count); + check_appended(&v, old_ptr, old_len, old_cap, count, k, j, fill, marker, s, src_tag, small); + + let (optr, _, ocap, alloc) = other.into_raw_parts_with_allocator(); + if !T::IS_ZST && ocap > 0 { + let layout = Layout::array::(ocap).unwrap(); + unsafe { alloc.deallocate(NonNull::new_unchecked(optr).cast::(), layout) }; + } + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_elements_u8() { + verify_append_elements::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_elements_overaligned() { + verify_append_elements::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_append_elements_zst() { + verify_append_elements::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_elements_drop_tracker() { + verify_append_elements::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_append_elements_nonzero() { + verify_append_elements::>(); +} + +// ============================================================================ +// 22. Vec::into_boxed_slice +// ============================================================================ + +/// Shrinking counterpart of `model_growing_realloc`: checks the old block is +/// exactly `old_size` bytes and aligned, then uses CBMC's C `realloc`. +unsafe fn model_shrinking_realloc( + old: NonNull, + old_size: usize, + align: core::mem::Alignment, + new_size: usize, +) -> *mut u8 { + unsafe extern "C" { + fn realloc(ptr: *mut u8, new_size: usize) -> *mut u8; + } + assert!(0 < new_size && new_size < old_size); + assert!(Layout::from_size_align(old_size, align.as_usize()).is_ok()); + assert!(Layout::from_size_align(new_size, align.as_usize()).is_ok()); + assert!(old.as_ptr().addr().is_multiple_of(align.as_usize())); + assert!(kani::mem::is_inbounds(ptr::slice_from_raw_parts(old.as_ptr(), old_size))); + assert!(!kani::mem::is_inbounds(ptr::slice_from_raw_parts(old.as_ptr(), old_size + 1))); + let new_ptr = unsafe { realloc(old.as_ptr(), new_size) }; + assert!(new_ptr.is_null() || new_ptr.addr().is_multiple_of(align.as_usize())); + new_ptr +} + +fn verify_into_boxed_slice() { + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = any_vec_in_up::(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let deep = deep_min::(); + + reset_drops(); + let b = v.into_boxed_slice(); + + assert!(drops() == 0); + assert!(b.len() == len); + let (raw, alloc) = Box::into_raw_with_allocator(b); + let data = raw as *mut T; + assert!(data.is_aligned()); + assert!(!(T::IS_ZST || len == old_cap) || data as *const T == old_ptr); + let box_bounds_ok = T::IS_ZST || len == 0 || { + let bytes = len * mem::size_of::(); + kani::mem::is_inbounds(ptr::slice_from_raw_parts(data as *const u8, bytes)) + && !kani::mem::is_inbounds(ptr::slice_from_raw_parts(data as *const u8, bytes + 1)) + }; + assert!(box_bounds_ok); + check_elements(data as *const T, len, k, j, fill, marker, small); + kani::cover(small && len == 0 && old_cap > 0, "into_boxed_slice frees an empty buffer"); + kani::cover(small && len > 0 && len < old_cap, "into_boxed_slice shrinks in place"); + kani::cover(small && len == old_cap && len > 0, "into_boxed_slice keeps a full buffer"); + kani::cover(small && len > deep && len < old_cap, "into_boxed_slice shrinks a deep buffer"); + + if !T::IS_ZST && len > 0 { + let layout = Layout::array::(len).unwrap(); + unsafe { alloc.deallocate(NonNull::new_unchecked(data).cast::(), layout) }; + } +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_shrinking_realloc)] +fn check_into_boxed_slice_u8() { + verify_into_boxed_slice::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_shrinking_realloc)] +fn check_into_boxed_slice_overaligned() { + verify_into_boxed_slice::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_boxed_slice_zst() { + verify_into_boxed_slice::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_shrinking_realloc)] +fn check_into_boxed_slice_drop_tracker() { + verify_into_boxed_slice::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_shrinking_realloc)] +fn check_into_boxed_slice_nonzero() { + verify_into_boxed_slice::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_shrinking_realloc)] +fn check_into_boxed_slice_padded_niche() { + verify_into_boxed_slice::(); +} + +// ============================================================================ +// 23. Vec::into_flattened +// ============================================================================ + +/// Arrays of length 3 built and observed element-wise (no loops), forwarding +/// `T`'s padding and bulk-initialization validity rules. +impl Elem for [T; 3] { + const HAS_PADDING: bool = T::HAS_PADDING; + fn bulk_init_byte(fill: u8) -> u8 { + T::bulk_init_byte(fill) + } + fn from_tag(b: u8) -> Self { + [T::from_tag(b), T::from_tag(b), T::from_tag(b)] + } + fn tag(&self) -> u8 { + self[0].tag() + } + fn when_non_zst(f: impl FnOnce()) { + T::when_non_zst(f); + } + fn when_zst(f: impl FnOnce()) { + T::when_zst(f); + } + fn when_needs_drop(f: impl FnOnce()) { + T::when_needs_drop(f); + } +} + +fn verify_into_flattened() { + const N: usize = 3; + let fill = any_tag(); + let marker: u8 = kani::any_where(|&b: &u8| b != 0 && b != fill); + let (v, k, j) = any_vec_in_up::<[T; N], Global>(MAX_ALLOCATION_BYTES, fill, marker, Global); + let old_ptr = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + // Only ZST `len * N` can overflow (covered by a should_panic harness). + kani::assume(len.checked_mul(N).is_some()); + let small = witness_ok::<[T; N]>(cap); + let sub: usize = kani::any_where(|&i: &usize| i < N); + + reset_drops(); + let flat = v.into_flattened(); + + assert!(drops() == 0); + assert!(flat.len() == len * N); + assert!(flat.as_ptr() == old_ptr as *const T); + if T::IS_ZST { + assert!(flat.capacity() == usize::MAX); + } else { + assert!(flat.capacity() == cap * N); + if len > 0 { + assert!(unsafe { (&*flat.as_ptr().add(k * N + sub)).tag() } == marker); + if j < len && j != k { + assert!(unsafe { (&*flat.as_ptr().add(j * N + sub)).tag() } == fill); + T::when_non_zst(|| { + kani::cover(small && j > 4096, "deep flattened element checked"); + }); + } + } + } + kani::cover( + small && if T::IS_ZST { len == usize::MAX / N } else { cap == 0 }, + "zero capacity (or ZST max non-overflowing length)", + ); + kani::cover(small && len == 0 && cap > 0, "empty with nonzero capacity"); + kani::cover(small && len > 0 && len < cap, "partially filled"); + T::when_non_zst(|| { + kani::cover(small && len == cap && cap > 0, "full buffer"); + }); + kani::cover(small && len > 4096, "deep length > 4096"); + kani::cover(small && k > 4096 && sub == N - 1, "last sub-element of a deep array"); + + release_vec_buffer(flat); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_u8() { + verify_into_flattened::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_overaligned() { + verify_into_flattened::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_zst() { + verify_into_flattened::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_drop_tracker() { + verify_into_flattened::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_nonzero() { + verify_into_flattened::>(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_into_flattened_zst_overflow() { + let (v, _, _) = any_vec_in::<[(); 3], Global>(MAX_ALLOCATION_BYTES, 1, 1, Global); + kani::assume(v.len().checked_mul(3).is_none()); + kani::cover(v.len() == usize::MAX / 3 + 1, "smallest overflowing ZST length"); + let _ = v.into_flattened(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_flattened_n0_u8() { + let len: usize = kani::any(); + let mut v: Vec<[u8; 0]> = Vec::new(); + v.len = len; + assert!(v.capacity() == usize::MAX); + + let flat: Vec = v.into_flattened(); + assert!(flat.len() == 0); + assert!(flat.capacity() == 0); + assert!(flat.as_ptr().is_aligned()); + kani::cover(len == 0, "into_flattened N == 0 empty"); + kani::cover(len > 4096, "into_flattened N == 0 deep length"); + kani::cover(len == usize::MAX, "into_flattened N == 0 max ZST length"); +} + +// ============================================================================ +// Vec iterator construction and destruction +// ============================================================================ + +/// Builds a `Vec` with symbolic capacity up to `max_bytes` bytes using +/// `any_up_to` (optimal for MiniSat harnesses). Initializes 100% of `0..cap` +/// (hence every slot in `0..len` for arbitrary symbolic `len`) via +/// `__CPROVER_array_set` with `T::bulk_init_byte(fill)` so every element holds +/// a valid Rust `T` value before `Vec::from_parts_in`; then writes a typed +/// witness value at `index` so padded types still carry fresh uninitialized +/// padding bytes at the observed witness slot. +fn any_initialized_vec(alloc: A) -> (Vec, usize, u8) { + any_initialized_vec_up_to(MAX_ALLOCATION_BYTES, alloc) +} + +fn any_initialized_vec_with_fill_up_to( + max_bytes: usize, + alloc: A, +) -> (Vec, usize, u8, u8) { + let cap = if T::IS_ZST { usize::MAX } else { any_up_to(max_bytes / mem::size_of::()) }; + let len = any_up_to(cap); + let fill = any_tag(); + let marker = kani::any_where(|&b: &u8| b != 0 && b != fill); + let ptr = allocate_vec_buffer::(cap, T::bulk_init_byte(fill), &alloc); + let index = any_up_to(len.saturating_sub(1)); + if !T::IS_ZST && len != 0 { + // SAFETY: `index < len <= cap`. Typed `ptr::write` refreshes + // uninitialized padding bytes in `T` at the witness slot. + unsafe { ptr.as_ptr().add(index).write(T::from_tag(marker)) }; + } + // SAFETY: The allocation came from `alloc` and its layout matches `cap`. + (unsafe { Vec::from_parts_in(ptr, len, cap, alloc) }, index, fill, marker) +} + +fn any_initialized_vec_up_to( + max_bytes: usize, + alloc: A, +) -> (Vec, usize, u8) { + let (v, index, _fill, marker) = any_initialized_vec_with_fill_up_to::(max_bytes, alloc); + (v, index, marker) +} + +fn verify_into_iter(alloc: A, check_alloc: impl FnOnce(&A)) { + let (v, index, marker) = any_initialized_vec::(alloc); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + + reset_drops(); + reset_alloc_drops(); + let iter = v.into_iter(); + + assert!(drops() == 0); + assert!(alloc_drops() == 0); + assert!(iter.buf.as_ptr().cast_const() == base); + assert!(iter.ptr == iter.buf); + assert!(iter.cap == cap); + assert!(iter.len() == len); + assert!( + iter.end + == if T::IS_ZST { + ptr::without_provenance(base.addr().wrapping_add(len)) + } else { + // SAFETY: len <= cap. + unsafe { base.add(len) } + } + ); + check_alloc(iter.allocator()); + let remaining = iter.as_slice(); + assert!(remaining.len() == len); + assert!(remaining.as_ptr() == base); + if len != 0 { + assert!(remaining[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + cover_vec_regimes::(len, cap, small); + kani::cover(small && index > 4096, "deep element available in consuming iterator"); + T::when_zst(|| { + kani::cover( + base != NonNull::::dangling().as_ptr(), + "into_iter accepts non-canonical aligned ZST pointer", + ); + }); + + if mem::needs_drop::() { + // Exercise the constructor independently of IntoIter's slice drop glue. + let iter = mem::ManuallyDrop::new(iter); + if !T::IS_ZST && cap != 0 { + let layout = Layout::array::(cap).unwrap(); + // SAFETY: This iterator owns the original allocation with this layout. + unsafe { iter.allocator().deallocate(iter.buf.cast::(), layout) }; + } + } +} + +/// CBMC restricts pointer offsets to the bits outside the object ID. A ZST +/// Vec may carry any aligned non-null pointer (canonical dangling or +/// non-canonical from `from_raw_parts`); integer wrapping and reconstructing an +/// allocation-free pointer preserve Rust's ZST `wrapping_byte_add` semantics. +fn wrapping_byte_add_zst(base: *mut T, offset: usize) -> *mut T { + assert!(T::IS_ZST); + assert!(!base.is_null() && base.is_aligned()); + ptr::without_provenance_mut(base.addr().wrapping_add(offset)) +} + +/// Pick any valid normalized start and end, then independently choose the +/// bound variants that can encode those endpoints. +fn any_valid_bounds(len: usize) -> (usize, usize, (Bound, Bound)) { + let start = any_up_to(len); + let end = kani::any_where(|&end: &usize| start <= end && end <= len); + let start_bound = if start == 0 && kani::any() { + Bound::Unbounded + } else if start != 0 && kani::any() { + Bound::Excluded(start - 1) + } else { + Bound::Included(start) + }; + let end_bound = if end == len && kani::any() { + Bound::Unbounded + } else if end != 0 && kani::any() { + Bound::Included(end - 1) + } else { + Bound::Excluded(end) + }; + (start, end, (start_bound, end_bound)) +} + +fn cover_range( + len: usize, + start: usize, + end: usize, + bounds: (Bound, Bound), + small: bool, + deep: usize, +) { + kani::cover(small && len == 0, "empty input"); + kani::cover(small && start == end && len != 0, "empty range in nonempty input"); + kani::cover(small && start == len && len != 0, "empty range at the end"); + kani::cover(small && start == 0 && 0 < end && end < len, "nonempty prefix"); + kani::cover(small && 0 < start && start < end && end == len, "nonempty suffix"); + kani::cover(small && deep < start && start < end && end < len, "deep interior range"); + kani::cover(small && start == 0 && 0 < end && end == len, "entire nonempty input"); + kani::cover(small && matches!(bounds, (Bound::Unbounded, _)), "unbounded start"); + kani::cover(small && matches!(bounds, (_, Bound::Unbounded)), "unbounded end"); + kani::cover(small && matches!(bounds, (Bound::Included(_), _)), "included start"); + kani::cover(small && matches!(bounds, (_, Bound::Included(_))), "included end"); + kani::cover(small && matches!(bounds, (Bound::Excluded(_), _)), "excluded start"); + kani::cover(small && matches!(bounds, (_, Bound::Excluded(_))), "excluded end"); +} + +fn any_invalid_bounds(len: usize, small: bool) -> (Bound, Bound) { + let case = kani::any_where(|&x: &u8| x < 4); + kani::cover(small && case == 0, "end exceeds vector length"); + kani::cover(small && case == 1, "start exceeds end"); + kani::cover(small && case == 2, "included end would overflow"); + kani::cover(small && case == 3, "excluded start would overflow"); + kani::cover(small && len > 4096, "invalid range on a deep vector"); + match case { + 0 => (Bound::Unbounded, Bound::Excluded(len + 1)), + 1 => (Bound::Included(len + 1), Bound::Unbounded), + 2 => (Bound::Unbounded, Bound::Included(usize::MAX)), + _ => (Bound::Excluded(usize::MAX), Bound::Unbounded), + } +} + +fn verify_drain() { + let (mut v, index, marker) = any_initialized_vec::(Global); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + let (start, end, bounds) = any_valid_bounds(len); + let owner = &raw mut v; + + reset_drops(); + let drain = v.drain(bounds); + + assert!(drain.vec.as_ptr() == owner); + assert!(drain.tail_start == end); + assert!(drain.tail_len == len - end); + let drained = drain.as_slice(); + assert!(drained.len() == end - start); + // SAFETY: start <= len <= cap. + assert!(drained.as_ptr() == unsafe { base.add(start) }); + if start <= index && index < end { + assert!(drained[index - start].tag() == if T::IS_ZST { 0 } else { marker }); + } + cover_range(len, start, end, bounds, small, 4096); + kani::cover(small && start <= index && index < end && index > 4096, "deep drained element"); + + // Leaking a Drain must leave only the untouched prefix accessible. + mem::forget(drain); + assert!(v.len() == start); + assert!(v.capacity() == cap); + assert!(v.as_ptr() == base); + assert!(drops() == 0); + if index < start { + assert!(v[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + release_vec_buffer(v); +} + +fn verify_extract_if() { + let (mut v, index, marker) = any_initialized_vec::(Global); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + let (start, end, bounds) = any_valid_bounds(len); + if !T::IS_ZST && T::HAS_PADDING && start < end && start != index { + let start_tag = any_tag(); + // SAFETY: `start < end <= len <= cap`. + unsafe { v.as_mut_ptr().add(start).write(T::from_tag(start_tag)) }; + } + // SAFETY: start <= len <= cap, so this is in bounds or one past. + let first_ptr = unsafe { base.add(start) }; + + reset_drops(); + let mut calls = 0; + let mut extract = v.extract_if(bounds, |value| { + calls += 1; + assert!(ptr::eq(value, first_ptr)); + true + }); + assert!(extract.size_hint() == (0, Some(end - start))); + cover_range(len, start, end, bounds, small, 4096); + + if kani::any() { + // Drop an untouched iterator. The predicate must stay lazy, and the + // original allocation and prefix must be restored. + drop(extract); + assert!(calls == 0); + assert!(drops() == 0); + assert!(v.len() == len); + if index < len { + assert!(v[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + kani::cover(small && start > 4096, "drop an untouched deep extraction"); + } else { + // With an accepting predicate, a single next() takes at most one + // step. This observes the starting cursor without consuming the range. + let first = extract.next(); + assert!(first.is_some() == (start < end)); + if let Some(ref item) = first { + if !T::IS_ZST && start == index { + assert!(item.tag() == marker); + } + } + mem::forget(extract); + assert!(calls == usize::from(start < end)); + assert!(drops() == 0); + assert!(v.is_empty()); + drop(first); + assert!(drops() == usize::from(start < end && mem::needs_drop::())); + kani::cover( + small && start > 4096 && start < end, + "first element extracted at a deep index", + ); + kani::cover(small && start == end, "next on an empty extraction"); + } + assert!(v.capacity() == cap); + assert!(v.as_ptr() == base); + release_vec_buffer(v); +} + +fn verify_drop() { + let alloc = DropAlloc(nonzero_u8(any_tag())); + let (v, _, _) = any_initialized_vec::(alloc); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + cover_vec_regimes::(len, cap, witness_ok::(cap)); + + reset_drop_trace(); + reset_alloc_drops(); + drop(v); + + if mem::needs_drop::() { + assert!(drops() == len); + assert!(unsafe { LAST_DROP_LEN } == len); + assert!(unsafe { LAST_DROP_PTR } == base.addr()); + } else { + assert!(drops() == 0); + } + assert!(alloc_drops() == 1); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_u8() { + verify_into_iter::(Global, |_| {}); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_overaligned() { + verify_into_iter::(Global, |_| {}); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(<*mut ()>::wrapping_byte_add, wrapping_byte_add_zst)] +fn check_into_iter_zst() { + verify_into_iter::<(), _>(Global, |_| {}); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(<*mut AlignedZst>::wrapping_byte_add, wrapping_byte_add_zst)] +fn check_into_iter_aligned_zst() { + verify_into_iter::(Global, |_| {}); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_drop_tracker() { + verify_into_iter::(Global, |_| {}); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_nonzero() { + verify_into_iter::, _>(Global, |_| {}); +} + +fn verify_ref_into_iter() { + let (v, index, marker) = any_initialized_vec::(Global); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + + let iter = (&v).into_iter(); + let slice = iter.as_slice(); + assert!(slice.len() == len); + assert!(slice.as_ptr() == base); + if len != 0 { + assert!(slice[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + cover_vec_regimes::(len, cap, small); + kani::cover(small && index > 4096, "deep element available in shared ref iterator"); + release_vec_buffer(v); +} + +fn verify_mut_into_iter() { + let (mut v, index, marker) = any_initialized_vec::(Global); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + let new_tag = any_tag(); + + { + let mut iter = (&mut v).into_iter(); + let slice = iter.as_mut_slice(); + assert!(slice.len() == len); + assert!(slice.as_ptr() == base); + if len != 0 { + assert!(slice[index].tag() == if T::IS_ZST { 0 } else { marker }); + slice[index] = T::from_tag(new_tag); + } + } + if len != 0 { + assert!(v[index].tag() == if T::IS_ZST { 0 } else { new_tag }); + } + cover_vec_regimes::(len, cap, small); + kani::cover(small && index > 4096, "deep element mutated via mut ref iterator"); + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_ref_into_iter_u8() { + verify_ref_into_iter::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_ref_into_iter_overaligned() { + verify_ref_into_iter::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_ref_into_iter_zst() { + verify_ref_into_iter::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_mut_into_iter_u8() { + verify_mut_into_iter::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_mut_into_iter_overaligned() { + verify_mut_into_iter::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_mut_into_iter_zst() { + verify_mut_into_iter::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drain_u8() { + verify_drain::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drain_overaligned() { + verify_drain::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drain_zst() { + verify_drain::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drain_drop_tracker() { + verify_drain::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drain_nonzero() { + verify_drain::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_u8() { + verify_extract_if::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_overaligned() { + verify_extract_if::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_zst() { + verify_extract_if::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_drop_tracker() { + verify_extract_if::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extract_if_nonzero() { + verify_extract_if::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_u8() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_overaligned() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_zst() { + verify_drop::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(ptr::drop_in_place, drop_tracker_slice_stub)] +fn check_drop_drop_tracker() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_nonzero() { + verify_drop::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_large() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_aligned_zst() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_drop_padded_niche() { + verify_drop::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_into_iter_drop_alloc() { + let id = nonzero_u8(any_tag()); + verify_into_iter::(DropAlloc(id), |alloc| assert!(alloc.0 == id)); + assert!(alloc_drops() == 1); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::should_panic] +fn check_drain_invalid_range() { + let (mut v, _, _) = any_initialized_vec::(Global); + let bounds = any_invalid_bounds(v.len(), witness_ok::(v.capacity())); + mem::forget(v.drain(bounds)); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::should_panic] +fn check_extract_if_invalid_range() { + let (mut v, _, _) = any_initialized_vec::(Global); + let bounds = any_invalid_bounds(v.len(), witness_ok::(v.capacity())); + mem::forget(v.extract_if(bounds, |_| true)); +} + +// ============================================================================ +// 28. TryFrom> for [T; N] (Vec::try_from) +// ============================================================================ + +fn verify_try_from() { + let alloc_id = nonzero_u8(any_tag()); + let (mut v, index, marker) = any_initialized_vec::(DropAlloc(alloc_id)); + let base = v.as_ptr(); + let len = v.len(); + let cap = v.capacity(); + let small = witness_ok::(cap); + if !T::IS_ZST && T::HAS_PADDING && len == N { + let fill = any_tag(); + let mut i = 0; + while i < N { + if i != index { + // SAFETY: `i < N == len <= cap`. + unsafe { v.as_mut_ptr().add(i).write(T::from_tag(fill)) }; + } + i += 1; + } + } + + reset_drops(); + reset_alloc_drops(); + let res: Result<[T; N], Vec> = <[T; N]>::try_from(v); + + match res { + Ok(array) => { + assert!(len == N); + assert!(drops() == 0); + assert!(alloc_drops() == 1); + if N > 0 { + assert!(array[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + kani::cover( + small && if T::IS_ZST { len == N } else { len == N && cap == N }, + "try_from Ok with exact capacity (or ZST)", + ); + kani::cover(small && len == N && cap > N, "try_from Ok with spare capacity"); + kani::cover(small && len == N && cap > 4096, "try_from Ok with deep spare capacity"); + drop(array); + assert!(drops() == if mem::needs_drop::() { N } else { 0 }); + } + Err(returned) => { + assert!(len != N); + assert!(drops() == 0); + assert!(alloc_drops() == 0); + assert!(returned.len() == len); + assert!(returned.capacity() == cap); + assert!(returned.as_ptr() == base); + assert!(returned.allocator().0 == alloc_id); + if len > 0 { + assert!(returned[index].tag() == if T::IS_ZST { 0 } else { marker }); + } + kani::cover( + small && if N > 0 { len < N } else { len == cap && cap > 0 }, + "try_from Err shorter than N (or full buffer for N == 0)", + ); + kani::cover(small && len > N, "try_from Err longer than N"); + kani::cover(small && len > 4096 && index > 4096, "try_from Err deep length > 4096"); + release_vec_buffer(returned); + assert!(alloc_drops() == 1); + } + } +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_u8() { + verify_try_from::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_overaligned() { + verify_try_from::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_zst() { + verify_try_from::<(), 3>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_drop_tracker() { + verify_try_from::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_nonzero() { + verify_try_from::, 3>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_try_from_empty_drop_tracker() { + verify_try_from::(); +} + +// ============================================================================ +// 29. Vec::spec_extend_from_within & 30. Vec::extend_from_within +// ============================================================================ + +/// Harness-local state shared with `CloneZipFold::fold` to express the +/// unbounded loop invariant over `default unsafe fn spec_extend_from_within`'s +/// `iter::zip(to_clone, spare).map(...).for_each(...)` without modifying `core`. +/// Initialized to distinct non-zero sentinels to avoid `kani#5088`. +static mut EFW_LEN_PTR: *mut usize = ptr::without_provenance_mut(0x10); +static mut EFW_DST: *mut MaybeUninit = ptr::without_provenance_mut(0x20); +static mut EFW_DST_LEN: usize = 0x5A5A_5A5A_5A5A_5A60; +static mut EFW_TARGET: usize = 0x5A5A_5A5A_5A5A_5A61; +static mut EFW_EXPECTED_TAG: u8 = 0x5A; +static mut EFW_TARGET_VERIFIED: bool = true; + +// Record the actual spare-slice inputs passed to `iter::zip` while forwarding +// directly to the shipped `Zip` constructor. +fn capture_clone_zip(src: A, mut dst: B) -> iter::Zip +where + A: IntoIterator, + B: IntoIterator + AsMut<[MaybeUninit]>, +{ + let spare = dst.as_mut(); + unsafe { + EFW_DST = spare.as_mut_ptr(); + EFW_DST_LEN = spare.len(); + } + src.into_iter().zip(dst) +} + +unsafe fn verify_target_slot_written( + i: usize, + target: usize, + dst_target: *const T, + expected_tag: u8, + verified: &mut bool, +) { + if i == target { + let ok = T::IS_ZST || unsafe { (&*dst_target).tag() } == expected_tag; + assert!(ok); + *verified = true; + } +} + +// Mirrors `core::iter::adapters::zip::ZipImpl::fold` for `TrustedRandomAccessNoCoerce` +// (`for i in 0..len { accum = f(accum, zip.__iterator_get_unchecked(i)); }`) with +// a loop contract attached, executing the shipped getter and both callbacks. +struct CloneZipFold(core::marker::PhantomData<(A, B)>); + +impl CloneZipFold +where + A: Iterator + iter::TrustedRandomAccessNoCoerce, + B: Iterator + iter::TrustedRandomAccessNoCoerce, +{ + fn fold(mut zip: iter::Zip, init: Acc, mut f: F) -> Acc + where + F: FnMut(Acc, (A::Item, B::Item)) -> Acc, + { + let len = zip.size_hint().0; + let len_ptr = unsafe { EFW_LEN_PTR }; + let old_len = unsafe { *len_ptr }; + let dst_base = unsafe { EFW_DST }; + let target = unsafe { EFW_TARGET }; + let expected_tag = unsafe { EFW_EXPECTED_TAG }; + assert!(len <= unsafe { EFW_DST_LEN }); + let dst_slice = ptr::slice_from_raw_parts_mut(dst_base, len); + let dst_target: *const DropTracker = if target < len { + unsafe { dst_base.add(target).cast::() } + } else { + ptr::dangling() + }; + + let mut accum = init; + let mut i: usize = 0; + let mut target_verified = false; + #[kani::loop_invariant( + i <= len + && unsafe { *len_ptr == old_len + i } + && (target_verified == (len > 0 && target < i)) + )] + #[kani::loop_modifies(&i, &accum, &target_verified, len_ptr, dst_slice)] + while i < len { + accum = f(accum, unsafe { zip.__iterator_get_unchecked(i) }); + unsafe { + verify_target_slot_written( + i, + target, + dst_target, + expected_tag, + &mut target_verified, + ); + } + i += 1; + } + unsafe { EFW_TARGET_VERIFIED = len == 0 || target_verified }; + accum + } +} + +fn verify_spec_extend_from_within() { + let (mut v, index, fill, marker) = + any_initialized_vec_with_fill_up_to::(MAX_ALLOCATION_BYTES, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let deep = deep_min::(); + + let start = any_up_to(old_len); + let end = + kani::any_where(|&e: &usize| start <= e && e <= old_len && e - start <= old_cap - old_len); + let count = end - start; + let target = any_up_to(count.saturating_sub(1)); + let expected_new_tag = if !T::IS_ZST && count > 0 { + // Poison the arbitrary symbolic destination spare slot with genuine + // uninitialized bytes before publishing it through `spec_extend_from_within`. + unsafe { + v.as_mut_ptr() + .add(old_len + target) + .cast::>() + .write(MaybeUninit::uninit()); + } + if start + target == index { marker } else { T::bulk_init_byte(fill) } + } else { + 0 + }; + + if mem::needs_drop::() { + unsafe { + EFW_LEN_PTR = &raw mut v.len; + EFW_TARGET = target; + EFW_EXPECTED_TAG = expected_new_tag; + EFW_TARGET_VERIFIED = false; + } + } + reset_drops(); + + // SAFETY: `start <= end <= old_len` and `old_cap - old_len >= end - start`. + unsafe { v.spec_extend_from_within(start..end) }; + + assert!(drops() == 0); + assert!(v.len() == old_len + count); + assert!(v.capacity() == old_cap); + assert!(v.as_ptr() == old_ptr); + T::when_needs_drop(|| { + assert!(unsafe { EFW_TARGET_VERIFIED }); + kani::cover( + small && count > deep && target > deep, + "spec_extend_from_within newly published deep slot verified", + ); + }); + + kani::cover(small && old_len == 0 && count == 0, "spec_extend_from_within empty vec"); + kani::cover(small && old_len > 0 && count == 0, "spec_extend_from_within empty range"); + kani::cover( + small && count > 0 && count == old_cap - old_len, + "spec_extend_from_within fills exact spare capacity", + ); + kani::cover( + small && count > 0 && count < old_cap - old_len, + "spec_extend_from_within leaves spare capacity", + ); + kani::cover( + small && start == 0 && end == old_len && count > 0, + "spec_extend_from_within entire vec", + ); + kani::cover( + small && start > deep && count > 0 && end < old_len, + "spec_extend_from_within deep interior range", + ); + kani::cover( + small && start <= index && index < end && index > deep, + "spec_extend_from_within deep copied marker", + ); + + release_vec_buffer(v); +} + +#[kani::proof_for_contract( as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_u8() { + verify_spec_extend_from_within::(); +} + +#[kani::proof_for_contract( as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_overaligned() { + verify_spec_extend_from_within::(); +} + +#[kani::proof_for_contract( as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_zst() { + verify_spec_extend_from_within::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(iter::zip, capture_clone_zip)] +#[kani::stub( + , slice::IterMut<'_, MaybeUninit>> as core::iter::Iterator>::fold, + CloneZipFold::, slice::IterMut<'_, MaybeUninit>>::fold +)] +fn check_spec_extend_from_within_drop_tracker() { + verify_spec_extend_from_within::(); +} + +#[kani::proof_for_contract(> as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_nonzero() { + verify_spec_extend_from_within::>(); +} + +#[kani::proof_for_contract( as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_padded_niche() { + verify_spec_extend_from_within::(); +} + +#[kani::proof_for_contract( as ExtendFromWithinSpec>::spec_extend_from_within)] +#[kani::solver(minisat)] +fn check_spec_extend_from_within_large() { + verify_spec_extend_from_within::(); +} + +fn verify_extend_from_within() { + // Initial buffer <= MAX_ALLOCATION_BYTES / 2 so reserving up to `old_len` + // (doubling to at most `2 * old_cap`) stays within `MAX_ALLOCATION_BYTES`. + let (mut v, index, fill, marker) = + any_initialized_vec_with_fill_up_to::(MAX_ALLOCATION_BYTES / 2, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let deep = deep_min::(); + let (start, end, bounds) = any_valid_bounds(old_len); + let count = end - start; + // ZST capacity overflow is verified by `check_extend_from_within_zst_capacity_overflow`. + kani::assume(old_len.checked_add(count).is_some()); + let target = any_up_to(count.saturating_sub(1)); + let expected_new_tag = if !T::IS_ZST && count > 0 { + if old_len + target < old_cap { + unsafe { + v.as_mut_ptr() + .add(old_len + target) + .cast::>() + .write(MaybeUninit::uninit()); + } + } + if start + target == index { marker } else { T::bulk_init_byte(fill) } + } else { + 0 + }; + + reset_drops(); + v.extend_from_within(bounds); + + assert!(drops() == 0); + assert!(v.len() == old_len + count); + assert!(v.capacity() >= old_len + count); + let grow_ok = if count <= old_cap - old_len { + v.capacity() == old_cap && v.as_ptr() == old_ptr + } else { + v.capacity() > old_cap + }; + assert!(grow_ok); + + cover_range(old_len, start, end, bounds, small, deep); + kani::cover( + small && count <= old_cap - old_len && count > 0 && old_len > deep, + "extend_from_within in-place deep spare capacity", + ); + T::when_non_zst(|| { + kani::cover( + small && count > old_cap - old_len && old_len > deep && count > 0, + "extend_from_within grows deep buffer", + ); + }); + T::when_zst(|| { + kani::cover(small && old_len > 4096 && count > 4096, "extend_from_within ZST deep range"); + }); + kani::cover( + small && start <= index && index < end && index > deep, + "extend_from_within deep copied marker", + ); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_from_within_u8() { + verify_extend_from_within::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_from_within_overaligned() { + verify_extend_from_within::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extend_from_within_zst() { + verify_extend_from_within::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_from_within_large() { + verify_extend_from_within::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(iter::zip, capture_clone_zip)] +#[kani::stub( + , slice::IterMut<'_, MaybeUninit>> as core::iter::Iterator>::fold, + CloneZipFold::, slice::IterMut<'_, MaybeUninit>>::fold +)] +fn check_extend_from_within_drop_tracker() { + let (mut v, index, fill, marker) = + any_initialized_vec_with_fill_up_to::(MAX_ALLOCATION_BYTES / 2, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let small = witness_ok::(old_cap); + let (start, end, bounds) = any_valid_bounds(old_len); + let count = end - start; + let target = any_up_to(count.saturating_sub(1)); + let expected_new_tag = if count > 0 { + if old_len + target < old_cap { + unsafe { + v.as_mut_ptr() + .add(old_len + target) + .cast::>() + .write(MaybeUninit::uninit()); + } + } + if start + target == index { marker } else { fill } + } else { + 0 + }; + + unsafe { + EFW_LEN_PTR = &raw mut v.len; + EFW_TARGET = target; + EFW_EXPECTED_TAG = expected_new_tag; + EFW_TARGET_VERIFIED = false; + } + reset_drops(); + + v.extend_from_within(bounds); + + assert!(drops() == 0); + assert!(v.len() == old_len + count); + assert!(v.capacity() >= old_len + count); + let grow_ok = if count <= old_cap - old_len { + v.capacity() == old_cap && v.as_ptr() == old_ptr + } else { + v.capacity() > old_cap + }; + assert!(grow_ok); + assert!(unsafe { EFW_TARGET_VERIFIED }); + cover_range(old_len, start, end, bounds, small, 4096); + kani::cover( + small && count > 4096 && target > 4096, + "extend_from_within drop_tracker newly published deep slot verified", + ); + kani::cover( + small && count <= old_cap - old_len && count > 0 && old_len > 4096, + "extend_from_within drop_tracker in-place deep spare", + ); + kani::cover( + small && count > old_cap - old_len && old_len > 4096 && count > 0, + "extend_from_within drop_tracker grows deep buffer", + ); + kani::cover( + small && start <= index && index < end && index > 4096, + "extend_from_within drop_tracker deep copied marker > 4096", + ); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_from_within_nonzero() { + verify_extend_from_within::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::should_panic] +fn check_extend_from_within_invalid_range() { + let (mut v, _, _) = any_initialized_vec::(Global); + let bounds = any_invalid_bounds(v.len(), witness_ok::(v.capacity())); + v.extend_from_within(bounds); +} + +#[kani::proof] +#[kani::should_panic] +fn check_extend_from_within_zst_capacity_overflow() { + let old_len = any_up_to(usize::MAX); + let mut v: Vec<()> = Vec::new(); + v.len = old_len; + let (start, end, bounds) = any_valid_bounds(old_len); + let count = end - start; + kani::assume(old_len.checked_add(count).is_none()); + kani::cover(old_len == usize::MAX && count == 1, "extend_from_within ZST +1 overflow"); + v.extend_from_within(bounds); +} + +// ============================================================================ +// 31. Vec::extend_with (TrivialClone specialization in Kani; default T: Clone +// polymorphic unbounded proof in VeriFast 26.10 against real alloc::vec::Vec) +// ============================================================================ + +fn verify_extend_with() { + let val_tag = any_tag(); + // Keep initial buffer and added count each <= MAX_ALLOCATION_BYTES / 2 so + // any grown allocation (max(2 * old_cap, old_len + n)) fits in CBMC's 2^51-1 bound. + let (mut v, index, marker) = + any_initialized_vec_up_to::(MAX_ALLOCATION_BYTES / 2, Global); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let n: usize = if T::IS_ZST { + any_up_to(usize::MAX - old_len) + } else { + any_up_to((MAX_ALLOCATION_BYTES / 2) / mem::size_of::()) + }; + let small = witness_ok::(old_cap) && witness_ok::(n); + let deep = deep_min::(); + // Poison an arbitrary symbolic spare slot with genuine uninitialized bytes + // before `extend_with` runs so spare capacity is not relied upon to be + // pre-initialized. + let target = any_up_to(n.saturating_sub(1)); + if !T::IS_ZST && n > 0 && old_len + target < old_cap { + unsafe { + v.as_mut_ptr() + .add(old_len + target) + .cast::>() + .write(MaybeUninit::uninit()); + } + } + + reset_drops(); + v.extend_with(n, T::from_tag(val_tag)); + + assert!(drops() == 0); + assert!(v.len() == old_len + n); + assert!(v.capacity() >= old_len + n); + let grow_ok = if n <= old_cap - old_len { + v.capacity() == old_cap && v.as_ptr() == old_ptr + } else { + v.capacity() > old_cap + }; + assert!(grow_ok); + let marker_ok = + T::IS_ZST || old_len == 0 || unsafe { (&*v.as_ptr().add(index)).tag() } == marker; + assert!(marker_ok); + + kani::cover(small && n == 0, "extend_with n == 0"); + kani::cover(small && n == 1, "extend_with n == 1"); + kani::cover( + small && n > 1 && n <= old_cap - old_len && old_len > 0, + "extend_with in-place spare capacity", + ); + kani::cover( + small && n > deep && n <= old_cap - old_len && old_len > deep, + "extend_with deep in-place", + ); + T::when_non_zst(|| { + kani::cover(small && old_cap == 0 && n > 0, "extend_with from empty buffer"); + kani::cover( + small && n > old_cap - old_len && old_len > deep && n > deep, + "extend_with grows deep buffer", + ); + }); + T::when_zst(|| { + kani::cover(small && old_len == 0 && n > 4096, "extend_with empty ZST"); + kani::cover( + small && old_len > 4096 && n == usize::MAX - old_len, + "extend_with ZST max fill", + ); + }); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_with_u8() { + verify_extend_with::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_with_overaligned() { + verify_extend_with::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extend_with_zst() { + verify_extend_with::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_with_nonzero() { + verify_extend_with::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +fn check_extend_with_padded_niche() { + verify_extend_with::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +fn check_extend_with_aligned_zst() { + verify_extend_with::(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_extend_with_zst_capacity_overflow() { + let old_len = any_up_to(usize::MAX); + let n: usize = kani::any(); + kani::assume(old_len.checked_add(n).is_none()); + let mut v: Vec<()> = Vec::new(); + v.len = old_len; + kani::cover(old_len == usize::MAX && n == 1, "extend_with ZST +1 overflow"); + v.extend_with(n, ()); +} + +// ============================================================================ +// 32. Vec::retain_mut & 33. Vec::dedup_by (incl. Vec::dedup_tail) +// ============================================================================ +// +// Verified unboundedly for arbitrary generic `T`, arbitrary stateful `FnMut`, +// and arbitrary `Drop` in `verifast-proofs/alloc/vec/mod.rs/` (checked by +// `verifast-proofs/check-verifast-proofs.sh` and +// `verifast-proofs/check-verifast-proofs-negative.sh`), eliminating all +// restrictive Kani `loop_modifies` annotations from `library/alloc/src/vec/mod.rs`. + +// ============================================================================ +// 34. Vec::extend_trusted +// ============================================================================ + +/// Harness-local tracking state for `extend_trusted`'s peeled-iteration +/// `SymbolicTrustedIter::for_each` loop contract. Distinct non-zero sentinels +/// prevent `kani#5088` static aliasing. +static mut ET_LOCAL_LEN_PTR: *mut usize = ptr::without_provenance_mut(0x30); +static mut ET_BUF_PTR: *mut u8 = ptr::without_provenance_mut(0x40); + +pub(super) unsafe fn record_extend_trusted_len_ptr(p: *mut usize) { + if unsafe { ET_LOCAL_LEN_PTR }.is_null() { + unsafe { ET_LOCAL_LEN_PTR = p }; + } +} + +/// Zero-sized allocator delegating to `Global` while recording the live buffer +/// pointer across `allocate` and `grow` so `SymbolicTrustedIter::for_each` +/// knows the exact post-`reserve` destination slice with full provenance. +#[derive(Clone, Copy)] +struct TrackPtrAlloc; + +unsafe impl Allocator for TrackPtrAlloc { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + let res = Global.allocate(layout)?; + unsafe { ET_BUF_PTR = res.as_ptr() as *mut u8 }; + Ok(res) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + unsafe { Global.deallocate(ptr, layout) } + } + + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + let res = unsafe { Global.grow(ptr, old_layout, new_layout) }?; + unsafe { ET_BUF_PTR = res.as_ptr() as *mut u8 }; + Ok(res) + } +} + +/// Unbounded symbolic `TrustedLen` iterator whose `for_each` peels iteration 0 +/// to capture the stack address of `SetLenOnDrop::local_len` inside the moved +/// closure and discharges the remaining `1..n` iterations via an unbounded +/// `#[kani::loop_invariant]` while executing the exact shipped `extend_trusted` +/// closure on every step. +struct SymbolicTrustedIter { + remaining: usize, + old_len: usize, + target: usize, + target_tag: u8, + _marker: core::marker::PhantomData, +} + +fn pick_iter_tag(i: usize, target: usize, target_tag: u8) -> u8 { + if i == target { target_tag } else { any_tag() } +} + +impl Iterator for SymbolicTrustedIter { + type Item = T; + + fn next(&mut self) -> Option { + if self.remaining == 0 { + None + } else { + self.remaining -= 1; + Some(T::from_tag(any_tag())) + } + } + + fn size_hint(&self) -> (usize, Option) { + (self.remaining, Some(self.remaining)) + } + + fn for_each(self, mut f: F) + where + F: FnMut(Self::Item), + { + let n = self.remaining; + if n == 0 { + return; + } + let target = self.target; + let target_tag = self.target_tag; + let first_tag = if target == 0 { target_tag } else { any_tag() }; + f(T::from_tag(first_tag)); + let len_ptr = unsafe { ET_LOCAL_LEN_PTR }; + assert!(!len_ptr.is_null()); + let old_len = self.old_len; + let dst_base = if T::IS_ZST { + NonNull::::dangling().as_ptr() + } else { + // SAFETY: `self.reserve(n)` guaranteed `old_len + n <= cap`. + unsafe { (ET_BUF_PTR as *mut T).add(old_len) } + }; + let dst_slice = ptr::slice_from_raw_parts_mut(dst_base, n); + let dst_target: *const T = if !T::IS_ZST && target < n { + unsafe { dst_base.add(target) } + } else { + ptr::dangling() + }; + let mut target_verified = false; + unsafe { + verify_target_slot_written(0, target, dst_target, target_tag, &mut target_verified); + } + let mut i: usize = 1; + #[kani::loop_invariant( + 1 <= i + && i <= n + && unsafe { *len_ptr == old_len + i } + && (target_verified == (target < i)) + )] + #[kani::loop_modifies(&i, &target_verified, len_ptr, dst_slice)] + while i < n { + f(T::from_tag(pick_iter_tag(i, target, target_tag))); + unsafe { + verify_target_slot_written(i, target, dst_target, target_tag, &mut target_verified); + } + i += 1; + } + assert!(target_verified); + } +} + +// SAFETY: `SymbolicTrustedIter` yields exactly `self.remaining` items, matching +// its exact `size_hint() == (remaining, Some(remaining))`. +unsafe impl iter::TrustedLen for SymbolicTrustedIter {} + +/// `TrustedLen` iterator whose `size_hint()` reports `(usize::MAX, None)` to +/// verify `extend_trusted`'s eager capacity-overflow panic branch. +struct UnboundedNoneTrustedIter; + +impl Iterator for UnboundedNoneTrustedIter { + type Item = u8; + fn next(&mut self) -> Option { + Some(1) + } + fn size_hint(&self) -> (usize, Option) { + (usize::MAX, None) + } +} + +// SAFETY: `UnboundedNoneTrustedIter` is infinite, so `(usize::MAX, None)` is exact. +unsafe impl iter::TrustedLen for UnboundedNoneTrustedIter {} + +fn verify_extend_trusted() { + let (mut v, index, marker) = + any_initialized_vec_up_to::(MAX_ALLOCATION_BYTES / 2, TrackPtrAlloc); + let old_ptr = v.as_ptr(); + let old_len = v.len(); + let old_cap = v.capacity(); + let n: usize = if T::IS_ZST { + any_up_to(usize::MAX - old_len) + } else { + any_up_to((MAX_ALLOCATION_BYTES / 2) / mem::size_of::()) + }; + let small = witness_ok::(old_cap) && witness_ok::(n); + let deep = deep_min::(); + let target = any_up_to(n.saturating_sub(1)); + let target_tag = any_tag(); + if !T::IS_ZST && n > 0 && old_len + target < old_cap { + unsafe { + v.as_mut_ptr() + .add(old_len + target) + .cast::>() + .write(MaybeUninit::uninit()); + } + } + + unsafe { + ET_LOCAL_LEN_PTR = ptr::null_mut(); + ET_BUF_PTR = v.as_mut_ptr().cast::(); + } + reset_drops(); + + let iter = SymbolicTrustedIter:: { + remaining: n, + old_len, + target, + target_tag, + _marker: core::marker::PhantomData, + }; + v.extend_trusted(iter); + + assert!(drops() == 0); + assert!(v.len() == old_len + n); + assert!(v.capacity() >= old_len + n); + let grow_ok = if n <= old_cap - old_len { + v.capacity() == old_cap && v.as_ptr() == old_ptr + } else { + v.capacity() > old_cap + }; + assert!(grow_ok); + let marker_ok = + T::IS_ZST || old_len == 0 || unsafe { (&*v.as_ptr().add(index)).tag() } == marker; + assert!(marker_ok); + kani::cover( + small && n > deep && target > deep, + "extend_trusted newly published deep slot verified", + ); + + kani::cover(small && n == 0, "extend_trusted empty iterator"); + kani::cover(small && n == 1, "extend_trusted single element"); + kani::cover( + small && n > 1 && n <= old_cap - old_len && old_len > 0, + "extend_trusted in-place spare capacity", + ); + kani::cover( + small && n > deep && n <= old_cap - old_len && old_len > deep, + "extend_trusted deep in-place", + ); + T::when_non_zst(|| { + kani::cover(small && old_cap == 0 && n > 0, "extend_trusted allocates from empty"); + kani::cover( + small && n > old_cap - old_len && old_len > deep && n > deep, + "extend_trusted grows deep buffer", + ); + }); + T::when_zst(|| { + kani::cover(small && old_len == 0 && n > 4096, "extend_trusted empty ZST"); + kani::cover( + small && old_len > 4096 && n == usize::MAX - old_len, + "extend_trusted ZST max fill", + ); + }); + + release_vec_buffer(v); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_u8() { + verify_extend_trusted::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_overaligned() { + verify_extend_trusted::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_zst() { + verify_extend_trusted::<()>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_drop_tracker() { + verify_extend_trusted::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_nonzero() { + verify_extend_trusted::>(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(crate::alloc::__rust_realloc, model_growing_realloc)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_padded_niche() { + verify_extend_trusted::(); +} + +#[kani::proof] +#[kani::solver(minisat)] +#[kani::stub(SetLenOnDrop::increment_len, SetLenOnDrop::kani_trace_increment_len)] +fn check_extend_trusted_aligned_zst() { + verify_extend_trusted::(); +} + +#[kani::proof] +#[kani::should_panic] +fn check_extend_trusted_none_overflow() { + let (mut v, _, _) = any_initialized_vec::(Global); + let small = witness_ok::(v.capacity()); + kani::cover(small && v.len() > 4096, "extend_trusted None upper bound panics on deep vec"); + v.extend_trusted(UnboundedNoneTrustedIter); +} + +#[kani::proof] +#[kani::should_panic] +fn check_extend_trusted_zst_capacity_overflow() { + let old_len = any_up_to(usize::MAX); + let n: usize = kani::any(); + kani::assume(old_len.checked_add(n).is_none()); + let mut v: Vec<()> = Vec::new(); + v.len = old_len; + kani::cover(old_len == usize::MAX && n == 1, "extend_trusted ZST +1 overflow"); + let iter = SymbolicTrustedIter::<()> { + remaining: n, + old_len, + target: 0, + target_tag: 1, + _marker: core::marker::PhantomData, + }; + v.extend_trusted(iter); +} diff --git a/verifast-proofs/alloc/vec/mod.rs-negative/README.md b/verifast-proofs/alloc/vec/mod.rs-negative/README.md new file mode 100644 index 0000000000000..6266ccbbd857e --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs-negative/README.md @@ -0,0 +1,32 @@ +Negative regression suite for the `alloc::vec::mod.rs` VeriFast 26.10 proof. + +First runs a **positive control** on the unmodified staged crate (`verified_base`) +and unmodified companion proof (`set_len_on_drop_proof.rs`), verifying that both +`verifast` (`0 errors found`) and `refinement-checker` succeed cleanly before +injecting any mutations. + +Then injects 6 targeted 1-line faults (4 in the staged `alloc` crate + 2 in +the zero-`assume` `SetLenOnDrop` companion proof) and confirms that VeriFast +rejects every mutant with its exact mutated-term diagnostic (and +`refinement-checker` rejects all 4 staged-crate mutants with a clean +`^ERROR: In function ...` mismatch and zero `Fatal error` exceptions): + +1. `Vec::extend_desugared`: `base_ptr.add(len)` -> `base_ptr.add(len + 1)` + (OOB write past reserved spare slot — rejected by VeriFast on + `ptr_add_(base_ptr, (len0 + 1)` and by `refinement-checker`). +2. Default `SpecExtendWith::spec_extend_with`: `ptr.add(1)` -> `ptr.add(1).add(1)` + (OOB +2 pointer stride — rejected by VeriFast on `Pointer may be out of bounds` / + `ptr_add_` and cleanly by `refinement-checker` with `^ERROR: In function`). +3. `Vec::retain_mut`: `g.v.as_mut_ptr().add(g.read)` -> `g.v.as_mut_ptr().add(g.read + 1)` + (OOB read past initialized prefix — rejected by VeriFast on + `PanicGuard_read(g_cur) + 1` and by `refinement-checker`). +4. `Vec::dedup_tail`: `start.add(gap.read)` -> `start.add(gap.read + 1)` + (OOB read past initialized prefix — rejected by VeriFast on + `FillGapOnDrop_read(gap_cur) + 1` and by `refinement-checker`). +5a. `SetLenOnDropTrait::drop` (companion `impl<'a> Drop`): `*self.len = self.local_len;` + -> `*self.len = usize::MAX;` (non-overflowing OOB length writeback — rejected by + VeriFast with `Cannot prove 18446744073709551615 <= bound`). +5b. `SetLenOnDrop::drop_writeback_exact` (companion safe helper): + `*self.len = self.local_len;` -> `*self.len = self.local_len.wrapping_sub(1);` + (non-overflowing wrong-value length writeback — rejected by VeriFast with + `Cannot prove ... == get_SetLenOnDrop_local_len(s0)`). diff --git a/verifast-proofs/alloc/vec/mod.rs-negative/update.sh b/verifast-proofs/alloc/vec/mod.rs-negative/update.sh new file mode 100644 index 0000000000000..b47f32f85990f --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs-negative/update.sh @@ -0,0 +1,5 @@ +set -x -e + +# Negative proof delegates source tracking to ../mod.rs and injects its UB +# mutation dynamically in verify.sh, so updating ../mod.rs keeps it in sync. +true diff --git a/verifast-proofs/alloc/vec/mod.rs-negative/verify.sh b/verifast-proofs/alloc/vec/mod.rs-negative/verify.sh new file mode 100755 index 0000000000000..140f71a181874 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs-negative/verify.sh @@ -0,0 +1,275 @@ +set -e -x + +export VFVERSION=26.10 + +. ../../../setup-verifast-home +if ! rustup toolchain list | grep -q '^nightly-2026-09-25'; then + rustup toolchain install nightly-2026-09-25 +fi + +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +if [[ "$(uname)" == "Darwin" ]]; then + SO_EXT="dylib" +else + SO_EXT="so" +fi + +rustc +nightly-2026-09-25 --edition 2021 --crate-type proc-macro --crate-name safety \ + -o "$STAGE/libsafety.$SO_EXT" ../mod.rs/safety_stub.rs + +ALLOC_SRC="../../../../library/alloc/src" +VF_ORIG="$VERIFAST_HOME/tests/rust/safe_abstraction/vec/original" + +stage_tree() { + local dst="$1" + mkdir -p "$dst/boxed" "$dst/collections/vec_deque" "$dst/raw_vec" "$dst/vec" + cp ../mod.rs/lib.rs "$dst/lib.rs" + for f in alloc.rs borrow.rs boxed.rs fmt.rs intrinsics.rs macros.rs panicking.rs slice.rs str.rs string.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$VF_ORIG/$f" > "$dst/$f" + done + for f in "$VF_ORIG/boxed/"*.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$f" > "$dst/boxed/$(basename "$f")" + done + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$VF_ORIG/collections/mod.rs" > "$dst/collections/mod.rs" + for f in "$VF_ORIG/collections/vec_deque/"*.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$f" > "$dst/collections/vec_deque/$(basename "$f")" + done + cp "$ALLOC_SRC/raw_vec/mod.rs" "$dst/raw_vec/mod.rs" + for f in "$ALLOC_SRC/vec/"*.rs; do + base="$(basename "$f")" + case "$base" in + verify*.rs) ;; + *) cp "$f" "$dst/vec/$base" ;; + esac + done +} + +stage_tree "$STAGE/original" +cp ../mod.rs/original/vec_mod.rs "$STAGE/original/vec/mod.rs" +cp ../mod.rs/original/spec_extend_with.rs "$STAGE/original/vec/spec_extend_with.rs" +cp ../mod.rs/original/set_len_on_drop.rs "$STAGE/original/vec/set_len_on_drop.rs" + +cp -a "$STAGE/original" "$STAGE/with-directives" +cp ../../raw_vec/mod.rs/with-directives/raw_vec.rs "$STAGE/with-directives/raw_vec/mod.rs" +cp ../mod.rs/with-directives/spec_extend_with.rs "$STAGE/with-directives/vec/spec_extend_with.rs" + +cp -a "$STAGE/with-directives" "$STAGE/verified_base" +cp ../mod.rs/verified/raw_vec_mod.rs "$STAGE/verified_base/raw_vec/mod.rs" +cp ../mod.rs/verified/vec_mod.rs "$STAGE/verified_base/vec/mod.rs" +cp ../mod.rs/verified/spec_extend_with.rs "$STAGE/verified_base/vec/spec_extend_with.rs" +cp ../mod.rs/verified/set_len_on_drop.rs "$STAGE/verified_base/vec/set_len_on_drop.rs" + +RUSTC_ARGS="--crate-name alloc --edition 2024 --extern safety=$STAGE/libsafety.$SO_EXT" + +# ---- Positive Control: Unmutated staged crate & companion MUST PASS ---- +verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/verified_base/lib.rs" > "$STAGE/vf_ctrl.log" 2>&1 +grep -q "0 errors found" "$STAGE/vf_ctrl.log" +refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/verified_base/lib.rs" > "$STAGE/rc_ctrl.log" 2>&1 +verifast -rustc_args "--edition 2024" -ignore_unwind_paths ../mod.rs/set_len_on_drop_proof.rs > "$STAGE/vf_ctrl_slod.log" 2>&1 +grep -q "0 errors found" "$STAGE/vf_ctrl_slod.log" +echo "POSITIVE CONTROL (unmutated staged crate + companion): OK" + +# ---- Negative Test 1: 1-line OOB UB mutant in Vec::extend_desugared ---- +cp -a "$STAGE/verified_base" "$STAGE/mut_extend_desugared" +python3 - "$STAGE/mut_extend_desugared/vec/mod.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +anchor = "fn extend_desugared" +old = "let dst = base_ptr.add(len);" +new = "let dst = base_ptr.add(len + 1);" +pos = txt.index(anchor) +idx = txt.index(old, pos) +txt = txt[:idx] + new + txt[idx + len(old):] +open(p, "w").write(txt) +PY + +if verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/mut_extend_desugared/lib.rs" > "$STAGE/vf1.log" 2>&1; then + cat "$STAGE/vf1.log" + echo "ERROR: extend_desugared UB mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf1.log" +if ! grep -qE "No matching heap chunks:.*ptr_add_\(base_ptr, \(len0 \+ 1\)" "$STAGE/vf1.log"; then + echo "ERROR: extend_desugared UB mutant failed VeriFast for an unexpected reason!" + exit 1 +fi +if refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/mut_extend_desugared/lib.rs" > "$STAGE/rc1.log" 2>&1; then + cat "$STAGE/rc1.log" + echo "ERROR: extend_desugared UB mutant unexpectedly PASSED refinement-checker!" + exit 1 +fi +cat "$STAGE/rc1.log" +if grep -q "Fatal error" "$STAGE/rc1.log" || ! grep -qE "^ERROR: In function vec::Vec::::extend_desugared" "$STAGE/rc1.log"; then + echo "ERROR: extend_desugared refinement-checker failed for an unexpected reason!" + exit 1 +fi + +# ---- Negative Test 2: 1-line OOB UB mutant in default SpecExtendWith::spec_extend_with ---- +cp -a "$STAGE/verified_base" "$STAGE/mut_spec_extend_with" +python3 - "$STAGE/mut_spec_extend_with/vec/spec_extend_with.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +old = "ptr = unsafe { ptr.add(1) };" +new = "ptr = unsafe { ptr.add(1).add(1) };" +assert txt.count(old) == 1 +open(p, "w").write(txt.replace(old, new, 1)) +PY + +if verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/mut_spec_extend_with/lib.rs" > "$STAGE/vf2.log" 2>&1; then + cat "$STAGE/vf2.log" + echo "ERROR: spec_extend_with UB mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf2.log" +if ! grep -qE "Pointer may be out of bounds.*ptr_add_\(ptr_add_\(ptr0, 1" "$STAGE/vf2.log"; then + echo "ERROR: spec_extend_with UB mutant failed VeriFast for an unexpected reason!" + exit 1 +fi +if refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/mut_spec_extend_with/lib.rs" > "$STAGE/rc2.log" 2>&1; then + cat "$STAGE/rc2.log" + echo "ERROR: spec_extend_with UB mutant unexpectedly PASSED refinement-checker!" + exit 1 +fi +cat "$STAGE/rc2.log" +if grep -q "Fatal error" "$STAGE/rc2.log" || ! grep -qE "^ERROR: In function as vec::spec_extend_with::SpecExtendWith>::spec_extend_with" "$STAGE/rc2.log"; then + echo "ERROR: spec_extend_with refinement-checker failed for an unexpected reason!" + exit 1 +fi + +# ---- Negative Test 3: 1-line OOB UB mutant in Vec::retain_mut ---- +cp -a "$STAGE/verified_base" "$STAGE/mut_retain_mut" +python3 - "$STAGE/mut_retain_mut/vec/mod.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +anchor = "pub fn retain_mut" +old = "let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };" +new = "let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read + 1) };" +pos = txt.index(anchor) +idx = txt.index(old, pos) +txt = txt[:idx] + new + txt[idx + len(old):] +open(p, "w").write(txt) +PY + +if verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/mut_retain_mut/lib.rs" > "$STAGE/vf3.log" 2>&1; then + cat "$STAGE/vf3.log" + echo "ERROR: retain_mut UB mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf3.log" +if ! grep -qE "No matching heap chunks:.*PanicGuard_read\(g_cur\) \+ 1" "$STAGE/vf3.log"; then + echo "ERROR: retain_mut UB mutant failed VeriFast for an unexpected reason!" + exit 1 +fi +if refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/mut_retain_mut/lib.rs" > "$STAGE/rc3.log" 2>&1; then + cat "$STAGE/rc3.log" + echo "ERROR: retain_mut UB mutant unexpectedly PASSED refinement-checker!" + exit 1 +fi +cat "$STAGE/rc3.log" +if grep -q "Fatal error" "$STAGE/rc3.log" || ! grep -qE "^ERROR: In function vec::Vec::::retain_mut" "$STAGE/rc3.log"; then + echo "ERROR: retain_mut refinement-checker failed for an unexpected reason!" + exit 1 +fi + +# ---- Negative Test 4: 1-line OOB UB mutant in Vec::dedup_tail ---- +cp -a "$STAGE/verified_base" "$STAGE/mut_dedup_tail" +python3 - "$STAGE/mut_dedup_tail/vec/mod.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +anchor = "unsafe fn dedup_tail" +old = "let read_ptr = start.add(gap.read);" +new = "let read_ptr = start.add(gap.read + 1);" +pos = txt.index(anchor) +idx = txt.index(old, pos) +txt = txt[:idx] + new + txt[idx + len(old):] +open(p, "w").write(txt) +PY + +if verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/mut_dedup_tail/lib.rs" > "$STAGE/vf4.log" 2>&1; then + cat "$STAGE/vf4.log" + echo "ERROR: dedup_tail UB mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf4.log" +if ! grep -qE "No matching heap chunks:.*FillGapOnDrop_read\(gap_cur\) \+ 1" "$STAGE/vf4.log"; then + echo "ERROR: dedup_tail UB mutant failed VeriFast for an unexpected reason!" + exit 1 +fi +if refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/mut_dedup_tail/lib.rs" > "$STAGE/rc4.log" 2>&1; then + cat "$STAGE/rc4.log" + echo "ERROR: dedup_tail UB mutant unexpectedly PASSED refinement-checker!" + exit 1 +fi +cat "$STAGE/rc4.log" +if grep -q "Fatal error" "$STAGE/rc4.log" || ! grep -qE "^ERROR: In function vec::Vec::::dedup_tail" "$STAGE/rc4.log"; then + echo "ERROR: dedup_tail refinement-checker failed for an unexpected reason!" + exit 1 +fi + +# ---- Negative Test 5a: Companion NON-OVERFLOWING OOB-writeback mutant in SetLenOnDropTrait::drop ---- +cp ../mod.rs/set_len_on_drop_proof.rs "$STAGE/mut_slod_oob_drop.rs" +python3 - "$STAGE/mut_slod_oob_drop.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +anchor = "impl<'a> Drop for SetLenOnDropTrait<'a>" +old = "*self.len = self.local_len;" +new = "*self.len = usize::MAX;" +pos = txt.index(anchor) +idx = txt.index(old, pos) +txt = txt[:idx] + new + txt[idx + len(old):] +open(p, "w").write(txt) +PY + +if verifast -rustc_args "--edition 2024" -ignore_unwind_paths "$STAGE/mut_slod_oob_drop.rs" > "$STAGE/vf5a.log" 2>&1; then + cat "$STAGE/vf5a.log" + echo "ERROR: SetLenOnDropTrait::drop OOB-writeback mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf5a.log" +if ! grep -qE "Cannot prove 18446744073709551615 <= bound" "$STAGE/vf5a.log"; then + echo "ERROR: SetLenOnDropTrait::drop OOB-writeback mutant failed VeriFast for an unexpected reason!" + exit 1 +fi + +# ---- Negative Test 5b: Companion NON-OVERFLOWING wrong-value writeback mutant in drop_writeback_exact ---- +cp ../mod.rs/set_len_on_drop_proof.rs "$STAGE/mut_slod_wrong_val.rs" +python3 - "$STAGE/mut_slod_wrong_val.rs" << 'PY' +import sys +p = sys.argv[1] +txt = open(p).read() +anchor = "pub unsafe fn drop_writeback_exact" +old = "*self.len = self.local_len;" +new = "*self.len = self.local_len.wrapping_sub(1);" +pos = txt.index(anchor) +idx = txt.index(old, pos) +txt = txt[:idx] + new + txt[idx + len(old):] +open(p, "w").write(txt) +PY + +if verifast -rustc_args "--edition 2024" -ignore_unwind_paths "$STAGE/mut_slod_wrong_val.rs" > "$STAGE/vf5b.log" 2>&1; then + cat "$STAGE/vf5b.log" + echo "ERROR: drop_writeback_exact wrong-value mutant unexpectedly PASSED VeriFast!" + exit 1 +fi +cat "$STAGE/vf5b.log" +if ! grep -qE "Cannot prove .* == get_SetLenOnDrop_local_len\(s0\)" "$STAGE/vf5b.log"; then + echo "ERROR: drop_writeback_exact wrong-value mutant failed VeriFast for an unexpected reason!" + exit 1 +fi + +for pair in "vec_mod.rs:vec/mod.rs" "spec_extend_with.rs:vec/spec_extend_with.rs" "set_len_on_drop.rs:vec/set_len_on_drop.rs"; do + orig="${pair%%:*}" + src="${pair##*:}" + if ! diff "../mod.rs/original/$orig" "$ALLOC_SRC/$src"; then + echo "::error title=VeriFast negative proof out of date::original/$orig differs from library/alloc/src/$src" + false + fi +done +echo "CH23 VERIFAST NEGATIVE SUITE (4 staged-crate + 2 companion mutants = 6/6 rejected): OK" diff --git a/verifast-proofs/alloc/vec/mod.rs/README.md b/verifast-proofs/alloc/vec/mod.rs/README.md new file mode 100644 index 0000000000000..f920c8a0e3f3a --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/README.md @@ -0,0 +1,81 @@ +# VeriFast Proof for `Vec::{extend_desugared, retain_mut, dedup_by, dedup_tail}` and `default fn SpecExtendWith::spec_extend_with` + +This directory contains a unified, unbounded, universally polymorphic VeriFast 26.10 proof against the real +`alloc::vec::Vec` (backed by `alloc::raw_vec::RawVec`) verifying all four polymorphic +user-callback / arbitrary-`Drop` loops in Challenge 23 over arbitrary generic `T`, arbitrary `Iterator` / +stateful `FnMut`, arbitrary `Drop`, and arbitrary `A: Allocator` on normal-return execution paths +(with `-ignore_unwind_paths`, matching upstream `alloc/collections/linked_list.rs` and `alloc/raw_vec/mod.rs`; +portable `retain_mut` path, excluding the `aarch64` `target_feature = "sve"` fast path): + +- `Vec::extend_desugared>` in `library/alloc/src/vec/mod.rs` (plus `Vec::{reserve, capacity, as_mut_ptr, set_len, len}`, where `Vec::reserve` and `RawVec::reserve` are verified ghost wrappers propagating capacity and element-prefix preservation with zero extra `assume`s from a single trusted `RawVecInner::reserve` spec) +- `default fn SpecExtendWith::spec_extend_with` in `library/alloc/src/vec/spec_extend_with.rs` (plus `SetLenOnDrop::new` in `library/alloc/src/vec/set_len_on_drop.rs`, with `SetLenOnDrop::{increment_len, drop}` skipped in the unified crate and independently verified with zero `assume` in the standalone companion proof `set_len_on_drop_proof.rs` without `-allow_assume`) +- `Vec::retain_mut bool>` in `library/alloc/src/vec/mod.rs` (both loops + 3-way partition, proving `len1 <= len0`, exact pointer/capacity/allocation preservation, full survivor ownership, and public-API `safety_proof`) +- `Vec::dedup_by bool>` and `Vec::dedup_tail` in `library/alloc/src/vec/mod.rs` (both loops + 3-way gap-compaction partition, proving `len1 <= len0`, `len0 == 0 || len1 >= 1`, exact pointer/capacity/allocation preservation, full survivor ownership, and public-API `safety_proof`) + +## Key Properties & Verification Checks + +- `original/vec_mod.rs`, `original/spec_extend_with.rs`, and `original/set_len_on_drop.rs` are byte-identical to `library/alloc/src/vec/{mod.rs, spec_extend_with.rs, set_len_on_drop.rs}` (enforced by `diff` in `verify.sh`). +- `verified/raw_vec_mod.rs` is generated deterministically from the accepted Challenge 19 proof (`../../raw_vec/mod.rs/verified/raw_vec.rs`, PR `#422`) via `sync_raw_vec.py` (enforced by `python3 sync_raw_vec.py --check` in `verify.sh`): + - replaces Ch. 19's two `assume(false)` placeholders for `verifast#610` with explicit subtype/upcast axioms (zero `assume(false)`), + - adds a single trusted `RawVecInner::reserve` (`//@ assume_correct`) spec capturing both capacity growth (`len + additional <= capacity1`, which Ch. 19 proves in `RawVecInner::try_reserve` / `grow_amortized`, because VeriFast 26.10's preprocessor rejects specs on the nested `fn do_reserve_and_handle`) and `0..len * elem_layout.size()` byte-prefix preservation (because VeriFast 26.10's `Allocator::grow` spec returns uninitialized bytes), and proves `RawVec::reserve` (and `Vec::reserve`) on top of it with zero extra `assume`s, + - strips 6 uncalled Ch. 19 function specs (`RawVec::{into_box, with_capacity_in, shrink_to_fit}`, `RawVecInner::{with_capacity_in, shrink_to_fit}`, `handle_error`) that remain independently verified in `verifast-proofs/alloc/raw_vec/mod.rs` and are skipped here under `-skip_specless_fns`. +- `set_len_on_drop_proof.rs` is a standalone companion proof verified by `verify.sh` **without `-allow_assume`** (`104` statements verified, strictly zero `assume` statements). It independently proves `SetLenOnDrop<'a>` (`new_checked`, `increment_len_checked`, bound-preserving `increment_len_preserves_bound`, bounded `drop_writeback_preserves_fbc`, and exact `drop_writeback_exact` (`*s0.len |-> s0.local_len`, under a direct `*s0.len |-> _` premise) on the exact `&'a mut usize` struct) AND a full Rust `impl<'a> Drop for SetLenOnDropTrait<'a>` carrying the unified crate's exact bounded `SetLenOnDrop_fbc(s.len, bound)` ownership invariant (`0 <= bound <= usize::MAX`, `s.local_len <= bound`, `full_borrow('a, SetLenOnDrop_fbc(s.len, bound))` — storing `len: *mut usize` + invariant `PhantomData &'a ()>` because VeriFast 26.10's automatic Drop-glue check requires `<&'a mut usize>.own == full_borrow('a, usize_full_borrow_content)` on drop exit, which cannot be weakened from `SetLenOnDrop_fbc`). `verify.sh` parses and compares the complete scoped executable bodies (stripping comments/ghost blocks) of 7/8 production-derived methods against `library/alloc/src/vec/set_len_on_drop.rs` plus the 1 raw-pointer surrogate constructor `SetLenOnDropTrait::new`, and enforces zero `assume(`. In the unified `spec_extend_with` proof itself, `SetLenOnDrop::drop` (`verified/set_len_on_drop.rs:105-110`) and specless `SetLenOnDrop::increment_len` (`verified/set_len_on_drop.rs:83-85`) are skipped under `-skip_specless_fns` (due to VeriFast 26.10's `'_` drop limitation and `pub(super)` safety-proof behavior), so `spec_extend_with` relies on `SetLenOnDrop::drop` preserving `SetLenOnDrop_fbc` (`final_len <= len0 + n`) while the standalone companion independently verifies both bounded `impl<'a> Drop` writeback and exact writeback. +- `vec_get_unchecked_mut__VeriFast_wrapper` requires full initialized-prefix ownership (`array_at_lft` + `foreach(elems, own)`), an exclusive lifetime token `[q]lifetime_token(alloc_id.lft)`, and `index < len`, and hands out a scoped exclusive borrow `*result |-> nth(index, elems)` + `close_points_to_at_lft_token(1, alloc_id.lft, result, q)` restored after the callback. +- `forget_vec_guard__VeriFast_wrapper` requires caller-supplied ghost witnesses for `thread_token(t)`, a live `full_borrow(k, Vec_exact_fbc(...))`, and valid guard cursor ordering `0 <= write <= read <= orig_len` (no `req true`; the guard-to-borrow link is established at the two call sites). +- `verify.sh` stages `library/alloc/src/{raw_vec, vec}` together with version-substituted (`CURRENT_RUSTC_VERSION` -> `1.100.0`) support modules from `$VERIFAST_HOME/tests/rust/safe_abstraction/vec/original/`, compiles the no-op `safety` proc-macro stub with VeriFast's pinned `nightly-2026-09-25` toolchain, runs `verifast` on both the unified crate (`2,720` statements verified, `0` errors) and `set_len_on_drop_proof.rs` (`104` statements verified, no `-allow_assume`), checks scoped method-body sync (`7/8` production-derived + `1` surrogate constructor, `0 assume`), and checks both `refinement-checker` passes (`--ignore-directives` and body refinement). +- `update.sh` (registered in `verifast-proofs/patch-verifast-proofs.sh`) merges upstream `rust-lang/rust` subtree updates into `vec_mod.rs`, `spec_extend_with.rs`, `set_len_on_drop.rs`, and `raw_vec_mod.rs`. +- `../mod.rs-negative/` runs an unmutated positive control first, then injects 4 staged real-`alloc` UB mutations (`extend_desugared`, `default spec_extend_with`, `retain_mut`, `dedup_tail`) plus 2 non-overflowing companion `set_len_on_drop_proof.rs` mutations (`*self.len = usize::MAX;` against `SetLenOnDropTrait::drop`'s `<= bound` invariant + `wrapping_sub(1)` against `drop_writeback_exact`'s exact equality postcondition) and enforces target-specific rejection diagnostics in `verifast` and clean `^ERROR: In function` mismatches (rejecting `Fatal error`) in `refinement-checker`. + +## Local vs. Inherited Trust Boundary Notes + +Across the 5 local proof files (`verified/{vec_mod.rs, spec_extend_with.rs, set_len_on_drop.rs, raw_vec_mod.rs}` and `set_len_on_drop_proof.rs`), there are **9 local ghost `assume(...)` lines**, **10 local `//@ assume_correct` directives**, **2 skipped internal `SetLenOnDrop` methods** in the unified crate, and **0 `assume(false)`**: +- **Inherited from upstream VeriFast 26.10:** `Vec_share_full` (`verified/vec_mod.rs:940`, verbatim from `$VERIFAST_HOME/tests/rust/safe_abstraction/vec/verified/vec/mod.rs:849-855`: lifetime-inclusion assumption absent from its precondition), plus VeriFast 26.10's installed `std/lib.rsspec` contracts (note: `std/lib.rsspec:304` specifies `ptr_offset_from` in byte units rather than element units; none of the 4 verified loops invoke cross-allocation `offset_from`). +- **Added / replaced by Challenge 23:** 8 explicit `verifast#610` `upcast`/subtype-monotone identity axioms (`vec_mod.rs:580,598-599`, `set_len_on_drop.rs:50`, `raw_vec_mod.rs:204,765-767` — replacing upstream's and Ch. 19's `assume(false)` placeholders), 1 trusted `RawVecInner::reserve` spec (`raw_vec_mod.rs:2690`), 9 single-line `__VeriFast_wrapper` functions (`spec_extend_with.rs:17,30`, `vec_mod.rs:5521,5531,5539,5551,5560,5613,5636`) checked for MIR refinement by `refinement-checker`, plus skipped `SetLenOnDrop::drop` (`verified/set_len_on_drop.rs:105-110`) and specless `SetLenOnDrop::increment_len` (`verified/set_len_on_drop.rs:83-85`) in the unified crate (both independently verified with 0 `assume` in `set_len_on_drop_proof.rs`). +- **Standalone Challenge 19 note:** When running repo-wide `check-verifast-proofs.sh`, the separate inherited `alloc/raw_vec/mod.rs` invocation emits a VeriFast Redux `possible axiom inconsistency` notice before its `0 errors found (1690 statements verified)` result; that notice belongs exclusively to the inherited Ch. 19 invocation and does not occur in this unified `alloc/vec/mod.rs` crate. Also note that unmodified upstream `verifast-proofs/alloc/collections/linked_list.rs-negative` (outside Ch. 23 scope) hits a pre-existing specification type mismatch in VeriFast before its refinement-checker check. + +## Upstream Attribution & License Notice + +This proof builds on and adapts two upstream MIT-licensed works: + +1. **VeriFast 26.10** ([release 26.10](https://github.com/verifast/verifast/releases/tag/26.10), [LICENSE.md](https://github.com/verifast/verifast/blob/master/LICENSE.md)) — specifically `tests/rust/safe_abstraction/vec/verified/vec/mod.rs`, `tests/rust/safe_abstraction/vec/original/`, and `tests/rust/safe_abstraction/linked_list/verified/linked_list.rs`: + - `verified/vec_mod.rs` adapts the core `Vec` ownership/sharing predicates and lemmas (`Vec`, `Vec_own`, `Vec_share_`, `share_Vec`, `end_share_Vec`, `Vec_share_full`, etc.) and `Vec::{len, capacity, as_mut_ptr, set_len}` specs from VeriFast 26.10's `safe_abstraction/vec/verified/vec/mod.rs`. + - `call_fn_mut{1,2}__VeriFast_wrapper` follow VeriFast's `linked_list/verified/linked_list.rs` `call_pred__VeriFast_wrapper` idiom. + - `verify.sh` stages unmodified non-`vec` support modules from `$VERIFAST_HOME/tests/rust/safe_abstraction/vec/original/`. +2. **Accepted Challenge 19 (`verifast-proofs/alloc/raw_vec/mod.rs`, [PR #422](https://github.com/model-checking/verify-rust-std/pull/422)):** + - `verified/raw_vec_mod.rs` is generated deterministically from `verifast-proofs/alloc/raw_vec/mod.rs/verified/raw_vec.rs` via `sync_raw_vec.py` (dual-licensed MIT / Apache-2.0 under `model-checking/verify-rust-std`). + +**New contributions authored for Challenge 23:** +- `array_at_lft_own_mono` and the structural `Vec_own_mono` proof in `verified/vec_mod.rs` (replacing upstream's `assume(false)` placeholder for `verifast#610`); +- `Vec_drop`, `array_at_lft_snoc`, `array_at_lft_uncons`, `array_at_lft_cons`, `array_at_lft_unsnoc`, `array_at_lft_snoc_own`, ZST-safe `array_at_lft_join_len`, and `Vec_exact_fbc` in `verified/vec_mod.rs`; +- `sync_raw_vec.py` plus verified zero-assume ghost wrappers for `RawVec::reserve` and `Vec::reserve`; +- Full unbounded polymorphic proofs for `Vec::extend_desugared`, `default fn SpecExtendWith::spec_extend_with`, `Vec::retain_mut`, `Vec::dedup_by`, and `Vec::dedup_tail` (including `verified/spec_extend_with.rs` and `verified/set_len_on_drop.rs`); +- Standalone zero-`assume` companion proof `set_len_on_drop_proof.rs` and scoped 8-method body-sync checker; +- `verify.sh`, `update.sh`, `safety_stub.rs`, and the 6-mutant negative proof suite (with positive control) in `../mod.rs-negative/`. + +### Verbatim Upstream MIT License Notice (VeriFast) + +```text +VeriFast + +Copyright (c) 2008-2016 Katholieke Universiteit Leuven + +The MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/verifast-proofs/alloc/vec/mod.rs/lib.rs b/verifast-proofs/alloc/vec/mod.rs/lib.rs new file mode 100644 index 0000000000000..96ce9a980749e --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/lib.rs @@ -0,0 +1,270 @@ +// verifast_options{skip_specless_fns} + +//! # The Rust core allocation and collections library +//! +//! This library provides smart pointers and collections for managing +//! heap-allocated values. +//! +//! This library, like core, normally doesn’t need to be used directly +//! since its contents are re-exported in the [`std` crate](../std/index.html). +//! Crates that use the `#![no_std]` attribute however will typically +//! not depend on `std`, so they’d use this crate instead. +//! +//! ## Boxed values +//! +//! The [`Box`] type is a smart pointer type. There can only be one owner of a +//! [`Box`], and the owner can decide to mutate the contents, which live on the +//! heap. +//! +//! This type can be sent among threads efficiently as the size of a `Box` value +//! is the same as that of a pointer. Tree-like data structures are often built +//! with boxes because each node often has only one owner, the parent. +//! +//! ## Reference counted pointers +//! +//! The [`Rc`] type is a non-threadsafe reference-counted pointer type intended +//! for sharing memory within a thread. An [`Rc`] pointer wraps a type, `T`, and +//! only allows access to `&T`, a shared reference. +//! +//! This type is useful when inherited mutability (such as using [`Box`]) is too +//! constraining for an application, and is often paired with the [`Cell`] or +//! [`RefCell`] types in order to allow mutation. +//! +//! ## Atomically reference counted pointers +//! +//! The [`Arc`] type is the threadsafe equivalent of the [`Rc`] type. It +//! provides all the same functionality of [`Rc`], except it requires that the +//! contained type `T` is shareable. Additionally, [`Arc`][`Arc`] is itself +//! sendable while [`Rc`][`Rc`] is not. +//! +//! This type allows for shared access to the contained data, and is often +//! paired with synchronization primitives such as mutexes to allow mutation of +//! shared resources. +//! +//! ## Collections +//! +//! Implementations of the most common general purpose data structures are +//! defined in this library. They are re-exported through the +//! [standard collections library](../std/collections/index.html). +//! +//! ## Heap interfaces +//! +//! The [`alloc`](alloc/index.html) module defines the low-level interface to the +//! default global allocator. It is not compatible with the libc allocator API. +//! +//! [`Arc`]: sync +//! [`Box`]: boxed +//! [`Cell`]: core::cell +//! [`Rc`]: rc +//! [`RefCell`]: core::cell + +#![allow(unused_features)] +#![allow(incomplete_features)] +#![expect(clippy::partialeq_ne_impl, reason = "we need to implement ne for a lot of alloc types")] +#![stable(feature = "alloc", since = "1.36.0")] +#![doc( + html_playground_url = "https://play.rust-lang.org/", + issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/", + test(no_crate_inject, attr(allow(unused_variables, duplicate_features), deny(warnings))) +)] +#![doc(auto_cfg( + hide(no_global_oom_handling, no_rc, no_sync), + hide(target_has_atomic, values("ptr")), +))] +#![doc(rust_logo)] +#![feature(rustdoc_internals)] +#![no_std] +#![needs_allocator] +// Lints: +#![deny(unsafe_op_in_unsafe_fn)] +#![deny(implicit_provenance_casts)] +#![warn(deprecated_in_future)] +#![warn(missing_debug_implementations)] +#![warn(missing_docs)] +#![allow(explicit_outlives_requirements)] +#![warn(multiple_supertrait_upcastable)] +#![allow(internal_features)] +#![allow(rustdoc::redundant_explicit_links)] +#![warn(rustdoc::unescaped_backticks)] +#![deny(ffi_unwind_calls)] +#![warn(unreachable_pub)] +// +// Library features: +// tidy-alphabetical-start +#![feature(allocator_ext)] +#![feature(array_into_iter_constructors)] +#![feature(ascii_char)] +#![feature(async_fn_traits)] +#![feature(async_iterator)] +#![feature(borrowed_buf_init)] +#![feature(bstr)] +#![feature(bstr_internals)] +#![feature(can_vector)] +#![feature(case_ignorable)] +#![feature(cast_maybe_uninit)] +#![feature(cell_get_cloned)] +#![feature(char_internals)] +#![feature(clone_to_uninit)] +#![feature(coerce_unsized)] +#![feature(const_clone)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_default)] +#![feature(const_destruct)] +#![feature(const_drop_in_place)] +#![feature(const_eval_select)] +#![feature(const_heap)] +#![feature(const_index)] +#![feature(const_option_ops)] +#![feature(const_result_trait_fn)] +#![feature(const_try)] +#![feature(copied_into_inner)] +#![feature(core_intrinsics)] +#![feature(core_io)] +#![feature(core_io_borrowed_buf)] +#![feature(core_io_internals)] +#![feature(cursor_split)] +#![feature(deprecated_suggestion)] +#![feature(deref_pure_trait)] +#![feature(derive_const)] +#![feature(diagnostic_on_move)] +#![feature(dispatch_from_dyn)] +#![feature(ergonomic_clones)] +#![feature(error_generic_member_access)] +#![feature(exact_size_is_empty)] +#![feature(extend_one)] +#![feature(extend_one_unchecked)] +#![feature(fmt_arguments_from_str)] +#![feature(fmt_internals)] +#![feature(fn_traits)] +#![feature(formatting_options)] +#![feature(freeze)] +#![feature(generic_atomic)] +#![feature(hasher_prefixfree_extras)] +#![feature(inplace_iteration)] +#![feature(io_const_error)] +#![feature(io_const_error_internals)] +#![feature(io_slice_as_bytes)] +#![feature(iter_advance_by)] +#![feature(iter_next_chunk)] +#![feature(legacy_receiver_trait)] +#![feature(likely_unlikely)] +#![feature(local_waker)] +#![feature(marker_trait_attr)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_fill)] +#![feature(maybe_uninit_uninit_array_transpose)] +#![feature(panic_internals)] +#![feature(pattern)] +#![feature(pin_coerce_unsized_trait)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_slice)] +#![feature(ptr_internals)] +#![feature(ptr_metadata)] +#![feature(random)] +#![feature(raw_os_error_ty)] +#![feature(rev_into_inner)] +#![feature(seek_stream_len)] +#![feature(set_ptr_value)] +#![feature(share_trait)] +#![feature(sized_type_properties)] +#![feature(slice_from_ptr_range)] +#![feature(slice_index_methods)] +#![feature(slice_iter_mut_as_mut_slice)] +#![feature(slice_ptr_get)] +#![feature(slice_range)] +#![feature(std_internals)] +#![feature(temporary_niche_types)] +#![feature(titlecase)] +#![feature(transmutability)] +#![feature(trivial_clone)] +#![feature(trusted_fused)] +#![feature(trusted_len)] +#![feature(trusted_random_access)] +#![feature(try_blocks)] +#![feature(try_trait_v2)] +#![feature(try_trait_v2_residual)] +#![feature(tuple_trait)] +#![feature(ub_checks)] +#![feature(unicode_internals)] +#![feature(unsize)] +#![feature(unwrap_infallible)] +#![feature(write_all_vectored)] +#![feature(wtf8_internals)] +// tidy-alphabetical-end +// +// Language features: +// tidy-alphabetical-start +#![feature(allocator_internals)] +#![feature(allow_internal_unstable)] +#![feature(cfg_sanitize)] +#![feature(const_closures)] +#![feature(const_precise_live_drops)] +#![feature(const_trait_impl)] +#![feature(coroutine_trait)] +#![feature(decl_macro)] +#![feature(dropck_eyepatch)] +#![feature(fundamental)] +#![feature(impl_restriction)] +#![feature(intrinsics)] +#![feature(lang_items)] +#![feature(min_specialization)] +#![feature(multiple_supertrait_upcastable)] +#![feature(negative_impls)] +#![feature(optimize_attribute)] +#![feature(rustc_attrs)] +#![feature(proc_macro_hygiene)] +#![feature(register_tool)] +#![feature(try_reserve_kind)] +#![feature(const_alloc_error)] +#![register_tool(lint)] +#![feature(slice_internals)] +#![feature(staged_api)] +#![feature(stmt_expr_attributes)] +#![feature(strict_provenance_lints)] +#![feature(unboxed_closures)] +#![feature(unsized_fn_params)] +#![feature(with_negative_coherence)] +#![rustc_preserve_ub_checks] +// tidy-alphabetical-end +// +// Rustdoc features: +#![feature(doc_cfg)] +#![feature(doc_notable_trait)] +// Technically, this is a bug in rustdoc: rustdoc sees the documentation on `#[lang = slice_alloc]` +// blocks is for `&[T]`, which also has documentation using this feature in `core`, and gets mad +// that the feature-gate isn't enabled. Ideally, it wouldn't check for the feature gate for docs +// from other crates, but since this can only appear for lang items, it doesn't seem worth fixing. +#![feature(intra_doc_pointers)] + +// Module with internal macros used by other modules (needs to be included before other modules). +#[macro_use] +mod macros; + +mod raw_vec; + +// Heaps provided for low-level allocation strategies +pub mod alloc; + +// Primitive types using the heaps above + +// Need to conditionally define the mod from `boxed.rs` to avoid +// duplicating the lang-items when building in test cfg; but also need +// to allow code to have `use boxed::Box;` declarations. +pub mod borrow; +pub mod boxed; +pub mod collections; +pub mod fmt; +pub mod intrinsics; +pub mod panicking; +pub mod slice; +pub mod str; +pub mod string; +pub mod vec; + +#[doc(hidden)] +#[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")] +pub mod __export { + pub use core::format_args; + pub use core::hint::must_use; +} diff --git a/verifast-proofs/alloc/vec/mod.rs/original/set_len_on_drop.rs b/verifast-proofs/alloc/vec/mod.rs/original/set_len_on_drop.rs new file mode 100644 index 0000000000000..e79a79f388e94 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/original/set_len_on_drop.rs @@ -0,0 +1,45 @@ +// Set the length of the vec when the `SetLenOnDrop` value goes out of scope. +// +// The idea is: The length field in SetLenOnDrop is a local variable +// that the optimizer will see does not alias with any stores through the Vec's data +// pointer. This is a workaround for alias analysis issue #32155 +pub(super) struct SetLenOnDrop<'a> { + len: &'a mut usize, + local_len: usize, +} + +impl<'a> SetLenOnDrop<'a> { + #[inline] + pub(super) fn new(len: &'a mut usize) -> Self { + SetLenOnDrop { local_len: *len, len } + } + + #[inline] + pub(super) fn increment_len(&mut self, increment: usize) { + self.local_len += increment; + } + + #[inline] + pub(super) fn current_len(&self) -> usize { + self.local_len + } + + #[cfg(all(kani, not(no_global_oom_handling)))] + pub(super) fn kani_trace_increment_len(&mut self, increment: usize) { + self.local_len += increment; + // SAFETY: Kani verification harnesses are single-threaded; record the + // stack address of `self.local_len` once on the peeled iteration so + // `extend_trusted`'s loop invariant can observe the closure's exact + // `SetLenOnDrop` counter without modifying shipped code. + unsafe { + crate::vec::verify_ch23::record_extend_trusted_len_ptr(&raw mut self.local_len); + } + } +} + +impl Drop for SetLenOnDrop<'_> { + #[inline] + fn drop(&mut self) { + *self.len = self.local_len; + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/original/spec_extend_with.rs b/verifast-proofs/alloc/vec/mod.rs/original/spec_extend_with.rs new file mode 100644 index 0000000000000..9059f79fb2329 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/original/spec_extend_with.rs @@ -0,0 +1,114 @@ +use core::clone::TrivialClone; +#[cfg(kani)] +use core::kani; +use core::{mem, ptr}; + +use crate::alloc::Allocator; +use crate::vec::{SetLenOnDrop, Vec}; + +pub(super) trait SpecExtendWith { + /// Extend the vector by `n` clones of value. + fn spec_extend_with(&mut self, n: usize, value: T); +} + +impl SpecExtendWith for Vec { + default fn spec_extend_with(&mut self, n: usize, value: T) { + self.reserve(n); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let mut ptr = unsafe { self.as_mut_ptr().add(self.len()) }; + // Use SetLenOnDrop to work around bug where compiler + // might not realize the store through `ptr` through self.set_len() + // don't alias. + let mut local_len = SetLenOnDrop::new(&mut self.len); + + // Write all elements except the last one + for _ in 1..n { + // three things have been taken into consideration: + // - `T::clone` can be provided by the user, and can panic. + // - `T` may implement Drop. + // - Since we already have a `value: T`, we can clone `n - 1` times. + + // This loop runs at most `n - 1` times, for all slots except the last one. + // As per the guarantee of `reserve`, increments to `ptr` within this range won't wrap around. + + // if clone() panics and starts unwinding; + // - the write has not been done yet + // - the length will be set by SetLenOnDrop, to the amount of initialized elements + // - later, when the Vec is dropped, only initialized elements are dropped. + // SAFETY: According to the diagram above, this write is within bounds. + unsafe { ptr::write(ptr, value.clone()) }; + // SAFETY: According to the diagram above, this increment is within bounds of the + // allocation and won't wrap around + ptr = unsafe { ptr.add(1) }; + // Increment the length of SetLenOnDrop in every step in case clone() panics to drop the + // already-initialized elements. + local_len.increment_len(1); + } + + if n > 0 { + // We can write the last element directly without cloning needlessly + + // SAFETY: According to the diagram above, the last element is not yet written, + // so this write is within bounds. + unsafe { ptr::write(ptr, value) }; + local_len.increment_len(1); + } + + // len set by scope guard + } +} + +impl SpecExtendWith for Vec { + fn spec_extend_with(&mut self, n: usize, value: T) { + // The `n == 0` check is already being inserted by the loop canonicalization pass, + // so this costs nothing. + // https://llvm.org/docs/LoopTerminology.html#more-canonical-loops + if n == 0 { + // three things: + // `self.reserve(0)` does not need to be run, since reserving space for 0 elements + // is a no-op. since the `value` argument did not have anywhere to be moved to, it is + // dropped here. with this branch present here, we can elide the write through self.len, + // since `self.len += 0` would be a no-op. + return; + } + + self.reserve(n); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let ptr = unsafe { self.as_mut_ptr().add(self.len()) }; + + let mut i = 0; + // Write all the elements by copying `value`. + // We use an incrementing index here instead of incrementing pointer because the former + // has been observed to have less register pressure in the loop initialization. + // https://llvm.org/docs/Vectorizers.html#inductions + #[cfg_attr(kani, kani::loop_invariant(i <= n))] + #[cfg_attr(kani, kani::loop_modifies(&i, ptr::slice_from_raw_parts_mut(ptr, n)))] + while i < n { + // SAFETY: `TrivialClone` indicates that copying `value` is equivalent to + // calling `Clone::clone` for `T`. As per the safety comment for `ptr`, this pointer + // is within bounds, won't wrap around while `i < n`, and valid for writes. The values + // do not overlap since `value` is stored as a function argument, and the target is + // in the Vec. + unsafe { ptr.add(i).copy_from_nonoverlapping(&value, 1) }; + + // Because above is infallible, we don't need to worry about setting the len + // in this loop, and instead we just increment the loop induction variable. + i += 1; + } + + // Above, `n` items have been infallibly copied into the vector + self.len += n; + + // The reason we did not treat the last position in the vector specially by doing + // `n - 1` copies and semantically moving `value` into it is that we are forced to do `n` + // copies of the value no matter what, and it's better to do it in the above loop than + // by manually writing since it can be vectorized. + // Then, `value` was never semantically moved into the vec, only copied from, + // so we forget it here to prevent the Drop. + mem::forget(value); + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/original/vec_mod.rs b/verifast-proofs/alloc/vec/mod.rs/original/vec_mod.rs new file mode 100644 index 0000000000000..d6bb6c303febe --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/original/vec_mod.rs @@ -0,0 +1,4966 @@ +//! A contiguous growable array type with heap-allocated contents, written +//! `Vec`. +//! +//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and +//! *O*(1) pop (from the end). +//! +//! Vectors ensure they never allocate more than `isize::MAX` bytes. +//! +//! # Examples +//! +//! You can explicitly create a [`Vec`] with [`Vec::new`]: +//! +//! ``` +//! let v: Vec = Vec::new(); +//! ``` +//! +//! ...or by using the [`vec!`] macro: +//! +//! ``` +//! let v: Vec = vec![]; +//! +//! let v = vec![1, 2, 3, 4, 5]; +//! +//! let v = vec![0; 10]; // ten zeroes +//! ``` +//! +//! You can [`push`] values onto the end of a vector (which will grow the vector +//! as needed): +//! +//! ``` +//! let mut v = vec![1, 2]; +//! +//! v.push(3); +//! ``` +//! +//! Popping values works in much the same way: +//! +//! ``` +//! let mut v = vec![1, 2]; +//! +//! let two = v.pop(); +//! ``` +//! +//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): +//! +//! ``` +//! let mut v = vec![1, 2, 3]; +//! let three = v[2]; +//! v[1] = v[1] + 5; +//! ``` +//! +//! # Memory layout +//! +//! A [`Vec`] conceptually consists of a raw pointer `ptr` to the start of the allocation, a +//! length `len`, a capacity `cap`, and an allocator `alloc`. +//! While the exact fields and their order are not specified, a [`Vec`] can be converted to and +//! from these parts using [`Vec::into_raw_parts_with_allocator`], [`Vec::from_raw_parts_in`], +//! [`Vec::into_raw_parts`], and [`Vec::from_raw_parts`], as well as their [`NonNull`]-based +//! versions. +//! +//! The parts of a [`Vec`] have the following invariants: +//! +//! * If [`size_of::()`](size_of) and `cap` are non-zero, then: +//! - `ptr` must point to the start of a memory block [*currently allocated*] via `alloc`. +//! - [`Layout::array::(cap)`] must [*fit*] the memory block of `ptr`. In particular, +//! * `T` must have the same alignment as the [`Layout`] `ptr` was allocated with, and +//! * `size_of::() * cap` must be at least the size of the [`Layout`] `ptr` was +//! allocated with, and at most the size of the allocation returned the allocator. +//! - `size_of::() * cap` must be at most [`isize::MAX`]. +//! See the safety documentation of [`pointer::offset`]. +//! * If [`size_of::()`](size_of) or `cap` is zero, then `ptr` must be any sufficiently aligned non-null pointer. +//! +//! NOTE: `ptr` will not be passed to the allocator for deallocation by the destructor of [`Vec`] +//! in this case. Thus, it is unwise to use a pointer acquired from the allocator for this, as +//! overallocated memory may end up being leaked. Use [`ptr::dangling`] instead. +//! * The following must always be satisfied: +//! - `len` needs to be less than or equal to `cap`. +//! - At `ptr`, there are at least `len` valid values of type `T`, laid out contiguously +//! (like an array). These values are considered owned by the [`Vec`]. +//! +//! It is sound to create a [`Vec`] from parts that satisfy these invariants. +//! +//! Conversely, the memory backing `ptr` obtained from [`Vec::as_mut_ptr`] or +//! [`Vec::into_raw_parts_with_allocator`]-like methods may be deallocated +//! using the allocator, with layout [`Layout::array::(cap)`], provided +//! that [`size_of::()`](size_of) or `cap` is non-zero. +//! To automatically handle the case where the allocation is zero-sized, +//! it is recommended to use [`Vec::from_raw_parts_in`], instead of manually +//! deallocating. +//! +//! [*fit*]: crate::alloc::Allocator#memory-fitting +//! [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory +//! [`allocate`]: crate::alloc::Allocator::allocate +//! [`push`]: Vec::push +//! [`ptr::NonNull::dangling`]: NonNull::dangling +//! [`Layout`]: crate::alloc::Layout +//! [`Layout::array::(cap)`]: crate::alloc::Layout::array + +#![stable(feature = "rust1", since = "1.0.0")] + +#[cfg(not(no_global_oom_handling))] +use core::clone::TrivialClone; +use core::cmp::Ordering; +use core::hash::{Hash, Hasher}; +#[cfg(not(no_global_oom_handling))] +use core::iter; +#[cfg(kani)] +use core::kani; +use core::marker::{Destruct, Freeze, PhantomData}; +use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom}; +use core::ops::{self, Index, IndexMut, Range, RangeBounds}; +use core::ptr::{self, NonNull}; +use core::slice::{self, SliceIndex}; +use core::{cmp, fmt, hint, intrinsics, ub_checks}; + +use safety::{ensures, requires}; + +#[stable(feature = "extract_if", since = "1.87.0")] +pub use self::extract_if::ExtractIf; +use crate::alloc::{Allocator, AllocatorNightly, Global}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::collections::TryReserveError; +use crate::raw_vec::RawVec; + +mod extract_if; + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_splice", since = "1.21.0")] +pub use self::splice::Splice; + +#[cfg(not(no_global_oom_handling))] +mod splice; + +#[stable(feature = "drain", since = "1.6.0")] +pub use self::drain::Drain; + +mod drain; + +#[cfg(not(no_global_oom_handling))] +mod cow; + +#[cfg(not(no_global_oom_handling))] +pub(crate) use self::in_place_collect::AsVecIntoIter; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::into_iter::IntoIter; + +mod into_iter; + +#[cfg(not(no_global_oom_handling))] +use self::is_zero::IsZero; + +#[cfg(not(no_global_oom_handling))] +mod is_zero; + +#[cfg(not(no_global_oom_handling))] +mod in_place_collect; + +mod partial_eq; + +#[unstable(feature = "vec_peek_mut", issue = "122742")] +pub use self::peek_mut::PeekMut; + +mod peek_mut; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_elem::SpecFromElem; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_elem; + +#[cfg(all(kani, not(no_global_oom_handling)))] +#[unstable(feature = "kani", issue = "none")] +mod verify_ch23; + +/// Kani-only: partial check of documented `Vec` raw-parts layout invariants (see module docs). +/// Checks `length <= capacity`, non-null and alignment of `ptr`, `Layout::array::(capacity)` +/// fitting within `isize::MAX` bytes, `can_write`, base-offset-0 (rejecting interior pointers +/// via `!same_allocation(ptr, ptr - 1)`), and in-bounds byte extent of at least +/// `capacity * size_of::()` (permitting legal over-allocated custom-allocator blocks). +/// Remaining caller safety obligations NOT machine-checked by this predicate (due to Kani/CBMC +/// limitations) remain documented caller preconditions: (1) `ptr` was allocated via the matching +/// `Allocator` instance, (2) `ptr` was allocated with `T`'s exact alignment and a fitting layout +/// (`requested_size <= capacity * size_of::() <= actual_size`), and (3) the first `length` +/// elements are initialized to valid values of `T`. +#[cfg(kani)] +fn vec_parts_valid(ptr: *mut T, length: usize, capacity: usize) -> bool { + length <= capacity + && !ptr.is_null() + && ptr.is_aligned() + && (T::IS_ZST || crate::alloc::Layout::array::(capacity).is_ok()) + && ub_checks::can_write(ptr::slice_from_raw_parts_mut(ptr, capacity)) + && (T::IS_ZST + || capacity == 0 + || (kani::mem::is_inbounds(ptr::slice_from_raw_parts( + ptr as *const u8, + capacity * mem::size_of::(), + )) && !kani::mem::same_allocation( + ptr as *const u8, + (ptr as *const u8).wrapping_byte_sub(1), + ))) +} + +#[cfg(not(no_global_oom_handling))] +use self::set_len_on_drop::SetLenOnDrop; + +#[cfg(not(no_global_oom_handling))] +mod set_len_on_drop; + +#[cfg(not(no_global_oom_handling))] +use self::in_place_drop::{InPlaceDrop, InPlaceDstDataSrcBufDrop}; + +#[cfg(not(no_global_oom_handling))] +mod in_place_drop; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_iter_nested::SpecFromIterNested; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_iter_nested; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_iter::SpecFromIter; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_iter; + +#[cfg(not(no_global_oom_handling))] +use self::spec_extend::SpecExtend; + +#[cfg(not(no_global_oom_handling))] +mod spec_extend; + +#[cfg(not(no_global_oom_handling))] +use self::spec_extend_with::SpecExtendWith; + +#[cfg(not(no_global_oom_handling))] +mod spec_extend_with; + +#[cfg(all(target_arch = "aarch64", target_feature = "sve"))] +mod sve_retain; + +/// A contiguous growable array type, written as `Vec`, short for 'vector'. +/// +/// # Examples +/// +/// ``` +/// let mut vec = Vec::new(); +/// vec.push(1); +/// vec.push(2); +/// +/// assert_eq!(vec.len(), 2); +/// assert_eq!(vec[0], 1); +/// +/// assert_eq!(vec.pop(), Some(2)); +/// assert_eq!(vec.len(), 1); +/// +/// vec[0] = 7; +/// assert_eq!(vec[0], 7); +/// +/// vec.extend([1, 2, 3]); +/// +/// for x in &vec { +/// println!("{x}"); +/// } +/// assert_eq!(vec, [7, 1, 2, 3]); +/// ``` +/// +/// The [`vec!`] macro is provided for convenient initialization: +/// +/// ``` +/// let mut vec1 = vec![1, 2, 3]; +/// vec1.push(4); +/// let vec2 = Vec::from([1, 2, 3, 4]); +/// assert_eq!(vec1, vec2); +/// ``` +/// +/// It can also initialize each element of a `Vec` with a given value. +/// This may be more efficient than performing allocation and initialization +/// in separate steps, especially when initializing a vector of zeros: +/// +/// ``` +/// let vec = vec![0; 5]; +/// assert_eq!(vec, [0, 0, 0, 0, 0]); +/// +/// // The following is equivalent, but potentially slower: +/// let mut vec = Vec::with_capacity(5); +/// vec.resize(5, 0); +/// assert_eq!(vec, [0, 0, 0, 0, 0]); +/// ``` +/// +/// For more information, see +/// [Capacity and Reallocation](#capacity-and-reallocation). +/// +/// Use a `Vec` as an efficient stack: +/// +/// ``` +/// let mut stack = Vec::new(); +/// +/// stack.push(1); +/// stack.push(2); +/// stack.push(3); +/// +/// while let Some(top) = stack.pop() { +/// // Prints 3, 2, 1 +/// println!("{top}"); +/// } +/// ``` +/// +/// # Indexing +/// +/// The `Vec` type allows access to values by index, because it implements the +/// [`Index`] trait. An example will be more explicit: +/// +/// ``` +/// let v = vec![0, 2, 4, 6]; +/// println!("{}", v[1]); // it will display '2' +/// ``` +/// +/// However be careful: if you try to access an index which isn't in the `Vec`, +/// your software will panic! You cannot do this: +/// +/// ```should_panic +/// let v = vec![0, 2, 4, 6]; +/// println!("{}", v[6]); // it will panic! +/// ``` +/// +/// Use [`get`] and [`get_mut`] if you want to check whether the index is in +/// the `Vec`. +/// +/// # Slicing +/// +/// A `Vec` can be mutable. On the other hand, slices are read-only objects. +/// To get a [slice][prim@slice], use [`&`]. Example: +/// +/// ``` +/// fn read_slice(slice: &[usize]) { +/// // ... +/// } +/// +/// let v = vec![0, 1]; +/// read_slice(&v); +/// +/// // ... and that's all! +/// // you can also do it like this: +/// let u: &[usize] = &v; +/// // or like this: +/// let u: &[_] = &v; +/// ``` +/// +/// In Rust, it's more common to pass slices as arguments rather than vectors +/// when you just want to provide read access. The same goes for [`String`] and +/// [`&str`]. +/// +/// # Capacity and reallocation +/// +/// The capacity of a vector is the amount of space allocated for any future +/// elements that will be added onto the vector. This is not to be confused with +/// the *length* of a vector, which specifies the number of actual elements +/// within the vector. If a vector's length exceeds its capacity, its capacity +/// will automatically be increased, but its elements will have to be +/// reallocated. +/// +/// For example, a vector with capacity 10 and length 0 would be an empty vector +/// with space for 10 more elements. Pushing 10 or fewer elements onto the +/// vector will not change its capacity or cause reallocation to occur. However, +/// if the vector's length is increased to 11, it will have to reallocate, which +/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] +/// whenever possible to specify how big the vector is expected to get. +/// +/// # Guarantees +/// +/// The following section is to be read as an addendum of the +/// [memory layout](self#memory-layout) section. +/// +/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees +/// about its design. This ensures that it's as low-overhead as possible in +/// the general case, and can be correctly manipulated in primitive ways +/// by unsafe code. +/// +/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be +/// visualized as below. The top part is the `Vec` struct, it contains a +/// pointer to the head of the allocation in the heap, length and capacity. +/// The bottom part is the allocation on the heap, a contiguous memory block. +/// +/// ```text +/// ptr len capacity +/// +--------+--------+--------+ +/// | 0x0123 | 2 | 4 | +/// +--------+--------+--------+ +/// | +/// v +/// Heap +--------+--------+--------+--------+ +/// | 'a' | 'b' | uninit | uninit | +/// +--------+--------+--------+--------+ +/// ``` +/// +/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`]. +/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory +/// layout (including the order of fields). +/// +/// `Vec` will never perform a "small optimization" where elements are actually +/// stored on the stack for two reasons: +/// +/// * It would make it more difficult for unsafe code to correctly manipulate +/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were +/// only moved, and it would be more difficult to determine if a `Vec` had +/// actually allocated memory. +/// +/// * It would penalize the general case, incurring an additional branch +/// on every access. +/// +/// `Vec` will never automatically shrink itself, even if completely empty. This +/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` +/// and then filling it back up to the same [`len`] should incur no calls to +/// the allocator. If you wish to free up unused memory, use +/// [`shrink_to_fit`] or [`shrink_to`]. +/// +/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is +/// sufficient. [`push`] and [`insert`] *will* (re)allocate if +/// [len] == [capacity]. That is, the reported capacity is completely +/// accurate, and can be relied on. It can even be used to manually free the memory +/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even +/// when not necessary. +/// +/// `Vec` does not guarantee any particular growth strategy when reallocating +/// when full, nor when [`reserve`] is called. The current strategy is basic +/// and it may prove desirable to use a non-constant growth factor. Whatever +/// strategy is used will of course guarantee *O*(1) amortized [`push`]. +/// +/// It is guaranteed, in order to respect the intentions of the programmer, that +/// all of `vec![e_1, e_2, ..., e_n]`, `vec![x; n]`, and [`Vec::with_capacity(n)`] produce a `Vec` +/// that requests an allocation of the exact size needed for precisely `n` elements from the allocator, +/// and no other size (such as, for example: a size rounded up to the nearest power of 2). +/// The allocator will return an allocation that is at least as large as requested, but it may be larger. +/// +/// It is guaranteed that the [`Vec::capacity`] method returns a value that is at least the requested capacity +/// and not more than the allocated capacity. +/// +/// The method [`Vec::shrink_to_fit`] will attempt to discard excess capacity an allocator has given to a `Vec`. +/// If [len] == [capacity], then a `Vec` can be converted +/// to and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. +/// `Vec` exploits this fact as much as reasonable when implementing common conversions +/// such as [`into_boxed_slice`]. +/// +/// `Vec` will not specifically overwrite any data that is removed from it, +/// but also won't specifically preserve it. Its uninitialized memory is +/// scratch space that it may use however it wants. It will generally just do +/// whatever is most efficient or otherwise easy to implement. Do not rely on +/// removed data to be erased for security purposes. Even if you drop a `Vec`, its +/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory +/// first, that might not actually happen because the optimizer does not consider +/// this a side-effect that must be preserved. There is one case which we will +/// not break, however: using `unsafe` code to write to the excess capacity, +/// and then increasing the length to match, is always valid. +/// +/// Currently, `Vec` does not guarantee the order in which elements are dropped. +/// The order has changed in the past and may change again. +/// +/// [`get`]: slice::get +/// [`get_mut`]: slice::get_mut +/// [`String`]: crate::string::String +/// [`&str`]: type@str +/// [`shrink_to_fit`]: Vec::shrink_to_fit +/// [`shrink_to`]: Vec::shrink_to +/// [capacity]: Vec::capacity +/// [`capacity`]: Vec::capacity +/// [`Vec::capacity`]: Vec::capacity +/// [size_of::\]: size_of +/// [len]: Vec::len +/// [`len`]: Vec::len +/// [`push`]: Vec::push +/// [`insert`]: Vec::insert +/// [`reserve`]: Vec::reserve +/// [`Vec::with_capacity(n)`]: Vec::with_capacity +/// [`MaybeUninit`]: core::mem::MaybeUninit +/// [owned slice]: Box +/// [`into_boxed_slice`]: Vec::into_boxed_slice +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_diagnostic_item = "Vec"] +#[rustc_insignificant_dtor] +#[doc(alias = "list")] +#[doc(alias = "vector")] +pub struct Vec { + buf: RawVec, + len: usize, +} + +//////////////////////////////////////////////////////////////////////////////// +// Inherent methods +//////////////////////////////////////////////////////////////////////////////// + +impl Vec { + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unused_mut)] + /// let mut vec: Vec = Vec::new(); + /// ``` + #[inline] + #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] + #[rustc_diagnostic_item = "vec_new"] + #[stable(feature = "rust1", since = "1.0.0")] + #[must_use] + pub const fn new() -> Self { + Vec { buf: RawVec::new(), len: 0 } + } + + /// Constructs a new, empty `Vec` with at least the specified capacity. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, the vector + /// [will not allocate], and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// [will not allocate]: self#memory-layout + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert!(vec.capacity() >= 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert!(vec.capacity() >= 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<()>::with_capacity(10); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[must_use] + #[rustc_diagnostic_item = "vec_with_capacity"] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn with_capacity(capacity: usize) -> Self { + Self::with_capacity_in(capacity, Global) + } + + /// Constructs a new, empty `Vec` with at least the specified capacity. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// # Errors + /// + /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, + /// or if the allocator reports allocation failure. + /// + /// [will not allocate]: self#memory-layout + #[inline] + #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity(capacity: usize) -> Result { + Self::try_with_capacity_in(capacity, Global) + } + + /// Creates a `Vec` directly from a pointer, a length, and a capacity. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section, + /// with allocator [`Global`]. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is normally **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length + /// `size_t`, doing so is only safe if the array was initially allocated by + /// a `Vec` or `String`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. To avoid + /// these issues, it is often preferable to do casting/transmuting using + /// [`slice::from_raw_parts`] instead. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::ptr; + /// + /// let v = vec![1, 2, 3]; + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap) = v.into_raw_parts(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// ptr::write(p.add(i), 4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_raw_parts(p, len, cap); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{alloc, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = alloc(layout).cast::(); + /// if mem.is_null() { + /// return; + /// } + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts(mem, 1, 16) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr, length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } + } + + #[doc(alias = "from_non_null_parts")] + /// Creates a `Vec` directly from a `NonNull` pointer, a length, and a capacity. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section, + /// with allocator [`Global`]. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is normally **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length + /// `size_t`, doing so is only safe if the array was initially allocated by + /// a `Vec` or `String`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. To avoid + /// these issues, it is often preferable to do casting/transmuting using + /// [`NonNull::slice_from_raw_parts`] instead. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// let v = vec![1, 2, 3]; + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap) = v.into_parts(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// p.add(i).write(4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_parts(p, len, cap); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{alloc, Layout}; + /// use std::ptr::NonNull; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let Some(mem) = NonNull::new(alloc(layout).cast::()) else { + /// return; + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_parts(mem, 1, 16) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "box_vec_non_null", since = "1.99.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_parts(ptr: NonNull, length: usize, capacity: usize) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_parts_in(ptr, length, capacity, Global) } + } + + /// Creates a `Vec` where each element is produced by calling `f` with + /// that element's index while walking forward through the `Vec`. + /// + /// This is essentially the same as writing + /// + /// ```text + /// vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)] + /// ``` + /// and is similar to `(0..i).map(f)`, just for `Vec`s not iterators. + /// + /// If `length == 0`, this produces an empty `Vec` without ever calling `f`. + /// + /// # Example + /// + /// ```rust + /// let vec = Vec::from_fn(5, |i| i); + /// + /// // indexes are: 0 1 2 3 4 + /// assert_eq!(vec, [0, 1, 2, 3, 4]); + /// + /// let vec2 = Vec::from_fn(8, |i| i * 2); + /// + /// // indexes are: 0 1 2 3 4 5 6 7 + /// assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]); + /// + /// let bool_vec = Vec::from_fn(5, |i| i % 2 == 0); + /// + /// // indexes are: 0 1 2 3 4 + /// assert_eq!(bool_vec, [true, false, true, false, true]); + /// ``` + /// + /// The `Vec` is generated in ascending index order, starting from the front + /// and going towards the back, so you can use closures with mutable state: + /// ``` + /// let mut state = 1; + /// let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x }); + /// + /// assert_eq!(a, [1, 2, 4, 8, 16, 32]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "vec_from_fn", since = "1.100.0")] + pub fn from_fn(length: usize, f: F) -> Self + where + F: FnMut(usize) -> T, + { + (0..length).map(f).collect() + } + + /// Decomposes a `Vec` into its raw components: `(pointer, length, capacity)`. + /// + /// Returns the raw pointer to the underlying data, the length of + /// the vector (in elements), and the allocated capacity of the + /// data (in elements). These are the same arguments in the same + /// order as the arguments to [`from_raw_parts`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. Most often, one does + /// this by converting the raw pointer, length, and capacity back + /// into a `Vec` with the [`from_raw_parts`] function; more generally, + /// if `T` is non-zero-sized and the capacity is nonzero, one may use + /// any method that calls [`dealloc`] with a layout of + /// `Layout::array::(capacity)`; if `T` is zero-sized or the + /// capacity is zero, nothing needs to be done. + /// + /// [`from_raw_parts`]: Vec::from_raw_parts + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// + /// # Examples + /// + /// ``` + /// let v: Vec = vec![-1, 0, 1]; + /// + /// let (ptr, len, cap) = v.into_raw_parts(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr as *mut u32; + /// + /// Vec::from_raw_parts(ptr, len, cap) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "vec_into_raw_parts", since = "1.93.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_raw_parts(self) -> (*mut T, usize, usize) { + let mut me = ManuallyDrop::new(self); + (me.as_mut_ptr(), me.len(), me.capacity()) + } + + #[doc(alias = "into_non_null_parts")] + /// Decomposes a `Vec` into its raw components: `(NonNull pointer, length, capacity)`. + /// + /// Returns the `NonNull` pointer to the underlying data, the length of + /// the vector (in elements), and the allocated capacity of the + /// data (in elements). These are the same arguments in the same + /// order as the arguments to [`from_parts`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the `NonNull` pointer, length, and capacity back + /// into a `Vec` with the [`from_parts`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_parts`]: Vec::from_parts + /// + /// # Examples + /// + /// ``` + /// let v: Vec = vec![-1, 0, 1]; + /// + /// let (ptr, len, cap) = v.into_parts(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr.cast::(); + /// + /// Vec::from_parts(ptr, len, cap) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "box_vec_non_null", since = "1.99.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_parts(self) -> (NonNull, usize, usize) { + let (ptr, len, capacity) = self.into_raw_parts(); + // SAFETY: A `Vec` always has a non-null pointer. + (unsafe { NonNull::new_unchecked(ptr) }, len, capacity) + } + + /// Interns the `Vec`, making the underlying memory read-only. This method should be + /// called during compile time. (This is a no-op if called during runtime) + /// + /// This method must be called if the memory used by `Vec` needs to appear in the final + /// values of constants. + #[unstable(feature = "const_heap", issue = "79597")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn const_make_global(mut self) -> &'static [T] + where + T: Freeze, + { + // `const_make_global` requires the pointer to point to the beginning of a heap allocation, + // which is not the case when `self.capacity()` is 0, or if `T::IS_ZST`, + // which is why we instead return a new slice in this case. + if self.capacity() == 0 || T::IS_ZST { + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(NonNull::::dangling().as_ptr(), me.len) } + } else { + // ignore-tidy-undocumented-unsafe + unsafe { core::intrinsics::const_make_global(self.as_mut_ptr().cast()) }; + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(me.as_ptr(), me.len) } + } + } +} + +#[cfg(not(no_global_oom_handling))] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl Vec { + /// Constructs a new, empty `Vec` with at least the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, the vector + /// [will not allocate], and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// [will not allocate]: self#memory-layout + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut vec = Vec::with_capacity_in(10, System); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert!(vec.capacity() >= 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert!(vec.capacity() >= 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } + } + + /// Appends an element to the back of a collection. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2]; + /// vec.push(3); + /// assert_eq!(vec, [1, 2, 3]); + /// ``` + /// + /// # Time complexity + /// + /// Takes amortized *O*(1) time. If the vector's length would exceed its + /// capacity after the push, *O*(*capacity*) time is taken to copy the + /// vector's elements to a larger allocation. This expensive operation is + /// offset by the *capacity* *O*(1) insertions it allows. + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_confusables("push_back", "put", "append")] + pub fn push(&mut self, value: T) { + let _ = self.push_mut(value); + } + + /// Appends an element to the back of a collection, returning a reference to it. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2]; + /// let last = vec.push_mut(3); + /// assert_eq!(*last, 3); + /// assert_eq!(vec, [1, 2, 3]); + /// + /// let last = vec.push_mut(3); + /// *last += 1; + /// assert_eq!(vec, [1, 2, 3, 4]); + /// ``` + /// + /// # Time complexity + /// + /// Takes amortized *O*(1) time. If the vector's length would exceed its + /// capacity after the push, *O*(*capacity*) time is taken to copy the + /// vector's elements to a larger allocation. This expensive operation is + /// offset by the *capacity* *O*(1) insertions it allows. + #[inline] + #[stable(feature = "push_mut", since = "1.95.0")] + #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"] + pub fn push_mut(&mut self, value: T) -> &mut T { + // Inform codegen that the length does not change across grow_one(). + let len = self.len; + // This will panic or abort if we would allocate > isize::MAX bytes + // or if the length increment would overflow for zero-sized types. + if len == self.buf.capacity() { + self.buf.grow_one(); + } + // ignore-tidy-undocumented-unsafe + unsafe { + let end = self.as_mut_ptr().add(len); + ptr::write(end, value); + self.len = len + 1; + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + &mut *end + } + } +} + +impl Vec { + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let vec: Vec = Vec::new_in(System); + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")] + pub const fn new_in(alloc: A) -> Self { + Vec { buf: RawVec::new_in(alloc), len: 0 } + } + + /// Constructs a new, empty `Vec` with at least the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// # Errors + /// + /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, + /// or if the allocator reports allocation failure. + /// + /// [will not allocate]: self#memory-layout + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + // #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) + } + + /// Creates a `Vec` directly from a pointer, a length, a capacity, + /// and an allocator. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length `size_t`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [`allocate`]: crate::alloc::Allocator::allocate + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// use std::ptr; + /// + /// let mut v = Vec::with_capacity_in(3, System); + /// v.push(1); + /// v.push(2); + /// v.push(3); + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap, alloc) = v.into_raw_parts_with_allocator(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// ptr::write(p.add(i), 4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{AllocError, Allocator, Global, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = match Global.allocate(layout) { + /// Ok(mem) => mem.cast::().as_ptr(), + /// Err(AllocError) => return, + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts_in(mem, 1, 16, Global) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const unsafe fn from_raw_parts_in( + ptr: *mut T, + length: usize, + capacity: usize, + alloc: A, + ) -> Self { + ub_checks::assert_unsafe_precondition!( + check_library_ub, + "Vec::from_raw_parts_in requires that length <= capacity", + (length: usize = length, capacity: usize = capacity) => length <= capacity + ); + // SAFETY: Upheld by caller. + unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } + } + + #[doc(alias = "from_non_null_parts_in")] + /// Creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, + /// and an allocator. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length `size_t`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v = Vec::with_capacity_in(3, System); + /// v.push(1); + /// v.push(2); + /// v.push(3); + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap, alloc) = v.into_parts_with_allocator(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// p.add(i).write(4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone()); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{AllocError, Allocator, Global, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = match Global.allocate(layout) { + /// Ok(mem) => mem.cast::(), + /// Err(AllocError) => return, + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_parts_in(mem, 1, 16, Global) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_parts_in( + ptr: NonNull, + length: usize, + capacity: usize, + alloc: A, + ) -> Self { + ub_checks::assert_unsafe_precondition!( + check_library_ub, + "Vec::from_parts_in requires that length <= capacity", + (length: usize = length, capacity: usize = capacity) => length <= capacity + ); + // SAFETY: Upheld by caller. + unsafe { Vec { buf: RawVec::from_nonnull_in(ptr, capacity, alloc), len: length } } + } + + /// Decomposes a `Vec` into its raw components: `(pointer, length, capacity, allocator)`. + /// + /// Returns the raw pointer to the underlying data, the length of the vector (in elements), + /// the allocated capacity of the data (in elements), and the allocator. These are the same + /// arguments in the same order as the arguments to [`from_raw_parts_in`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the raw pointer, length, and capacity back + /// into a `Vec` with the [`from_raw_parts_in`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_raw_parts_in`]: Vec::from_raw_parts_in + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v: Vec = Vec::new_in(System); + /// v.push(-1); + /// v.push(0); + /// v.push(1); + /// + /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr as *mut u32; + /// + /// Vec::from_raw_parts_in(ptr, len, cap, alloc) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_raw_parts_with_allocator(self) -> (*mut T, usize, usize, A) { + let mut me = ManuallyDrop::new(self); + let len = me.len(); + let capacity = me.capacity(); + let ptr = me.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + let alloc = unsafe { ptr::read(me.allocator()) }; + (ptr, len, capacity, alloc) + } + + #[doc(alias = "into_non_null_parts_with_alloc")] + /// Decomposes a `Vec` into its raw components: `(NonNull pointer, length, capacity, allocator)`. + /// + /// Returns the `NonNull` pointer to the underlying data, the length of the vector (in elements), + /// the allocated capacity of the data (in elements), and the allocator. These are the same + /// arguments in the same order as the arguments to [`from_parts_in`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the `NonNull` pointer, length, and capacity back + /// into a `Vec` with the [`from_parts_in`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_parts_in`]: Vec::from_parts_in + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v: Vec = Vec::new_in(System); + /// v.push(-1); + /// v.push(0); + /// v.push(1); + /// + /// let (ptr, len, cap, alloc) = v.into_parts_with_allocator(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr.cast::(); + /// + /// Vec::from_parts_in(ptr, len, cap, alloc) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_parts_with_allocator(self) -> (NonNull, usize, usize, A) { + let (ptr, len, capacity, alloc) = self.into_raw_parts_with_allocator(); + // SAFETY: A `Vec` always has a non-null pointer. + (unsafe { NonNull::new_unchecked(ptr) }, len, capacity, alloc) + } + + /// Returns the total number of elements the vector can hold without + /// reallocating. + /// + /// # Examples + /// + /// ``` + /// let mut vec: Vec = Vec::with_capacity(10); + /// vec.push(42); + /// assert!(vec.capacity() >= 10); + /// ``` + /// + /// A vector with zero-sized elements will always have a capacity of usize::MAX: + /// + /// ``` + /// #[derive(Clone)] + /// struct ZeroSized; + /// + /// fn main() { + /// assert_eq!(std::mem::size_of::(), 0); + /// let v = vec![ZeroSized; 0]; + /// assert_eq!(v.capacity(), usize::MAX); + /// } + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn capacity(&self) -> usize { + self.buf.capacity() + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the given `Vec`. The collection may reserve more space to + /// speculatively avoid frequent reallocations. After calling `reserve`, + /// capacity will be greater than or equal to `self.len() + additional`. + /// Does nothing if capacity is already sufficient. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.reserve(10); + /// assert!(vec.capacity() >= 11); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_reserve"] + pub fn reserve(&mut self, additional: usize) { + self.buf.reserve(self.len, additional); + } + + /// Reserves the minimum capacity for at least `additional` more elements to + /// be inserted in the given `Vec`. Unlike [`reserve`], this will not + /// deliberately over-allocate to speculatively avoid frequent allocations. + /// After calling `reserve_exact`, capacity will be greater than or equal to + /// `self.len() + additional`. Does nothing if the capacity is already + /// sufficient. + /// + /// Note that the allocator may give the collection more space than it + /// requests. Therefore, capacity can not be relied upon to be precisely + /// minimal. Prefer [`reserve`] if future insertions are expected. + /// + /// [`reserve`]: Vec::reserve + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.reserve_exact(10); + /// assert!(vec.capacity() >= 11); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn reserve_exact(&mut self, additional: usize) { + self.buf.reserve_exact(self.len, additional); + } + + /// Tries to reserve capacity for at least `additional` more elements to be inserted + /// in the given `Vec`. The collection may reserve more space to speculatively avoid + /// frequent reallocations. After calling `try_reserve`, capacity will be + /// greater than or equal to `self.len() + additional` if it returns + /// `Ok(())`. Does nothing if capacity is already sufficient. This method + /// preserves the contents even if an error occurs. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use std::collections::TryReserveError; + /// + /// fn process_data(data: &[u32]) -> Result, TryReserveError> { + /// let mut output = Vec::new(); + /// + /// // Pre-reserve the memory, exiting if we can't + /// output.try_reserve(data.len())?; + /// + /// // Now we know this can't OOM in the middle of our complex work + /// output.extend(data.iter().map(|&val| { + /// val * 2 + 5 // very complicated + /// })); + /// + /// Ok(output) + /// } + /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail"); + /// ``` + #[stable(feature = "try_reserve", since = "1.57.0")] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.buf.try_reserve(self.len, additional) + } + + /// Tries to reserve the minimum capacity for at least `additional` + /// elements to be inserted in the given `Vec`. Unlike [`try_reserve`], + /// this will not deliberately over-allocate to speculatively avoid frequent + /// allocations. After calling `try_reserve_exact`, capacity will be greater + /// than or equal to `self.len() + additional` if it returns `Ok(())`. + /// Does nothing if the capacity is already sufficient. + /// + /// Note that the allocator may give the collection more space than it + /// requests. Therefore, capacity can not be relied upon to be precisely + /// minimal. Prefer [`try_reserve`] if future insertions are expected. + /// + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use std::collections::TryReserveError; + /// + /// fn process_data(data: &[u32]) -> Result, TryReserveError> { + /// let mut output = Vec::new(); + /// + /// // Pre-reserve the memory, exiting if we can't + /// output.try_reserve_exact(data.len())?; + /// + /// // Now we know this can't OOM in the middle of our complex work + /// output.extend(data.iter().map(|&val| { + /// val * 2 + 5 // very complicated + /// })); + /// + /// Ok(output) + /// } + /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail"); + /// ``` + #[stable(feature = "try_reserve", since = "1.57.0")] + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.buf.try_reserve_exact(self.len, additional) + } + + /// Shrinks the capacity of the vector as much as possible. + /// + /// When `vec.len() == vec.capacity()` the allocation is unchanged. Otherwise, the behavior of + /// this method depends on the allocator, which may either shrink the vector in-place or + /// reallocate. The resulting vector might still have some excess capacity, just as + /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details. + /// + /// [`with_capacity`]: Vec::with_capacity + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.shrink_to_fit(); + /// assert!(vec.capacity() >= 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn shrink_to_fit(&mut self) { + // The capacity is never less than the length, and there's nothing to do when + // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` + // by only calling it with a greater capacity. + if self.capacity() > self.len { + self.buf.shrink_to_fit(self.len); + } + } + + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// If the current capacity is less than the lower limit, this is a no-op. + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.shrink_to(4); + /// assert!(vec.capacity() >= 4); + /// vec.shrink_to(0); + /// assert!(vec.capacity() >= 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "shrink_to", since = "1.56.0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + if self.capacity() > min_capacity { + self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); + } + } + + /// Tries to shrink the capacity of the vector as much as possible + /// + /// The behavior of this method depends on the allocator, which may either shrink the vector + /// in-place or reallocate. The resulting vector might still have some excess capacity, just as + /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details. + /// + /// [`with_capacity`]: Vec::with_capacity + /// + /// # Errors + /// + /// This function returns an error if the allocator fails to shrink the allocation, + /// the vector thereafter is still safe to use, the capacity remains unchanged + /// however. See [`Allocator::shrink`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_fallible_shrink)] + /// + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.try_shrink_to_fit().expect("for this test, shrink shouldn't fail"); + /// assert!(vec.capacity() >= 3); + /// ``` + #[unstable(feature = "vec_fallible_shrink", issue = "152350")] + #[inline] + pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> { + if self.capacity() > self.len { self.buf.try_shrink_to_fit(self.len) } else { Ok(()) } + } + + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// If the current capacity is less than the lower limit, this is a no-op. + /// + /// # Errors + /// + /// This function returns an error if the allocator fails to shrink the allocation, + /// the vector thereafter is still safe to use, the capacity remains unchanged + /// however. See [`Allocator::shrink`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_fallible_shrink)] + /// + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.try_shrink_to(4).expect("for this test, shrink shouldn't fail"); + /// assert!(vec.capacity() >= 4); + /// vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved."); + /// assert!(vec.capacity() >= 3); + /// ``` + #[unstable(feature = "vec_fallible_shrink", issue = "152350")] + #[inline] + pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), TryReserveError> { + if self.capacity() > min_capacity { + self.buf.try_shrink_to_fit(cmp::max(self.len, min_capacity)) + } else { + Ok(()) + } + } + + /// Converts the vector into a boxed slice. + /// + /// This conversion is in-place if `vec.len() == vec.capacity()`. + /// + /// Before doing the conversion, this method adjusts the vector's allocation as + /// needed so that, if a backing allocation is present, the layout of the returned + /// slice [*fits*] that allocation. Thus, the vector's former capacity is not needed + /// to determine a layout suitable for deallocation. + /// + /// [*fits*]: crate::alloc::Allocator#memory-fitting + /// + /// # Examples + /// + /// ``` + /// let v = vec![1, 2, 3]; + /// + /// let slice = v.into_boxed_slice(); + /// ``` + /// + /// The vector's spare capacity is not retained: + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// + /// assert!(vec.capacity() >= 10); + /// let slice = vec.into_boxed_slice(); + /// assert_eq!(slice.into_vec().capacity(), 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn into_boxed_slice(mut self) -> Box<[T], A> { + self.shrink_to_fit(); + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { + let buf = ptr::read(&me.buf); + let len = me.len(); + buf.into_box(len).assume_init() + } + } + + /// Converts the Vec into a boxed array. This conversion will discard any spare capacity, + /// if there is any, see [`Vec::into_boxed_slice`]. + /// If you merely wish for a reference to an array, use [`as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array). + /// + /// # Errors + /// + /// Returns the original `Vec` in the `Err` variant if [`Vec::len`] does not equal `N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(alloc_slice_into_array)] + /// let vec: Vec = vec![1, 2, 3]; + /// let box_array: Box<[i32; 3]> = vec.clone().into_array().unwrap(); + /// let not_enough_elements: Result, Vec> = vec.into_array::<4>(); + /// assert_eq!(not_enough_elements, Err(vec![1, 2, 3])); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "alloc_slice_into_array", issue = "148082")] + pub fn into_array(self) -> Result, Self> { + if self.len() == N { + // SAFETY: `Box::into_array` is guaranteed to return `Ok` if the + // length of the slice is equal to `N`. + // `self.into_boxed_slice().len()` is equal to `self.len()`, + // which we just checked. + Ok(unsafe { self.into_boxed_slice().into_array().unwrap_unchecked() }) + } else { + Err(self) + } + } + + /// Shortens the vector, keeping the first `len` elements and dropping + /// the rest. + /// + /// If `len` is greater or equal to the vector's current length, this has + /// no effect. + /// + /// The [`drain`] method can emulate `truncate`, but causes the excess + /// elements to be returned instead of dropped. + /// + /// Note that this method has no effect on the allocated capacity + /// of the vector. + /// + /// # Examples + /// + /// Truncating a five element vector to two elements: + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4, 5]; + /// vec.truncate(2); + /// assert_eq!(vec, [1, 2]); + /// ``` + /// + /// No truncation occurs when `len` is greater than or equal to the + /// vector's current length: + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.truncate(8); + /// assert_eq!(vec, [1, 2, 3]); + /// ``` + /// + /// Truncating when `len == 0` is equivalent to calling the [`clear`] + /// method. + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.truncate(0); + /// assert_eq!(vec, []); + /// ``` + /// + /// [`clear`]: Vec::clear + /// [`drain`]: Vec::drain + #[stable(feature = "rust1", since = "1.0.0")] + pub fn truncate(&mut self, len: usize) { + // SAFETY: `BufWriter::flush_buf` assumes that this will not + // de-initialize any elements of the spare capacity. + + // This is safe because: + // + // * the slice passed to `drop_in_place` is valid; the `len >= self.len` + // case avoids creating an invalid slice, and + // * the `len` of the vector is shrunk before calling `drop_in_place`, + // such that no value will be dropped twice in case `drop_in_place` + // were to panic once (if it panics twice, the program aborts). + unsafe { + if len >= self.len { + return; + } + let remaining_len = self.len - len; + let s = self.as_mut_ptr().add(len).cast_slice(remaining_len); + self.len = len; + ptr::drop_in_place(s); + } + } + + /// Extracts a slice containing the entire vector. + /// + /// Equivalent to `&s[..]`. + /// + /// # Examples + /// + /// ``` + /// use std::io::{self, Write}; + /// let buffer = vec![1, 2, 3, 5, 8]; + /// io::sink().write(buffer.as_slice()).unwrap(); + /// ``` + #[inline] + #[stable(feature = "vec_as_slice", since = "1.7.0")] + #[rustc_diagnostic_item = "vec_as_slice"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn as_slice(&self) -> &[T] { + // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size + // `len` containing properly-initialized `T`s. Data must not be mutated for the returned + // lifetime. Further, `len * size_of::` <= `isize::MAX`, and allocation does not + // "wrap" through overflowing memory addresses. + // + // * Vec API guarantees that self.buf: + // * contains only properly-initialized items within 0..len + // * is aligned, contiguous, and valid for `len` reads + // * obeys size and address-wrapping constraints + // + // * We only construct `&mut` references to `self.buf` through `&mut self` methods; borrow- + // check ensures that it is not possible to mutably alias `self.buf` within the + // returned lifetime. + unsafe { + // normally this would use `slice::from_raw_parts`, but it's + // instantiated often enough that avoiding the UB check is worth it + &*core::intrinsics::aggregate_raw_ptr::<*const [T], _, _>(self.as_ptr(), self.len) + } + } + + /// Extracts a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + /// + /// # Examples + /// + /// ``` + /// use std::io::{self, Read}; + /// let mut buffer = vec![0; 3]; + /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); + /// ``` + #[inline] + #[stable(feature = "vec_as_slice", since = "1.7.0")] + #[rustc_diagnostic_item = "vec_as_mut_slice"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn as_mut_slice(&mut self) -> &mut [T] { + // SAFETY: `BufWriter::flush_buf` assumes that this will not + // de-initialize any elements of the spare capacity. + + // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of + // size `len` containing properly-initialized `T`s. Data must not be accessed through any + // other pointer for the returned lifetime. Further, `len * size_of::` <= + // `isize::MAX` and allocation does not "wrap" through overflowing memory addresses. + // + // * Vec API guarantees that self.buf: + // * contains only properly-initialized items within 0..len + // * is aligned, contiguous, and valid for `len` reads + // * obeys size and address-wrapping constraints + // + // * We only construct references to `self.buf` through `&self` and `&mut self` methods; + // borrow-check ensures that it is not possible to construct a reference to `self.buf` + // within the returned lifetime. + unsafe { + // normally this would use `slice::from_raw_parts_mut`, but it's + // instantiated often enough that avoiding the UB check is worth it + &mut *core::intrinsics::aggregate_raw_ptr::<*mut [T], _, _>(self.as_mut_ptr(), self.len) + } + } + + /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer + /// valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// The caller must also ensure that the memory the pointer (non-transitively) points to + /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer + /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`]. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize mutable references to the slice, + /// or mutable references to specific elements you are planning on accessing through this pointer, + /// as well as writing to those elements, may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// + /// # Examples + /// + /// ``` + /// let x = vec![1, 2, 4]; + /// let x_ptr = x.as_ptr(); + /// + /// unsafe { + /// for i in 0..x.len() { + /// assert_eq!(*x_ptr.add(i), 1 << i); + /// } + /// } + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// unsafe { + /// let mut v = vec![0, 1, 2]; + /// let ptr1 = v.as_ptr(); + /// let _ = ptr1.read(); + /// let ptr2 = v.as_mut_ptr().offset(2); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1` + /// // because it mutated a different element: + /// let _ = ptr1.read(); + /// } + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [didn't allocate]: self#memory-layout + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[inline] + #[lint::as_ptr] + #[lint::never_returns_null_ptr] + pub const fn as_ptr(&self) -> *const T { + // We shadow the slice method of the same name to avoid going through + // `deref`, which creates an intermediate reference. + self.buf.ptr() + } + + /// Returns a raw mutable pointer to the vector's buffer, or a dangling + /// raw pointer valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize references to the slice, + /// or references to specific elements you are planning on accessing through this pointer, + /// may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is + /// nonzero, the pointer may be passed into [`dealloc`] with a layout of + /// `Layout::array::(capacity)` in order to deallocate the backing memory. If this is done, + /// be careful not to run the destructor of the `Vec`, as dropping it will result in + /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this. + /// + /// # Examples + /// + /// ``` + /// // Allocate vector big enough for 4 elements. + /// let size = 4; + /// let mut x: Vec = Vec::with_capacity(size); + /// let x_ptr = x.as_mut_ptr(); + /// + /// // Initialize elements via raw pointer writes, then set length. + /// unsafe { + /// for i in 0..size { + /// *x_ptr.add(i) = i as i32; + /// } + /// x.set_len(size); + /// } + /// assert_eq!(&*x, &[0, 1, 2, 3]); + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// unsafe { + /// let mut v = vec![0]; + /// let ptr1 = v.as_mut_ptr(); + /// ptr1.write(1); + /// let ptr2 = v.as_mut_ptr(); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`: + /// ptr1.write(3); + /// } + /// ``` + /// + /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally): + /// + /// ``` + /// use std::mem::{ManuallyDrop, MaybeUninit}; + /// + /// let mut v = ManuallyDrop::new(vec![0, 1, 2]); + /// let ptr = v.as_mut_ptr(); + /// let capacity = v.capacity(); + /// let slice_ptr: *mut [MaybeUninit] = + /// std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); + /// drop(unsafe { Box::from_raw(slice_ptr) }); + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// [`ManuallyDrop`]: core::mem::ManuallyDrop + /// [didn't allocate]: self#memory-layout + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[lint::as_ptr] + #[lint::never_returns_null_ptr] + #[inline] + pub const fn as_mut_ptr(&mut self) -> *mut T { + // We shadow the slice method of the same name to avoid going through + // `deref_mut`, which creates an intermediate reference. + self.buf.ptr() + } + + /// Returns a `NonNull` pointer to the vector's buffer, or a dangling + /// `NonNull` pointer valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize references to the slice, + /// or references to specific elements you are planning on accessing through this pointer, + /// may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_as_non_null)] + /// + /// // Allocate vector big enough for 4 elements. + /// let size = 4; + /// let mut x: Vec = Vec::with_capacity(size); + /// let x_ptr = x.as_non_null(); + /// + /// // Initialize elements via raw pointer writes, then set length. + /// unsafe { + /// for i in 0..size { + /// x_ptr.add(i).write(i as i32); + /// } + /// x.set_len(size); + /// } + /// assert_eq!(&*x, &[0, 1, 2, 3]); + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// #![feature(vec_as_non_null)] + /// + /// unsafe { + /// let mut v = vec![0]; + /// let ptr1 = v.as_non_null(); + /// ptr1.write(1); + /// let ptr2 = v.as_non_null(); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`: + /// ptr1.write(3); + /// } + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [didn't allocate]: self#memory-layout + #[unstable(feature = "vec_as_non_null", issue = "157843")] + #[rustc_const_unstable(feature = "vec_as_non_null", issue = "157843")] + #[lint::as_ptr] + #[inline] + pub const fn as_non_null(&mut self) -> NonNull { + self.buf.non_null() + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn allocator(&self) -> &A { + self.buf.allocator() + } + + /// Forces the length of the vector to `new_len`. + /// + /// This is a low-level operation that maintains none of the normal + /// invariants of the type. Normally changing the length of a vector + /// is done using one of the safe operations instead, such as + /// [`truncate`], [`resize`], [`extend`], or [`clear`]. + /// + /// [`truncate`]: Vec::truncate + /// [`resize`]: Vec::resize + /// [`extend`]: Extend::extend + /// [`clear`]: Vec::clear + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`capacity()`]. + /// - The elements at `old_len..new_len` must be initialized. + /// + /// [`capacity()`]: Vec::capacity + /// + /// # Examples + /// + /// See [`spare_capacity_mut()`] for an example with safe + /// initialization of capacity elements and use of this method. + /// + /// `set_len()` can be useful for situations in which the vector + /// is serving as a buffer for other code, particularly over FFI: + /// + /// ```no_run + /// # #![allow(dead_code)] + /// # // This is just a minimal skeleton for the doc example; + /// # // don't use this as a starting point for a real library. + /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } + /// # const Z_OK: i32 = 0; + /// # unsafe extern "C" { + /// # fn deflateGetDictionary( + /// # strm: *mut std::ffi::c_void, + /// # dictionary: *mut u8, + /// # dictLength: *mut usize, + /// # ) -> i32; + /// # } + /// # impl StreamWrapper { + /// pub fn get_dictionary(&self) -> Option> { + /// // Per the FFI method's docs, "32768 bytes is always enough". + /// let mut dict = Vec::with_capacity(32_768); + /// let mut dict_length = 0; + /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: + /// // 1. `dict_length` elements were initialized. + /// // 2. `dict_length` <= the capacity (32_768) + /// // which makes `set_len` safe to call. + /// unsafe { + /// // Make the FFI call... + /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); + /// if r == Z_OK { + /// // ...and update the length to what was initialized. + /// dict.set_len(dict_length); + /// Some(dict) + /// } else { + /// None + /// } + /// } + /// } + /// # } + /// ``` + /// + /// While the following example is sound, there is a memory leak since + /// the inner vectors were not freed prior to the `set_len` call: + /// + /// ``` + /// let mut vec = vec![vec![1, 0, 0], + /// vec![0, 1, 0], + /// vec![0, 0, 1]]; + /// // SAFETY: + /// // 1. `old_len..0` is empty so no elements need to be initialized. + /// // 2. `0 <= capacity` always holds whatever `capacity` is. + /// unsafe { + /// vec.set_len(0); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # vec.set_len(3); + /// } + /// ``` + /// + /// Normally, here, one would use [`clear`] instead to correctly drop + /// the contents and thus not leak memory. + /// + /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(new_len <= self.capacity())] + #[requires( + new_len <= self.len + || ub_checks::can_dereference(ptr::slice_from_raw_parts( + self.as_ptr().wrapping_add(self.len), + new_len - self.len, + )) + )] + #[cfg_attr(kani, kani::modifies(&self.len))] + #[ensures(|_| self.len() == new_len)] + pub const unsafe fn set_len(&mut self, new_len: usize) { + ub_checks::assert_unsafe_precondition!( + check_library_ub, + "Vec::set_len requires that new_len <= capacity()", + (new_len: usize = new_len, capacity: usize = self.capacity()) => new_len <= capacity + ); + + self.len = new_len; + } + + /// Removes an element from the vector and returns it. + /// + /// The removed element is replaced by the last element of the vector. + /// + /// This does not preserve ordering of the remaining elements, but is *O*(1). + /// If you need to preserve the element order, use [`remove`] instead. + /// + /// [`remove`]: Vec::remove + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec!["foo", "bar", "baz", "qux"]; + /// + /// assert_eq!(v.swap_remove(1), "bar"); + /// assert_eq!(v, ["foo", "qux", "baz"]); + /// + /// assert_eq!(v.swap_remove(0), "foo"); + /// assert_eq!(v, ["baz", "qux"]); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn swap_remove(&mut self, index: usize) -> T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("swap_remove index (is {index}) should be < len (is {len})"); + } + + let len = self.len(); + if index >= len { + assert_failed(index, len); + } + // ignore-tidy-undocumented-unsafe + unsafe { + // We replace self[index] with the last element. Note that if the + // bounds check above succeeds there must be a last element (which + // can be self[index] itself). + let value = ptr::read(self.as_ptr().add(index)); + let base_ptr = self.as_mut_ptr(); + ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); + self.set_len(len - 1); + value + } + } + + /// Inserts an element at position `index` within the vector, shifting all + /// elements after it to the right. + /// + /// # Panics + /// + /// Panics if `index > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!['a', 'b', 'c']; + /// vec.insert(1, 'd'); + /// assert_eq!(vec, ['a', 'd', 'b', 'c']); + /// vec.insert(4, 'e'); + /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be + /// shifted to the right. In the worst case, all elements are shifted when + /// the insertion index is 0. + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[track_caller] + pub fn insert(&mut self, index: usize, element: T) { + let _ = self.insert_mut(index, element); + } + + /// Inserts an element at position `index` within the vector, shifting all + /// elements after it to the right, and returning a reference to the new + /// element. + /// + /// # Panics + /// + /// Panics if `index > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 3, 5, 9]; + /// let x = vec.insert_mut(3, 6); + /// *x += 1; + /// assert_eq!(vec, [1, 3, 5, 7, 9]); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be + /// shifted to the right. In the worst case, all elements are shifted when + /// the insertion index is 0. + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "push_mut", since = "1.95.0")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"] + pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("insertion index (is {index}) should be <= len (is {len})"); + } + + let len = self.len(); + if index > len { + assert_failed(index, len); + } + + // space for the new element + if len == self.buf.capacity() { + self.buf.grow_one(); + } + + // ignore-tidy-undocumented-unsafe + unsafe { + // infallible + // The spot to put the new value + let p = self.as_mut_ptr().add(index); + { + if index < len { + // Shift everything over to make space. (Duplicating the + // `index`th element into two consecutive places.) + ptr::copy(p, p.add(1), len - index); + } + // Write it in, overwriting the first copy of the `index`th + // element. + ptr::write(p, element); + } + self.set_len(len + 1); + &mut *p + } + } + + /// Removes and returns the element at position `index` within the vector, + /// shifting all elements after it to the left. + /// + /// Note: Because this shifts over the remaining elements, it has a + /// worst-case performance of *O*(*n*). If you don't need the order of elements + /// to be preserved, use [`swap_remove`] instead. If you'd like to remove + /// elements from the beginning of the `Vec`, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`swap_remove`]: Vec::swap_remove + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec!['a', 'b', 'c']; + /// assert_eq!(v.remove(1), 'b'); + /// assert_eq!(v, ['a', 'c']); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[track_caller] + #[rustc_confusables("delete", "take")] + pub fn remove(&mut self, index: usize) -> T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("removal index (is {index}) should be < len (is {len})"); + } + + match self.try_remove(index) { + Some(elem) => elem, + None => assert_failed(index, self.len()), + } + } + + /// Remove and return the element at position `index` within the vector, + /// shifting all elements after it to the left, or [`None`] if it does not + /// exist. + /// + /// Note: Because this shifts over the remaining elements, it has a + /// worst-case performance of *O*(*n*). If you'd like to remove + /// elements from the beginning of the `Vec`, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// assert_eq!(v.try_remove(0), Some(1)); + /// assert_eq!(v.try_remove(2), None); + /// ``` + #[stable(feature = "vec_try_remove", since = "1.101.0")] + #[rustc_confusables("delete", "take", "remove")] + pub fn try_remove(&mut self, index: usize) -> Option { + let len = self.len(); + if index >= len { + return None; + } + // infallible + let ret; + // ignore-tidy-undocumented-unsafe + unsafe { + { + // the place we are taking from. + let ptr = self.as_mut_ptr().add(index); + // copy it out, unsafely having a copy of the value on + // the stack and in the vector at the same time. + ret = ptr::read(ptr); + + // Shift everything down to fill in that spot. + ptr::copy(ptr.add(1), ptr, len - index - 1); + } + self.set_len(len - 1); + } + Some(ret) + } + + /// Retains only the elements specified by the predicate. + /// + /// In other words, remove all elements `e` for which `f(&e)` returns `false`. + /// This method operates in place, visiting each element exactly once in the + /// original order, and preserves the order of the retained elements. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// vec.retain(|&x| x % 2 == 0); + /// assert_eq!(vec, [2, 4]); + /// ``` + /// + /// Because the elements are visited exactly once in the original order, + /// external state may be used to decide which elements to keep. + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4, 5]; + /// let keep = [false, true, true, false, true]; + /// let mut iter = keep.iter(); + /// vec.retain(|_| *iter.next().unwrap()); + /// assert_eq!(vec, [2, 3, 5]); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + pub fn retain(&mut self, mut f: F) + where + F: FnMut(&T) -> bool, + { + self.retain_mut(|elem| f(elem)); + } + + /// Retains only the elements specified by the predicate, passing a mutable reference to it. + /// + /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. + /// This method operates in place, visiting each element exactly once in the + /// original order, and preserves the order of the retained elements. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// vec.retain_mut(|x| if *x <= 3 { + /// *x += 1; + /// true + /// } else { + /// false + /// }); + /// assert_eq!(vec, [2, 3, 4]); + /// ``` + #[stable(feature = "vec_retain_mut", since = "1.61.0")] + pub fn retain_mut(&mut self, mut f: F) + where + F: FnMut(&mut T) -> bool, + { + let original_len = self.len(); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + + #[cfg(all(target_arch = "aarch64", target_feature = "sve"))] + { + let long_enough = match mem::size_of::() { + 1 => original_len >= sve_retain::MIN_SVE_SIZE_1, + 2 => original_len >= sve_retain::MIN_SVE_SIZE_2, + 4 => original_len >= sve_retain::MIN_SVE_SIZE_4, + 8 => original_len >= sve_retain::MIN_SVE_SIZE_8, + _ => false, + }; + if long_enough { + // SAFETY: size_of::() is 1, 2, 4 or 8, matching + // the kernel lane widths. + return unsafe { sve_retain::chunked_retain(self, f) }; + } + } + + // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] + // | ^- write ^- read | + // |<- original_len ->| + // Kept: Elements which predicate returns true on. + // Hole: Moved or dropped element slot. + // Unchecked: Unchecked valid elements. + // + // This drop guard will be invoked when predicate or `drop` of element panicked. + // It shifts unchecked elements to cover holes and `set_len` to the correct length. + // In cases when predicate and `drop` never panick, it will be optimized out. + struct PanicGuard<'a, T, A: Allocator> { + v: &'a mut Vec, + read: usize, + write: usize, + original_len: usize, + } + + impl Drop for PanicGuard<'_, T, A> { + #[cold] + fn drop(&mut self) { + let remaining = self.original_len - self.read; + // SAFETY: Trailing unchecked items must be valid since we never touch them. + unsafe { + ptr::copy( + self.v.as_ptr().add(self.read), + self.v.as_mut_ptr().add(self.write), + remaining, + ); + } + // SAFETY: After filling holes, all items are in contiguous memory. + unsafe { + self.v.set_len(self.write + remaining); + } + } + } + + let mut read = 0; + loop { + // SAFETY: read < original_len + let cur = unsafe { self.get_unchecked_mut(read) }; + if hint::unlikely(!f(cur)) { + break; + } + read += 1; + if read == original_len { + // All elements are kept, return early. + return; + } + } + + // Critical section starts here and at least one element is going to be removed. + // Advance `g.read` early to avoid double drop if `drop_in_place` panicked. + let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len }; + // SAFETY: previous `read` is always less than original_len. + unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) }; + + while g.read < g.original_len { + // SAFETY: `read` is always less than original_len. + let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) }; + if !f(cur) { + // Advance `read` early to avoid double drop if `drop_in_place` panicked. + g.read += 1; + // SAFETY: We never touch this element again after dropped. + unsafe { ptr::drop_in_place(cur) }; + } else { + // SAFETY: `read` > `write`, so the slots don't overlap. + // We use copy for move, and never touch the source element again. + unsafe { + let hole = g.v.as_mut_ptr().add(g.write); + ptr::copy_nonoverlapping(cur, hole, 1); + } + g.write += 1; + g.read += 1; + } + } + + // We are leaving the critical section and no panic happened, + // Commit the length change and forget the guard. + // SAFETY: `write` is always less than or equal to original_len. + unsafe { g.v.set_len(g.write) }; + mem::forget(g); + } + + /// Retains only the elements specified by the predicate, passing a mutable reference to it. + /// + /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. + /// This method does not maintain the relative order of the retained elements. If order matters, + /// consider using [`Vec::retain_mut`] instead. However, if no items are removed, then all items + /// are left in their original positions. + /// + /// Generally, this method is faster than [`Vec::retain_mut`] due to its weak ordering guarantees. + /// + /// [`Vec::retain_mut`]: crate::vec::Vec::retain_mut + /// + /// Time complexity: *O*(*n*) + /// + /// + /// # Examples + /// + /// ``` + /// #![feature(retain_unstable)] + /// let mut vec = vec![4, 3, 2, 1]; + /// vec.retain_unstable(|x| if *x <= 3 { + /// *x += 1; + /// true + /// } else { + /// false + /// }); + /// + /// vec.sort(); // it might be in any order, so normalize before asserting + /// assert_eq!(vec, [2, 3, 4]); + /// ``` + #[unstable(feature = "retain_unstable", issue = "164152")] + pub fn retain_unstable(&mut self, mut f: F) + where + F: FnMut(&mut T) -> bool, + { + // Currently this does the following: + // 1) Search backward until you find an element you want to remove + // 2) Swap this element with an element that was kept in the back + // (or if there are no remaining elements, simply truncate the vec) + // 3) Repeat from 1) until there's no element to iterate through + + let original_len = self.len(); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + + let mut read_back = original_len; + let mut hole = loop { + if read_back == 0 { + // All elements are kept + return; + } + // SAFETY: read_back - 1 < original_len + let cur = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) }; + if hint::unlikely(!f(cur)) { + break cur; + } + read_back -= 1; + }; + + if read_back < self.len { + let swap = self.pop().unwrap(); + *hole = swap; + } else { + self.truncate(self.len - 1); + } + read_back -= 1; + + while read_back > 0 { + // SAFETY: read_back - 1 is always less than current length of + // the vector and the loop condition, read_back > 0, prevents + // read_back from underflowing + hole = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) }; + if !f(hole) { + if read_back < self.len { + let swap = self.pop().unwrap(); + *hole = swap; + } else { + self.truncate(self.len - 1); + } + } + read_back -= 1; + } + } + + /// Removes all but the first of consecutive elements in the vector that resolve to the same + /// key. + /// + /// If the vector is sorted, this removes all duplicates. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![10, 20, 21, 30, 20]; + /// + /// vec.dedup_by_key(|i| *i / 10); + /// + /// assert_eq!(vec, [10, 20, 30, 20]); + /// ``` + #[stable(feature = "dedup_by", since = "1.16.0")] + #[inline] + pub fn dedup_by_key(&mut self, mut key: F) + where + F: FnMut(&mut T) -> K, + K: PartialEq, + { + self.dedup_by(|a, b| key(a) == key(b)) + } + + /// Removes all but the first of consecutive elements in the vector that are + /// "equal" according to the given predicate function. + /// + /// The predicate `same_bucket(x, p)` is passed references to two elements. + /// If it returns `true`, the element `x` is removed from the vector. + /// + /// The element `p` occurs *before* `x` in the vector (`[.., p, .., x, ..]`), + /// so `same_bucket(x, p)` is receiving them in reversed order (unlike [`windows`]). + /// + /// If the vector is sorted, this removes all duplicates. For more complicated predicates + /// however, the order (ascending vs. descending) can matter. + /// + /// [`windows`]: slice::windows + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; + /// vec.dedup_by(|x, p| x.eq_ignore_ascii_case(p)); + /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); + /// ``` + /// + /// Both references passed to `same_bucket` are mutable. + /// This allows merging elements by mutating `p` and returning `true`: + /// + /// ``` + /// let mut ranges = vec![1..2, 2..4, 2..5, 8..9]; + /// + /// // Sort ranges by start, and if equal, by end (lexicographically) + /// // Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail + /// ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end))); + /// + /// // Merge touching (`1..2` and `2..4`) and then overlapping (`1..4` and `2..5`) ranges + /// ranges.dedup_by(|x, p| { + /// if p.end >= x.start { + /// p.end = p.end.max(x.end); + /// true + /// } else { + /// false + /// } + /// }); + /// + /// assert_eq!(ranges, [1..5, 8..9]); + /// ``` + #[stable(feature = "dedup_by", since = "1.16.0")] + pub fn dedup_by(&mut self, mut same_bucket: F) + where + F: FnMut(&mut T, &mut T) -> bool, + { + let len = self.len(); + if len <= 1 { + return; + } + + // Check if we ever want to remove anything. + // This allows to use copy_non_overlapping in next cycle. + // And avoids any memory writes if we don't need to remove anything. + let mut first_duplicate_idx: usize = 1; + let start = self.as_mut_ptr(); + while first_duplicate_idx != len { + let found_duplicate = { + // SAFETY: first_duplicate always in range [1..len). + // Note that we start iteration from 1 so we never overflow. + let prev = unsafe { start.add(first_duplicate_idx.wrapping_sub(1)) }; + // ignore-tidy-undocumented-unsafe + let current = unsafe { start.add(first_duplicate_idx) }; + // We explicitly say in docs that references are reversed. + // ignore-tidy-undocumented-unsafe + unsafe { same_bucket(&mut *current, &mut *prev) } + }; + if found_duplicate { + break; + } + first_duplicate_idx += 1; + } + // Don't need to remove anything. + // We cannot get bigger than len. + if first_duplicate_idx == len { + return; + } + // SAFETY: first_duplicate_idx always in range [1..len) + unsafe { + self.dedup_tail(same_bucket, first_duplicate_idx); + } + } + + /// Continues deduplication after the first duplicate is found. + /// + /// The function treats `self[first_duplicate]` as the first duplicated + /// element and drops it. + /// + /// # Safety + /// + /// `1 <= first_duplicate < self.len()` + unsafe fn dedup_tail(&mut self, mut same_bucket: F, first_duplicate: usize) + where + F: FnMut(&mut T, &mut T) -> bool, + { + /* INVARIANT: vec.len() > read > write > write-1 >= 0 */ + struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { + /* Offset of the element we want to check if it is duplicate */ + read: usize, + + /* Offset of the place where we want to place the non-duplicate + * when we find it. */ + write: usize, + + /* The Vec that would need correction if `same_bucket` panicked */ + vec: &'a mut Vec, + } + + impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> { + fn drop(&mut self) { + /* This code gets executed when `same_bucket` panics */ + + // SAFETY: invariant guarantees that `read - write` + // and `len - read` never overflow and that the copy is always + // in-bounds. + unsafe { + let ptr = self.vec.as_mut_ptr(); + let len = self.vec.len(); + + /* How many items were left when `same_bucket` panicked. + * Basically vec[read..].len() */ + let items_left = len.wrapping_sub(self.read); + + /* Pointer to first item in vec[write..write+items_left] slice */ + let dropped_ptr = ptr.add(self.write); + /* Pointer to first item in vec[read..] slice */ + let valid_ptr = ptr.add(self.read); + + /* Copy `vec[read..]` to `vec[write..write+items_left]`. + * The slices can overlap, so `copy_nonoverlapping` cannot be used */ + ptr::copy(valid_ptr, dropped_ptr, items_left); + + /* How many items have been already dropped + * Basically vec[read..write].len() */ + let dropped = self.read.wrapping_sub(self.write); + + self.vec.set_len(len - dropped); + } + } + } + + let start = self.as_mut_ptr(); + let len = self.len(); + + /* Drop items while going through Vec, it should be more efficient than + * doing slice partition_dedup + truncate */ + + // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics. + let mut gap = + FillGapOnDrop { read: first_duplicate + 1, write: first_duplicate, vec: self }; + + // SAFETY: By this function's safety contract, `first_duplicate < self.len()`. + // If drop panics, `gap` would remove this item without drop. + unsafe { + ptr::drop_in_place(start.add(first_duplicate)); + } + + // SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr + // are always in-bounds and read_ptr never aliases prev_ptr + unsafe { + while gap.read < len { + let read_ptr = start.add(gap.read); + let prev_ptr = start.add(gap.write.wrapping_sub(1)); + + // We explicitly say in docs that references are reversed. + let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr); + if found_duplicate { + // Increase `gap.read` now since the drop may panic. + gap.read += 1; + /* We have found duplicate, drop it in-place */ + ptr::drop_in_place(read_ptr); + } else { + let write_ptr = start.add(gap.write); + + /* read_ptr cannot be equal to write_ptr because at this point + * we guaranteed to skip at least one element (before loop starts). + */ + ptr::copy_nonoverlapping(read_ptr, write_ptr, 1); + + /* We have filled that place, so go further */ + gap.write += 1; + gap.read += 1; + } + } + + /* Technically we could let `gap` clean up with its Drop, but + * when `same_bucket` is guaranteed to not panic, this bloats a little + * the codegen, so we just do it manually */ + gap.vec.set_len(gap.write); + mem::forget(gap); + } + } + + /// Appends an element and returns a reference to it if there is sufficient spare capacity, + /// otherwise an error is returned with the element. + /// + /// Unlike [`push`] this method will not reallocate when there's insufficient capacity. + /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. + /// + /// [`push`]: Vec::push + /// [`reserve`]: Vec::reserve + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Examples + /// + /// A manual, panic-free alternative to [`FromIterator`]: + /// + /// ``` + /// #![feature(vec_push_within_capacity)] + /// + /// use std::collections::TryReserveError; + /// fn from_iter_fallible(iter: impl Iterator) -> Result, TryReserveError> { + /// let mut vec = Vec::new(); + /// for value in iter { + /// if let Err(value) = vec.push_within_capacity(value) { + /// vec.try_reserve(1)?; + /// // this cannot fail, the previous line either returned or added at least 1 free slot + /// let _ = vec.push_within_capacity(value); + /// } + /// } + /// Ok(vec) + /// } + /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100))); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*(1) time. + #[inline] + #[unstable(feature = "vec_push_within_capacity", issue = "100486")] + pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> { + if self.len == self.buf.capacity() { + return Err(value); + } + + // ignore-tidy-undocumented-unsafe + let end = unsafe { self.as_mut_ptr().add(self.len) }; + // ignore-tidy-undocumented-unsafe + unsafe { ptr::write(end, value) }; + self.len += 1; + + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + Ok(unsafe { &mut *end }) + } + + /// Removes the last element from a vector and returns it, or [`None`] if it + /// is empty. + /// + /// If you'd like to pop the first element, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// assert_eq!(vec.pop(), Some(3)); + /// assert_eq!(vec, [1, 2]); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*(1) time. + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_pop"] + pub fn pop(&mut self) -> Option { + if self.len == 0 { + None + } else { + self.len -= 1; + // ignore-tidy-undocumented-unsafe + unsafe { + core::hint::assert_unchecked(self.len < self.capacity()); + Some(ptr::read(self.as_ptr().add(self.len()))) + } + } + } + + /// Removes and returns the last element from a vector if the predicate + /// returns `true`, or [`None`] if the predicate returns false or the vector + /// is empty (the predicate will not be called in that case). + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// let pred = |x: &mut i32| *x % 2 == 0; + /// + /// assert_eq!(vec.pop_if(pred), Some(4)); + /// assert_eq!(vec, [1, 2, 3]); + /// assert_eq!(vec.pop_if(pred), None); + /// ``` + #[stable(feature = "vec_pop_if", since = "1.86.0")] + pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option { + let last = self.last_mut()?; + if predicate(last) { self.pop() } else { None } + } + + /// Returns a mutable reference to the last item in the vector, or + /// `None` if it is empty. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(vec_peek_mut)] + /// let mut vec = Vec::new(); + /// assert!(vec.peek_mut().is_none()); + /// + /// vec.push(1); + /// vec.push(5); + /// vec.push(2); + /// assert_eq!(vec.last(), Some(&2)); + /// if let Some(mut val) = vec.peek_mut() { + /// *val = 0; + /// } + /// assert_eq!(vec.last(), Some(&0)); + /// ``` + #[inline] + #[unstable(feature = "vec_peek_mut", issue = "122742")] + pub fn peek_mut(&mut self) -> Option> + where + A: AllocatorNightly, + { + PeekMut::new(self) + } + + /// Moves all the elements of `other` into `self`, leaving `other` empty. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// let mut vec2 = vec![4, 5, 6]; + /// vec.append(&mut vec2); + /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); + /// assert_eq!(vec2, []); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "append", since = "1.4.0")] + pub fn append(&mut self, other: &mut Self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements(other.as_slice() as _); + other.set_len(0); + } + } + + /// Appends elements to `self` from other buffer. + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn append_elements(&mut self, other: *const [T]) { + self.reserve(other.len()); + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements_unreserved(other); + } + } + + /// Appends elements to `self` from other buffer, returning [`TryReserveError`] on OOM. + #[inline] + unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> { + self.try_reserve(other.len())?; + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements_unreserved(other); + } + Ok(()) + } + + /// Appends elements to `self` from other buffer without reserving additional capacity. + #[inline] + unsafe fn append_elements_unreserved(&mut self, other: *const [T]) { + let count = other.len(); + let len = self.len(); + if count > 0 { + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) + }; + } + self.len += count; + } + + /// Removes the subslice indicated by the given range from the vector, + /// returning a double-ended iterator over the removed subslice. + /// + /// If the iterator is dropped before being fully consumed, + /// it drops the remaining removed elements. + /// + /// The returned iterator keeps a mutable borrow on the vector to optimize + /// its implementation. + /// + /// # Panics + /// + /// Panics if the range has `start_bound > end_bound`, or, if the range is + /// bounded on either end and past the length of the vector. + /// + /// # Leaking + /// + /// If the returned iterator goes out of scope without being dropped (due to + /// [`mem::forget`], for example), the vector may have lost and leaked + /// elements arbitrarily, including elements outside the range. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// let u: Vec<_> = v.drain(1..).collect(); + /// assert_eq!(v, &[1]); + /// assert_eq!(u, &[2, 3]); + /// + /// // A full range clears the vector, like `clear()` does + /// v.drain(..); + /// assert_eq!(v, &[]); + /// ``` + #[stable(feature = "drain", since = "1.6.0")] + pub fn drain(&mut self, range: R) -> Drain<'_, T, A> + where + A: AllocatorNightly, + R: RangeBounds, + { + // Memory safety + // + // When the Drain is first created, it shortens the length of + // the source vector to make sure no uninitialized or moved-from elements + // are accessible at all if the Drain's destructor never gets to run. + // + // Drain will ptr::read out the values to remove. + // When finished, remaining tail of the vec is copied back to cover + // the hole, and the vector length is restored to the new length. + // + let len = self.len(); + let Range { start, end } = slice::range(range, ..len); + + // ignore-tidy-undocumented-unsafe + unsafe { + // set self.vec length's to start, to be safe in case Drain is leaked + self.set_len(start); + let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start); + Drain { + tail_start: end, + tail_len: len - end, + iter: range_slice.iter(), + vec: NonNull::from(self), + } + } + } + + /// Clears the vector, removing all values. + /// + /// Note that this method has no effect on the allocated capacity + /// of the vector. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// + /// v.clear(); + /// + /// assert!(v.is_empty()); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn clear(&mut self) { + // Though this is equivalent to `truncate(0)`, the manual version + // optimizes better, justifying the additional complexity + // (see #96002 and #154095 for context). + + let elems: *mut [T] = self.as_mut_slice(); + + // SAFETY: + // - `elems` comes directly from `as_mut_slice` and is therefore valid. + // - Setting `self.len` before calling `drop_in_place` means that, + // if an element's `Drop` impl panics, the vector's `Drop` impl will + // do nothing (leaking the rest of the elements) instead of dropping + // some twice. + unsafe { + self.len = 0; + ptr::drop_in_place(elems); + } + } + + /// Returns the number of elements in the vector, also referred to + /// as its 'length'. + /// + /// # Examples + /// + /// ``` + /// let a = vec![1, 2, 3]; + /// assert_eq!(a.len(), 3); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[rustc_confusables("length", "size")] + pub const fn len(&self) -> usize { + let len = self.len; + + // SAFETY: The maximum capacity of `Vec` is `isize::MAX` bytes, so the maximum value can + // be returned is `usize::checked_div(size_of::()).unwrap_or(usize::MAX)`, which + // matches the definition of `T::MAX_SLICE_LEN`. + unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) }; + + len + } + + /// Returns `true` if the vector contains no elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = Vec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1); + /// assert!(!v.is_empty()); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_is_empty"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Splits the collection into two at the given index. + /// + /// Returns a newly allocated vector containing the elements in the range + /// `[at, len)`. After the call, the original vector will be left containing + /// the elements `[0, at)` with its previous capacity unchanged. + /// + /// - If you want to take ownership of the entire contents and capacity of + /// the vector, see [`mem::take`] or [`mem::replace`]. + /// - If you don't need the returned vector at all, see [`Vec::truncate`]. + /// - If you want to take ownership of an arbitrary subslice, or you don't + /// necessarily want to store the removed items in a vector, see [`Vec::drain`]. + /// + /// # Panics + /// + /// Panics if `at > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!['a', 'b', 'c']; + /// let vec2 = vec.split_off(1); + /// assert_eq!(vec, ['a']); + /// assert_eq!(vec2, ['b', 'c']); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[must_use = "use `.truncate()` if you don't need the other half"] + #[stable(feature = "split_off", since = "1.4.0")] + #[track_caller] + pub fn split_off(&mut self, at: usize) -> Self + where + A: Clone, + { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(at: usize, len: usize) -> ! { + panic!("`at` split index (is {at}) should be <= len (is {len})"); + } + + if at > self.len() { + assert_failed(at, self.len()); + } + + let other_len = self.len - at; + let mut other = Vec::with_capacity_in(other_len, self.allocator().clone()); + + // Unsafely `set_len` and copy items to `other`. + // ignore-tidy-undocumented-unsafe + unsafe { + self.set_len(at); + other.set_len(other_len); + + ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); + } + other + } + + /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the `Vec` is extended by the + /// difference, with each additional slot filled with the result of + /// calling the closure `f`. The return values from `f` will end up + /// in the `Vec` in the order they have been generated. + /// + /// If `new_len` is less than or equal to `len`, the `Vec` is simply + /// truncated. + /// + /// This method uses a closure to create new values on every push. If + /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you + /// want to use the [`Default`] trait to generate values, you can + /// pass [`Default::default`] as the second argument. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.resize_with(5, Default::default); + /// assert_eq!(vec, [1, 2, 3, 0, 0]); + /// + /// let mut vec = vec![]; + /// let mut p = 1; + /// vec.resize_with(4, || { p *= 2; p }); + /// assert_eq!(vec, [2, 4, 8, 16]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_resize_with", since = "1.33.0")] + pub fn resize_with(&mut self, new_len: usize, f: F) + where + F: FnMut() -> T, + { + let len = self.len(); + if new_len > len { + self.extend_trusted(iter::repeat_with(f).take(new_len - len)); + } else { + self.truncate(new_len); + } + } + + /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, + /// `&'a mut [T]`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. + /// + /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, + /// so the leaked allocation may include unused capacity that is not part + /// of the returned slice. + /// + /// This function is mainly useful for data that lives for the remainder of + /// the program's life. Dropping the returned reference will cause a memory + /// leak. + /// + /// # Examples + /// + /// Simple usage: + /// + /// ``` + /// let x = vec![1, 2, 3]; + /// let static_ref: &'static mut [usize] = x.leak(); + /// static_ref[0] += 1; + /// assert_eq!(static_ref, &[2, 2, 3]); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Box::from_raw(static_ref) }); + /// ``` + #[stable(feature = "vec_leak", since = "1.47.0")] + #[inline] + pub fn leak<'a>(self) -> &'a mut [T] + where + A: 'a, + { + let mut me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) } + } + + /// Returns the remaining spare capacity of the vector as a slice of + /// `MaybeUninit`. + /// + /// The returned slice can be used to fill the vector with data (e.g. by + /// reading from a file) before marking the data as initialized using the + /// [`set_len`] method. + /// + /// [`set_len`]: Vec::set_len + /// + /// # Examples + /// + /// ``` + /// // Allocate vector big enough for 10 elements. + /// let mut v = Vec::with_capacity(10); + /// + /// // Fill in the first 3 elements. + /// let uninit = v.spare_capacity_mut(); + /// uninit[0].write(0); + /// uninit[1].write(1); + /// uninit[2].write(2); + /// + /// // Mark the first 3 elements of the vector as being initialized. + /// unsafe { + /// v.set_len(3); + /// } + /// + /// assert_eq!(&v, &[0, 1, 2]); + /// ``` + #[stable(feature = "vec_spare_capacity", since = "1.60.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // Note: + // This method is not implemented in terms of `split_at_spare_mut`, + // to prevent invalidation of pointers to the buffer. + // ignore-tidy-undocumented-unsafe + unsafe { + slice::from_raw_parts_mut( + self.as_mut_ptr().add(self.len) as *mut MaybeUninit, + self.buf.capacity() - self.len, + ) + } + } + + /// Returns vector content as a slice of `T`, along with the remaining spare + /// capacity of the vector as a slice of `MaybeUninit`. + /// + /// The returned spare capacity slice can be used to fill the vector with data + /// (e.g. by reading from a file) before marking the data as initialized using + /// the [`set_len`] method. + /// + /// [`set_len`]: Vec::set_len + /// + /// Note that this is a low-level API, which should be used with care for + /// optimization purposes. If you need to append data to a `Vec` + /// you can use [`push`], [`extend`], [`extend_from_slice`], + /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or + /// [`resize_with`], depending on your exact needs. + /// + /// [`push`]: Vec::push + /// [`extend`]: Vec::extend + /// [`extend_from_slice`]: Vec::extend_from_slice + /// [`extend_from_within`]: Vec::extend_from_within + /// [`insert`]: Vec::insert + /// [`append`]: Vec::append + /// [`resize`]: Vec::resize + /// [`resize_with`]: Vec::resize_with + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_split_at_spare)] + /// + /// let mut v = vec![1, 1, 2]; + /// + /// // Reserve additional space big enough for 10 elements. + /// v.reserve(10); + /// + /// let (init, uninit) = v.split_at_spare_mut(); + /// let sum = init.iter().copied().sum::(); + /// + /// // Fill in the next 4 elements. + /// uninit[0].write(sum); + /// uninit[1].write(sum * 2); + /// uninit[2].write(sum * 3); + /// uninit[3].write(sum * 4); + /// + /// // Mark the 4 elements of the vector as being initialized. + /// unsafe { + /// let len = v.len(); + /// v.set_len(len + 4); + /// } + /// + /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]); + /// ``` + #[unstable(feature = "vec_split_at_spare", issue = "81944")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit]) { + // SAFETY: + // - len is ignored and so never changed + let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() }; + (init, spare) + } + + /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`. + /// + /// This method provides unique access to all vec parts at once in `extend_from_within`. + #[requires(self.len <= self.buf.capacity())] + #[ensures(|result| result.0.len() == *result.2 && result.0.len() + result.1.len() == old(self.capacity()))] + const unsafe fn split_at_spare_mut_with_len( + &mut self, + ) -> (&mut [T], &mut [MaybeUninit], &mut usize) { + let ptr = self.as_mut_ptr(); + // SAFETY: + // - `ptr` is guaranteed to be valid for `self.len` elements + // - but the allocation extends out to `self.buf.capacity()` elements, possibly + // uninitialized + let spare_ptr = unsafe { ptr.add(self.len) }; + let spare_ptr = spare_ptr.cast_uninit(); + let spare_len = self.buf.capacity() - self.len; + + // SAFETY: + // - `ptr` is guaranteed to be valid for `self.len` elements + // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` + unsafe { + let initialized = slice::from_raw_parts_mut(ptr, self.len); + let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); + + (initialized, spare, &mut self.len) + } + } + + /// Groups every `N` elements in the `Vec` into chunks to produce a `Vec<[T; N]>`, dropping + /// elements in the remainder. `N` must be greater than zero. + /// + /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the + /// nearest multiple with a reallocation or deallocation. + /// + /// This function can be used to reverse [`Vec::into_flattened`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_into_chunks)] + /// + /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; + /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]); + /// + /// let vec = vec![0, 1, 2, 3]; + /// let chunks: Vec<[u8; 10]> = vec.into_chunks(); + /// assert!(chunks.is_empty()); + /// + /// let flat = vec![0; 8 * 8 * 8]; + /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks(); + /// assert_eq!(reshaped.len(), 1); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_into_chunks", issue = "142137")] + pub fn into_chunks(mut self) -> Vec<[T; N], A> { + const { + assert!(N != 0, "chunk size must be greater than zero"); + } + + let (len, cap) = (self.len(), self.capacity()); + + let len_remainder = len % N; + if len_remainder != 0 { + self.truncate(len - len_remainder); + } + + let cap_remainder = cap % N; + if !T::IS_ZST && cap_remainder != 0 { + self.buf.shrink_to_fit(cap - cap_remainder); + } + + let (ptr, _, _, alloc) = self.into_raw_parts_with_allocator(); + + // SAFETY: + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` + // - `[T; N]` has the same alignment as `T` + // - `size_of::<[T; N]>() * cap / N == size_of::() * cap` + // - `len / N <= cap / N` because `len <= cap` + // - the allocated memory consists of `len / N` valid values of type `[T; N]` + // - `cap / N` fits the size of the allocated memory after shrinking + unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) } + } + + /// This clears out this `Vec` and recycles the allocation into a new `Vec`. + /// The item type of the resulting `Vec` needs to have the same size and + /// alignment as the item type of the original `Vec`. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_recycle, transmutability)] + /// let a: Vec = vec![0; 100]; + /// let capacity = a.capacity(); + /// let addr = a.as_ptr().addr(); + /// let b: Vec = a.recycle(); + /// assert_eq!(b.len(), 0); + /// assert_eq!(b.capacity(), capacity); + /// assert_eq!(b.as_ptr().addr(), addr); + /// ``` + /// + /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// let vec: Vec<[u8; 2]> = Vec::new(); + /// let _: Vec<[u8; 1]> = vec.recycle(); + /// ``` + /// ...or different alignments: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// let vec: Vec<[u16; 0]> = Vec::new(); + /// let _: Vec<[u8; 0]> = vec.recycle(); + /// ``` + /// + /// However, due to temporary implementation limitations of `Recyclable`, + /// this method is not yet callable when `T` or `U` are slices, trait objects, + /// or other exotic types; e.g.: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// # let inputs = ["a b c", "d e f"]; + /// # fn process(_: &[&str]) {} + /// let mut storage: Vec<&[&str]> = Vec::new(); + /// + /// for input in inputs { + /// let mut buffer: Vec<&str> = storage.recycle(); + /// buffer.extend(input.split(" ")); + /// process(&buffer); + /// storage = buffer.recycle(); + /// } + /// ``` + #[unstable(feature = "vec_recycle", issue = "148227")] + #[expect(private_bounds)] + pub fn recycle(mut self) -> Vec + where + U: Recyclable, + { + self.clear(); + const { + // FIXME(const-hack, 146097): compare `Layout`s + assert!(size_of::() == size_of::()); + assert!(align_of::() == align_of::()); + }; + let (ptr, length, capacity, alloc) = self.into_parts_with_allocator(); + debug_assert_eq!(length, 0); + // SAFETY: + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` + // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later + // - the original vector was cleared, so there is no problem with "transmuting" the stored values + unsafe { Vec::from_parts_in(ptr.cast::(), length, capacity, alloc) } + } +} + +/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`. +/// +/// # Safety +/// +/// `Self` is `Recyclable` if `Layout::new::() == Layout::new::()`. +unsafe trait Recyclable: Sized {} + +#[unstable_feature_bound(transmutability)] +// SAFETY: enforced by `TransmuteFrom` +unsafe impl Recyclable for To +where + for<'a> &'a MaybeUninit: TransmuteFrom<&'a MaybeUninit, { Assume::SAFETY }>, + for<'a> &'a MaybeUninit: TransmuteFrom<&'a MaybeUninit, { Assume::SAFETY }>, +{ +} + +impl Vec { + /// Create a new `Vec` that contains `elem` `n` times. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// + /// If `n` is zero, the vector will not allocate. + /// + /// # Panics + /// + /// Panics if `size_of::() * n` exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_repeat)] + /// let vec = Vec::repeat(0, 3); + /// assert_eq!(vec, [0; 3]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_repeat", issue = "164215")] + #[inline] + pub fn repeat(elem: T, n: usize) -> Self { + ::from_elem(elem, n, Global) + } +} + +impl Vec { + /// Create a new `Vec` with the provided allocator that contains `elem` `n` times. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// + /// If `n` is zero, the vector will not allocate. + /// + /// # Panics + /// + /// Panics if `size_of::() * n` exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_repeat)] + /// use std::alloc::System; + /// + /// let vec = Vec::repeat_in(0, 3, System); + /// assert_eq!(vec, [0; 3]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_repeat", issue = "164215")] + #[inline] + pub fn repeat_in(elem: T, n: usize, alloc: A) -> Self { + ::from_elem(elem, n, alloc) + } + + /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the `Vec` is extended by the + /// difference, with each additional slot filled with `value`. + /// If `new_len` is less than or equal to `len`, the `Vec` is simply + /// truncated. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// If you need more flexibility (or want to rely on [`Default`] instead of + /// [`Clone`]), use [`Vec::resize_with`]. + /// If you only need to resize to a smaller size, use [`Vec::truncate`]. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!["hello"]; + /// vec.resize(3, "world"); + /// assert_eq!(vec, ["hello", "world", "world"]); + /// + /// let mut vec = vec!['a', 'b', 'c', 'd']; + /// vec.resize(2, '_'); + /// assert_eq!(vec, ['a', 'b']); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_resize", since = "1.5.0")] + pub fn resize(&mut self, new_len: usize, value: T) { + let len = self.len(); + + if new_len > len { + self.extend_with(new_len - len, value) + } else { + self.truncate(new_len); + } + } + + /// Clones and appends all elements in a slice to the `Vec`. + /// + /// Iterates over the slice `other`, clones each element, and then appends + /// it to this `Vec`. The `other` slice is traversed in-order. + /// + /// Note that this function is the same as [`extend`], + /// except that it also works with slice elements that are Clone but not Copy. + /// If Rust gets specialization this function may be deprecated. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.extend_from_slice(&[2, 3, 4]); + /// assert_eq!(vec, [1, 2, 3, 4]); + /// ``` + /// + /// [`extend`]: Vec::extend + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] + pub fn extend_from_slice(&mut self, other: &[T]) { + self.spec_extend(other.iter()) + } + + /// Given a range `src`, clones a slice of elements in that range and appends it to the end. + /// + /// `src` must be a range that can form a valid subslice of the `Vec`. + /// + /// # Panics + /// + /// Panics if starting index is greater than the end index, if the index is + /// greater than the length of the vector, or if the new capacity exceeds + /// `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut characters = vec!['a', 'b', 'c', 'd', 'e']; + /// characters.extend_from_within(2..); + /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']); + /// + /// let mut numbers = vec![0, 1, 2, 3, 4]; + /// numbers.extend_from_within(..2); + /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]); + /// + /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")]; + /// strings.extend_from_within(1..=2); + /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_extend_from_within", since = "1.53.0")] + pub fn extend_from_within(&mut self, src: R) + where + R: RangeBounds, + { + let range = slice::range(src, ..self.len()); + self.reserve(range.len()); + + // SAFETY: + // - `slice::range` guarantees that the given range is valid for indexing self + unsafe { + self.spec_extend_from_within(range); + } + } +} + +impl Vec { + #[cfg_attr( + not(no_global_oom_handling), + expect( + dead_code, + reason = "currently only used in IO module when global OOM handling is disabled" + ) + )] + pub(crate) fn try_extend_from_slice_of_bytes( + &mut self, + other: &[u8], + ) -> Result<(), TryReserveError> { + // ignore-tidy-undocumented-unsafe + unsafe { self.try_append_elements(other) } + } +} + +impl Vec<[T; N], A> { + /// Takes a `Vec<[T; N]>` and flattens it into a `Vec`. + /// + /// # Panics + /// + /// Panics if the length of the resulting vector would overflow a `usize`. + /// + /// This is only possible when flattening a vector of arrays of zero-sized + /// types, and thus tends to be irrelevant in practice. If + /// `size_of::() > 0`, this will never panic. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + /// assert_eq!(vec.pop(), Some([7, 8, 9])); + /// + /// let mut flattened = vec.into_flattened(); + /// assert_eq!(flattened.pop(), Some(6)); + /// ``` + #[stable(feature = "slice_flatten", since = "1.80.0")] + pub fn into_flattened(self) -> Vec { + let (ptr, len, cap, alloc) = self.into_raw_parts_with_allocator(); + let (new_len, new_cap) = if T::IS_ZST { + ( + len.checked_mul(N).expect("the product of vec len and N shouldn't overflow"), + usize::MAX, + ) + } else { + // SAFETY: + // - `cap * N` cannot overflow because the allocation is already in + // the address space. + // - Each `[T; N]` has `N` valid elements, so there are `len * N` + // valid elements in the allocation. + unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) } + }; + // SAFETY: + // - `ptr` was allocated by `self` + // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`. + // - `new_cap` refers to the same sized allocation as `cap` because + // `new_cap * size_of::()` == `cap * size_of::<[T; N]>()` + // - `len` <= `cap`, so `len * N` <= `cap * N`. + unsafe { Vec::::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) } + } +} + +impl Vec { + #[cfg(not(no_global_oom_handling))] + /// Extend the vector by `n` clones of value. + fn extend_with(&mut self, n: usize, value: T) { + self.spec_extend_with(n, value); + } +} + +impl Vec { + /// Removes consecutive repeated elements in the vector according to the + /// [`PartialEq`] trait implementation. + /// + /// If the vector is sorted, this removes all duplicates. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 2, 3, 2]; + /// + /// vec.dedup(); + /// + /// assert_eq!(vec, [1, 2, 3, 2]); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn dedup(&mut self) { + // Vectorize the process of finding first duplicate if possible + if let Some(chunk_size) = dedup_simd_chunk_size::() { + // Unlike dedup_by, we don't guarantee the order + // and time in which we call `PartialEq::eq`. + let Some(first_duplicate) = find_first_duplicate(self.as_slice(), chunk_size) else { + return; + }; + + // SAFETY: `1 <= first_duplicate < self.len()` + unsafe { + self.dedup_tail(|a, b| a == b, first_duplicate); + } + } else { + self.dedup_by(|a, b| a == b); + } + } +} + +const fn dedup_simd_chunk_size() -> Option { + // The minimal SIMD width on supported platforms + #[allow(unused)] + const SIMD_WIDTH: usize = 16; + let size = size_of::(); + + // We only have SIMD implementations for these element sizes. + if !matches!(size, 1 | 2 | 4 | 8) { + return None; + } + + let simd_width: Option = cfg_select! { + all(target_arch = "arm", target_feature = "neon") => { + // Packed 64-bit integer lane equality is unavailable on arm neon + if size == 8 { None } else { Some(SIMD_WIDTH) } + } + + all(target_arch = "aarch64", target_feature = "neon") => Some(SIMD_WIDTH), + + all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse4.1") => { + Some(SIMD_WIDTH) + } + + all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse2") => { + // Packed 64-bit integer lane equality is only available on sse4.1 + if size == 8 { None } else { Some(SIMD_WIDTH) } + } + + all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "v") => { + Some(SIMD_WIDTH) + } + + all(any(target_arch = "loongarch32", target_arch = "loongarch64"), target_feature = "lsx") => { + Some(SIMD_WIDTH) + } + + _ => None, + }; + + if let Some(simd_width) = simd_width { Some(simd_width * 2 / size) } else { None } +} + +fn find_first_duplicate(v: &[T], chunk_size: usize) -> Option { + let len = v.len(); + if len <= 1 { + return None; + } + + let mut i = 1; + + // The scalar fallback path if the length is not long enough + if len < chunk_size + 1 { + while i < len { + // It keeps the same comparison order as `dedup_tail` + // + // SAFETY: i always in range [1..len) + if unsafe { v.get_unchecked(i) == v.get_unchecked(i - 1) } { + return Some(i); + } + i += 1; + } + return None; + } + + /// # Safety + /// - `start > 0` and `start + chunk_size <= v.len()` + /// - `0 < chunk_size <= 32` + #[inline(always)] + unsafe fn find_duplicate( + v: &[T], + start: usize, + chunk_size: usize, + ) -> Option { + let mut mask: u32 = 0; + debug_assert!( + u32::BITS as usize >= chunk_size, + "the bit width of mask must be greater than or equal to chunk_size" + ); + for j in 0..chunk_size { + // SAFETY: start + j always in range [1..v.len()) + let eq = unsafe { v.get_unchecked(start + j) == v.get_unchecked(start + j - 1) }; + mask |= (eq as u32) << j; + } + if mask != 0 { + return Some(start + mask.trailing_zeros() as usize); + } + None + } + + // This loop performs chunk_size comparisons in parallel without early exit, + // which is what allows for SIMD optimization. + while i + chunk_size <= len { + // SAFETY: `i >= 1` and `i + chunk_size <= len` + if let Some(duplicate) = unsafe { find_duplicate(v, i, chunk_size) } { + return Some(duplicate); + } + i += chunk_size; + } + + // This may check the same elements multiple times. + // However we don't guarantee `PartialEq::eq` is only called once per pair. + if i < len { + let start = len - chunk_size; + // SAFETY: `len - chunk_size >= 1` and `start + chunk_size <= len` + if let Some(duplicate) = unsafe { find_duplicate(v, start, chunk_size) } { + return Some(duplicate); + } + } + + None +} + +//////////////////////////////////////////////////////////////////////////////// +// Internal methods and functions +//////////////////////////////////////////////////////////////////////////////// + +// This function is no longer used internally (`from_elem_global` is used instead). +// It is only kept so as not to break a few crates who mistakenly used it at a +// time when we didn't have the ability to gate internal methods used by public macros. +#[doc(hidden)] +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +// NOTE: the real deprecation version is the same as the stabilization version. +// I.e. it should never have been used even in version 1.0. +#[deprecated(since = "1.101.0", note = "use the `vec!` macro instead")] +pub fn from_elem(elem: T, n: usize) -> Vec { + vec![elem; n] +} + +// This function is required because it ensures the `vec_from_elem` diagnostic +// item is emitted, which is consumed by Clippy to detect calls to +// `vec![elem; n]`. We cannot add the item to `Vec::repeat` because then we +// would end up confusing Clippy. +#[doc(hidden)] +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "liballoc_internals", issue = "none")] +#[rustc_diagnostic_item = "vec_from_elem"] +pub fn from_elem_global(elem: T, n: usize) -> Vec { + Vec::repeat(elem, n) +} + +#[cfg(not(no_global_oom_handling))] +trait ExtendFromWithinSpec { + /// # Safety + /// + /// - `src` needs to be valid index + /// - `self.capacity() - self.len()` must be `>= src.len()` + unsafe fn spec_extend_from_within(&mut self, src: Range); +} + +#[cfg(not(no_global_oom_handling))] +impl ExtendFromWithinSpec for Vec { + default unsafe fn spec_extend_from_within(&mut self, src: Range) { + // SAFETY: + // - len is increased only after initializing elements + let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() }; + + // SAFETY: + // - caller guarantees that src is a valid index + let to_clone = unsafe { this.get_unchecked(src) }; + + iter::zip(to_clone, spare) + .map(|(src, dst)| dst.write(src.clone())) + // Note: + // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len + // - len is increased after each element to prevent leaks (see issue #82533) + .for_each(|_| *len += 1); + } +} + +#[cfg(not(no_global_oom_handling))] +impl ExtendFromWithinSpec for Vec { + #[requires(src.start <= src.end && src.end <= self.len())] + #[requires(src.end - src.start <= self.capacity() - self.len())] + #[ensures(|_| self.len() == old(self.len()) + old(src.end - src.start))] + #[ensures(|_| self.capacity() == old(self.capacity()))] + #[ensures(|_| self.as_ptr() == old(self.as_ptr()))] + #[cfg_attr( + kani, + kani::modifies( + &self.len, + ptr::slice_from_raw_parts(self.as_ptr().wrapping_add(self.len()), src.end - src.start), + ) + )] + unsafe fn spec_extend_from_within(&mut self, src: Range) { + let count = src.len(); + { + let (init, spare) = self.split_at_spare_mut(); + + // SAFETY: + // - caller guarantees that `src` is a valid index + let source = unsafe { init.get_unchecked(src) }; + + // SAFETY: + // - Both pointers are created from unique slice references (`&mut [_]`) + // so they are valid and do not overlap. + // - Elements implement `TrivialClone` so this is equivalent to calling + // `clone` on every one of them. + // - `count` is equal to the len of `source`, so source is valid for + // `count` reads + // - `.reserve(count)` guarantees that `spare.len() >= count` so spare + // is valid for `count` writes + unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) }; + } + + // SAFETY: + // - The elements were just initialized by `copy_nonoverlapping` + self.len += count; + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Common trait implementations for Vec +//////////////////////////////////////////////////////////////////////////////// + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl ops::Deref for Vec { + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl ops::DerefMut for Vec { + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + self.as_mut_slice() + } +} + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl ops::DerefPure for Vec {} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Clone for Vec { + /// Creates a new `Vec` by deep-copying the contents of an existing `Vec`. + /// + /// This method will allocate a new `Vec` and `clone` all of `self`'s contents + /// into it. The capacity of the duplicate `Vec` is not forced to match the + /// capacity of the original. + fn clone(&self) -> Self { + let alloc = self.allocator().clone(); + <[T]>::to_vec_in(self, alloc) + } + + /// Overwrites the contents of `self` with a clone of the contents of `source`. + /// + /// This method is preferred over simply assigning `source.clone()` to `self`, + /// as it avoids reallocation if possible. Additionally, if the element type + /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s + /// elements as well. + /// + /// # Examples + /// + /// ``` + /// let x = vec![5, 6, 7]; + /// let mut y = vec![8, 9, 10]; + /// let yp: *const i32 = y.as_ptr(); + /// + /// y.clone_from(&x); + /// + /// // The value is the same + /// assert_eq!(x, y); + /// + /// // And no reallocation occurred + /// assert_eq!(yp, y.as_ptr()); + /// ``` + fn clone_from(&mut self, source: &Self) { + crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self); + } +} + +/// The hash of a vector is the same as that of the corresponding slice, +/// as required by the `core::borrow::Borrow` implementation. +/// +/// ``` +/// use std::hash::BuildHasher; +/// +/// let b = std::hash::RandomState::new(); +/// let v: Vec = vec![0xa8, 0x3c, 0x09]; +/// let s: &[u8] = &[0xa8, 0x3c, 0x09]; +/// assert_eq!(b.hash_one(v), b.hash_one(s)); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +impl Hash for Vec { + #[inline] + fn hash(&self, state: &mut H) { + Hash::hash(&**self, state) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_index", issue = "143775")] +const impl, A: Allocator> Index for Vec { + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&**self, index) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_index", issue = "143775")] +const impl, A: Allocator> IndexMut for Vec { + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut **self, index) + } +} + +/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`] +/// +/// # Allocation behavior +/// +/// In general `Vec` does not guarantee any particular growth or allocation strategy. +/// That also applies to this trait impl. +/// +/// **Note:** This section covers implementation details and is therefore exempt from +/// stability guarantees. +/// +/// Vec may use any or none of the following strategies, +/// depending on the supplied iterator: +/// +/// * preallocate based on [`Iterator::size_hint()`] +/// * and panic if the number of items is outside the provided lower/upper bounds +/// * use an amortized growth strategy similar to `pushing` one item at a time +/// * perform the iteration in-place on the original allocation backing the iterator +/// +/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory +/// consumption and improves cache locality. But when big, short-lived allocations are created, +/// only a small fraction of their items get collected, no further use is made of the spare capacity +/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large +/// allocations having their lifetimes unnecessarily extended which can result in increased memory +/// footprint. +/// +/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`], +/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces +/// the size of the long-lived struct. +/// +/// [owned slice]: Box +/// +/// ```rust +/// # use std::sync::Mutex; +/// static LONG_LIVED: Mutex>> = Mutex::new(Vec::new()); +/// +/// for i in 0..10 { +/// let big_temporary: Vec = (0..1024).collect(); +/// // discard most items +/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect(); +/// // without this a lot of unused capacity might be moved into the global +/// result.shrink_to_fit(); +/// LONG_LIVED.lock().unwrap().push(result); +/// } +/// ``` +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl FromIterator for Vec { + #[inline] + fn from_iter>(iter: I) -> Vec { + >::from_iter(iter.into_iter()) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + + /// Creates a consuming iterator, that is, one that moves each value out of + /// the vector (from start to end). The vector cannot be used after calling + /// this. + /// + /// # Examples + /// + /// ``` + /// let v = vec!["a".to_string(), "b".to_string()]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, Some("a".to_string())); + /// assert_eq!(v_iter.next(), Some("b".to_string())); + /// assert_eq!(v_iter.next(), None); + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { + let alloc = ManuallyDrop::new(ptr::read(me.allocator())); + let buf = me.buf.non_null(); + let begin = buf.as_ptr(); + let end = if T::IS_ZST { + begin.wrapping_byte_add(me.len()) + } else { + begin.add(me.len()) as *const T + }; + let cap = me.buf.capacity(); + IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end } + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T, A: Allocator> IntoIterator for &'a Vec { + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { + type Item = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Extend for Vec { + #[inline] + fn extend>(&mut self, iter: I) { + >::spec_extend(self, iter.into_iter()) + } + + #[inline] + fn extend_one(&mut self, item: T) { + self.push(item); + } + + #[inline] + fn extend_reserve(&mut self, additional: usize) { + self.reserve(additional); + } + + #[inline] + unsafe fn extend_one_unchecked(&mut self, item: T) { + // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly. + unsafe { + let len = self.len(); + ptr::write(self.as_mut_ptr().add(len), item); + self.set_len(len + 1); + } + } +} + +impl Vec { + // leaf method to which various SpecFrom/SpecExtend implementations delegate when + // they have no further optimizations to apply + #[cfg(not(no_global_oom_handling))] + fn extend_desugared>(&mut self, mut iterator: I) { + // This is the case for a general iterator. + // + // This function should be the moral equivalent of: + // + // for item in iterator { + // self.push(item); + // } + while let Some(element) = iterator.next() { + let len = self.len(); + if len == self.capacity() { + let (lower, _) = iterator.size_hint(); + self.reserve(lower.saturating_add(1)); + } + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::write(self.as_mut_ptr().add(len), element); + // Since next() executes user code which can panic we have to bump the length + // after each step. + // NB can't overflow since we would have had to alloc the address space + self.set_len(len + 1); + } + } + } + + // specific extend for `TrustedLen` iterators, called both by the specializations + // and internal places where resolving specialization makes compilation slower + #[cfg(not(no_global_oom_handling))] + fn extend_trusted(&mut self, iterator: impl iter::TrustedLen) { + let (low, high) = iterator.size_hint(); + if let Some(additional) = high { + debug_assert_eq!( + low, + additional, + "TrustedLen iterator's size hint is not exact: {:?}", + (low, high) + ); + self.reserve(additional); + let ptr = self.as_mut_ptr(); + let mut local_len = SetLenOnDrop::new(&mut self.len); + // ignore-tidy-undocumented-unsafe + unsafe { + iterator.for_each(move |element| { + ptr::write(ptr.add(local_len.current_len()), element); + // Since the loop executes user code which can panic we have to update + // the length every step to correctly drop what we've written. + // NB can't overflow since we would have had to alloc the address space + local_len.increment_len(1); + }); + } + } else { + // Per TrustedLen contract a `None` upper bound means that the iterator length + // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway. + // Since the other branch already panics eagerly (via `reserve()`) we do the same here. + // This avoids additional codegen for a fallback code path which would eventually + // panic anyway. + panic!("capacity overflow"); + } + } + + /// Creates a splicing iterator that replaces the specified range in the vector + /// with the given `replace_with` iterator and yields the removed items. + /// `replace_with` does not need to be the same length as `range`. + /// + /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped. + /// + /// It is unspecified how many elements are removed from the vector + /// if the `Splice` value is leaked. + /// + /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. + /// + /// This is optimal if: + /// + /// * The tail (elements in the vector after `range`) is empty, + /// * or `replace_with` yields fewer or equal elements than `range`'s length + /// * or the lower bound of its `size_hint()` is exact. + /// + /// Otherwise, a temporary vector is allocated and the tail is moved twice. + /// + /// # Panics + /// + /// Panics if the range has `start_bound > end_bound`, or, if the range is + /// bounded on either end and past the length of the vector. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3, 4]; + /// let new = [7, 8, 9]; + /// let u: Vec<_> = v.splice(1..3, new).collect(); + /// assert_eq!(v, [1, 7, 8, 9, 4]); + /// assert_eq!(u, [2, 3]); + /// ``` + /// + /// Using `splice` to insert new items into a vector efficiently at a specific position + /// indicated by an empty range: + /// + /// ``` + /// let mut v = vec![1, 5]; + /// let new = [2, 3, 4]; + /// v.splice(1..1, new); + /// assert_eq!(v, [1, 2, 3, 4, 5]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "vec_splice", since = "1.21.0")] + pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> + where + A: AllocatorNightly, + R: RangeBounds, + I: IntoIterator, + { + Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } + } + + /// Creates an iterator which uses a closure to determine if an element in the range should be removed. + /// + /// If the closure returns `true`, the element is removed from the vector + /// and yielded. If the closure returns `false`, or panics, the element + /// remains in the vector and will not be yielded. + /// + /// Only elements that fall in the provided range are considered for extraction, but any elements + /// after the range will still have to be moved if any element has been extracted. + /// + /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating + /// or the iteration short-circuits, then the remaining elements will be retained. + /// Use `extract_if().for_each(drop)` if you do not need the returned iterator, + /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range. + /// + /// [`retain_mut`]: Vec::retain_mut + /// + /// Using this method is equivalent to the following code: + /// + /// ``` + /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 }; + /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6]; + /// # let mut vec2 = vec.clone(); + /// # let range = 1..5; + /// let mut i = range.start; + /// let end_items = vec.len() - range.end; + /// # let mut extracted = vec![]; + /// + /// while i < vec.len() - end_items { + /// if some_predicate(&mut vec[i]) { + /// let val = vec.remove(i); + /// // your code here + /// # extracted.push(val); + /// } else { + /// i += 1; + /// } + /// } + /// + /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect(); + /// # assert_eq!(vec, vec2); + /// # assert_eq!(extracted, extracted2); + /// ``` + /// + /// But `extract_if` is easier to use. `extract_if` is also more efficient, + /// because it can backshift the elements of the array in bulk. + /// + /// The iterator also lets you mutate the value of each element in the + /// closure, regardless of whether you choose to keep or remove it. + /// + /// # Panics + /// + /// If `range` is out of bounds. + /// + /// # Examples + /// + /// Splitting a vector into even and odd values, reusing the original vector: + /// + /// ``` + /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; + /// + /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::>(); + /// let odds = numbers; + /// + /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); + /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); + /// ``` + /// + /// Using the range argument to only process a part of the vector: + /// + /// ``` + /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]; + /// let ones = items.extract_if(7.., |x| *x == 1).collect::>(); + /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]); + /// assert_eq!(ones.len(), 3); + /// ``` + #[stable(feature = "extract_if", since = "1.87.0")] + pub fn extract_if(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A> + where + A: AllocatorNightly, + F: FnMut(&mut T) -> bool, + R: RangeBounds, + { + ExtractIf::new(self, filter, range) + } +} + +/// Extend implementation that copies elements out of references before pushing them onto the Vec. +/// +/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to +/// append the entire slice at once. +/// +/// [`copy_from_slice`]: slice::copy_from_slice +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "extend_ref", since = "1.2.0")] +impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec { + fn extend>(&mut self, iter: I) { + self.spec_extend(iter.into_iter()) + } + + #[inline] + fn extend_one(&mut self, &item: &'a T) { + self.push(item); + } + + #[inline] + fn extend_reserve(&mut self, additional: usize) { + self.reserve(additional); + } + + #[inline] + unsafe fn extend_one_unchecked(&mut self, &item: &'a T) { + // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly. + unsafe { + let len = self.len(); + ptr::write(self.as_mut_ptr().add(len), item); + self.set_len(len + 1); + } + } +} + +/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison). +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd> for Vec +where + T: PartialOrd, + A1: Allocator, + A2: Allocator, +{ + #[inline] + fn partial_cmp(&self, other: &Vec) -> Option { + PartialOrd::partial_cmp(&**self, &**other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Eq for Vec {} + +/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison). +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Vec { + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(&**self, &**other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const unsafe impl<#[may_dangle] T: [const] Destruct, A: [const] Allocator + [const] Destruct> Drop + for Vec +{ + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + // use drop for [T] + // use a raw slice to refer to the elements of the vector as weakest necessary type; + // could avoid questions of validity in certain cases + self.as_mut_ptr().cast_slice(self.len).drop_in_place() + } + // RawVec handles deallocation + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +const impl Default for Vec { + /// Creates an empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + fn default() -> Vec { + Vec::new() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef> for Vec { + fn as_ref(&self) -> &Vec { + self + } +} + +#[stable(feature = "vec_as_mut", since = "1.5.0")] +impl AsMut> for Vec { + fn as_mut(&mut self) -> &mut Vec { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef<[T]> for Vec { + fn as_ref(&self) -> &[T] { + self + } +} + +#[stable(feature = "vec_as_mut", since = "1.5.0")] +impl AsMut<[T]> for Vec { + fn as_mut(&mut self) -> &mut [T] { + self + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl From<&[T]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); + /// ``` + fn from(s: &[T]) -> Vec { + s.to_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_mut", since = "1.19.0")] +impl From<&mut [T]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); + /// ``` + fn from(s: &mut [T]) -> Vec { + s.to_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array_ref", since = "1.74.0")] +impl From<&[T; N]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: &[T; N]) -> Vec { + Self::from(s.as_slice()) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array_ref", since = "1.74.0")] +impl From<&mut [T; N]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: &mut [T; N]) -> Vec { + Self::from(s.as_mut_slice()) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array", since = "1.44.0")] +impl From<[T; N]> for Vec { + /// Allocates a `Vec` and moves `s`'s items into it. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: [T; N]) -> Vec { + <[T]>::into_vec(Box::new(s)) + } +} + +#[stable(feature = "vec_from_cow_slice", since = "1.14.0")] +impl<'a, T> From> for Vec +where + [T]: ToOwned>, +{ + /// Converts a clone-on-write slice into a vector. + /// + /// If `s` already owns a `Vec`, it will be returned directly. + /// If `s` is borrowing a slice, a new `Vec` will be allocated and + /// filled by cloning `s`'s items into it. + /// + /// # Examples + /// + /// ``` + /// # use std::borrow::Cow; + /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]); + /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]); + /// assert_eq!(Vec::from(o), Vec::from(b)); + /// ``` + fn from(s: Cow<'a, [T]>) -> Vec { + s.into_owned() + } +} + +#[stable(feature = "vec_from_box", since = "1.18.0")] +impl From> for Vec { + /// Converts a boxed slice into a vector by transferring ownership of + /// the existing heap allocation. + /// + /// # Examples + /// + /// ``` + /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice(); + /// assert_eq!(Vec::from(b), vec![1, 2, 3]); + /// ``` + fn from(s: Box<[T], A>) -> Self { + s.into_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "box_from_vec", since = "1.20.0")] +impl From> for Box<[T], A> { + /// Converts a vector into a boxed slice. + /// + /// This is equivalent to [`Vec::into_boxed_slice`]. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); + /// ``` + fn from(v: Vec) -> Self { + v.into_boxed_slice() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl From<&str> for Vec { + /// Allocates a `Vec` and fills it with a UTF-8 string. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']); + /// ``` + fn from(s: &str) -> Vec { + From::from(s.as_bytes()) + } +} + +#[stable(feature = "array_try_from_vec", since = "1.48.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl + TryFrom> for [T; N] +{ + type Error = Vec; + + /// Gets the entire contents of the `Vec` as an array, + /// if its size exactly matches that of the requested array. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3])); + /// assert_eq!(>::new().try_into(), Ok([])); + /// ``` + /// + /// If the length doesn't match, the input comes back in `Err`: + /// ``` + /// let r: Result<[i32; 4], _> = (0..10).collect::>().try_into(); + /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); + /// ``` + /// + /// If you're fine with just getting a prefix of the `Vec`, + /// you can call [`.truncate(N)`](Vec::truncate) first. + /// ``` + /// let mut v = String::from("hello world").into_bytes(); + /// v.sort(); + /// v.truncate(2); + /// let [a, b]: [_; 2] = v.try_into().unwrap(); + /// assert_eq!(a, b' '); + /// assert_eq!(b, b'd'); + /// ``` + fn try_from(mut vec: Vec) -> Result<[T; N], Vec> { + if vec.len() != N { + return Err(vec); + } + + // SAFETY: `.set_len(0)` is always sound. + unsafe { vec.set_len(0) }; + + // SAFETY: A `Vec`'s pointer is always aligned properly, and + // the alignment the array needs is the same as the items. + // We checked earlier that we have sufficient items. + // The items will not double-drop as the `set_len` + // tells the `Vec` not to also drop them. + let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) }; + Ok(array) + } +} + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use core::kani; + + use crate::vec::Vec; + + // Size chosen for testing the empty vector (0), middle element removal (1) + // and last element removal (2) cases while keeping verification tractable + const ARRAY_LEN: usize = 3; + + #[kani::proof] + pub fn verify_swap_remove() { + // Creating a vector directly from a fixed length arbitrary array + let mut arr: [i32; ARRAY_LEN] = kani::Arbitrary::any_array(); + let mut vect = Vec::from(&arr); + + // Recording the original length and a copy of the vector for validation + let original_len = vect.len(); + let original_vec = vect.clone(); + + // Generating a nondeterministic index which is guaranteed to be within bounds + let index: usize = kani::any_where(|x| *x < original_len); + + let removed = vect.swap_remove(index); + + // Verifying that the length of the vector decreases by one after the operation is performed + assert!(vect.len() == original_len - 1, "Length should decrease by 1"); + + // Verifying that the removed element matches the original element at the index + assert!(removed == original_vec[index], "Removed element should match original"); + + // Verifying that the removed index now contains the element originally at the vector's last index if applicable + if index < original_len - 1 { + assert!( + vect[index] == original_vec[original_len - 1], + "Index should contain last element" + ); + } + + // Check that all other unaffected elements remain unchanged + let k = kani::any_where(|&x: &usize| x < original_len - 1); + if k != index { + assert!(vect[k] == arr[k]); + } + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/safety_stub.rs b/verifast-proofs/alloc/vec/mod.rs/safety_stub.rs new file mode 100644 index 0000000000000..f7f0573a899ff --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/safety_stub.rs @@ -0,0 +1,22 @@ +extern crate proc_macro; +use proc_macro::TokenStream; +#[proc_macro_attribute] +pub fn requires(_: TokenStream, item: TokenStream) -> TokenStream { + item +} +#[proc_macro_attribute] +pub fn ensures(_: TokenStream, item: TokenStream) -> TokenStream { + item +} +#[proc_macro_attribute] +pub fn loop_invariant(_: TokenStream, item: TokenStream) -> TokenStream { + item +} +#[proc_macro_attribute] +pub fn invariant(_: TokenStream, item: TokenStream) -> TokenStream { + item +} +#[proc_macro_derive(Invariant)] +pub fn derive_invariant(_: TokenStream) -> TokenStream { + TokenStream::new() +} diff --git a/verifast-proofs/alloc/vec/mod.rs/set_len_on_drop_proof.rs b/verifast-proofs/alloc/vec/mod.rs/set_len_on_drop_proof.rs new file mode 100644 index 0000000000000..788c30996be50 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/set_len_on_drop_proof.rs @@ -0,0 +1,202 @@ +#![feature(negative_impls)] + +use std::marker::PhantomData; + +// Companion VeriFast 26.10 proof of `alloc::vec::set_len_on_drop::SetLenOnDrop`, +// verified WITHOUT `-allow_assume` (strictly zero `assume` statements). +// +// Why this companion file is run alongside `verified/set_len_on_drop.rs`: +// 1. VeriFast 26.10 rejects verifying `impl Drop for SetLenOnDrop<'_>` with: +// "A drop function for a struct type whose type arguments are not identical +// to its type parameters is not yet supported" (due to elided `'_`), while +// `refinement-checker` rejects changing `'_` to `<'a>` in `verified/`. +// 2. VeriFast 26.10 runs a public-API `safety_proof` on `pub(super) fn increment_len` +// ignoring Rust's `pub(super)` module privacy; `SetLenOnDrop` is an internal +// `alloc::vec` scope guard whose `increment_len` is sound specifically under its +// caller-discharged bound (`s0.local_len + increment <= bound <= usize::MAX`). +// 3. For `impl<'a> Drop`, VeriFast 26.10's automatic Drop-glue postcondition requires +// `.own` for every field (`<&'a mut usize>.own == full_borrow('a, +// usize_full_borrow_content)`), which cannot be weakened from the stronger +// `full_borrow('a, SetLenOnDrop_fbc(s.len, bound))` even though `&'a mut usize` +// has no-op drop glue. We therefore verify BOTH: +// - `SetLenOnDrop<'a>` (exact `&'a mut usize` field and safe executable bodies +// for `new`, `increment_len`, and both bounded/exact `*self.len = self.local_len;` +// writeback helpers), AND +// - `SetLenOnDropTrait<'a>` (real Rust `impl<'a> Drop`, holding `len: *mut usize` +// + invariant `PhantomData &'a ()>` so `Drop::drop` enforces the +// exact bounded `SetLenOnDrop_fbc(s.len, bound)` invariant on writeback with +// zero `assume` statements). +// +// `verify.sh` programmatically checks that the executable bodies of `new`, +// `increment_len`, and `drop` below match `library/alloc/src/vec/set_len_on_drop.rs` +// statement-for-statement (with the explicit `unsafe { ... }` wrapper on +// `SetLenOnDropTrait::drop`). + +pub struct SetLenOnDrop<'a> { + len: &'a mut usize, + local_len: usize, +} + +/*@ +pred_ctor SetLenOnDrop_fbc(p: *usize, bound: usize)() = + *p |-> ?actual &*& actual <= bound; + +pred SetLenOnDrop_guarded<'a>(s: SetLenOnDrop<'a>, k: lifetime_t, bound: usize) = + 0 <= bound &*& bound <= usize::MAX &*& + s.local_len <= bound &*& + full_borrow(k, SetLenOnDrop_fbc(s.len, bound)); +@*/ + +impl<'a> SetLenOnDrop<'a> { + #[inline] + pub unsafe fn new_checked(len: &'a mut usize) -> Self + //@ req *len |-> ?v; + //@ ens *len |-> v &*& result == SetLenOnDrop::<'a> { len: len, local_len: v }; + { + SetLenOnDrop { local_len: *len, len } + } + + #[inline] + pub unsafe fn increment_len_checked(&mut self, increment: usize) + //@ req *self |-> ?s0 &*& s0.local_len + increment <= usize::MAX; + //@ ens *self |-> SetLenOnDrop::<'a> { len: s0.len, local_len: s0.local_len + increment }; + { + //@ open_points_to(self); + self.local_len += increment; + //@ close_points_to(self); + } + + #[inline] + pub unsafe fn increment_len_preserves_bound(&mut self, increment: usize) + //@ req *self |-> ?s0 &*& SetLenOnDrop_guarded::<'a>(s0, ?k, ?bound) &*& s0.local_len + increment <= bound; + //@ ens *self |-> ?s1 &*& s1 == SetLenOnDrop::<'a> { len: s0.len, local_len: s0.local_len + increment } &*& SetLenOnDrop_guarded::<'a>(s1, k, bound); + { + //@ open SetLenOnDrop_guarded::<'a>(s0, k, bound); + //@ open_points_to(self); + self.local_len += increment; + //@ close_points_to(self); + //@ close SetLenOnDrop_guarded::<'a>(*self, k, bound); + } + + #[inline] + pub unsafe fn drop_writeback_preserves_fbc(&mut self) + //@ req *self |-> ?s0 &*& [?q]lifetime_token(?k) &*& SetLenOnDrop_guarded::<'a>(s0, k, ?bound); + //@ ens *self |-> s0 &*& [q]lifetime_token(k) &*& full_borrow(k, SetLenOnDrop_fbc(s0.len, bound)); + { + //@ open SetLenOnDrop_guarded::<'a>(s0, k, bound); + //@ open_points_to(self); + //@ open_full_borrow(q, k, SetLenOnDrop_fbc(s0.len, bound)); + //@ open SetLenOnDrop_fbc(s0.len, bound)(); + *self.len = self.local_len; + //@ close SetLenOnDrop_fbc(s0.len, bound)(); + //@ close_full_borrow(SetLenOnDrop_fbc(s0.len, bound)); + //@ close_points_to(self); + } + + #[inline] + pub unsafe fn drop_writeback_exact(&mut self) + //@ req *self |-> ?s0 &*& *s0.len |-> _; + //@ ens *self |-> s0 &*& *s0.len |-> s0.local_len; + { + //@ open_points_to(self); + *self.len = self.local_len; + //@ close_points_to(self); + } +} + +// Also verify a full Rust `impl<'a> Drop for SetLenOnDropTrait<'a>` trait impl +// carrying the unified crate's exact bounded `SetLenOnDrop_fbc(s.len, bound)` +// ownership invariant (`0 <= bound <= usize::MAX`, `s.local_len <= bound`, +// `full_borrow('a, SetLenOnDrop_fbc(s.len, bound))`) — zero `assume` statements. +pub struct SetLenOnDropTrait<'a> { + len: *mut usize, + local_len: usize, + _marker: PhantomData &'a ()>, +} + +/*@ +pred<'a> >.own(t, s) = + exists::(?bound) &*& + 0 <= bound &*& bound <= usize::MAX &*& + s.local_len <= bound &*& + full_borrow('a, SetLenOnDrop_fbc(s.len, bound)); +@*/ + +impl<'a> !Send for SetLenOnDropTrait<'a> {} + +impl<'a> SetLenOnDropTrait<'a> { + #[inline] + pub unsafe fn new(len: &'a mut usize) -> Self + /*@ + req thread_token(?t) &*& [?q]lifetime_token('a) &*& + exists::(?bound) &*& 0 <= bound &*& bound <= usize::MAX &*& + full_borrow('a, SetLenOnDrop_fbc(len, bound)); + @*/ + //@ ens thread_token(t) &*& [q]lifetime_token('a) &*& >.own(t, result); + { + //@ open exists::(bound); + //@ let klong = open_full_borrow_strong('a, SetLenOnDrop_fbc(len, bound), q); + //@ open SetLenOnDrop_fbc(len, bound)(); + let local_len = *len; + /*@ + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + SetLenOnDrop_fbc(len, bound), + klong, + SetLenOnDrop_fbc(len, bound) + )() { + open Ctx(); + } { + close Ctx(); + close SetLenOnDrop_fbc(len, bound)(); + close_full_borrow_strong(klong, SetLenOnDrop_fbc(len, bound), SetLenOnDrop_fbc(len, bound)); + full_borrow_mono(klong, 'a, SetLenOnDrop_fbc(len, bound)); + } + } + @*/ + let res = SetLenOnDropTrait { local_len, len: len as *mut usize, _marker: PhantomData }; + //@ close exists::(bound); + //@ close >.own(t, res); + res + } + + #[inline] + pub unsafe fn increment_len(&mut self, increment: usize) + /*@ + req thread_token(?t) &*& + (*self).len |-> ?p &*& (*self).local_len |-> ?l &*& + exists::(?bound) &*& 0 <= bound &*& bound <= usize::MAX &*& + l + increment <= bound &*& + full_borrow('a, SetLenOnDrop_fbc(p, bound)); + @*/ + /*@ + ens thread_token(t) &*& + (*self).len |-> p &*& (*self).local_len |-> l + increment &*& + exists::(bound) &*& 0 <= bound &*& bound <= usize::MAX &*& + l + increment <= bound &*& + full_borrow('a, SetLenOnDrop_fbc(p, bound)); + @*/ + { + //@ open exists::(bound); + self.local_len += increment; + //@ close exists::(bound); + } +} + +impl<'a> Drop for SetLenOnDropTrait<'a> { + #[inline] + fn drop(&mut self) { + //@ open >.full_borrow_content(_t, self)(); + //@ open >.own(_t, ?s0); + //@ open exists::(?bound); + //@ open_points_to(self); + //@ open_full_borrow(_q_a, 'a, SetLenOnDrop_fbc(s0.len, bound)); + //@ open SetLenOnDrop_fbc(s0.len, bound)(); + unsafe { *self.len = self.local_len; } + //@ close SetLenOnDrop_fbc(s0.len, bound)(); + //@ close_full_borrow(SetLenOnDrop_fbc(s0.len, bound)); + //@ leak full_borrow('a, SetLenOnDrop_fbc(s0.len, bound)); + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/sync_raw_vec.py b/verifast-proofs/alloc/vec/mod.rs/sync_raw_vec.py new file mode 100644 index 0000000000000..5f07d7345852d --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/sync_raw_vec.py @@ -0,0 +1,268 @@ +#!/usr/bin/env python3 +"""Synchronize verifast-proofs/alloc/vec/mod.rs/verified/raw_vec_mod.rs from +the accepted Ch19 proof verifast-proofs/alloc/raw_vec/mod.rs/verified/raw_vec.rs. + +Preserves the Ch19 specifications used by `Vec`, adapts the crate-internal +`std::collections` VeriFast import path to `collections`, replaces the two +upstream `assume(false)` placeholders for verifast#610 with explicit subtype +upcast axioms (zero `assume(false)`), adds a single trusted +`RawVecInner::reserve` (`//@ assume_correct`) spec plus a verified +`RawVec::reserve` ghost wrapper (zero extra `assume`s), strips 6 uncalled Ch19 +specs (`into_box`, `with_capacity_in` x2, `shrink_to_fit` x2, `handle_error`) +that are independently verified in `verifast-proofs/alloc/raw_vec/mod.rs`, and +removes trailing whitespace. + +Pass `--check` to verify that `verified/raw_vec_mod.rs` matches the generated +output byte-for-byte without modifying it. +""" +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SRC = HERE / "../../raw_vec/mod.rs/verified/raw_vec.rs" +DST = HERE / "verified/raw_vec_mod.rs" + +txt = SRC.read_text() + +old_import = "//@ use std::collections::{TryReserveError, TryReserveErrorKind};" +assert old_import in txt, "Expected std::collections VeriFast import not found" +txt = txt.replace("std::collections::", "collections::") + +old_inner_mono = """lem RawVecInner_own_mono() + req type_interp::() &*& type_interp::() &*& RawVecInner_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& RawVecInner_own::(t, RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }); +{ + assume(false); // https://github.com/verifast/verifast/issues/610 +}""" + +new_inner_mono = """lem RawVecInner_own_mono() + req type_interp::() &*& type_interp::() &*& RawVecInner_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& RawVecInner_own::(t, RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }); +{ + open RawVecInner_own::(t, v); + open RawVecInner0(v, ?elemLayout, ?ptr, ?capacity); + own_mono::(t, v.alloc); + std::ptr::NonNull_upcast::(v.ptr); + // `upcast` on `UsizeNoHighBit` is identity (https://github.com/verifast/verifast/issues/610). + assume(upcast::(v.cap) == v.cap); + let v1 = RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }; + close RawVecInner0::(v1, elemLayout, ptr, capacity); + close RawVecInner_own::(t, v1); +}""" + +assert old_inner_mono in txt, "Expected RawVecInner_own_mono not found" +txt = txt.replace(old_inner_mono, new_inner_mono, 1) + +old_rv_mono = """lem RawVec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +{ + assume(false); // https://github.com/verifast/verifast/issues/610 +}""" + +new_rv_mono = """lem RawVec_mono(t: thread_id_t, v: RawVec) + req RawVec::(t, v, ?alloc_id, ?ptr, ?capacity) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens RawVec::(t, RawVec:: { inner: upcast(v.inner) }, alloc_id, ptr as *T1, capacity) &*& + std::mem::size_of::() == std::mem::size_of::() &*& std::mem::align_of::() == std::mem::align_of::(); +{ + open RawVec::(t, v, alloc_id, ptr, capacity); + open RawVecInner::(t, v.inner, Layout::new::(), alloc_id, ?ptr_, capacity); + std::alloc::Allocator_upcast::(v.inner.alloc); + std::ptr::NonNull_upcast::(v.inner.ptr); + // Rust subtyping preserves type layout and upcasts fields componentwise (verifast#610). + assume(std::mem::size_of::() == std::mem::size_of::() && std::mem::align_of::() == std::mem::align_of::()); + assume(upcast::, RawVecInner>(v.inner) == RawVecInner:: { ptr: upcast(v.inner.ptr), cap: upcast(v.inner.cap), alloc: upcast(v.inner.alloc) }); + assume(upcast::(v.inner.cap) == v.inner.cap); + close RawVecInner::(t, upcast(v.inner), Layout::new::(), alloc_id, ptr_, capacity); + close RawVec::(t, RawVec:: { inner: upcast(v.inner) }, alloc_id, ptr as *T1, capacity); +} + +lem RawVec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +{ + open RawVec_own::(t, v); + assert RawVec::(t, v, ?alloc_id, ?ptr, ?capacity); + RawVec_mono::(t, v); + array_at_lft__to_u8s_at_lft_::(ptr, capacity); + u8s_at_lft__to_array_at_lft_::(ptr as *T1, capacity); + close RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +}""" + +assert old_rv_mono in txt, "Expected RawVec_own_mono not found" +txt = txt.replace(old_rv_mono, new_rv_mono, 1) + +# `RawVec::into_box` returns crate-local `boxed::Box` when compiled inside crate `alloc`, +# whereas the standalone Ch19 proof uses `std::boxed::Box_in`. `into_box` is verified in +# `verifast-proofs/alloc/raw_vec/mod.rs` and is not called by `Vec::extend_desugared`. +old_into_box = """ pub(crate) unsafe fn into_box(mut self, len: usize) -> Box<[MaybeUninit], A> + //@ req thread_token(?t) &*& RawVec(t, self, ?alloc_id, ?ptr, ?capacity_) &*& array_at_lft_(alloc_id.lft, ptr as *T, len, ?vs) &*& if std::mem::size_of::() == 0 { true } else { len == capacity_ }; + //@ ens thread_token(t) &*& std::boxed::Box_in::<[std::mem::MaybeUninit], A>(t, result, alloc_id, slice_of_elems(map(std::mem::MaybeUninit::new_maybe_uninit, vs))); + //@ on_unwind_ens thread_token(t);""" + +new_into_box = """ pub(crate) unsafe fn into_box(mut self, len: usize) -> Box<[MaybeUninit], A>""" + +assert old_into_box in txt, "Expected RawVec::into_box spec not found" +txt = txt.replace(old_into_box, new_into_box, 1) + +# `RawVecInner::reserve` calls Ch19's verified `needs_to_grow` + `grow_amortized` +# through a nested `#[cold] unsafe fn do_reserve_and_handle` + `handle_error -> !`. +# VeriFast 26.10's preprocessor rejects specs on nested `fn` items inside a function +# body (`crate::VeriFast_ghost_command()` syntax error), which is why upstream Ch19 +# left `RawVecInner::reserve` unannotated and proved the capacity bound in +# `RawVecInner::try_reserve` immediately below. Additionally, VeriFast 26.10's +# built-in `Allocator::grow` spec (`std/lib.rsspec:1308`) returns uninitialized `_` +# bytes rather than preserving the `0..old_layout.size()` prefix. Folding both +# obligations into this single trusted `RawVecInner::reserve` spec lets +# `RawVec::reserve` and `Vec::reserve` propagate `elems` with zero extra `assume`s +# and no free-standing value-manufacturing lemma. +old_rv_reserve = """ #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn reserve(&mut self, len: usize, additional: usize) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve(len, additional, T::LAYOUT) } + }""" + +new_rv_reserve = """ #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn reserve(&mut self, len: usize, additional: usize) + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, ?vs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, ?vs1) &*& + (len > capacity0 || (len + additional <= capacity1 && take(len, vs1) == take(len, vs0))); + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + call(); + close >.own(_t, *self); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + /*@ + if len <= capacity0 { + array_at_lft__split(ptr0, len); + array_at_lft__to_u8s_at_lft_(ptr0, len); + assert array_at_lft_(alloc_id.lft, ptr0 as *u8, len * std::mem::size_of::(), ?bs_i); + array_at_lft__to_u8s_at_lft_(ptr0 + len, capacity0 - len); + assert array_at_lft_(alloc_id.lft, (ptr0 + len) as *u8, (capacity0 - len) * std::mem::size_of::(), ?bs_s); + array_at_lft__join(ptr0 as *u8); + take_append(len * std::mem::size_of::(), bs_i, bs_s); + } else { + array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + } + @*/ + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve(len, additional, T::LAYOUT) } + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + //@ close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + /*@ + if len <= capacity0 { + assert array_at_lft_(alloc_id.lft, ptr1 as *u8, capacity1 * std::mem::size_of::(), ?bs1); + std::alloc::Layout_inv(std::alloc::Layout::new::()); + mul_mono_l(len, capacity1, std::mem::size_of::()); + array_at_lft__split(ptr1 as *u8, len * std::mem::size_of::()); + u8s_at_lft__to_array_at_lft_(ptr1, len); + { + lem ptr_add_aligned(p: *T, n: usize) + req 0 <= n &*& 0 <= p as usize &*& p as usize % std::mem::align_of::() == 0 &*& + 0 <= std::mem::size_of::() &*& std::mem::size_of::() % std::mem::align_of::() == 0 &*& + 0 < std::mem::align_of::(); + ens 0 <= (p + n) as usize &*& (p + n) as usize % std::mem::align_of::() == 0; + { + if n > 0 { + ptr_add_aligned(p, n - 1); + let al = std::mem::align_of::(); + let sz = std::mem::size_of::(); + div_rem_nonneg((p + (n - 1)) as usize, al); + div_rem_nonneg(sz, al); + div_rem_nonneg_unique((p + n) as usize, al, (p + (n - 1)) as usize / al + sz / al, 0); + } + } + ptr_add_aligned(ptr1, len); + } + u8s_at_lft__to_array_at_lft_(ptr1 + len, capacity1 - len); + assert array_at_lft_(alloc_id.lft, ptr1, len, ?vs1_i); + assert array_at_lft_(alloc_id.lft, ptr1 + len, capacity1 - len, ?vs1_s); + array_at_lft__join(ptr1); + take_append(len, vs1_i, vs1_s); + } else { + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + @*/ + }""" + +assert old_rv_reserve in txt, "Expected RawVec::reserve not found" +txt = txt.replace(old_rv_reserve, new_rv_reserve, 1) + +old_rvi_reserve = """ #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) {""" + +new_rvi_reserve = """ #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), ?bs1) &*& + (len > capacity0 || (len + additional <= capacity1 && take(len * elem_layout.size(), bs1) == take(len * elem_layout.size(), bs0))); + @*/ + //@ assume_correct + {""" + +assert old_rvi_reserve in txt, "Expected RawVecInner::reserve not found" +txt = txt.replace(old_rvi_reserve, new_rvi_reserve, 1) + +# `handle_error`, `with_capacity_in`, and `shrink_to_fit` are verified in +# `verifast-proofs/alloc/raw_vec/mod.rs` and are not called by `Vec::extend_desugared` +# or `SpecExtendWith::spec_extend_with`. +def strip_fn_spec(text: str, sig_line: str) -> str: + idx = text.index(sig_line) + end_sig = idx + len(sig_line) + brace = text.index("\n {\n", end_sig) if sig_line.startswith(" ") else text.index("\n{\n", end_sig) + return text[:end_sig] + text[brace:] + +for sig in [ + " pub(crate) fn with_capacity_in(capacity: usize, alloc: A) -> Self", + " pub(crate) fn shrink_to_fit(&mut self, cap: usize)", + " fn with_capacity_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self", + " unsafe fn shrink_to_fit(&mut self, cap: usize, elem_layout: Layout)", + "const fn handle_error(e: TryReserveError) -> !", +]: + txt = strip_fn_spec(txt, sig) + +# Strip trailing whitespace on every line so git diff --check is clean. +lines = [line.rstrip(" \t") for line in txt.splitlines()] +rendered = "\n".join(lines) + "\n" +assert "assume(false)" not in rendered, "assume(false) leaked into raw_vec_mod.rs!" + +if "--check" in sys.argv[1:]: + actual = DST.read_text() if DST.exists() else "" + if actual != rendered: + print(f"ERROR: {DST} is out of sync with sync_raw_vec.py / Ch19 raw_vec.rs!", file=sys.stderr) + sys.exit(1) + print(f"OK: {DST} matches sync_raw_vec.py ({len(lines)} lines, 0 assume(false))") +else: + DST.write_text(rendered) + print(f"Synced {DST} ({len(lines)} lines, 0 assume(false))") diff --git a/verifast-proofs/alloc/vec/mod.rs/update.sh b/verifast-proofs/alloc/vec/mod.rs/update.sh new file mode 100644 index 0000000000000..ab994a4e81d11 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/update.sh @@ -0,0 +1,23 @@ +set -x -e + +if ! git diff --quiet .; then + echo "Working directory not clean. Please stash your changes and try again" + false +else + UPSTREAM_VEC=../../../../library/alloc/src/vec/mod.rs + UPSTREAM_SEW=../../../../library/alloc/src/vec/spec_extend_with.rs + UPSTREAM_SLOD=../../../../library/alloc/src/vec/set_len_on_drop.rs + + git merge-file --diff3 verified/vec_mod.rs original/vec_mod.rs "$UPSTREAM_VEC" + cp "$UPSTREAM_VEC" original/vec_mod.rs + + git merge-file --diff3 with-directives/spec_extend_with.rs original/spec_extend_with.rs "$UPSTREAM_SEW" + git merge-file --diff3 verified/spec_extend_with.rs original/spec_extend_with.rs "$UPSTREAM_SEW" + cp "$UPSTREAM_SEW" original/spec_extend_with.rs + + git merge-file --diff3 verified/set_len_on_drop.rs original/set_len_on_drop.rs "$UPSTREAM_SLOD" + cp "$UPSTREAM_SLOD" original/set_len_on_drop.rs + + # Keep verified/raw_vec_mod.rs synchronized with the accepted Ch19 RawVec proof + python3 sync_raw_vec.py +fi diff --git a/verifast-proofs/alloc/vec/mod.rs/verified/raw_vec_mod.rs b/verifast-proofs/alloc/vec/mod.rs/verified/raw_vec_mod.rs new file mode 100644 index 0000000000000..3e8792166fbee --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/verified/raw_vec_mod.rs @@ -0,0 +1,3356 @@ +#![unstable(feature = "raw_vec_internals", reason = "unstable const warnings", issue = "none")] +#![cfg_attr(test, allow(dead_code))] + +//@ use std::num::{niche_types::UsizeNoHighBit, NonZero}; +//@ use std::mem::Alignment; +//@ use std::ptr::{NonNull, NonNull_ptr, Unique}; +//@ use std::alloc::{Layout, alloc_id_t, Allocator, alloc_block_in}; +//@ use std::option::Option; + +// Note: This module is also included in the alloctests crate using #[path] to +// run the tests. See the comment there for an explanation why this is the case. + +use core::marker::{Destruct, PhantomData}; +use core::mem::{Alignment, ManuallyDrop, MaybeUninit, SizedTypeProperties}; +use core::panic::UnwindSafe; +use core::ptr::{self, NonNull}; +use core::{cmp, hint}; + +#[cfg(not(no_global_oom_handling))] +use crate::alloc::handle_alloc_error; +use crate::alloc::{Allocator, Global, Layout}; +use crate::boxed::Box; +use crate::collections::TryReserveError; +use crate::collections::TryReserveErrorKind::*; + +//@ use collections::{TryReserveError, TryReserveErrorKind}; + +#[cfg(test)] +mod tests; + +/*@ + +lem mul_zero(x: i32, y: i32) + req 0 <= x &*& 0 <= y; + ens (x * y == 0) == (x == 0 || y == 0); +{ + if x == 0 { + if y == 0 { + } else { + } + } else { + if y == 0 { + } else { + mul_mono_l(1, y, x); + } + } +} + +@*/ + +// One central function responsible for reporting capacity overflows. This'll +// ensure that the code generation related to these panics is minimal as there's +// only one location which panics rather than a bunch throughout the module. +#[cfg(not(no_global_oom_handling))] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +const fn capacity_overflow() -> ! +//@ req thread_token(?t); +//@ ens false; +{ + panic!("capacity overflow"); +} + +enum AllocInit { + /// The contents of the new memory are uninitialized. + Uninitialized, + #[cfg(not(no_global_oom_handling))] + /// The new memory is guaranteed to be zeroed. + Zeroed, +} + +type Cap = core::num::niche_types::UsizeNoHighBit; + +//@ fix Cap::new(n: usize) -> UsizeNoHighBit { UsizeNoHighBit::new(n) } + +const ZERO_CAP: Cap = unsafe { Cap::new_unchecked(0) }; + +/// `Cap(cap)`, except if `T` is a ZST then `Cap::ZERO`. +/// +/// # Safety: cap must be <= `isize::MAX`. +const unsafe fn new_cap(cap: usize) -> Cap +//@ req std::mem::size_of::() == 0 || cap <= isize::MAX; +//@ ens result == if std::mem::size_of::() == 0 { Cap::new(0) } else { Cap::new(cap) }; +//@ on_unwind_ens false; +{ + if T::IS_ZST { ZERO_CAP } else { unsafe { Cap::new_unchecked(cap) } } +} + +/// A low-level utility for more ergonomically allocating, reallocating, and deallocating +/// a buffer of memory on the heap without having to worry about all the corner cases +/// involved. This type is excellent for building your own data structures like Vec and VecDeque. +/// In particular: +/// +/// * Produces `NonNull::dangling()` on zero-sized types. +/// * Produces `NonNull::dangling()` on zero-length allocations. +/// * Avoids freeing `NonNull::dangling()`. +/// * Catches all overflows in capacity computations (promotes them to "capacity overflow" panics). +/// * Guards against 32-bit systems allocating more than `isize::MAX` bytes. +/// * Provides niches for capacities greater than `isize::MAX`. +/// * Guards against overflowing your length. +/// * Calls `handle_alloc_error` for fallible allocations. +/// * Implements `Send`, `Sync` and `UnwindSafe` iff `(T, A)` does. +/// * Carries `PhantomData` for auto trait and `may_dangle` correctness. +/// * Uses the excess returned from the allocator to use the largest available capacity. +/// +/// This type does not in anyway inspect the memory that it manages. When dropped it *will* +/// free its memory, but it *won't* try to drop its contents. It is up to the user of `RawVec` +/// to handle the actual things *stored* inside of a `RawVec`. +/// +/// Note that the excess of a zero-sized types is always infinite, so `capacity()` always returns +/// `usize::MAX`. This means that you need to be careful when round-tripping this type with a +/// `Box<[T]>`, since `capacity()` won't yield the length. +#[allow(missing_debug_implementations)] +pub(crate) struct RawVec { + inner: RawVecInner, + _marker: PhantomData, +} + +/// Like a `RawVec`, but only generic over the allocator, not the type. +/// +/// As such, all the methods need the layout passed-in as a parameter. +/// +/// Having this separation reduces the amount of code we need to monomorphize, +/// as most operations don't need the actual type, just its layout. +#[allow(missing_debug_implementations)] +struct RawVecInner { + ptr: NonNull, + /// Never used for ZSTs; it's `capacity()`'s responsibility to return usize::MAX in that case. + /// + /// # Safety + /// + /// `cap` must be in the `0..=isize::MAX` range. + cap: Cap, + alloc: A, +} + +// FIXME: Consider moving these impls to `RawVec`, once #162850 is resolved. +unsafe impl Send for RawVecInner {} +unsafe impl Sync for RawVecInner {} +impl UnwindSafe for RawVecInner {} + +/*@ + +fix logical_capacity(cap: UsizeNoHighBit, elem_size: usize) -> usize { + if elem_size == 0 { usize::MAX } else { cap.as_inner() } +} + +pred RawVecInner(t: thread_id_t, self: RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + Allocator(t, self.alloc, alloc_id) &*& + capacity == logical_capacity(self.cap, elemLayout.size()) &*& + ptr == self.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + +pred_ctor RawVecInner_full_borrow_content_(t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize)() = + *l |-> ?self_ &*& RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + +pred RawVecInner_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + full_borrow(k, RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity)); + +lem RawVecInner_send_(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVecInner::(?t0, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& RawVecInner::(t1, self_, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner(t0, self_, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_send(t1, self_.alloc); + close RawVecInner(t1, self_, elemLayout, alloc_id, ptr, capacity); +} + +pred RawVecInner0(self: RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize) = + capacity == logical_capacity(self.cap, elemLayout.size()) &*& + ptr == self.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +pred >.own(t, self_) = + .own(t, self_.alloc) &*& + RawVecInner0(self_, ?elemLayout, ?ptr, ?capacity); + +lem RawVecInner_drop() + req RawVecInner_own::(?_t, ?_v); + ens std::num::niche_types::UsizeNoHighBit_own(_t, _v.cap) &*& .own(_t, _v.alloc); +{ + open RawVecInner_own::(_t, _v); + open RawVecInner0(_, _, _, _); + std::num::niche_types::close_UsizeNoHighBit_own(_t, _v.cap); +} + +lem RawVecInner_own_mono() + req type_interp::() &*& type_interp::() &*& RawVecInner_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& RawVecInner_own::(t, RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }); +{ + open RawVecInner_own::(t, v); + open RawVecInner0(v, ?elemLayout, ?ptr, ?capacity); + own_mono::(t, v.alloc); + std::ptr::NonNull_upcast::(v.ptr); + // `upcast` on `UsizeNoHighBit` is identity (https://github.com/verifast/verifast/issues/610). + assume(upcast::(v.cap) == v.cap); + let v1 = RawVecInner:: { ptr: upcast(v.ptr), cap: upcast(v.cap), alloc: upcast(v.alloc) }; + close RawVecInner0::(v1, elemLayout, ptr, capacity); + close RawVecInner_own::(t, v1); +} + +lem RawVecInner_send(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVecInner_own::(?t0, ?v); + ens type_interp::() &*& RawVecInner_own::(t1, v); +{ + open RawVecInner_own::(t0, v); + Send::send::(t0, t1, v.alloc); + close RawVecInner_own::(t1, v); +} + +lem_auto RawVecInner_inv() + req RawVecInner::(?t, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens RawVecInner::(t, self_, elemLayout, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % elemLayout.align() == 0 &*& + elemLayout.repeat(capacity) != none &*& + 0 <= capacity &*& capacity <= usize::MAX; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + std::alloc::Allocator_inv(); + std::alloc::Layout_inv(elemLayout); + close RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_inv2() + req RawVecInner::(?t, ?self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens RawVecInner::(t, self_, elemLayout, alloc_id, ptr, capacity) &*& + pointer_within_limits(ptr) == true &*& ptr as usize % elemLayout.align() == 0 &*& + 0 <= capacity &*& capacity <= usize::MAX &*& + if elemLayout.size() == 0 { capacity == usize::MAX } else { capacity <= isize::MAX }; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +pred_ctor RawVecInner_frac_borrow_content(l: *RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize)(;) = + struct_RawVecInner_padding(l) &*& + (*l).ptr |-> ?u &*& + (*l).cap |-> ?cap &*& + capacity == logical_capacity(cap, elemLayout.size()) &*& + ptr == u.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +pred RawVecInner_share_(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + pointer_within_limits(&(*l).alloc) == true &*& + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, alloc_id) &*& + elemLayout.repeat(capacity) != none &*& capacity <= usize::MAX &*& + [_]frac_borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& ptr != 0; + +lem RawVecInner_share__inv() + req [_]RawVecInner_share_::(?k, ?t, ?l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens ptr != 0 &*& elemLayout.repeat(capacity) != none &*& capacity <= usize::MAX; +{ + open RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_share__mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVecInner_share_::(k, t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& [_]RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + frac_borrow_mono(k, k1, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + close RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_::(k1, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem RawVecInner_sync_(t1: thread_id_t) + req type_interp::() &*& is_Sync(typeid(A)) == true &*& [_]RawVecInner_share_::(?k, ?t0, ?l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& [_]RawVecInner_share_::(k, t1, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_share_(k, t0, l, elemLayout, alloc_id, ptr, capacity); + std::alloc::Allocator_sync::(t1); + close RawVecInner_share_(k, t1, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t1, l, elemLayout, alloc_id, ptr, capacity); +} + +pred RawVecInner_share_end_token(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + borrow_end_token(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)) &*& + borrow_end_token(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + +pred RawVecInner_share0_end_token(k: lifetime_t, t: thread_id_t, l: *RawVecInner, elemLayout: Layout, alloc_id: alloc_id_t, ptr: *u8, capacity: usize) = + borrow_end_token(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)) &*& + borrow_end_token(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)) &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + +lem RawVecInner_share_full_(k: lifetime_t, l: *RawVecInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + RawVecInner_full_borrow(k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_full_borrow(k, t, l, elemLayout, alloc_id, ptr, capacity); + let klong = open_full_borrow_strong_m(k, RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity), q); + open RawVecInner_full_borrow_content_::(t, l, elemLayout, alloc_id, ptr, capacity)(); + assert *l |-> ?self_; + open_points_to(l); + points_to_limits(&(*l).alloc); + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))(); + { + pred Ctx() = + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + alloc_block_in(alloc_id, ptr, allocLayout) + }; + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)), + klong, + RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity) + )() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + let self1 = *l; + close RawVecInner(t, self1, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_full_borrow_content_::(t, l, elemLayout, alloc_id, ptr, capacity)(); + } { + close_full_borrow_strong_m( + klong, + RawVecInner_full_borrow_content_(t, l, elemLayout, alloc_id, ptr, capacity), + sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)) + ); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity))); + } + } + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem share_RawVecInner(k: lifetime_t, l: *RawVecInner) + nonghost_callers_only + req [?q]lifetime_token(k) &*& + *l |-> ?self_ &*& + RawVecInner(?t, self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + full_borrow_into_frac(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + points_to_limits(&(*l).alloc); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + borrow(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem end_share_RawVecInner(l: *RawVecInner) + nonghost_callers_only + req RawVecInner_share_end_token(?k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +{ + open RawVecInner_share_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + borrow_end(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + borrow_end(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close RawVecInner(t, *l, elemLayout, alloc_id, ptr, capacity); +} + +lem share_RawVecInner0(k: lifetime_t, l: *RawVecInner, elemLayout: Layout, ptr: *u8, capacity: usize) + nonghost_callers_only + req [?q]lifetime_token(k) &*& + *l |-> ?self_ &*& + Allocator(?t, self_.alloc, ?alloc_id) &*& + capacity == logical_capacity(self_.cap, elemLayout.size()) &*& + ptr == self_.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); +{ + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + borrow(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + full_borrow_into_frac(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + points_to_limits(&(*l).alloc); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + borrow(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::share_Allocator_full_borrow_content_(k, t, &(*l).alloc, alloc_id); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem end_share_RawVecInner0(l: *RawVecInner) + nonghost_callers_only + req RawVecInner_share0_end_token(?k, ?t, l, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& + Allocator(t, self_.alloc, alloc_id) &*& + capacity == logical_capacity(self_.cap, elemLayout.size()) &*& + ptr == self_.ptr.as_ptr() &*& + ptr as usize % elemLayout.align() == 0 &*& + pointer_within_limits(ptr) == true &*& + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); +{ + open RawVecInner_share0_end_token(k, t, l, elemLayout, alloc_id, ptr, capacity); + borrow_end(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id)); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + borrow_end(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); +} + +lem init_ref_RawVecInner_(l: *RawVecInner) + nonghost_callers_only + req ref_init_perm(l, ?l0) &*& + [_]RawVecInner_share_(?k, ?t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& + [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& + [_]frac_borrow(k, ref_initialized_(l)); +{ + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, elemLayout, alloc_id, ptr, capacity); + std::alloc::init_ref_Allocator_share(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + open_frac_borrow_strong_( + k, + sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), + q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + open [f]ref_initialized_::(&(*l).alloc)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + init_ref_readonly(&(*l).ptr, 1/2); + init_ref_readonly(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close [f]ref_initialized_::>(l)(); + close scaledp(f, ref_initialized_(l))(); + close sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))(); + + { + pred Ctx() = + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f]ref_padding_initialized(l) &*& + ref_readonly_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f]ref_initialized(&(*l).ptr) &*& + ref_readonly_end_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f]ref_initialized(&(*l).cap); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow( + Ctx, + sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l))), + f, + sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))(); + open scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open Ctx(); + open_ref_initialized_RawVecInner(l); + end_ref_readonly(&(*l).ptr); + end_ref_readonly(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close_frac_borrow_strong_(); + } + } + full_borrow_into_frac(k, sep_(scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l)))); + frac_borrow_split(k, scaledp(f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f/2, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +lem init_ref_RawVecInner_m(l: *RawVecInner) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVecInner_share_(?k, ?t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, elemLayout, alloc_id, ptr, capacity); + std::alloc::init_ref_Allocator_share_m(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + open [f]ref_initialized_::(&(*l).alloc)(); + std::ptr::init_ref_NonNull(&(*l).ptr, 1/2); + std::num::niche_types::init_ref_UsizeNoHighBit(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f/2]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*l).alloc) &*& + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f/2]ref_padding_initialized(l) &*& + ref_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f/2]ref_initialized(&(*l).ptr) &*& + std::num::niche_types::end_ref_UsizeNoHighBit_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f/2]ref_initialized(&(*l).cap); + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))), klong, f, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + open sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open ref_initialized_::>(l)(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open_ref_initialized_RawVecInner(l); + open Ctx(); + std::ptr::end_ref_NonNull(&(*l).ptr); + std::num::niche_types::end_ref_UsizeNoHighBit(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(l)(); + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close [f/2]sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + } + } + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + frac_borrow_split(k, ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); +} + +pred >.share(k, t, l) = [_]RawVecInner_share_(k, t, l, _, _, _, _); + +lem RawVecInner_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVecInner_share::(k, t, l); + ens type_interp::() &*& [_]RawVecInner_share::(k1, t, l); +{ + open RawVecInner_share::(k, t, l); + RawVecInner_share__mono(k, k1, t, l); + close RawVecInner_share::(k1, t, l); + leak RawVecInner_share::(k1, t, l); +} + +lem RawVecInner_share_full(k: lifetime_t, t: thread_id_t, l: *RawVecInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, RawVecInner_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& ref_origin(l) == l; + ens type_interp::() &*& atomic_mask(MaskTop) &*& [_]RawVecInner_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, RawVecInner_full_borrow_content(t, l), q); + open RawVecInner_full_borrow_content::(t, l)(); + open >.own(t, *l); + std::alloc::open_Allocator_own((*l).alloc); + assert Allocator(_, _, ?alloc_id); + open RawVecInner0(?self_, ?elemLayout, ?ptr, ?capacity); + { + pred Ctx() = true; + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)), klong, RawVecInner_full_borrow_content(t, l))() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + std::alloc::Allocator_to_own((*l).alloc); + close RawVecInner0(*l, elemLayout, ptr, capacity); + close >.own(t, *l); + close RawVecInner_full_borrow_content::(t, l)(); + } { + close Ctx(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).alloc); + close RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close_full_borrow_strong_m(klong, RawVecInner_full_borrow_content(t, l), sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).alloc, alloc_id), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + } + } + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + std::num::niche_types::UsizeNoHighBit_inv(self_.cap); + close RawVecInner_share_::(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_::(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share::(k, t, l); + leak RawVecInner_share::(k, t, l); +} + +lem init_ref_RawVecInner(l: *RawVecInner) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVecInner_share::(?k, ?t, l0) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVecInner_share::(k, t, l) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVecInner_share::(k, t, l0); + open_ref_init_perm_RawVecInner(l); + open RawVecInner_share_(k, t, l0, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + std::alloc::init_ref_Allocator_share_m(k, t, &(*l).alloc); + frac_borrow_sep(k, RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)); + let klong = open_frac_borrow_strong_m(k, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)), q); + open [?f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + open [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + let ptr_ = (*l0).ptr; + let cap_ = (*l0).cap; + open [f]ref_initialized_::(&(*l).alloc)(); + std::ptr::init_ref_NonNull(&(*l).ptr, 1/2); + std::num::niche_types::init_ref_UsizeNoHighBit(&(*l).cap, 1/2); + init_ref_padding_RawVecInner(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f/2]P(); + close_ref_initialized_RawVecInner(l); + open P(); + } + { + pred Ctx() = + [f/2]ref_initialized(&(*l).alloc) &*& + ref_padding_end_token(l, l0, f/2) &*& [f/2]struct_RawVecInner_padding(l0) &*& [1 - f/2]ref_padding_initialized(l) &*& + ref_end_token(&(*l).ptr, &(*l0).ptr, f/2) &*& [f/2](*l0).ptr |-> ptr_ &*& [1 - f/2]ref_initialized(&(*l).ptr) &*& + std::num::niche_types::end_ref_UsizeNoHighBit_token(&(*l).cap, &(*l0).cap, f/2) &*& [f/2](*l0).cap |-> cap_ &*& [1 - f/2]ref_initialized(&(*l).cap); + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))), klong, f, sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc)))() { + open scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + open sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + open ref_initialized_::>(l)(); + open RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + open_ref_initialized_RawVecInner(l); + open Ctx(); + std::ptr::end_ref_NonNull(&(*l).ptr); + std::num::niche_types::end_ref_UsizeNoHighBit(&(*l).cap); + end_ref_padding_RawVecInner(l); + close [f]RawVecInner_frac_borrow_content::(l0, elemLayout, ptr, capacity)(); + close [f]ref_initialized_::(&(*l).alloc)(); + close [f]sep_(RawVecInner_frac_borrow_content(l0, elemLayout, ptr, capacity), ref_initialized_(&(*l).alloc))(); + } { + close Ctx(); + close [f/2]ref_initialized_::>(l)(); + close [f/2]RawVecInner_frac_borrow_content::(l, elemLayout, ptr, capacity)(); + close [f/2]sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))(); + close scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + } + } + full_borrow_into_frac_m(k, scaledp(f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)))); + frac_borrow_implies_scaled(k, f/2, sep_(ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity))); + frac_borrow_split(k, ref_initialized_(l), RawVecInner_frac_borrow_content(l, elemLayout, ptr, capacity)); + assert pointer_within_limits(ref_origin(&(*l0).alloc)) == true; + close RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + leak RawVecInner_share_(k, t, l, elemLayout, alloc_id, ptr, capacity); + close RawVecInner_share::(k, t, l); + leak RawVecInner_share(k, t, l); +} + +lem RawVecInner_sync(t1: thread_id_t) + req type_interp::() &*& is_Sync(typeid(A)) == true &*& [_]RawVecInner_share::(?k, ?t0, ?l); + ens type_interp::() &*& [_]RawVecInner_share::(k, t1, l); +{ + open RawVecInner_share::(k, t0, l); + RawVecInner_sync_::(t1); + close RawVecInner_share::(k, t1, l); + leak RawVecInner_share(k, t1, l); +} + +fix RawVecInner::alloc(self_: RawVecInner) -> A { self_.alloc } + +lem RawVecInner_into_raw_parts(self_: RawVecInner) + req RawVecInner(?t, self_, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + ens Allocator(t, self_.alloc(), alloc_id) &*& + if capacity * elemLayout.size() == 0 { + true + } else { + elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr, allocLayout) + }; +{ + open RawVecInner(t, self_, elemLayout, alloc_id, ptr, capacity); +} + +@*/ + +/*@ + +pred RawVec(t: thread_id_t, self: RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner(t, self.inner, Layout::new::, alloc_id, ?ptr_, capacity) &*& ptr == ptr_ as *T; + +fix RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) -> pred() { + RawVecInner_full_borrow_content_(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity) +} + +lem close_RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); + ens RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)(); +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + open_points_to(l); + close RawVecInner_full_borrow_content_::(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity)(); +} + +lem open_RawVec_full_borrow_content_(t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)(); + ens *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); +{ + open RawVecInner_full_borrow_content_::(t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity)(); + close RawVec(t, *l, alloc_id, ptr, capacity); + close_points_to(l); +} + +pred RawVec_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner_full_borrow(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem close_RawVec_full_borrow(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) + req full_borrow(k, RawVec_full_borrow_content_::(t, l, alloc_id, ptr, capacity)); + ens RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); +{ + close RawVecInner_full_borrow(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); +} + +pred >.own(t, self_) = RawVec(t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + +lem RawVec_mono(t: thread_id_t, v: RawVec) + req RawVec::(t, v, ?alloc_id, ?ptr, ?capacity) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens RawVec::(t, RawVec:: { inner: upcast(v.inner) }, alloc_id, ptr as *T1, capacity) &*& + std::mem::size_of::() == std::mem::size_of::() &*& std::mem::align_of::() == std::mem::align_of::(); +{ + open RawVec::(t, v, alloc_id, ptr, capacity); + open RawVecInner::(t, v.inner, Layout::new::(), alloc_id, ?ptr_, capacity); + std::alloc::Allocator_upcast::(v.inner.alloc); + std::ptr::NonNull_upcast::(v.inner.ptr); + // Rust subtyping preserves type layout and upcasts fields componentwise (verifast#610). + assume(std::mem::size_of::() == std::mem::size_of::() && std::mem::align_of::() == std::mem::align_of::()); + assume(upcast::, RawVecInner>(v.inner) == RawVecInner:: { ptr: upcast(v.inner.ptr), cap: upcast(v.inner.cap), alloc: upcast(v.inner.alloc) }); + assume(upcast::(v.inner.cap) == v.inner.cap); + close RawVecInner::(t, upcast(v.inner), Layout::new::(), alloc_id, ptr_, capacity); + close RawVec::(t, RawVec:: { inner: upcast(v.inner) }, alloc_id, ptr as *T1, capacity); +} + +lem RawVec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +{ + open RawVec_own::(t, v); + assert RawVec::(t, v, ?alloc_id, ?ptr, ?capacity); + RawVec_mono::(t, v); + array_at_lft__to_u8s_at_lft_::(ptr, capacity); + u8s_at_lft__to_array_at_lft_::(ptr as *T1, capacity); + close RawVec_own::(t, RawVec:: { inner: upcast(v.inner) }); +} + +lem RawVec_send_(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& RawVec::(?t0, ?v, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& RawVec::(t1, v, alloc_id, ptr, capacity); +{ + open RawVec(t0, v, alloc_id, ptr, capacity); + RawVecInner_send_::(t1); + close RawVec(t1, v, alloc_id, ptr, capacity); +} + +lem RawVec_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Send(typeid(RawVec)) == true &*& RawVec_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& RawVec_own::(t1, v); +{ + open >.own(t0, v); + RawVec_send_(t1); + close >.own(t1, v); +} + +lem RawVec_inv() + req RawVec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity); + ens RawVec::(t, self_, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % std::mem::align_of::() == 0 &*& + 0 <= capacity &*& capacity <= usize::MAX; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_inv(); + close RawVec(t, self_, alloc_id, ptr, capacity); +} + +lem RawVec_inv2() + req RawVec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity); + ens RawVec::(t, self_, alloc_id, ptr, capacity) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& ptr as usize % std::mem::align_of::() == 0 &*& + 0 <= capacity &*& + Layout::new::().repeat(capacity) != none &*& + if std::mem::size_of::() == 0 { capacity == usize::MAX } else { capacity <= isize::MAX }; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_inv2(); + close RawVec(t, self_, alloc_id, ptr, capacity); +} + +lem RawVec_to_own(self_: RawVec) + req RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + ens >.own(t, self_); +{ + close >.own(t, self_); +} + +lem open_RawVec_own(self_: RawVec) + req >.own(?t, self_); + ens RawVec(t, self_, ?alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); +{ + open >.own(t, self_); +} + +pred RawVec_share_(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + [_]RawVecInner_share_(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem RawVec_share__inv() + req [_]RawVec_share_::(?k, ?t, ?l, ?alloc_id, ?ptr, ?capacity); + ens ptr != 0 &*& Layout::new::().repeat(capacity) != none &*& capacity <= usize::MAX; +{ + open RawVec_share_(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share__inv(); +} + +lem RawVec_share__mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVec_share_::(k, t, l, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share_::(k1, t, l, alloc_id, ptr, capacity); +{ + open RawVec_share_(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share__mono(k, k1, t, &(*l).inner); + close RawVec_share_(k1, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k1, t, l, alloc_id, ptr, capacity); +} + +lem RawVec_sync_(t1: thread_id_t) + req type_interp::() &*& [_]RawVec_share_::(?k, ?t0, ?l, ?alloc_id, ?ptr, ?capacity) &*& is_Sync(typeid(RawVec)) == true; + ens type_interp::() &*& [_]RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); +{ + open RawVec_share_::(k, t0, l, alloc_id, ptr, capacity); + RawVecInner_sync_::(t1); + close RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); + leak RawVec_share_::(k, t1, l, alloc_id, ptr, capacity); +} + +pred RawVec_share_end_token(k: lifetime_t, t: thread_id_t, l: *RawVec, alloc_id: alloc_id_t, ptr: *T, capacity: usize) = + RawVecInner_share_end_token(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + +lem RawVec_share_full_(k: lifetime_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + RawVec_full_borrow(k, ?t, l, ?alloc_id, ?ptr, ?capacity); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity); +{ + open RawVec_full_borrow(k, t, l, alloc_id, ptr, capacity); + RawVecInner_share_full_(k, &(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); +} + +lem share_RawVec(k: lifetime_t, l: *RawVec) + nonghost_callers_only + req [?q]lifetime_token(k) &*& *l |-> ?self_ &*& RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity); + ens [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + open_points_to(l); + share_RawVecInner(k, &(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + close RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); +} + +lem end_share_RawVec(l: *RawVec) + nonghost_callers_only + req RawVec_share_end_token(?k, ?t, l, ?alloc_id, ?ptr, ?capacity) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& RawVec(t, self_, alloc_id, ptr, capacity); +{ + open RawVec_share_end_token(k, t, l, alloc_id, ptr, capacity); + end_share_RawVecInner(&(*l).inner); + close_points_to(l); + close RawVec(t, *l, alloc_id, ptr, capacity); +} + +lem init_ref_RawVec_(l: *RawVec) + nonghost_callers_only + req ref_init_perm(l, ?l0) &*& [_]RawVec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share_(k, t, l0, alloc_id, ptr, capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + + let klong = open_frac_borrow_strong(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong(klong, ref_initialized_(&(*l).inner), scaledp(f, ref_initialized_(l))); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +lem init_ref_RawVec_m(l: *RawVec) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVec_share_(k, t, l, alloc_id, ptr, capacity) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share_(k, t, l0, alloc_id, ptr, capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_m(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + + let klong = open_frac_borrow_strong_m(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac_m(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +pred >.share(k, t, l) = [_]RawVec_share_(k, t, l, ?alloc_id, ?ptr, ?capacity); + +lem RawVec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]RawVec_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share::(k1, t, l); +{ + open RawVec_share::(k, t, l); + RawVec_share__mono(k, k1, t, l); + close RawVec_share::(k1, t, l); + leak RawVec_share::(k1, t, l); +} + +lem RawVec_share_full(k: lifetime_t, t: thread_id_t, l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, RawVec_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& ref_origin(l) == l; + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [_]RawVec_share::(k, t, l) &*& [q]lifetime_token(k); +{ + let klong = open_full_borrow_strong_m(k, RawVec_full_borrow_content::(t, l), q); + open RawVec_full_borrow_content::(t, l)(); + let self_ = *l; + points_to_limits(&(*l).inner.alloc); + open >.own(t, self_); + open RawVec(t, self_, ?alloc_id, ?ptr, ?capacity); + open RawVecInner(t, self_.inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + { + pred Ctx() = + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr, capacity, _); + produce_lem_ptr_chunk full_borrow_convert_strong(Ctx, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)), klong, RawVec_full_borrow_content(t, l))() { + open Ctx(); + open sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))(); + std::alloc::open_Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id); + open RawVecInner_frac_borrow_content::(&(*l).inner, Layout::new::(), ptr as *u8, capacity)(); + close RawVecInner(t, (*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec(t, *l, alloc_id, ptr, capacity); + close >.own(t, *l); + close RawVec_full_borrow_content::(t, l)(); + } { + close Ctx(); + std::alloc::close_Allocator_full_borrow_content_(t, &(*l).inner.alloc); + close RawVecInner_frac_borrow_content::(&(*l).inner, Layout::new::(), ptr as *u8, capacity)(); + close sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))(); + close_full_borrow_strong_m(klong, RawVec_full_borrow_content(t, l), sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))); + full_borrow_mono(klong, k, sep(std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_(t, &(*l).inner.alloc, alloc_id), RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)); + } + } + std::alloc::share_Allocator_full_borrow_content_m(k, t, &(*l).inner.alloc, alloc_id); + full_borrow_into_frac_m(k, RawVecInner_frac_borrow_content(&(*l).inner, Layout::new::(), ptr as *u8, capacity)); + close RawVecInner_share_::(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + leak RawVecInner_share_::(k, t, &(*l).inner, Layout::new::(), alloc_id, ptr as *u8, capacity); + close RawVec_share_::(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_::(k, t, l, alloc_id, ptr, capacity); + close RawVec_share::(k, t, l); + leak RawVec_share::(k, t, l); +} + +lem RawVec_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Sync(typeid(RawVec)) == true &*& [_]RawVec_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]RawVec_share::(k, t1, l); +{ + open RawVec_share::(k, t0, l); + RawVec_sync_::(t1); + close RawVec_share::(k, t1, l); + leak RawVec_share::(k, t1, l); +} + +lem init_ref_RawVec(l: *RawVec) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]RawVec_share::(?k, ?t, l0) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]RawVec_share::(k, t, l) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open RawVec_share::(k, t, l0); + open RawVec_share_(k, t, l0, ?alloc_id, ?ptr, ?capacity); + open_ref_init_perm_RawVec(l); + init_ref_RawVecInner_m(&(*l).inner); + close RawVec_share_(k, t, l, alloc_id, ptr, capacity); + leak RawVec_share_(k, t, l, alloc_id, ptr, capacity); + close RawVec_share::(k, t, l); + leak RawVec_share::(k, t, l); + + let klong = open_frac_borrow_strong_m(k, ref_initialized_(&(*l).inner), q); + open [?f]ref_initialized_::>(&(*l).inner)(); + close_ref_initialized_RawVec(l, f); + close [f]ref_initialized_::>(l)(); + { + pred Ctx() = true; + produce_lem_ptr_chunk frac_borrow_convert_strong(Ctx, scaledp(f, ref_initialized_(l)), klong, f, ref_initialized_(&(*l).inner))() { + open Ctx(); + open scaledp(f, ref_initialized_(l))(); + open ref_initialized_::>(l)(); + open_ref_initialized_RawVec(l); + close [f]ref_initialized_::>(&(*l).inner)(); + } { + close Ctx(); + close scaledp(f, ref_initialized_(l))(); + close_frac_borrow_strong_m(); + full_borrow_mono(klong, k, scaledp(f, ref_initialized_(l))); + full_borrow_into_frac_m(k, scaledp(f, ref_initialized_(l))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + } + } +} + +fix RawVec::alloc(self_: RawVec) -> A { self_.inner.alloc() } + +lem RawVec_into_raw_parts(self_: RawVec) + req RawVec(?t, self_, ?alloc_id, ?ptr, ?capacity); + ens Allocator(t, self_.alloc(), alloc_id) &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + }; +{ + open RawVec(t, self_, alloc_id, ptr, capacity); + RawVecInner_into_raw_parts(self_.inner); +} + +@*/ + +impl RawVec { + /// Creates the biggest possible `RawVec` (on the system heap) + /// without allocating. If `T` has positive size, then this makes a + /// `RawVec` with capacity `0`. If `T` is zero-sized, then it makes a + /// `RawVec` with capacity `usize::MAX`. Useful for implementing + /// delayed allocation. + #[must_use] + pub(crate) const fn new() -> Self { + Self::new_in(Global) + } + + /// Creates a `RawVec` (on the system heap) with exactly the + /// capacity and alignment requirements for a `[T; capacity]`. This is + /// equivalent to calling `RawVec::new` when `capacity` is `0` or `T` is + /// zero-sized. Note that if `T` is zero-sized this means you will + /// *not* get a `RawVec` with the requested capacity. + /// + /// Non-fallible version of `try_with_capacity` + /// + /// # Panics + /// + /// Panics if the requested capacity exceeds `isize::MAX` bytes. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { inner: RawVecInner::with_capacity(capacity, T::LAYOUT), _marker: PhantomData } + } + + /// Like `with_capacity`, but guarantees the buffer is zeroed. + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + pub(crate) fn with_capacity_zeroed(capacity: usize) -> Self { + Self { + inner: RawVecInner::with_capacity_zeroed_in(capacity, Global, T::LAYOUT), + _marker: PhantomData, + } + } +} + +impl RawVecInner { + #[cfg(not(any(no_global_oom_handling, test)))] + #[must_use] + #[inline] + fn with_capacity(capacity: usize, elem_layout: Layout) -> Self { + match Self::try_allocate_in(capacity, AllocInit::Uninitialized, Global, elem_layout) { + Ok(res) => res, + Err(err) => handle_error(err), + } + } +} + +// Tiny Vecs are dumb. Skip to: +// - 8 if the element size is 1, because any heap allocator is likely +// to round up a request of less than 8 bytes to at least 8 bytes. +// - 4 if elements are moderate-sized (<= 1 KiB). +// - 1 otherwise, to avoid wasting too much space for very short Vecs. +const fn min_non_zero_cap(size: usize) -> usize +//@ req true; +//@ ens true; +//@ on_unwind_ens false; +{ + if size == 1 { + 8 + } else if size <= 1024 { + 4 + } else { + 1 + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl RawVec { + /// Like `with_capacity`, but parameterized over the choice of + /// allocator for the returned `RawVec`. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn with_capacity_in(capacity: usize, alloc: A) -> Self + { + //@ size_align::(); + let r = Self { + inner: RawVecInner::with_capacity_in(capacity, alloc, T::LAYOUT), + _marker: PhantomData, + }; + //@ close RawVec(t, r, alloc_id, ?ptr, ?capacity_); + //@ u8s_at_lft__to_array_at_lft_(ptr, capacity_); + r + } + + /// A specialized version of `self.reserve(len, 1)` which requires the + /// caller to ensure `len == self.capacity()`. + #[cfg(not(no_global_oom_handling))] + #[inline(never)] + pub(crate) fn grow_one(&mut self) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.grow_one(T::LAYOUT) } + } +} + +impl RawVec { + #[cfg(not(no_global_oom_handling))] + pub(crate) const MIN_NON_ZERO_CAP: usize = min_non_zero_cap(size_of::()); + + /// Like `new`, but parameterized over the choice of allocator for + /// the returned `RawVec`. + #[inline] + pub(crate) const fn new_in(alloc: A) -> Self + //@ req thread_token(?t) &*& Allocator(t, alloc, ?alloc_id); + //@ ens thread_token(t) &*& RawVec::(t, result, alloc_id, ?ptr, ?capacity) &*& array_at_lft_(alloc_id.lft, ptr, capacity, _); + /*@ + safety_proof { + std::alloc::open_Allocator_own(alloc); + let result = call(); + close >.own(_t, result); + } + @*/ + { + // Check assumption made in `current_memory` + const { assert!(T::LAYOUT.size() % T::LAYOUT.align() == 0) }; + //@ close exists(std::mem::size_of::()); + //@ std::alloc::Layout_inv(Layout::new::()); + //@ std::alloc::is_valid_layout_size_of_align_of::(); + //@ std::mem::Alignment_as_nonzero_usize_new(std::mem::align_of::()); + let r = Self { inner: RawVecInner::new_in(alloc, Alignment::of::()), _marker: PhantomData }; + //@ close RawVec::(t, r, alloc_id, ?ptr, ?capacity); + //@ u8s_at_lft__to_array_at_lft_(ptr, capacity); + r + } + + /// Like `try_with_capacity`, but parameterized over the choice of + /// allocator for the returned `RawVec`. + #[inline] + pub(crate) fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + match RawVecInner::try_with_capacity_in(capacity, alloc, T::LAYOUT) { + Ok(inner) => Ok(Self { inner, _marker: PhantomData }), + Err(e) => Err(e), + } + } + + /// Like `with_capacity_zeroed`, but parameterized over the choice + /// of allocator for the returned `RawVec`. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { + Self { + inner: RawVecInner::with_capacity_zeroed_in(capacity, alloc, T::LAYOUT), + _marker: PhantomData, + } + } + + /// Converts the entire buffer into `Box<[MaybeUninit]>` with the specified `len`. + /// + /// Note that this will correctly reconstitute any `cap` changes + /// that may have been performed. (See description of type for details.) + /// + /// # Safety + /// + /// * `len` must be greater than or equal to the most recently requested capacity, and + /// * `len` must be less than or equal to `self.capacity()`. + /// + /// Note, that the requested capacity and `self.capacity()` could differ, as + /// an allocator could overallocate and return a greater memory block than requested. + pub(crate) unsafe fn into_box(mut self, len: usize) -> Box<[MaybeUninit], A> + { + //@ RawVec_inv2(); + + // Sanity-check one half of the safety requirement (we cannot check the other half). + if cfg!(debug_assertions) { //~allow_dead_code + //@ let k = begin_lifetime(); + //@ share_RawVec(k, &self); + //@ let self_ref = precreate_ref(&self); + //@ init_ref_RawVec_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let capacity = self.capacity(); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVec(&self); + //@ open_points_to(&self); + + if !(len <= capacity) { + unsafe { core::hint::unreachable_unchecked(); } + } + } + + let mut me = ManuallyDrop::new(self); + //@ close_points_to(&self); + unsafe { + //@ let k0 = begin_lifetime(); + //@ close_points_to(&me); + //@ share_RawVec(k0, &me); + //@ let me_ref0 = precreate_ref(&me); + //@ init_ref_RawVec_(me_ref0); + //@ open_frac_borrow(k0, ref_initialized_(me_ref0), 1/2); + //@ open [?f0]ref_initialized_::>(me_ref0)(); + let me_ref = > as core::ops::Deref>::deref(&me); + let ptr_ = me_ref.ptr(); + let slice = ptr_.cast::>().cast_slice(len); + //@ close [f0]ref_initialized_::>(me_ref0)(); + //@ close_frac_borrow(f0, ref_initialized_(me_ref0)); + //@ end_lifetime(k0); + //@ end_share_RawVec(&me); + + //@ let me_ref1 = precreate_ref(&me); + //@ init_ref_readonly(me_ref1, 1/2); + //@ open_points_to(me_ref1); + //@ let alloc_ref = precreate_ref(&(*me_ref1).inner.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + let alloc = ptr::read(&me.inner.alloc); + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(me_ref1, 1/2); + //@ end_ref_readonly(me_ref1); + //@ open_points_to(&me); + //@ std::mem::array_at_lft__to_array_at_lft_MaybeUninit(slice as *T); + //@ open RawVec(_, _, _, _, _); + //@ open RawVecInner(_, _, _, _, _, _); + //@ size_align::(); + //@ if len * std::mem::size_of::() != 0 { std::alloc::Layout_repeat_some_size_aligned(Layout::new::(), len); } + //@ close_points_to_slice_at_lft(slice); + Box::from_raw_in(slice, alloc) + } + } + + /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. + /// + /// # Safety + /// + /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given + /// `capacity`. + /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit + /// systems). For ZSTs capacity is ignored. + /// If the `ptr` and `capacity` come from a `RawVec` created via `alloc`, then this is + /// guaranteed. + #[inline] + pub(crate) const unsafe fn from_raw_parts_in(ptr: *mut T, capacity: usize, alloc: A) -> Self + /*@ + req Allocator(?t, alloc, ?alloc_id) &*& + ptr as usize != 0 &*& + ptr as usize % std::mem::align_of::() == 0 &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr as *u8, allocLayout) + }; + @*/ + //@ ens RawVec(t, result, alloc_id, ptr, ?capacity_) &*& capacity <= capacity_; + { + // SAFETY: Precondition passed to the caller + unsafe { + let ptr = ptr.cast(); + //@ std::alloc::Layout_inv(Layout::new::()); + /*@ + if 1 <= std::mem::size_of::() { + if capacity != 0 { + mul_zero(capacity, std::mem::size_of::()); + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + div_rem_nonneg(isize::MAX, std::mem::align_of::()); + mul_mono_l(1, std::mem::size_of::(), capacity); + mul_mono_l(std::mem::size_of::(), stride, capacity); + std::alloc::Layout_inv(allocLayout); + } + } + @*/ + let capacity = new_cap::(capacity); + //@ close exists(Layout::new::()); + let r = Self { + inner: RawVecInner::from_raw_parts_in(ptr, capacity, alloc), + _marker: PhantomData, + }; + //@ close RawVec(t, r, alloc_id, ptr, _); + r + } + } + + /// A convenience method for hoisting the non-null precondition out of [`RawVec::from_raw_parts_in`]. + /// + /// # Safety + /// + /// See [`RawVec::from_raw_parts_in`]. + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub(crate) const unsafe fn from_nonnull_in(ptr: NonNull, capacity: usize, alloc: A) -> Self + /*@ + req Allocator(?t, alloc, ?alloc_id) &*& + ptr.as_ptr() as usize % std::mem::align_of::() == 0 &*& + pointer_within_limits(ptr.as_ptr()) == true &*& + if capacity * std::mem::size_of::() == 0 { + true + } else { + Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr.as_ptr() as *u8, allocLayout) + }; + @*/ + //@ ens RawVec(t, result, alloc_id, ptr.as_ptr(), ?capacity_) &*& capacity <= capacity_; + { + // SAFETY: Precondition passed to the caller + unsafe { + let ptr = ptr.cast(); + //@ std::ptr::NonNull_Sized_as_ptr(ptr); + //@ std::alloc::Layout_inv(Layout::new::()); + /*@ + if 1 <= std::mem::size_of::() && capacity != 0 { + mul_zero(capacity, std::mem::size_of::()); + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + std::alloc::Layout_inv(allocLayout); + div_rem_nonneg(isize::MAX, std::mem::align_of::()); + mul_mono_l(1, std::mem::size_of::(), capacity); + mul_mono_l(std::mem::size_of::(), stride, capacity); + } + @*/ + let capacity = new_cap::(capacity); + //@ close exists(Layout::new::()); + let r = Self { inner: RawVecInner::from_nonnull_in(ptr, capacity, alloc), _marker: PhantomData }; + //@ close RawVec(t, r, alloc_id, _, _); + r + } + } + + /// Gets a raw pointer to the start of the allocation. Note that this is + /// `NonNull::dangling()` if `capacity == 0` or `T` is zero-sized. In the former case, you must + /// be careful. + #[inline] + pub(crate) const fn ptr(&self) -> *mut T + //@ req [_]RawVec_share_(?k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == ptr; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVec_share_(k, t, self, alloc_id, ptr, capacity); + //@ let inner_ref = precreate_ref(&(*self).inner); + //@ init_ref_RawVecInner_(inner_ref); + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.ptr(); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + #[inline] + pub(crate) const fn non_null(&self) -> NonNull { + self.inner.non_null() + } + + /// Gets the capacity of the allocation. + /// + /// This will always be `usize::MAX` if `T` is zero-sized. + #[inline] + pub(crate) const fn capacity(&self) -> usize + //@ req [_]RawVec_share_(?k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == capacity; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVec_share_(k, t, self, alloc_id, ptr, capacity); + //@ let inner_ref = precreate_ref(&(*self).inner); + //@ init_ref_RawVecInner_(inner_ref); + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.capacity(size_of::()); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + /// Returns a shared reference to the allocator backing this `RawVec`. + #[inline] + pub(crate) const fn allocator(&self) -> &A + /*@ + req + [?q]lifetime_token(?k) &*& + exists(?readOnly) &*& + if readOnly { + [_]points_to_shared(k, self, ?self_) &*& + ens [q]lifetime_token(k) &*& + [_]points_to_shared(k, result, self_.alloc()) &*& + [_]frac_borrow(k, ref_initialized_(result)) + } else { + [_]RawVec_share_(k, ?t, self, ?alloc_id, ?ptr, ?capacity) &*& + ens [q]lifetime_token(k) &*& + [_]std::alloc::Allocator_share(k, t, result, alloc_id) &*& + [_]frac_borrow(k, ref_initialized_(result)) + }; + @*/ + //@ ens true; + /*@ + safety_proof { + open >.share(?k, _t, self); + close exists(false); + let result = call(); + std::alloc::close_Allocator_share(k, _t, result); + } + @*/ + { + //@ let inner_ref = precreate_ref(&(*self).inner); + /*@ + if readOnly { + open points_to_shared(k, self, ?self_); + open_frac_borrow_strong_(k, mk_points_to(self, self_), q); + open [?f]mk_points_to::>(self, self_)(); + open_points_to(self); + close [f]mk_points_to::>(&(*self).inner, self_.inner)(); + close scaledp(f, mk_points_to(&(*self).inner, self_.inner))(); + produce_lem_ptr_chunk restore_frac_borrow(True, scaledp(f, mk_points_to(&(*self).inner, self_.inner)), f, mk_points_to(self, self_))() { + open scaledp(f, mk_points_to(&(*self).inner, self_.inner))(); + open mk_points_to::>(&(*self).inner, self_.inner)(); + open_points_to(&(*self).inner); + close_points_to(self, f); + close [f]mk_points_to::>(self, self_)(); + } { + close_frac_borrow_strong_(); + } + full_borrow_into_frac(k, scaledp(f, mk_points_to(&(*self).inner, self_.inner))); + frac_borrow_implies_scaled(k, f, mk_points_to(&(*self).inner, self_.inner)); + close points_to_shared(k, &(*self).inner, self_.inner); + leak points_to_shared(k, &(*self).inner, self_.inner); + init_ref_readonly_points_to_shared(inner_ref); + } else { + open RawVec_share_(k, ?t, self, ?alloc_id, ?ptr, ?capacity); + init_ref_RawVecInner_(inner_ref); + } + @*/ + //@ open_frac_borrow(k, ref_initialized_(inner_ref), q/2); + //@ open [?f]ref_initialized_::>(inner_ref)(); + let r = self.inner.allocator(); + //@ assert [f]ref_initialized::>(inner_ref); + //@ close [f]ref_initialized_::>(inner_ref)(); + //@ close_frac_borrow(f, ref_initialized_(inner_ref)); + r + } + + /// Ensures that the buffer contains at least enough space to hold `len + + /// additional` elements. If it doesn't already have enough capacity, will + /// reallocate enough space plus comfortable slack space to get amortized + /// *O*(1) behavior. Will limit this behavior if it would needlessly cause + /// itself to panic. + /// + /// If `len` exceeds `self.capacity()`, this may fail to actually allocate + /// the requested space. This is not really unsafe, but the unsafe + /// code *you* write that relies on the behavior of this function may break. + /// + /// This is ideal for implementing a bulk-push operation like `extend`. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn reserve(&mut self, len: usize, additional: usize) + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, ?vs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, ?vs1) &*& + (len > capacity0 || (len + additional <= capacity1 && take(len, vs1) == take(len, vs0))); + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + call(); + close >.own(_t, *self); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + /*@ + if len <= capacity0 { + array_at_lft__split(ptr0, len); + array_at_lft__to_u8s_at_lft_(ptr0, len); + assert array_at_lft_(alloc_id.lft, ptr0 as *u8, len * std::mem::size_of::(), ?bs_i); + array_at_lft__to_u8s_at_lft_(ptr0 + len, capacity0 - len); + assert array_at_lft_(alloc_id.lft, (ptr0 + len) as *u8, (capacity0 - len) * std::mem::size_of::(), ?bs_s); + array_at_lft__join(ptr0 as *u8); + take_append(len * std::mem::size_of::(), bs_i, bs_s); + } else { + array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + } + @*/ + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve(len, additional, T::LAYOUT) } + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + //@ close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + /*@ + if len <= capacity0 { + assert array_at_lft_(alloc_id.lft, ptr1 as *u8, capacity1 * std::mem::size_of::(), ?bs1); + std::alloc::Layout_inv(std::alloc::Layout::new::()); + mul_mono_l(len, capacity1, std::mem::size_of::()); + array_at_lft__split(ptr1 as *u8, len * std::mem::size_of::()); + u8s_at_lft__to_array_at_lft_(ptr1, len); + { + lem ptr_add_aligned(p: *T, n: usize) + req 0 <= n &*& 0 <= p as usize &*& p as usize % std::mem::align_of::() == 0 &*& + 0 <= std::mem::size_of::() &*& std::mem::size_of::() % std::mem::align_of::() == 0 &*& + 0 < std::mem::align_of::(); + ens 0 <= (p + n) as usize &*& (p + n) as usize % std::mem::align_of::() == 0; + { + if n > 0 { + ptr_add_aligned(p, n - 1); + let al = std::mem::align_of::(); + let sz = std::mem::size_of::(); + div_rem_nonneg((p + (n - 1)) as usize, al); + div_rem_nonneg(sz, al); + div_rem_nonneg_unique((p + n) as usize, al, (p + (n - 1)) as usize / al + sz / al, 0); + } + } + ptr_add_aligned(ptr1, len); + } + u8s_at_lft__to_array_at_lft_(ptr1 + len, capacity1 - len); + assert array_at_lft_(alloc_id.lft, ptr1, len, ?vs1_i); + assert array_at_lft_(alloc_id.lft, ptr1 + len, capacity1 - len, ?vs1_s); + array_at_lft__join(ptr1); + take_append(len, vs1_i, vs1_s); + } else { + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + @*/ + } + + /// The same as `reserve`, but returns on errors instead of panicking or aborting. + pub(crate) fn try_reserve( + &mut self, + len: usize, + additional: usize, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVec(t, self1, alloc_id, ptr0, capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _) &*& + .own(t, e) + }; + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + let result = call(); + close >.own(_t, *self); + match result { + Result::Ok(u) => { + tuple_0_eq(u); + close_tuple_0_own(_t); + } + Result::Err(e) => { + } + } + close >.own(_t, result); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.try_reserve(len, additional, T::LAYOUT) }; + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + /*@ + match r { + Result::Ok(u) => { + close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + Result::Err(e) => { + close RawVec(t, self1, alloc_id, ptr0, capacity0); + u8s_at_lft__to_array_at_lft_(ptr0, capacity0); + } + } + @*/ + r + } + + /// Ensures that the buffer contains at least enough space to hold `len + + /// additional` elements. If it doesn't already, will reallocate the + /// minimum possible amount of memory necessary. Generally this will be + /// exactly the amount of memory necessary, but in principle the allocator + /// is free to give back more than we asked for. + /// + /// If `len` exceeds `self.capacity()`, this may fail to actually allocate + /// the requested space. This is not really unsafe, but the unsafe code + /// *you* write that relies on the behavior of this function may break. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + pub(crate) fn reserve_exact(&mut self, len: usize, additional: usize) { + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + unsafe { self.inner.reserve_exact(len, additional, T::LAYOUT) } + } + + /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. + pub(crate) fn try_reserve_exact( + &mut self, + len: usize, + additional: usize, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& + RawVec(t, self0, ?alloc_id, ?ptr0, ?capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVec(t, self1, alloc_id, ?ptr1, ?capacity1) &*& array_at_lft_(alloc_id.lft, ptr1, capacity1, _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVec(t, self1, alloc_id, ptr0, capacity0) &*& array_at_lft_(alloc_id.lft, ptr0, capacity0, _) &*& + .own(t, e) + }; + @*/ + /*@ + safety_proof { + open >.own(_t, *self); + let result = call(); + close >.own(_t, *self); + match result { + Result::Ok(u) => { + tuple_0_eq(u); + close_tuple_0_own(_t); + } + Result::Err(e) => { + } + } + close >.own(_t, result); + } + @*/ + { + //@ size_align::(); + //@ open_points_to(self); + //@ close_points_to(&(*self).inner); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.try_reserve_exact(len, additional, T::LAYOUT) }; + //@ open_points_to(&(*self).inner); + //@ close_points_to(self); + //@ assert *self |-> ?self1; + /*@ + match r { + Result::Ok(u) => { + close RawVec(t, self1, alloc_id, ?ptr1, ?capacity1); + u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + } + Result::Err(e) => { + close RawVec(t, self1, alloc_id, ptr0, capacity0); + u8s_at_lft__to_array_at_lft_(ptr0, capacity0); + } + } + @*/ + r + } + + /// Shrinks the buffer down to the specified capacity. If the given amount + /// is 0, actually completely deallocates. + /// + /// # Panics + /// + /// Panics if the given amount is *larger* than the current capacity. + /// + /// # Aborts + /// + /// Aborts on OOM. + #[cfg(not(no_global_oom_handling))] + #[inline] + pub(crate) fn shrink_to_fit(&mut self, cap: usize) + { + //@ size_align::(); + //@ open_points_to(self); + //@ open RawVec(t, self0, alloc_id, ptr0, capacity0); + //@ RawVecInner_inv2(); + //@ array_at_lft__to_u8s_at_lft_(ptr0, capacity0); + //@ assert array_at_lft_::(_, _, _, ?bs); + //@ array_at_lft__inv(); + // SAFETY: All calls on self.inner pass T::LAYOUT as the elem_layout + let r = unsafe { self.inner.shrink_to_fit(cap, T::LAYOUT) }; + //@ close_points_to(self); + //@ close RawVec(t, *self, alloc_id, ?ptr1, ?capacity1); + //@ u8s_at_lft__to_array_at_lft_(ptr1, capacity1); + //@ vals__of_u8s__take::(capacity1, bs, capacity0); + r + } + + /// Shrinks the buffer down to the specified capacity. If the given amount + /// is 0, actually completely deallocates. + /// + /// # Errors + /// + /// This function returns an error if the allocator cannot shrink the allocation. + /// + /// # Panics + /// + /// Panics if the given amount is *larger* than the current capacity. + #[inline] + pub(crate) fn try_shrink_to_fit(&mut self, cap: usize) -> Result<(), TryReserveError> { + // SAFETY: Layout is valid for T. + unsafe { self.inner.try_shrink_to_fit(cap, T::LAYOUT) } + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const unsafe impl<#[may_dangle] T, A: [const] Allocator + [const] Destruct> Drop for RawVec { + /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. + fn drop(&mut self) + //@ req thread_token(?t) &*& t == currentThread &*& >.full_borrow_content(t, self)(); + //@ ens thread_token(t) &*& (*self).inner |-> ?inner &*& >.own(t, inner); + { + //@ open >.full_borrow_content(t, self)(); + //@ open >.own(t, *self); + //@ open RawVec(t, *self, ?alloc_id, ?ptr, ?capacity); + //@ array_at_lft__to_u8s_at_lft_(ptr, capacity); + //@ size_align::(); + // SAFETY: We are in a Drop impl, self.inner will not be used again. + unsafe { self.inner.deallocate(T::LAYOUT) } + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl RawVecInner { + #[cfg(not(no_global_oom_handling))] + #[inline] + fn with_capacity_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self + { + match Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) { + Ok(mut this) => { + unsafe { + // Make it more obvious that a subsequent Vec::reserve(capacity) will not allocate. + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, &this); + //@ let this_ref = precreate_ref(&this); + //@ init_ref_RawVecInner_(this_ref); + //@ open_frac_borrow(k, ref_initialized_(this_ref), 1/2); + //@ open [?f]ref_initialized_::>(this_ref)(); + let needs_to_grow = this.needs_to_grow(0, capacity, elem_layout); + //@ close [f]ref_initialized_::>(this_ref)(); + //@ close_frac_borrow(f, ref_initialized_(this_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(&this); + //@ open_points_to(&this); + + hint::assert_unchecked(!needs_to_grow); + } + this + } + Err(err) => handle_error(err), + } + } + + fn try_allocate_in( + capacity: usize, + init: AllocInit, + mut alloc: A, + elem_layout: Layout, + ) -> Result + /*@ + req thread_token(?t) &*& + Allocator(t, alloc, ?alloc_id) &*& + t == currentThread; + @*/ + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(v) => + RawVecInner(t, v, elem_layout, alloc_id, ?ptr, ?capacity_) &*& + capacity <= capacity_ &*& + match init { + AllocInit::Uninitialized => + array_at_lft_(alloc_id.lft, ptr, ?n, _) &*& + elem_layout.size() % elem_layout.align() != 0 || n == capacity_ * elem_layout.size(), + AllocInit::Zeroed => + array_at_lft(alloc_id.lft, ptr, ?n, ?bs) &*& + elem_layout.size() % elem_layout.align() != 0 || n == capacity_ * elem_layout.size() &*& + forall(bs, (eq)(0)) == true + }, + Result::Err(e) => .own(t, e) + }; + @*/ + /*@ + safety_proof { + leak .own(_t, init) &*& .own(_t, elem_layout); + std::alloc::open_Allocator_own(alloc); + let result = call(); + match result { + Result::Ok(r) => { + open RawVecInner(_t, r, elem_layout, ?alloc_id, ?ptr, ?capacity_); + if capacity_ * elem_layout.size() != 0 { + leak alloc_block_in(_, _, _); + } + std::alloc::Allocator_to_own(r.alloc); + close RawVecInner0(r, elem_layout, ptr, capacity_); + close >.own(_t, r); + match init { + AllocInit::Uninitialized => { leak array_at_lft_(_, _, _, _); } + AllocInit::Zeroed => { leak array_at_lft(_, _, _, _); } + } + } + Result::Err(e) => { } + } + close , TryReserveError>>.own(_t, result); + } + @*/ + { + //@ std::alloc::Layout_inv(elem_layout); + + // We avoid `unwrap_or_else` here because it bloats the amount of + // LLVM IR generated. + let layout = match layout_array(capacity, elem_layout) { + Ok(layout) => layout, + Err(_) => { + //@ leak .own(_, _); + //@ std::alloc::Allocator_to_own(alloc); + //@ close .own(currentThread, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()) + }, + }; + + //@ let elemLayout = elem_layout; + //@ let layout_ = layout; + //@ assert elemLayout.repeat(capacity) == some(pair(layout_, ?stride)); + //@ std::alloc::Layout_repeat_some(elemLayout, capacity); + //@ mul_mono_l(elemLayout.size(), stride, capacity); + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + if layout.size() == 0 { + let elem_layout_alignment = elem_layout.alignment(); + //@ close exists(elem_layout.size()); + let r = Self::new_in(alloc, elem_layout_alignment); + //@ RawVecInner_inv2::(); + //@ assert RawVecInner(_, _, _, _, ?ptr_, ?capacity_); + //@ mul_mono_l(0, capacity, elem_layout.size()); + //@ mul_zero(capacity, elem_layout.size()); + /*@ + match init { + AllocInit::Uninitialized => { close array_at_lft_(alloc_id.lft, ptr_, 0, []); } + AllocInit::Zeroed => { close array_at_lft(alloc_id.lft, ptr_, 0, []); } + } + @*/ + return Ok(r); + } + + let result = match init { + AllocInit::Uninitialized => { + let r; + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k = begin_lifetime(); + unsafe { + //@ let_lft 'a = k; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = alloc.allocate/*@::@*/(layout); + //@ leak Allocator(_, _, _); + } + //@ end_lifetime(k); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + r + } + #[cfg(not(no_global_oom_handling))] + AllocInit::Zeroed => { + let r; + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k = begin_lifetime(); + { + //@ let_lft 'a = k; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = alloc.allocate_zeroed/*@::@*/(layout); + //@ leak Allocator(_, _, _); + } + //@ end_lifetime(k); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + r + } + }; + let ptr = match result { + Ok(ptr) => ptr, + Err(_) => { + //@ std::alloc::Allocator_to_own(alloc); + let err1 = AllocError { layout, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(currentThread, layout); + //@ close_tuple_0_own(currentThread); + //@ close .own(currentThread, err1); + return Err(err1.into()) + } + }; + + // Allocators currently return a `NonNull<[u8]>` whose length + // matches the size requested. If that ever changes, the capacity + // here should change to `ptr.len() / size_of::()`. + /*@ + if elem_layout.size() % elem_layout.align() == 0 { + div_rem_nonneg(elem_layout.size(), elem_layout.align()); + div_rem_nonneg(stride, elem_layout.align()); + if elem_layout.size() / elem_layout.align() < stride / elem_layout.align() { + mul_mono_l(elem_layout.size() / elem_layout.align() + 1, stride / elem_layout.align(), elem_layout.align()); + } else { + if elem_layout.size() / elem_layout.align() > stride / elem_layout.align() { + mul_mono_l(stride / elem_layout.align() + 1, elem_layout.size() / elem_layout.align(), elem_layout.align()); + assert false; + } + } + assert stride == elem_layout.size(); + } + @*/ + //@ mul_mono_l(1, elem_layout.size(), capacity); + let res = Self { + ptr: ptr.cast(), + cap: unsafe { Cap::new_unchecked(capacity) }, + alloc, + }; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ close RawVecInner(t, res, elem_layout, alloc_id, ptr.as_ptr() as *u8, _); + Ok(res) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn grow_one(&mut self, elem_layout: Layout) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { self.grow_amortized(self.cap.as_inner(), 1, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + unsafe fn grow_amortized( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 < len + additional; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + // This is ensured by the calling contexts. + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated with a dead `else` branch is the entire `if` statement :-( + assert!(additional > 0); + } + + if elem_layout.size() == 0 { + // Since we return a capacity of `usize::MAX` when `elem_size` is + // 0, getting to here necessarily means the `RawVec` is overfull. + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + return Err(CapacityOverflow.into()); + } + + // Nothing we can really do about these checks, sadly. + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; + //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ open_points_to(self); + //@ std::num::niche_types::UsizeNoHighBit_inv(self0.cap); + // This guarantees exponential growth. The doubling cannot overflow + // because `cap <= isize::MAX` and the type of `cap` is `usize`. + let cap0 = cmp::max(self.cap.as_inner() * 2, required_cap); + let cap = cmp::max(min_non_zero_cap(elem_layout.size()), cap0); + + //@ let k = begin_lifetime(); + //@ open RawVecInner(t, self0, elem_layout, alloc_id, ptr0, capacity0); + //@ share_RawVecInner0(k, self, elem_layout, ptr0, capacity0); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let finish_grow_result; + { + //@ let_lft 'a = k; + finish_grow_result = unsafe { self.finish_grow/*@::@*/(cap, elem_layout) }; + } + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner0(self); + + //@ open_points_to(self); + + //@ mul_mono_l(1, elem_layout.size(), cap); + + // SAFETY: Precondition passed to caller + `current_memory` does the right thing + match core::ops::Try::branch(finish_grow_result) { + core::ops::ControlFlow::Break(residual) => { + //@ let self1 = *self; + //@ close RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0); + core::ops::FromResidual::from_residual(residual) + } + core::ops::ControlFlow::Continue(ptr) => { + unsafe { + // SAFETY: layout_array would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items + self.set_ptr_and_cap(ptr, cap); + //@ let self1 = *self; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ std::num::niche_types::UsizeNoHighBit_as_inner_new(cap); + //@ mul_zero(elem_layout.size(), cap); + //@ assert 0 <= self0.cap.as_inner(); + //@ assert 0 <= logical_capacity(self0.cap, elem_layout.size()); + //@ assert cap != 0; + //@ std::alloc::Layout_inv(elem_layout); + //@ assert 0 <= cap * elem_layout.size(); + //@ assert cap * elem_layout.size() <= isize::MAX - isize::MAX % elem_layout.align(); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, cap); + //@ assert ptr.as_ptr() as usize % Layout::from_size_align(cap * elem_layout.size(), elem_layout.align()).align() == 0; + //@ std::alloc::Layout_align_Layout_from_size_align(cap * elem_layout.size(), elem_layout.align()); + //@ close RawVecInner::(t, self1, elem_layout, alloc_id, ptr.as_ptr() as *u8, cap); + } + Ok(()) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be greater than the current capacity + // not marked inline(never) since we want optimizers to be able to observe the specifics of this + // function, see tests/codegen-llvm/vec-reserve-extend.rs. + #[cold] + unsafe fn finish_grow<'a>( + &'a self, + cap: usize, + elem_layout: Layout, + ) -> Result, TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + 1 <= elem_layout.size() &*& + elem_layout.size() % elem_layout.align() == 0 &*& + [_]RawVecInner_share_('a, t, self, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& [?q]lifetime_token('a) &*& + if capacity0 * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)) &*& + std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 <= cap; + @*/ + /*@ + ens thread_token(t) &*& [q]lifetime_token('a) &*& + match result { + Result::Ok(new_ptr) => + elem_layout.repeat(cap) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, new_ptr.as_ptr() as *u8, allocLayout) &*& + array_at_lft_(alloc_id.lft, new_ptr.as_ptr() as *u8, cap * elem_layout.size(), _) &*& + cap * elem_layout.size() <= isize::MAX &*& + std::alloc::is_valid_layout(cap * elem_layout.size(), elem_layout.align()) == true, + Result::Err(e) => + if capacity0 * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)) &*& + std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout) + } &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(currentThread, e) + }; + @*/ + { + //@ std::alloc::Layout_inv(elem_layout); + + let new_layout = layout_array(cap, elem_layout)?; + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, cap); + + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow('a, ref_initialized_(self_ref), q/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { (&*(self as *const RawVecInner)).current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + + //@ open RawVecInner_share_('a, t, self, elem_layout, alloc_id, ptr0, capacity0); + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if capacity0 * elem_layout.size() != 0 { + let elemLayout = elem_layout; + assert elemLayout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some_size_aligned(elemLayout, capacity0); + std::alloc::Layout_inv(allocLayout); + } + @*/ + //@ std::alloc::Layout_size_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + //@ std::alloc::Layout_align_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + + //@ open_frac_borrow('a, RawVecInner_frac_borrow_content(self, elem_layout, ptr0, capacity0), q/2); + //@ open [?f1]RawVecInner_frac_borrow_content::(self, elem_layout, ptr0, capacity0)(); + //@ let cap0 = (*self).cap; + //@ std::num::niche_types::UsizeNoHighBit_inv(cap0); + //@ close [f1]RawVecInner_frac_borrow_content::(self, elem_layout, ptr0, capacity0)(); + //@ close_frac_borrow(f1, RawVecInner_frac_borrow_content(self, elem_layout, ptr0, capacity0)); + //@ mul_mono_l(1, elem_layout.size(), cap0.as_inner()); + //@ mul_mono_l(1, elem_layout.size(), cap); + //@ mul_mono_l(capacity0, cap, elem_layout.size()); + + let memory = if let Some((ptr, old_layout)) = current_memory { + // FIXME(const-hack): switch to `debug_assert_eq` + // debug_assert!(old_layout.align() == new_layout.align()); + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated + //with a dead `else` branch is the entire `if` statement :-( + if !(old_layout.align() == new_layout.align()) { + core::panicking::panic("assertion failed: old_layout.align() == new_layout.align()"); //~allow_dead_code + } + }; + unsafe { + // The allocator checks for alignment equality + hint::assert_unchecked(old_layout.align() == new_layout.align()); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity0); + //@ assert elem_layout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + //@ assert allocLayout == old_layout; + //@ assert ptr.as_ptr() as *u8 == ptr0; + //@ assert std::alloc::alloc_block_in(alloc_id, ptr0, allocLayout); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ std::alloc::init_ref_Allocator_share::('a, t, alloc_ref); + //@ open_frac_borrow('a, ref_initialized_::(alloc_ref), q/2); + //@ open [?f2]ref_initialized_::(alloc_ref)(); + //@ std::alloc::close_Allocator_ref::<'a, A>(t, alloc_ref); + let r = self.alloc.grow/*@::@*/(ptr, old_layout, new_layout); + //@ close [f2]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f2, ref_initialized_::(alloc_ref)); + //@ leak Allocator(_, _, _); + r + } + } else { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ std::alloc::init_ref_Allocator_share::('a, t, alloc_ref); + //@ open_frac_borrow('a, ref_initialized_::(alloc_ref), q/2); + //@ open [?f2]ref_initialized_::(alloc_ref)(); + //@ std::alloc::close_Allocator_ref::<'a, A>(t, alloc_ref); + let r = self.alloc.allocate/*@::@*/(new_layout); + //@ close [f2]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f2, ref_initialized_::(alloc_ref)); + //@ leak Allocator(_, _, _); + r + }; + + let new_layout_ref = &new_layout; + match memory { + Ok(ptr) => Ok(ptr), + Err(err) => { + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); + //@ close .own(t, e); + Err(e.into()) + } + } + } +} + +impl RawVecInner { + #[inline] + const fn new_in(alloc: A, align: Alignment) -> Self + /*@ + req exists::(?elemSize) &*& + thread_token(?t) &*& + Allocator(t, alloc, ?alloc_id) &*& + std::alloc::is_valid_layout(elemSize, align.as_nonzero_usize().get()) == true; + @*/ + /*@ + ens thread_token(t) &*& + RawVecInner(t, result, Layout::from_size_align(elemSize, align.as_nonzero_usize().get()), alloc_id, ?ptr, ?capacity) &*& + array_at_lft_(alloc_id.lft, ptr, capacity * elemSize, []) &*& + capacity * elemSize == 0; + @*/ + //@ on_unwind_ens false; + /*@ + safety_proof { + leak .own(_t, align); + close exists::(0); + std::alloc::open_Allocator_own(alloc); + std::mem::Alignment_is_power_of_2(align); + if align.as_nonzero_usize().get() <= isize::MAX { + div_rem_nonneg(isize::MAX, align.as_nonzero_usize().get()); + } else { + div_rem_nonneg_unique(isize::MAX, align.as_nonzero_usize().get(), 0, isize::MAX); + } + let result = call(); + open RawVecInner(_t, result, ?elemLayout, ?alloc_id, ?ptr, ?capacity); + std::num::niche_types::UsizeNoHighBit_inv(result.cap); + std::alloc::Layout_inv(elemLayout); + mul_zero(capacity, elemLayout.size()); + assert elemLayout == Layout::from_size_align(0, align.as_nonzero_usize().get()); + std::alloc::Layout_size_Layout_from_size_align(0, align.as_nonzero_usize().get()); + assert elemLayout.size() == 0; + assert capacity * elemLayout.size() == 0; + std::alloc::Allocator_to_own(result.alloc); + close RawVecInner0(result, elemLayout, ptr, capacity); + close >.own(_t, result); + leak array_at_lft_(_, _, _, _); + } + @*/ + { + let ptr = NonNull::without_provenance(align.as_nonzero_usize()); + // `cap: 0` means "unallocated". zero-sized types are ignored. + let cap = ZERO_CAP; + let r = Self { ptr, cap, alloc }; + //@ div_rem_nonneg_unique(align.as_nonzero_usize().get(), align.as_nonzero_usize().get(), 1, 0); + //@ let layout = Layout::from_size_align(elemSize, align.as_nonzero_usize().get()); + /*@ + if layout.size() == 0 { + div_rem_nonneg_unique(layout.size(), layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(layout, logical_capacity(cap, layout.size())); + } else { + std::alloc::Layout_repeat_0_intro(layout); + } + @*/ + //@ close RawVecInner(t, r, layout, alloc_id, _, _); + r + } + + #[inline] + fn try_with_capacity_in( + capacity: usize, + alloc: A, + elem_layout: Layout, + ) -> Result { + Self::try_allocate_in(capacity, AllocInit::Uninitialized, alloc, elem_layout) + } + + #[cfg(not(no_global_oom_handling))] + #[inline] + fn with_capacity_zeroed_in(capacity: usize, alloc: A, elem_layout: Layout) -> Self { + match Self::try_allocate_in(capacity, AllocInit::Zeroed, alloc, elem_layout) { + Ok(res) => res, + Err(err) => handle_error(err), + } + } + + #[inline] + const unsafe fn from_raw_parts_in(ptr: *mut u8, cap: Cap, alloc: A) -> Self + /*@ + req exists::(?elem_layout) &*& + Allocator(?t, alloc, ?alloc_id) &*& + ptr as usize != 0 &*& + ptr as usize % elem_layout.align() == 0 &*& + if cap.as_inner() * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(cap.as_inner()) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr, allocLayout) + }; + @*/ + //@ ens RawVecInner(t, result, elem_layout, alloc_id, ptr, logical_capacity(cap, elem_layout.size())); + { + let r = Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, cap, alloc }; + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if cap.as_inner() * elem_layout.size() == 0 { + std::num::niche_types::UsizeNoHighBit_inv(cap); + mul_zero(cap.as_inner(), elem_layout.size()); + if elem_layout.size() == 0 { + div_rem_nonneg_unique(elem_layout.size(), elem_layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(elem_layout, logical_capacity(cap, elem_layout.size())); + } else { + std::alloc::Layout_repeat_0_intro(elem_layout); + } + } + @*/ + //@ close RawVecInner(t, r, elem_layout, alloc_id, ptr, logical_capacity(cap, elem_layout.size())); + r + } + + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn from_nonnull_in(ptr: NonNull, cap: Cap, alloc: A) -> Self + /*@ + req exists::(?elem_layout) &*& + Allocator(?t, alloc, ?alloc_id) &*& + ptr.as_ptr() as usize % elem_layout.align() == 0 &*& + pointer_within_limits(ptr.as_ptr()) == true &*& + if cap.as_inner() * elem_layout.size() == 0 { + true + } else { + elem_layout.repeat(cap.as_inner()) == some(pair(?allocLayout, ?stride)) &*& + alloc_block_in(alloc_id, ptr.as_ptr(), allocLayout) + }; + @*/ + //@ ens RawVecInner(t, result, elem_layout, alloc_id, ptr.as_ptr(), logical_capacity(cap, elem_layout.size())); + { + let r = Self { ptr, cap, alloc }; + /*@ + if cap.as_inner() * elem_layout.size() == 0 { + std::num::niche_types::UsizeNoHighBit_inv(cap); + std::alloc::Layout_inv(elem_layout); + mul_zero(cap.as_inner(), elem_layout.size()); + if elem_layout.size() == 0 { + div_rem_nonneg_unique(elem_layout.size(), elem_layout.align(), 0, 0); + std::alloc::Layout_repeat_size_aligned_intro(elem_layout, usize::MAX); + } else { + std::alloc::Layout_repeat_0_intro(elem_layout); + } + } + @*/ + //@ close RawVecInner(t, r, elem_layout, alloc_id, _, _); + r + } + + #[inline] + const fn ptr(&self) -> *mut T + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + @*/ + //@ ens [q]lifetime_token(k) &*& result == ptr as *T; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ RawVecInner_share__inv::(); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), q/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let r = unsafe { &*(self as *const RawVecInner) }.non_null::(); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + r.as_ptr() + } + + #[inline] + const fn non_null(&self) -> NonNull + //@ req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result.as_ptr() == ptr as *T; + /*@ + safety_proof { + open >.share(?k, _t, self); + let result = call(); + std::ptr::close_NonNull_own::(_t, result); + } + @*/ + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + let r = self.ptr.cast(); + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity)); + r + } + + #[inline] + const fn capacity(&self, elem_size: usize) -> usize + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k); + @*/ + //@ ens [q]lifetime_token(k) &*& elem_size != elem_layout.size() || result == capacity; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + let r = + if elem_size == 0 { usize::MAX } else { self.cap.as_inner() }; + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity)); + r + } + + #[inline] + const fn allocator(&self) -> &A + /*@ + req [?q]lifetime_token(?k) &*& + exists(?readOnly) &*& + if readOnly { + [_]points_to_shared(k, self, ?self_) &*& + ens [q]lifetime_token(k) &*& + [_]points_to_shared(k, result, self_.alloc()) &*& + [_]frac_borrow(k, ref_initialized_(result)) + } else { + [_]RawVecInner_share_(k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + ens [q]lifetime_token(k) &*& + [_]std::alloc::Allocator_share(k, t, result, alloc_id) &*& + [_]frac_borrow(k, ref_initialized_(result)) + }; + @*/ + //@ ens true; + /*@ + safety_proof { + open >.share(?k, _t, self); + close exists(false); + let result = call(); + std::alloc::close_Allocator_share(k, _t, result); + } + @*/ + { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + /*@ + if readOnly { + open points_to_shared(k, self, ?self_); + open_frac_borrow_strong_(k, mk_points_to(self, self_), q); + open [?f]mk_points_to::>(self, self_)(); + open_points_to(self); + close [f]mk_points_to::(&(*self).alloc, self_.alloc)(); + close scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))(); + { + pred Ctx() = [f](*self).ptr |-> self_.ptr &*& [f](*self).cap |-> self_.cap &*& [f]struct_RawVecInner_padding(self); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow(Ctx, scaledp(f, mk_points_to(&(*self).alloc, self_.alloc)), f, mk_points_to(self, self_))() { + open Ctx(); + open scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))(); + open [f]mk_points_to::(&(*self).alloc, self_.alloc)(); + close [f]mk_points_to::>(self, self_)(); + } { + close_frac_borrow_strong_(); + full_borrow_into_frac(k, scaledp(f, mk_points_to(&(*self).alloc, self_.alloc))); + } + } + frac_borrow_implies_scaled(k, f, mk_points_to(&(*self).alloc, self_.alloc)); + close points_to_shared(k, &(*self).alloc, self_.alloc); + leak points_to_shared(k, &(*self).alloc, self_.alloc); + init_ref_readonly_points_to_shared(alloc_ref); + } else { + open RawVecInner_share_(k, ?t, self, ?elem_layout, ?alloc_id, ?ptr, ?capacity); + std::alloc::init_ref_Allocator_share(k, t, alloc_ref); + } + @*/ + //@ open_frac_borrow(k, ref_initialized_::(alloc_ref), q); + //@ open [?f]ref_initialized_::(alloc_ref)(); + let r = &self.alloc; + //@ close [f]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f, ref_initialized_::(alloc_ref)); + r + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn current_memory(&self, elem_layout: Layout) -> Option<(NonNull, Layout)> + /*@ + req [_]RawVecInner_share_(?k, ?t, self, elem_layout, ?alloc_id, ?ptr, ?capacity) &*& + [?q]lifetime_token(k) &*& elem_layout.size() % elem_layout.align() == 0; + @*/ + /*@ + ens [q]lifetime_token(k) &*& + if capacity * elem_layout.size() == 0 { + result == Option::None + } else { + result == Option::Some(?r) &*& + r.0.as_ptr() == ptr &*& + r.1 == Layout::from_size_align(capacity * elem_layout.size(), elem_layout.align()) + }; + @*/ + //@ on_unwind_ens false; + { + //@ open RawVecInner_share_(k, t, self, elem_layout, alloc_id, ptr, capacity); + //@ open_frac_borrow(k, RawVecInner_frac_borrow_content(self, elem_layout, ptr, capacity), q); + //@ open [?f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ std::num::niche_types::UsizeNoHighBit_inv((*self).cap); + //@ std::alloc::Layout_inv(elem_layout); + //@ mul_zero(capacity, elem_layout.size()); + if elem_layout.size() == 0 || self.cap.as_inner() == 0 { + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)); + None + } else { + // We could use Layout::array here which ensures the absence of isize and usize overflows + // and could hypothetically handle differences between stride and size, but this memory + // has already been allocated so we know it can't overflow and currently Rust does not + // support such types. So we can do better by skipping some checks and avoid an unwrap. + // SAFETY: Upheld by caller, unless the element size is 0 which is checked against. + unsafe { + //@ let elemLayout = elem_layout; + //@ assert elemLayout.repeat(capacity) == some(pair(?allocLayout, ?stride)); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity); + //@ std::alloc::Layout_inv(allocLayout); + //@ is_power_of_2_pos(elem_layout.align()); + //@ div_rem_nonneg(isize::MAX, elem_layout.align()); + let alloc_size = elem_layout.size().unchecked_mul(self.cap.as_inner()); + let layout = Layout::from_size_align_unchecked(alloc_size, elem_layout.align()); + let ptr_ = self.ptr; + //@ std::ptr::NonNull_new_as_ptr((*self).ptr); + //@ close [f]RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)(); + //@ close_frac_borrow(f, RawVecInner_frac_borrow_content::(self, elem_layout, ptr, capacity)); + Some((ptr_, layout)) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn reserve(&mut self, len: usize, additional: usize, elem_layout: Layout) + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), ?bs1) &*& + (len > capacity0 || (len + additional <= capacity1 && take(len * elem_layout.size(), bs1) == take(len * elem_layout.size(), bs0))); + @*/ + //@ assume_correct + { + // Callers expect this function to be very cheap when there is already sufficient capacity. + // Therefore, we move all the resizing and error-handling logic from grow_amortized and + // handle_reserve behind a call, while making sure that this function is likely to be + // inlined as just a comparison and a call if the comparison fails. + #[cold] + unsafe fn do_reserve_and_handle( + slf: &mut RawVecInner, + len: usize, + additional: usize, + elem_layout: Layout, + ) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { slf.grow_amortized(len, additional, elem_layout) } { + handle_error(err); + } + } + + if self.needs_to_grow(len, additional, elem_layout) { + // SAFETY: `needs_to_grow` ensures that `len + additional` is greater than + // the current capacity, with the other preconditions upheld by our caller. + unsafe { + do_reserve_and_handle(self, len, additional, elem_layout); + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + unsafe fn try_reserve( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let needs_to_grow = self.needs_to_grow(len, additional, elem_layout); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + if needs_to_grow { + // SAFETY: Precondition passed to caller + unsafe { + self.grow_amortized(len, additional, elem_layout)?; + } + } + // SAFETY: If we've already grown, we will not need to again immediately after. + unsafe { + //@ let k2 = begin_lifetime(); + //@ share_RawVecInner(k2, self); + //@ let self_ref2 = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref2); + //@ open_frac_borrow(k2, ref_initialized_(self_ref2), 1/2); + //@ open [?f2]ref_initialized_::>(self_ref2)(); + let needs_to_grow2 = self.needs_to_grow(len, additional, elem_layout); + //@ close [f2]ref_initialized_::>(self_ref2)(); + //@ close_frac_borrow(f2, ref_initialized_(self_ref2)); + //@ end_lifetime(k2); + //@ end_share_RawVecInner(self); + + // Inform the optimizer that the reservation has succeeded or wasn't needed + hint::assert_unchecked(!needs_to_grow2); + + } + Ok(()) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + #[cfg(not(no_global_oom_handling))] + unsafe fn reserve_exact(&mut self, len: usize, additional: usize, elem_layout: Layout) { + // SAFETY: Precondition passed to caller + if let Err(err) = unsafe { self.try_reserve_exact(len, additional, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + unsafe fn try_reserve_exact( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len > capacity0 || len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let needs_to_grow = self.needs_to_grow(len, additional, elem_layout); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + if needs_to_grow { + // SAFETY: Precondition passed to caller + unsafe { + self.grow_exact(len, additional, elem_layout)?; + } + } + // SAFETY: If we've already grown, we will not need to again immediately after. + unsafe { + //@ let k2 = begin_lifetime(); + //@ share_RawVecInner(k2, self); + //@ let self_ref2 = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref2); + //@ open_frac_borrow(k2, ref_initialized_(self_ref2), 1/2); + //@ open [?f2]ref_initialized_::>(self_ref2)(); + let needs_to_grow2 = self.needs_to_grow(len, additional, elem_layout); + //@ close [f2]ref_initialized_::>(self_ref2)(); + //@ close_frac_borrow(f2, ref_initialized_(self_ref2)); + //@ end_lifetime(k2); + //@ end_share_RawVecInner(self); + + // Inform the optimizer that the reservation has succeeded or wasn't needed + hint::assert_unchecked(!needs_to_grow2); + + } + Ok(()) + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn shrink_to_fit(&mut self, cap: usize, elem_layout: Layout) + { + if let Err(err) = unsafe { self.shrink(cap, elem_layout) } { + handle_error(err); + } + } + + /// # Safety + /// + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + unsafe fn try_shrink_to_fit( + &mut self, + cap: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> { + // SAFETY: Upheld by caller. + unsafe { self.shrink(cap, elem_layout) } + } + + #[inline] + const fn needs_to_grow(&self, len: usize, additional: usize, elem_layout: Layout) -> bool + /*@ + req [_]RawVecInner_share_(?k, ?t, self, ?elemLayout, ?alloc_id, ?ptr, ?capacity) &*& + [?qa]lifetime_token(k); + @*/ + //@ ens [qa]lifetime_token(k) &*& elem_layout != elemLayout || result == (additional > std::num::wrapping_sub_usize(capacity, len)); + /*@ + safety_proof { + leak .own(_t, elem_layout); + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), qa/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let r = additional > unsafe { &*(self as *const RawVecInner) }.capacity(elem_layout.size()).wrapping_sub(len); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + r + } + + #[inline] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + const unsafe fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) + //@ req (*self).ptr |-> _ &*& (*self).cap |-> _ &*& cap <= isize::MAX; + //@ ens (*self).ptr |-> ptr.as_non_null_ptr() &*& (*self).cap |-> UsizeNoHighBit::new(cap); + { + //@ std::ptr::NonNull_new_as_ptr(ptr.as_non_null_ptr()); + // Allocators currently return a `NonNull<[u8]>` whose length matches + // the size requested. If that ever changes, the capacity here should + // change to `ptr.len() / size_of::()`. + self.ptr = ptr.cast(); + // SAFETY: Upheld by caller. + self.cap = unsafe { Cap::new_unchecked(cap) }; + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - The sum of `len` and `additional` must be greater than the current capacity + unsafe fn grow_exact( + &mut self, + len: usize, + additional: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + capacity0 < len + additional; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), _) &*& + len + additional <= capacity1, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), _) &*& + .own(t, e) + }; + @*/ + { + if elem_layout.size() == 0 { + // Since we return a capacity of `usize::MAX` when the type size is + // 0, getting to here necessarily means the `RawVec` is overfull. + let e = CapacityOverflow; + //@ close .own(t, e); + return Err(e.into()); + } + + //@ close .own(t, TryReserveErrorKind::CapacityOverflow); + let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; + //@ leak .own(t, TryReserveErrorKind::CapacityOverflow); + + //@ let k = begin_lifetime(); + //@ open RawVecInner(t, self0, elem_layout, alloc_id, ptr0, capacity0); + //@ share_RawVecInner0(k, self, elem_layout, ptr0, capacity0); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let finish_grow_result; + { + //@ let_lft 'a = k; + finish_grow_result = unsafe { self.finish_grow/*@::@*/(cap, elem_layout) }; + } + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner0(self); + + //@ open_points_to(self); + + //@ mul_mono_l(1, elem_layout.size(), cap); + + // SAFETY: Precondition passed to caller + `current_memory` does the right thing + match core::ops::Try::branch(finish_grow_result) { + core::ops::ControlFlow::Break(residual) => { + //@ let self1 = *self; + //@ close RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0); + core::ops::FromResidual::from_residual(residual) + } + core::ops::ControlFlow::Continue(ptr) => { + // SAFETY: layout_array would have resulted in a capacity overflow if we tried to allocate more than `isize::MAX` items + unsafe { + //@ let elemLayout = elem_layout; + //@ assert elemLayout.repeat(cap) == some(pair(?new_layout, ?stride)); + //@ std::alloc::Layout_repeat_some_size_aligned(elemLayout, cap); + //@ assert new_layout.size() == elem_layout.size() * cap; + //@ mul_mono_l(1, elem_layout.size(), cap); + self.set_ptr_and_cap(ptr, cap); + //@ let self1 = *self; + //@ std::alloc::alloc_block_in_aligned(ptr.as_ptr() as *u8); + //@ std::num::niche_types::UsizeNoHighBit_as_inner_new(cap); + //@ mul_zero(elem_layout.size(), cap); + //@ assert 0 <= self0.cap.as_inner(); + //@ assert 0 <= logical_capacity(self0.cap, elem_layout.size()); + //@ assert cap != 0; + //@ std::alloc::Layout_inv(new_layout); + //@ close RawVecInner::(t, self1, elem_layout, alloc_id, _, _); + } + Ok(()) + } + } + } + + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// # Safety + /// - `elem_layout` must be valid for `self`, i.e. it must be the same `elem_layout` used to + /// initially construct `self` + /// - `elem_layout`'s size must be a multiple of its alignment + /// - `cap` must be less than or equal to `self.capacity(elem_layout.size())` + #[inline] + unsafe fn shrink(&mut self, cap: usize, elem_layout: Layout) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), take(capacity1 * elem_layout.size(), bs0)) &*& + cap <= capacity0 &*& + cap <= capacity1 &*& + capacity1 == if elem_layout.size() == 0 { usize::MAX } else { cap }, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), bs0) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + let capacity = self.capacity(elem_layout.size()); + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + assert!(cap <= capacity, "Tried to shrink to a larger capacity"); + // SAFETY: Just checked this isn't trying to grow + unsafe { self.shrink_unchecked(cap, elem_layout) } + } + + /// `shrink`, but without the capacity check. + /// + /// This is split out so that `shrink` can inline the check, since it + /// optimizes out in things like `shrink_to_fit`, without needing to + /// also inline all this code, as doing that ends up failing the + /// `vec-shrink-panic` codegen test when `shrink_to_fit` ends up being too + /// big for LLVM to be willing to inline. + /// + /// # Safety + /// - `cap <= self.capacity()` + /// - `elem_layout` must be valid for `self`. + unsafe fn shrink_unchecked( + &mut self, + cap: usize, + elem_layout: Layout, + ) -> Result<(), TryReserveError> + /*@ + req thread_token(?t) &*& t == currentThread &*& + elem_layout.size() % elem_layout.align() == 0 &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr0, ?capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), ?bs0) &*& + cap <= capacity0; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& + match result { + Result::Ok(u) => + RawVecInner(t, self1, elem_layout, alloc_id, ?ptr1, ?capacity1) &*& + array_at_lft_(alloc_id.lft, ptr1, capacity1 * elem_layout.size(), take(capacity1 * elem_layout.size(), bs0)) &*& + cap <= capacity1 &*& + capacity1 == if elem_layout.size() == 0 { usize::MAX } else { cap }, + Result::Err(e) => + RawVecInner(t, self1, elem_layout, alloc_id, ptr0, capacity0) &*& + array_at_lft_(alloc_id.lft, ptr0, capacity0 * elem_layout.size(), bs0) &*& + .own(t, e) + }; + @*/ + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { self.current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + let Some((ptr, layout)) = current_memory else { + //@ std::alloc::Layout_inv(elem_layout); + //@ mul_zero(capacity0, elem_layout.size()); + //@ RawVecInner_inv2(); + return Ok(()); + }; + + //@ open_points_to(self); + + //@ open RawVecInner(t, ?self01, elem_layout, alloc_id, ptr0, capacity0); + //@ assert self01.ptr.as_ptr() == ptr0; + //@ std::alloc::Layout_inv(elem_layout); + /*@ + if capacity0 * elem_layout.size() != 0 { + let elemLayout = elem_layout; + assert elemLayout.repeat(capacity0) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some_size_aligned(elemLayout, capacity0); + std::alloc::Layout_inv(allocLayout); + } + @*/ + //@ std::alloc::Layout_size_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + //@ std::alloc::Layout_align_Layout_from_size_align(capacity0 * elem_layout.size(), elem_layout.align()); + + // If shrinking to 0, deallocate the buffer. We don't reach this point + // for the T::IS_ZST case since current_memory() will have returned + // None. + if cap == 0 { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + unsafe { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + self.alloc.deallocate/*@::@*/(ptr, layout); + //@ leak Allocator(_, _, _); + }; + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + self.ptr = NonNull::without_provenance(elem_layout.alignment().as_nonzero_usize()); + self.cap = ZERO_CAP; + //@ let ptr1_ = (*self).ptr; + //@ assert ptr1_.as_ptr() as usize == elem_layout.align(); + //@ div_rem_nonneg_unique(elem_layout.align(), elem_layout.align(), 1, 0); + //@ std::alloc::Layout_repeat_0_intro(elem_layout); + //@ close RawVecInner(t, *self, elem_layout, alloc_id, _, _); + } else { + // SAFETY: `cap` is less than the previous capacity, which must have fit in an + // isize already for the non-ZST case. `shrink` is also sound to call since + // `current_memory` ensures `ptr` and `layout` are correct for the old allocation, + // while `new_layout` is computed with a smaller size than the old one per the + // requirement we instate on our callers. + let ptr = unsafe { + // Layout cannot overflow here because it would have + // overflowed earlier when capacity was larger. + //@ mul_mono_l(cap, capacity0, elem_layout.size()); + let new_size = elem_layout.size().unchecked_mul(cap); + let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + let r; + { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = self.alloc.shrink/*@::@*/(ptr, layout, new_layout); + //@ leak Allocator(_, _, _); + }; + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + let new_layout_ref = &new_layout; + match r { + Ok(ptr1) => Ok(ptr1), + Err(err) => { + //@ close RawVecInner(t, *self, elem_layout, alloc_id, ptr0, capacity0); + let e = AllocError { layout: *new_layout_ref, non_exhaustive: () }; + //@ std::alloc::close_Layout_own(t, new_layout); + //@ close_tuple_0_own(t); + //@ close .own(t, e); + Err(e) + } + }? + }; + // SAFETY: if the allocation is valid, then the capacity is too + unsafe { + //@ std::num::niche_types::UsizeNoHighBit_inv(self01.cap); + self.set_ptr_and_cap(ptr, cap); + //@ std::alloc::alloc_block_in_aligned(ptr_1.as_ptr() as *u8); + //@ mul_zero(cap, elem_layout.size()); + //@ std::alloc::Layout_repeat_size_aligned_intro(elem_layout, cap); + //@ close RawVecInner(t, *self, elem_layout, alloc_id, _, _); + } + } + Ok(()) + } +} + +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const impl RawVecInner { + /// # Safety + /// + /// This function deallocates the owned allocation, but does not update `ptr` or `cap` to + /// prevent double-free or use-after-free. Essentially, do not do anything with the caller + /// after this function returns. + /// Ideally this function would take `self` by move, but it cannot because it exists to be + /// called from a `Drop` impl. + unsafe fn deallocate(&mut self, elem_layout: Layout) + /*@ + req thread_token(?t) &*& + *self |-> ?self0 &*& + RawVecInner(t, self0, elem_layout, ?alloc_id, ?ptr_, ?capacity) &*& + elem_layout.size() % elem_layout.align() == 0 &*& + array_at_lft_(alloc_id.lft, ptr_, capacity * elem_layout.size(), _); + @*/ + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + //@ on_unwind_ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ let k = begin_lifetime(); + //@ share_RawVecInner(k, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_RawVecInner_(self_ref); + //@ open_frac_borrow(k, ref_initialized_(self_ref), 1/2); + //@ open [?f]ref_initialized_::>(self_ref)(); + // SAFETY: Precondition passed to caller + let current_memory = unsafe { self.current_memory(elem_layout) }; + //@ close [f]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f, ref_initialized_(self_ref)); + //@ end_lifetime(k); + //@ end_share_RawVecInner(self); + + //@ open_points_to(self); + //@ open RawVecInner(t, _, elem_layout, alloc_id, ptr_, capacity); + if let Some((ptr, layout)) = current_memory { + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + unsafe { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + //@ std::alloc::Layout_repeat_some_size_aligned(elem_layout, capacity); + //@ assert capacity * elem_layout.size() == layout.size(); + self.alloc.deallocate/*@::@*/(ptr, layout); + } + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } + //@ std::alloc::Allocator_to_own((*self).alloc); + //@ close RawVecInner0(*self, elem_layout, ptr_, capacity); + //@ close >.own(t, *self); + } +} + +// Central function for reserve error handling. +#[cfg(not(no_global_oom_handling))] +#[cold] +#[optimize(size)] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const fn handle_error(e: TryReserveError) -> ! +{ + match e.kind() { + CapacityOverflow => capacity_overflow(), + AllocError { layout, .. } => handle_alloc_error(layout), + } +} + +#[inline] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const fn layout_array(cap: usize, elem_layout: Layout) -> Result +//@ req thread_token(currentThread); +/*@ +ens thread_token(currentThread) &*& + elem_layout.size() % elem_layout.align() == 0 &*& // Established by the `debug_assert!` below + match result { + Result::Ok(layout) => elem_layout.repeat(cap) == some(pair(layout, ?stride)), + Result::Err(err) => .own(currentThread, err) + }; +@*/ +/*@ +safety_proof { + leak .own(_t, elem_layout); + let result = call(); + match result { + Result::Ok(layout) => { std::alloc::close_Layout_own(_t, layout); } + Result::Err(e) => {} + } + close >.own(_t, result); +} +@*/ +{ + // This is only used with `elem_layout`s which are those of real rust types, + // which lets us use the much-simpler `repeat_packed`. + // debug_assert!(elem_layout.size() == elem_layout.pad_to_align().size()); + if cfg!(debug_assertions) { //~allow_dead_code // FIXME: The source location associated + //with a dead `else` branch is the entire `if` statement :-( + if !(elem_layout.size() == elem_layout.pad_to_align().size()) { + core::panicking::panic("assertion failed: elem_layout.size() == elem_layout.pad_to_align().size()"); + } + }; + + // FIXME(const-hack) return to using `map` and `map_err` once `const_closures` is implemented + let r2 = match elem_layout.repeat_packed(cap) { + Ok(layout) => { + //@ std::alloc::Layout_repeat_size_aligned_intro(elem_layout, cap); + Ok(layout) + } + Err(err) => { + let e = CapacityOverflow; + //@ close .own(currentThread, e); + Err(e.into()) + } + }; + r2 +} diff --git a/verifast-proofs/alloc/vec/mod.rs/verified/set_len_on_drop.rs b/verifast-proofs/alloc/vec/mod.rs/verified/set_len_on_drop.rs new file mode 100644 index 0000000000000..999a47c451a83 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/verified/set_len_on_drop.rs @@ -0,0 +1,110 @@ +// Set the length of the vec when the `SetLenOnDrop` value goes out of scope. +// +// The idea is: The length field in SetLenOnDrop is a local variable +// that the optimizer will see does not alias with any stores through the Vec's data +// pointer. This is a workaround for alias analysis issue #32155 +pub(super) struct SetLenOnDrop<'a> { + len: &'a mut usize, + local_len: usize, +} + +/*@ +pred_ctor vec::set_len_on_drop::SetLenOnDrop_fbc(p: *usize, bound: usize)() = + *p |-> ?actual &*& actual <= bound; + +// Note: VeriFast 26.10 translates scope-exit `TerminatorKind::Drop(local_len)` to +// `std::ptr::drop_in_place::>` (erasing `'a` to `'static`) +// and does not support Drop specs on anonymous `impl Drop for SetLenOnDrop<'_>`. +// Therefore `SetLenOnDrop_own` carries the borrow lifetime `k` existentially and +// `SetLenOnDrop::drop` (`*self.len = self.local_len;`) is skipped under +// `-skip_specless_fns` (see PR description for full trust-boundary disclosure). +pred<'a> >.own(t, s) = + exists::>(pair(?k, ?bound)) &*& + 0 <= bound &*& bound <= usize::MAX &*& + s.local_len <= bound &*& + full_borrow(k, vec::set_len_on_drop::SetLenOnDrop_fbc(s.len, bound)); + +lem vec::set_len_on_drop::SetLenOnDrop_drop<'a>() + req vec::set_len_on_drop::SetLenOnDrop_own::<'a>(?_t, ?_v); + ens true; +{ + open >.own(_t, _v); + open exists::>(_); + leak full_borrow(_, _); +} + +lem vec::set_len_on_drop::SetLenOnDrop_send<'a>(t1: thread_id_t) + req is_Send(typeid(vec::set_len_on_drop::SetLenOnDrop<'a>)) == true &*& vec::set_len_on_drop::SetLenOnDrop_own::<'a>(?t0, ?v); + ens vec::set_len_on_drop::SetLenOnDrop_own::<'a>(t1, v); +{ + open >.own(t0, v); + close >.own(t1, v); +} + +lem vec::set_len_on_drop::SetLenOnDrop_own_mono<'a0, 'a1>() + req vec::set_len_on_drop::SetLenOnDrop_own::<'a0>(?t, ?v) &*& lifetime_inclusion('a1, 'a0) == true; + ens vec::set_len_on_drop::SetLenOnDrop_own::<'a1>(t, vec::set_len_on_drop::SetLenOnDrop::<'a1> { len: v.len as *_, local_len: upcast(v.local_len) }); +{ + open >.own(t, v); + // `upcast` on `usize` is identity (https://github.com/verifast/verifast/issues/610). + assume(upcast::(v.local_len) == v.local_len); + close >.own(t, vec::set_len_on_drop::SetLenOnDrop::<'a1> { len: v.len as *_, local_len: upcast(v.local_len) }); +} +@*/ + +impl<'a> SetLenOnDrop<'a> { + #[inline] + pub(super) fn new(len: &'a mut usize) -> Self + //@ req *len |-> ?v; + //@ ens *len |-> v &*& result == vec::set_len_on_drop::SetLenOnDrop::<'a> { len: len, local_len: v }; + /*@ + safety_proof { + let klong = open_full_borrow_strong('a, usize_full_borrow_content(_t, len), _q_a); + open usize_full_borrow_content(_t, len)(); + assert *len |-> ?v0; + let r = call(); + close vec::set_len_on_drop::SetLenOnDrop_fbc(len, usize::MAX)(); + produce_lem_ptr_chunk full_borrow_convert_strong(True, vec::set_len_on_drop::SetLenOnDrop_fbc(len, usize::MAX), klong, usize_full_borrow_content(_t, len))() { + open vec::set_len_on_drop::SetLenOnDrop_fbc(len, usize::MAX)(); + close usize_full_borrow_content(_t, len)(); + } { + close_full_borrow_strong(klong, usize_full_borrow_content(_t, len), vec::set_len_on_drop::SetLenOnDrop_fbc(len, usize::MAX)); + } + full_borrow_mono(klong, 'a, vec::set_len_on_drop::SetLenOnDrop_fbc(len, usize::MAX)); + close exists::>(pair('a, usize::MAX)); + close >.own(_t, r); + } + @*/ + { + SetLenOnDrop { local_len: *len, len } + } + + #[inline] + pub(super) fn increment_len(&mut self, increment: usize) { + self.local_len += increment; + } + + #[inline] + pub(super) fn current_len(&self) -> usize { + self.local_len + } + + #[cfg(all(kani, not(no_global_oom_handling)))] + pub(super) fn kani_trace_increment_len(&mut self, increment: usize) { + self.local_len += increment; + // SAFETY: Kani verification harnesses are single-threaded; record the + // stack address of `self.local_len` once on the peeled iteration so + // `extend_trusted`'s loop invariant can observe the closure's exact + // `SetLenOnDrop` counter without modifying shipped code. + unsafe { + crate::vec::verify_ch23::record_extend_trusted_len_ptr(&raw mut self.local_len); + } + } +} + +impl Drop for SetLenOnDrop<'_> { + #[inline] + fn drop(&mut self) { + *self.len = self.local_len; + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/verified/spec_extend_with.rs b/verifast-proofs/alloc/vec/mod.rs/verified/spec_extend_with.rs new file mode 100644 index 0000000000000..f015bb6a8cb19 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/verified/spec_extend_with.rs @@ -0,0 +1,232 @@ +use core::clone::TrivialClone; +#[cfg(kani)] +use core::kani; +use core::{mem, ptr}; + +use crate::alloc::Allocator; +use crate::vec::{SetLenOnDrop, Vec}; + +pub(super) trait SpecExtendWith { + /// Extend the vector by `n` clones of value. + fn spec_extend_with(&mut self, n: usize, value: T); +} + +fn clone__VeriFast_wrapper(val: &T) -> T +//@ req thread_token(?t) &*& [_](.share(?k, t, val)) &*& [?q]lifetime_token(k); +//@ ens thread_token(t) &*& [q]lifetime_token(k) &*& .own(t, result); +//@ assume_correct +{ + val.clone() +} + +// Bridges `SetLenOnDrop::increment_len(1)` (`pub(super)`) without triggering a +// synthetic public-API `safety_proof` on arbitrary external callers. The exact +// body (`self.local_len += increment;`) and its bound-preserving writeback +// contract are independently verified with zero `assume` statements in +// `set_len_on_drop_proof.rs` (checked in `verify.sh` without `-allow_assume`). +unsafe fn set_len_on_drop_increment_one__VeriFast_wrapper<'a>(guard: &mut SetLenOnDrop<'a>) +//@ req *guard |-> ?s0 &*& s0.local_len + 1 <= usize::MAX; +//@ ens *guard |-> vec::set_len_on_drop::SetLenOnDrop::<'a> { len: s0.len, local_len: s0.local_len + 1 }; +//@ assume_correct +{ + guard.increment_len(1); +} + +impl SpecExtendWith for Vec { + default fn spec_extend_with(&mut self, n: usize, /*@~mut@*/ value: T) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& >.own(t, self0) &*& .own(t, value); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + //@ open >.own(t, self0); + self.reserve(n); + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ vec::Vec_inv2(); + //@ assert vec::Vec(t, ?self1, ?alloc_id, ?base, ?cap, ?len0); + //@ assert array_at_lft(alloc_id.lft, base, len0, ?elems0); + //@ array_at_lft__inv(); + //@ array_at_lft__split(base + len0, n); + //@ array_at_lft__inv(); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let mut ptr = unsafe { + let base_ptr = self.as_mut_ptr(); + //@ let k_len = begin_lifetime(); + //@ vec::share_Vec(k_len, self); + //@ let self_ref = precreate_ref(self); + //@ vec::init_ref_Vec_(self_ref); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref), 1/4); + //@ open [?f1]ref_initialized_::>(self_ref)(); + //@ vec::Vec_share__inv(); + //@ open vec::Vec_share_(k_len, t, self_ref, alloc_id, base, cap, len0); + //@ open_frac_borrow(k_len, vec::Vec_frac_borrow_content(self_ref, len0), 1/8); + //@ open [?flen]vec::Vec_frac_borrow_content::(self_ref, len0)(); + let cur_len = self.len(); + //@ close [flen]vec::Vec_frac_borrow_content::(self_ref, len0)(); + //@ close_frac_borrow(flen, vec::Vec_frac_borrow_content(self_ref, len0)); + //@ close [f1]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f1, ref_initialized_(self_ref)); + //@ end_lifetime(k_len); + //@ vec::end_share_Vec(self); + //@ mul_mono_l(cur_len, cap, std::mem::size_of::()); + base_ptr.add(cur_len) + }; + // Use SetLenOnDrop to work around bug where compiler + // might not realize the store through `ptr` through self.set_len() + // don't alias. + //@ open vec::Vec(t, *self, alloc_id, base, cap, len0); + //@ open_points_to(self); + //@ let k_guard = begin_lifetime(); + { + let mut local_len = SetLenOnDrop::new(&mut self.len); + //@ assert local_len |-> ?ll_init &*& ll_init.local_len == len0; + //@ let len_ref = ll_init.len; + + // Write all elements except the last one + let mut iter = (1..n).into_iter(); + loop { + /*@ + inv thread_token(t) &*& lifetime_token(flft) &*& + iter |-> ?it_cur &*& it_cur.end == n &*& + (if n == 0 { it_cur.start == 1 } else { 1 <= it_cur.start && it_cur.start <= n }) &*& + ptr == base + len0 + (it_cur.start - 1) &*& + local_len |-> ?ll_cur &*& ll_cur.len == len_ref &*& ll_cur.local_len == len0 + (it_cur.start - 1) &*& + *len_ref |-> len0 &*& + array_at_lft(alloc_id.lft, base, len0 + (it_cur.start - 1), ?elems_cur) &*& + foreach(elems_cur, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len0 + (it_cur.start - 1), n - (it_cur.start - 1), _) &*& + value |-> ?val_cur &*& .own(t, val_cur); + @*/ + let iter_ref = &mut iter; + match core::iter::Iterator::next(iter_ref) { + None => break, + Some(_) => { + //@ let k_val = begin_lifetime(); + //@ close_full_borrow_content::(t, &value); + //@ borrow(k_val, .full_borrow_content(t, &value)); + //@ produce_type_interp::(); + //@ share_full_borrow::(k_val, t, &value); + //@ let val_ref = precreate_ref(&value); + //@ init_ref_share::(k_val, t, val_ref); + //@ leak type_interp::(); + //@ open_frac_borrow(k_val, ref_initialized_(val_ref), 1/2); + //@ open [?fval]ref_initialized_::(val_ref)(); + let cloned = clone__VeriFast_wrapper(&value); + //@ close [fval]ref_initialized_::(val_ref)(); + //@ close_frac_borrow(fval, ref_initialized_(val_ref)); + //@ end_lifetime(k_val); + //@ borrow_end(k_val, .full_borrow_content(t, &value)); + //@ open_full_borrow_content::(t, &value); + + //@ open array_at_lft_(alloc_id.lft, base + len0 + (it_cur.start - 1), n - (it_cur.start - 1), _); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_lft = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft_(ptr, q_lft); + unsafe { ptr::write(ptr, cloned) }; + //@ close_points_to_at_lft(ptr); + //@ lifetime_token_trade_back(q_lft, alloc_id.lft); + //@ vec::array_at_lft_snoc::(alloc_id.lft, base, len0 + (it_cur.start - 1)); + //@ close own::(t)(cloned); + //@ close foreach([], own::(t)); + //@ close foreach([cloned], own::(t)); + //@ foreach_append(elems_cur, [cloned]); + //@ mul_mono_l(len0 + it_cur.start, cap, std::mem::size_of::()); + ptr = unsafe { ptr.add(1) }; + unsafe { set_len_on_drop_increment_one__VeriFast_wrapper(&mut local_len) }; + } + } + } + + if n > 0 { + //@ open array_at_lft_(alloc_id.lft, base + len0 + (n - 1), 1, _); + //@ open array_at_lft_(alloc_id.lft, base + len0 + n, 0, _); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_lft = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft_(ptr, q_lft); + unsafe { ptr::write(ptr, value) }; + //@ close_points_to_at_lft(ptr); + //@ lifetime_token_trade_back(q_lft, alloc_id.lft); + //@ vec::array_at_lft_snoc::(alloc_id.lft, base, len0 + (n - 1)); + //@ close own::(t)(val_cur); + //@ close foreach([], own::(t)); + //@ close foreach([val_cur], own::(t)); + //@ foreach_append(elems_cur, [val_cur]); + unsafe { set_len_on_drop_increment_one__VeriFast_wrapper(&mut local_len) }; + } else { + //@ open array_at_lft_(alloc_id.lft, base + len0, 0, _); + } + + // Package SetLenOnDrop_own before natural scope drop of `local_len`. + //@ close vec::set_len_on_drop::SetLenOnDrop_fbc(len_ref, len0 + n)(); + //@ borrow(k_guard, vec::set_len_on_drop::SetLenOnDrop_fbc(len_ref, len0 + n)); + //@ close exists::>(pair(k_guard, len0 + n)); + //@ close >.own(t, *(&local_len)); + } + //@ end_lifetime(k_guard); + //@ borrow_end(k_guard, vec::set_len_on_drop::SetLenOnDrop_fbc(&(*self).len, len0 + n)); + //@ open vec::set_len_on_drop::SetLenOnDrop_fbc(&(*self).len, len0 + n)(); + //@ assert (*self).len |-> ?final_len; + //@ assert array_at_lft(alloc_id.lft, base, len0 + n, ?all_elems); + //@ array_at_lft_split(base, final_len); + //@ vec::foreach_take_own::(t, all_elems, final_len); + //@ { pred SavedInit() = array_at_lft(alloc_id.lft, base, final_len, take(final_len, all_elems)); close SavedInit(); array_at_lft_to_array_at_lft_(base + final_len); array_at_lft__join(base + final_len); open SavedInit(); } + //@ close_points_to(self); + //@ close vec::Vec(t, *self, alloc_id, base, cap, final_len); + //@ close >.own(t, *self); + } +} + +impl SpecExtendWith for Vec { + fn spec_extend_with(&mut self, n: usize, value: T) { + // The `n == 0` check is already being inserted by the loop canonicalization pass, + // so this costs nothing. + // https://llvm.org/docs/LoopTerminology.html#more-canonical-loops + if n == 0 { + // three things: + // `self.reserve(0)` does not need to be run, since reserving space for 0 elements + // is a no-op. since the `value` argument did not have anywhere to be moved to, it is + // dropped here. with this branch present here, we can elide the write through self.len, + // since `self.len += 0` would be a no-op. + return; + } + + self.reserve(n); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let ptr = unsafe { self.as_mut_ptr().add(self.len()) }; + + let mut i = 0; + // Write all the elements by copying `value`. + // We use an incrementing index here instead of incrementing pointer because the former + // has been observed to have less register pressure in the loop initialization. + // https://llvm.org/docs/Vectorizers.html#inductions + #[cfg_attr(kani, kani::loop_invariant(i <= n))] + #[cfg_attr(kani, kani::loop_modifies(&i, ptr::slice_from_raw_parts_mut(ptr, n)))] + while i < n { + // SAFETY: `TrivialClone` indicates that copying `value` is equivalent to + // calling `Clone::clone` for `T`. As per the safety comment for `ptr`, this pointer + // is within bounds, won't wrap around while `i < n`, and valid for writes. The values + // do not overlap since `value` is stored as a function argument, and the target is + // in the Vec. + unsafe { ptr.add(i).copy_from_nonoverlapping(&value, 1) }; + + // Because above is infallible, we don't need to worry about setting the len + // in this loop, and instead we just increment the loop induction variable. + i += 1; + } + + // Above, `n` items have been infallibly copied into the vector + self.len += n; + + // The reason we did not treat the last position in the vector specially by doing + // `n - 1` copies and semantically moving `value` into it is that we are forced to do `n` + // copies of the value no matter what, and it's better to do it in the above loop than + // by manually writing since it can be vectorized. + // Then, `value` was never semantically moved into the vec, only copied from, + // so we forget it here to prevent the Drop. + mem::forget(value); + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/verified/vec_mod.rs b/verifast-proofs/alloc/vec/mod.rs/verified/vec_mod.rs new file mode 100644 index 0000000000000..ecebc8155c318 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/verified/vec_mod.rs @@ -0,0 +1,6274 @@ +//! A contiguous growable array type with heap-allocated contents, written +//! `Vec`. +//! +//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and +//! *O*(1) pop (from the end). +//! +//! Vectors ensure they never allocate more than `isize::MAX` bytes. +//! +//! # Examples +//! +//! You can explicitly create a [`Vec`] with [`Vec::new`]: +//! +//! ``` +//! let v: Vec = Vec::new(); +//! ``` +//! +//! ...or by using the [`vec!`] macro: +//! +//! ``` +//! let v: Vec = vec![]; +//! +//! let v = vec![1, 2, 3, 4, 5]; +//! +//! let v = vec![0; 10]; // ten zeroes +//! ``` +//! +//! You can [`push`] values onto the end of a vector (which will grow the vector +//! as needed): +//! +//! ``` +//! let mut v = vec![1, 2]; +//! +//! v.push(3); +//! ``` +//! +//! Popping values works in much the same way: +//! +//! ``` +//! let mut v = vec![1, 2]; +//! +//! let two = v.pop(); +//! ``` +//! +//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits): +//! +//! ``` +//! let mut v = vec![1, 2, 3]; +//! let three = v[2]; +//! v[1] = v[1] + 5; +//! ``` +//! +//! # Memory layout +//! +//! A [`Vec`] conceptually consists of a raw pointer `ptr` to the start of the allocation, a +//! length `len`, a capacity `cap`, and an allocator `alloc`. +//! While the exact fields and their order are not specified, a [`Vec`] can be converted to and +//! from these parts using [`Vec::into_raw_parts_with_allocator`], [`Vec::from_raw_parts_in`], +//! [`Vec::into_raw_parts`], and [`Vec::from_raw_parts`], as well as their [`NonNull`]-based +//! versions. +//! +//! The parts of a [`Vec`] have the following invariants: +//! +//! * If [`size_of::()`](size_of) and `cap` are non-zero, then: +//! - `ptr` must point to the start of a memory block [*currently allocated*] via `alloc`. +//! - [`Layout::array::(cap)`] must [*fit*] the memory block of `ptr`. In particular, +//! * `T` must have the same alignment as the [`Layout`] `ptr` was allocated with, and +//! * `size_of::() * cap` must be at least the size of the [`Layout`] `ptr` was +//! allocated with, and at most the size of the allocation returned the allocator. +//! - `size_of::() * cap` must be at most [`isize::MAX`]. +//! See the safety documentation of [`pointer::offset`]. +//! * If [`size_of::()`](size_of) or `cap` is zero, then `ptr` must be any sufficiently aligned non-null pointer. +//! +//! NOTE: `ptr` will not be passed to the allocator for deallocation by the destructor of [`Vec`] +//! in this case. Thus, it is unwise to use a pointer acquired from the allocator for this, as +//! overallocated memory may end up being leaked. Use [`ptr::dangling`] instead. +//! * The following must always be satisfied: +//! - `len` needs to be less than or equal to `cap`. +//! - At `ptr`, there are at least `len` valid values of type `T`, laid out contiguously +//! (like an array). These values are considered owned by the [`Vec`]. +//! +//! It is sound to create a [`Vec`] from parts that satisfy these invariants. +//! +//! Conversely, the memory backing `ptr` obtained from [`Vec::as_mut_ptr`] or +//! [`Vec::into_raw_parts_with_allocator`]-like methods may be deallocated +//! using the allocator, with layout [`Layout::array::(cap)`], provided +//! that [`size_of::()`](size_of) or `cap` is non-zero. +//! To automatically handle the case where the allocation is zero-sized, +//! it is recommended to use [`Vec::from_raw_parts_in`], instead of manually +//! deallocating. +//! +//! [*fit*]: crate::alloc::Allocator#memory-fitting +//! [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory +//! [`allocate`]: crate::alloc::Allocator::allocate +//! [`push`]: Vec::push +//! [`ptr::NonNull::dangling`]: NonNull::dangling +//! [`Layout`]: crate::alloc::Layout +//! [`Layout::array::(cap)`]: crate::alloc::Layout::array + +#![stable(feature = "rust1", since = "1.0.0")] + +#[cfg(not(no_global_oom_handling))] +use core::clone::TrivialClone; +use core::cmp::Ordering; +use core::hash::{Hash, Hasher}; +#[cfg(not(no_global_oom_handling))] +use core::iter; +#[cfg(kani)] +use core::kani; +use core::marker::{Destruct, Freeze, PhantomData}; +use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom}; +use core::ops::{self, Index, IndexMut, Range, RangeBounds}; +use core::ptr::{self, NonNull}; +use core::slice::{self, SliceIndex}; +use core::{cmp, fmt, hint, intrinsics, ub_checks}; + +use safety::{ensures, requires}; + +#[stable(feature = "extract_if", since = "1.87.0")] +pub use self::extract_if::ExtractIf; +use crate::alloc::{Allocator, AllocatorNightly, Global}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::collections::TryReserveError; +use crate::raw_vec::RawVec; + +//@ use std::alloc::{alloc_id_t, Allocator, Layout, alloc_block_in}; +//@ use raw_vec::RawVec; +//@ use std::option::Option; + +mod extract_if; + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_splice", since = "1.21.0")] +pub use self::splice::Splice; + +#[cfg(not(no_global_oom_handling))] +mod splice; + +#[stable(feature = "drain", since = "1.6.0")] +pub use self::drain::Drain; + +mod drain; + +#[cfg(not(no_global_oom_handling))] +mod cow; + +#[cfg(not(no_global_oom_handling))] +pub(crate) use self::in_place_collect::AsVecIntoIter; +#[stable(feature = "rust1", since = "1.0.0")] +pub use self::into_iter::IntoIter; + +mod into_iter; + +#[cfg(not(no_global_oom_handling))] +use self::is_zero::IsZero; + +#[cfg(not(no_global_oom_handling))] +mod is_zero; + +#[cfg(not(no_global_oom_handling))] +mod in_place_collect; + +mod partial_eq; + +#[unstable(feature = "vec_peek_mut", issue = "122742")] +pub use self::peek_mut::PeekMut; + +mod peek_mut; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_elem::SpecFromElem; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_elem; + +#[cfg(all(kani, not(no_global_oom_handling)))] +#[unstable(feature = "kani", issue = "none")] +mod verify_ch23; + +/// Kani-only: partial check of documented `Vec` raw-parts layout invariants (see module docs). +/// Checks `length <= capacity`, non-null and alignment of `ptr`, `Layout::array::(capacity)` +/// fitting within `isize::MAX` bytes, `can_write`, base-offset-0 (rejecting interior pointers +/// via `!same_allocation(ptr, ptr - 1)`), and in-bounds byte extent of at least +/// `capacity * size_of::()` (permitting legal over-allocated custom-allocator blocks). +/// Remaining caller safety obligations NOT machine-checked by this predicate (due to Kani/CBMC +/// limitations) remain documented caller preconditions: (1) `ptr` was allocated via the matching +/// `Allocator` instance, (2) `ptr` was allocated with `T`'s exact alignment and a fitting layout +/// (`requested_size <= capacity * size_of::() <= actual_size`), and (3) the first `length` +/// elements are initialized to valid values of `T`. +#[cfg(kani)] +fn vec_parts_valid(ptr: *mut T, length: usize, capacity: usize) -> bool { + length <= capacity + && !ptr.is_null() + && ptr.is_aligned() + && (T::IS_ZST || crate::alloc::Layout::array::(capacity).is_ok()) + && ub_checks::can_write(ptr::slice_from_raw_parts_mut(ptr, capacity)) + && (T::IS_ZST + || capacity == 0 + || (kani::mem::is_inbounds(ptr::slice_from_raw_parts( + ptr as *const u8, + capacity * mem::size_of::(), + )) && !kani::mem::same_allocation( + ptr as *const u8, + (ptr as *const u8).wrapping_byte_sub(1), + ))) +} + +#[cfg(not(no_global_oom_handling))] +use self::set_len_on_drop::SetLenOnDrop; + +#[cfg(not(no_global_oom_handling))] +mod set_len_on_drop; + +#[cfg(not(no_global_oom_handling))] +use self::in_place_drop::{InPlaceDrop, InPlaceDstDataSrcBufDrop}; + +#[cfg(not(no_global_oom_handling))] +mod in_place_drop; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_iter_nested::SpecFromIterNested; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_iter_nested; + +#[cfg(not(no_global_oom_handling))] +use self::spec_from_iter::SpecFromIter; + +#[cfg(not(no_global_oom_handling))] +mod spec_from_iter; + +#[cfg(not(no_global_oom_handling))] +use self::spec_extend::SpecExtend; + +#[cfg(not(no_global_oom_handling))] +mod spec_extend; + +#[cfg(not(no_global_oom_handling))] +use self::spec_extend_with::SpecExtendWith; + +#[cfg(not(no_global_oom_handling))] +mod spec_extend_with; + +#[cfg(all(target_arch = "aarch64", target_feature = "sve"))] +mod sve_retain; + +/// A contiguous growable array type, written as `Vec`, short for 'vector'. +/// +/// # Examples +/// +/// ``` +/// let mut vec = Vec::new(); +/// vec.push(1); +/// vec.push(2); +/// +/// assert_eq!(vec.len(), 2); +/// assert_eq!(vec[0], 1); +/// +/// assert_eq!(vec.pop(), Some(2)); +/// assert_eq!(vec.len(), 1); +/// +/// vec[0] = 7; +/// assert_eq!(vec[0], 7); +/// +/// vec.extend([1, 2, 3]); +/// +/// for x in &vec { +/// println!("{x}"); +/// } +/// assert_eq!(vec, [7, 1, 2, 3]); +/// ``` +/// +/// The [`vec!`] macro is provided for convenient initialization: +/// +/// ``` +/// let mut vec1 = vec![1, 2, 3]; +/// vec1.push(4); +/// let vec2 = Vec::from([1, 2, 3, 4]); +/// assert_eq!(vec1, vec2); +/// ``` +/// +/// It can also initialize each element of a `Vec` with a given value. +/// This may be more efficient than performing allocation and initialization +/// in separate steps, especially when initializing a vector of zeros: +/// +/// ``` +/// let vec = vec![0; 5]; +/// assert_eq!(vec, [0, 0, 0, 0, 0]); +/// +/// // The following is equivalent, but potentially slower: +/// let mut vec = Vec::with_capacity(5); +/// vec.resize(5, 0); +/// assert_eq!(vec, [0, 0, 0, 0, 0]); +/// ``` +/// +/// For more information, see +/// [Capacity and Reallocation](#capacity-and-reallocation). +/// +/// Use a `Vec` as an efficient stack: +/// +/// ``` +/// let mut stack = Vec::new(); +/// +/// stack.push(1); +/// stack.push(2); +/// stack.push(3); +/// +/// while let Some(top) = stack.pop() { +/// // Prints 3, 2, 1 +/// println!("{top}"); +/// } +/// ``` +/// +/// # Indexing +/// +/// The `Vec` type allows access to values by index, because it implements the +/// [`Index`] trait. An example will be more explicit: +/// +/// ``` +/// let v = vec![0, 2, 4, 6]; +/// println!("{}", v[1]); // it will display '2' +/// ``` +/// +/// However be careful: if you try to access an index which isn't in the `Vec`, +/// your software will panic! You cannot do this: +/// +/// ```should_panic +/// let v = vec![0, 2, 4, 6]; +/// println!("{}", v[6]); // it will panic! +/// ``` +/// +/// Use [`get`] and [`get_mut`] if you want to check whether the index is in +/// the `Vec`. +/// +/// # Slicing +/// +/// A `Vec` can be mutable. On the other hand, slices are read-only objects. +/// To get a [slice][prim@slice], use [`&`]. Example: +/// +/// ``` +/// fn read_slice(slice: &[usize]) { +/// // ... +/// } +/// +/// let v = vec![0, 1]; +/// read_slice(&v); +/// +/// // ... and that's all! +/// // you can also do it like this: +/// let u: &[usize] = &v; +/// // or like this: +/// let u: &[_] = &v; +/// ``` +/// +/// In Rust, it's more common to pass slices as arguments rather than vectors +/// when you just want to provide read access. The same goes for [`String`] and +/// [`&str`]. +/// +/// # Capacity and reallocation +/// +/// The capacity of a vector is the amount of space allocated for any future +/// elements that will be added onto the vector. This is not to be confused with +/// the *length* of a vector, which specifies the number of actual elements +/// within the vector. If a vector's length exceeds its capacity, its capacity +/// will automatically be increased, but its elements will have to be +/// reallocated. +/// +/// For example, a vector with capacity 10 and length 0 would be an empty vector +/// with space for 10 more elements. Pushing 10 or fewer elements onto the +/// vector will not change its capacity or cause reallocation to occur. However, +/// if the vector's length is increased to 11, it will have to reallocate, which +/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`] +/// whenever possible to specify how big the vector is expected to get. +/// +/// # Guarantees +/// +/// The following section is to be read as an addendum of the +/// [memory layout](self#memory-layout) section. +/// +/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees +/// about its design. This ensures that it's as low-overhead as possible in +/// the general case, and can be correctly manipulated in primitive ways +/// by unsafe code. +/// +/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be +/// visualized as below. The top part is the `Vec` struct, it contains a +/// pointer to the head of the allocation in the heap, length and capacity. +/// The bottom part is the allocation on the heap, a contiguous memory block. +/// +/// ```text +/// ptr len capacity +/// +--------+--------+--------+ +/// | 0x0123 | 2 | 4 | +/// +--------+--------+--------+ +/// | +/// v +/// Heap +--------+--------+--------+--------+ +/// | 'a' | 'b' | uninit | uninit | +/// +--------+--------+--------+--------+ +/// ``` +/// +/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`]. +/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory +/// layout (including the order of fields). +/// +/// `Vec` will never perform a "small optimization" where elements are actually +/// stored on the stack for two reasons: +/// +/// * It would make it more difficult for unsafe code to correctly manipulate +/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were +/// only moved, and it would be more difficult to determine if a `Vec` had +/// actually allocated memory. +/// +/// * It would penalize the general case, incurring an additional branch +/// on every access. +/// +/// `Vec` will never automatically shrink itself, even if completely empty. This +/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec` +/// and then filling it back up to the same [`len`] should incur no calls to +/// the allocator. If you wish to free up unused memory, use +/// [`shrink_to_fit`] or [`shrink_to`]. +/// +/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is +/// sufficient. [`push`] and [`insert`] *will* (re)allocate if +/// [len] == [capacity]. That is, the reported capacity is completely +/// accurate, and can be relied on. It can even be used to manually free the memory +/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even +/// when not necessary. +/// +/// `Vec` does not guarantee any particular growth strategy when reallocating +/// when full, nor when [`reserve`] is called. The current strategy is basic +/// and it may prove desirable to use a non-constant growth factor. Whatever +/// strategy is used will of course guarantee *O*(1) amortized [`push`]. +/// +/// It is guaranteed, in order to respect the intentions of the programmer, that +/// all of `vec![e_1, e_2, ..., e_n]`, `vec![x; n]`, and [`Vec::with_capacity(n)`] produce a `Vec` +/// that requests an allocation of the exact size needed for precisely `n` elements from the allocator, +/// and no other size (such as, for example: a size rounded up to the nearest power of 2). +/// The allocator will return an allocation that is at least as large as requested, but it may be larger. +/// +/// It is guaranteed that the [`Vec::capacity`] method returns a value that is at least the requested capacity +/// and not more than the allocated capacity. +/// +/// The method [`Vec::shrink_to_fit`] will attempt to discard excess capacity an allocator has given to a `Vec`. +/// If [len] == [capacity], then a `Vec` can be converted +/// to and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements. +/// `Vec` exploits this fact as much as reasonable when implementing common conversions +/// such as [`into_boxed_slice`]. +/// +/// `Vec` will not specifically overwrite any data that is removed from it, +/// but also won't specifically preserve it. Its uninitialized memory is +/// scratch space that it may use however it wants. It will generally just do +/// whatever is most efficient or otherwise easy to implement. Do not rely on +/// removed data to be erased for security purposes. Even if you drop a `Vec`, its +/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory +/// first, that might not actually happen because the optimizer does not consider +/// this a side-effect that must be preserved. There is one case which we will +/// not break, however: using `unsafe` code to write to the excess capacity, +/// and then increasing the length to match, is always valid. +/// +/// Currently, `Vec` does not guarantee the order in which elements are dropped. +/// The order has changed in the past and may change again. +/// +/// [`get`]: slice::get +/// [`get_mut`]: slice::get_mut +/// [`String`]: crate::string::String +/// [`&str`]: type@str +/// [`shrink_to_fit`]: Vec::shrink_to_fit +/// [`shrink_to`]: Vec::shrink_to +/// [capacity]: Vec::capacity +/// [`capacity`]: Vec::capacity +/// [`Vec::capacity`]: Vec::capacity +/// [size_of::\]: size_of +/// [len]: Vec::len +/// [`len`]: Vec::len +/// [`push`]: Vec::push +/// [`insert`]: Vec::insert +/// [`reserve`]: Vec::reserve +/// [`Vec::with_capacity(n)`]: Vec::with_capacity +/// [`MaybeUninit`]: core::mem::MaybeUninit +/// [owned slice]: Box +/// [`into_boxed_slice`]: Vec::into_boxed_slice +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_diagnostic_item = "Vec"] +#[rustc_insignificant_dtor] +#[doc(alias = "list")] +#[doc(alias = "vector")] +pub struct Vec { + buf: RawVec, + len: usize, +} +/*@ + +fix Vec::alloc(v: Vec) -> A { v.buf.alloc() } + +pred Vec(t: thread_id_t, self: Vec, alloc_id: alloc_id_t, ptr: *T, capacity: usize, length: usize) = + RawVec(t, self.buf, alloc_id, ptr, capacity) &*& length == self.len &*& 0 <= length &*& length <= capacity; + +lem Vec_inv2() + req Vec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity, ?length); + ens Vec::(t, self_, alloc_id, ptr, capacity, length) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + ptr != 0 &*& 0 <= length &*& length <= capacity &*& + length <= std::mem::MAX_SLICE_LEN::() &*& + if std::mem::size_of::() == 0 { capacity == usize::MAX } else { capacity <= isize::MAX &*& length <= isize::MAX / std::mem::size_of::() }; +{ + open Vec(t, self_, alloc_id, ptr, capacity, length); + raw_vec::RawVec_inv2(); + if std::mem::size_of::() != 0 { + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + std::alloc::Layout_inv(Layout::new::()); + std::alloc::Layout_inv(allocLayout); + div_rem_nonneg(isize::MAX, std::mem::size_of::()); + let len = length; + if len > isize::MAX / std::mem::size_of::() { + mul_mono_l(isize::MAX / std::mem::size_of::() + 1, len, std::mem::size_of::()); + assert (isize::MAX / std::mem::size_of::() + 1) * std::mem::size_of::() <= len * std::mem::size_of::(); + assert isize::MAX < (isize::MAX / std::mem::size_of::() + 1) * std::mem::size_of::(); + mul_mono_l(std::mem::size_of::(), stride, capacity); + assert capacity * std::mem::size_of::() <= allocLayout.size(); + mul_mono_l(len, capacity, std::mem::size_of::()); + assert len * std::mem::size_of::() <= allocLayout.size(); + div_rem_nonneg(isize::MAX, allocLayout.align()); + //assert allocLayout.size() <= isize::MAX; + assert false; + } + } + close Vec(t, self_, alloc_id, ptr, capacity, length); + std::mem::MAX_SLICE_LEN_def::(); +} + +lem Vec_inv() + req Vec::(?t, ?self_, ?alloc_id, ?ptr, ?capacity, ?length); + ens Vec::(t, self_, alloc_id, ptr, capacity, length) &*& + lifetime_inclusion(lft_of_type::(), alloc_id.lft) == true &*& + length <= std::mem::MAX_SLICE_LEN::() &*& + ptr != 0 &*& 0 <= length &*& length <= capacity &*& capacity <= usize::MAX; +{ + Vec_inv2(); +} + +lem Vec_send_(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(A)) == true &*& Vec::(?t0, ?v, ?alloc_id, ?ptr, ?capacity, ?length); + ens type_interp::() &*& Vec::(t1, v, alloc_id, ptr, capacity, length); +{ + open Vec(t0, v, alloc_id, ptr, capacity, length); + raw_vec::RawVec_send_(t1); + close Vec(t1, v, alloc_id, ptr, capacity, length); +} + +pred >.own(t, v) = + Vec(t, v, ?alloc_id, ?ptr, ?capacity, ?len) &*& + array_at_lft(alloc_id.lft, ptr, len, ?elems) &*& foreach(elems, own(t)) &*& + array_at_lft_(alloc_id.lft, ptr + len, capacity - len, _); + +lem array_at_lft_own_mono(k: lifetime_t, t: thread_id_t, p: *T0, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& foreach(elems, own::(t)) &*& + type_interp::() &*& type_interp::() &*& + is_subtype_of::() == true &*& + std::mem::size_of::() == std::mem::size_of::() &*& + std::mem::align_of::() == std::mem::align_of::(); + ens array_at_lft::(k, p as *T1, n, ?elems1) &*& foreach(elems1, own::(t)) &*& + type_interp::() &*& type_interp::(); +{ + open array_at_lft::(k, p, n, elems); + open foreach(elems, own::(t)); + if n == 0 { + close foreach::([], own::(t)); + close array_at_lft::(k, p as *T1, 0, []); + } else { + assert elems == cons(?x, ?xs); + open own::(t)(x); + own_mono::(t, x); + open points_to_at_lft::(k, p, x); + to_u8s__at_lft::(p); + assert array_at_lft_(k, p as *u8, std::mem::size_of::(), ?bs); + from_u8s__at_lft::(p as *T1); + // Rust subtyping preserves value bit representation (verifast#610). + assume(of_u8s_::(bs) == some(upcast::(x))); + close points_to_at_lft::(k, p as *T1, upcast::(x)); + array_at_lft_own_mono::(k, t, p + 1, n - 1); + assert array_at_lft::(k, (p + 1) as *T1, n - 1, ?elems1_tail); + close own::(t)(upcast::(x)); + close foreach::(cons(upcast::(x), elems1_tail), own::(t)); + close array_at_lft::(k, p as *T1, n, cons(upcast::(x), elems1_tail)); + } +} + +lem Vec_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& vec::Vec_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& vec::Vec_own::(t, vec::Vec:: { buf: upcast(v.buf), len: upcast(v.len) }); +{ + open >.own(t, v); + open Vec::(t, v, ?alloc_id, ?ptr, ?capacity, ?len); + raw_vec::RawVec_mono::(t, v.buf); + // upcast on usize and RawVec (verifast#610). + assume(upcast::(v.len) == v.len); + assume(upcast::, RawVec>(v.buf) == raw_vec::RawVec:: { inner: upcast(v.buf.inner) }); + array_at_lft_own_mono::(alloc_id.lft, t, ptr, len); + array_at_lft__to_u8s_at_lft_::(ptr + len, capacity - len); + u8s_at_lft__to_array_at_lft_::((ptr as *T1) + len, capacity - len); + let v1 = vec::Vec:: { buf: upcast(v.buf), len: upcast(v.len) }; + close Vec::(t, v1, alloc_id, ptr as *T1, capacity, len); + close >.own(t, v1); +} + +lem Vec_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Send(typeid(Vec)) == true &*& Vec_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& Vec_own::(t1, v); +{ + open >.own(t0, v); + Vec_send_(t1); + { + lem iter() + req foreach::(?elems, own(t0)) &*& type_interp::(); + ens foreach(elems, own(t1)) &*& type_interp::(); + { + open foreach(elems, own(t0)); + match elems { + nil => {} + cons(elem, elems0) => { + open own::(t0)(elem); + Send::send(t0, t1, elem); + close own::(t1)(elem); + iter(); + } + } + close foreach(elems, own(t1)); + } + iter(); + } + close >.own(t1, v); +} + +pred_ctor Vec_frac_borrow_content(l: *Vec, length: usize)(;) = (*l).len |-> length &*& struct_Vec_padding(l); + +pred Vec_share_(k: lifetime_t, t: thread_id_t, l: *Vec, alloc_id: alloc_id_t, ptr: *T, capacity: usize, length: usize) = + pointer_within_limits(&(*l).buf) == true &*& + [_]raw_vec::RawVec_share_(k, t, &(*l).buf, alloc_id, ptr, capacity) &*& length <= capacity &*& + [_]frac_borrow(k, Vec_frac_borrow_content(l, length)); + +lem Vec_share__inv() + req [_]Vec_share_::(?k, ?t, ?l, ?alloc_id, ?ptr, ?capacity, ?length); + ens length <= std::mem::MAX_SLICE_LEN::() &*& + if std::mem::size_of::() == 0 { true } else { length <= isize::MAX / std::mem::size_of::() }; +{ + open Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + raw_vec::RawVec_share__inv(); + if std::mem::size_of::() != 0 { + assert Layout::new::().repeat(capacity) == some(pair(?allocLayout, ?stride)); + std::alloc::Layout_repeat_some(Layout::new::(), capacity); + std::alloc::Layout_inv(Layout::new::()); + std::alloc::Layout_inv(allocLayout); + div_rem_nonneg(isize::MAX, std::mem::size_of::()); + let len = length; + if len > isize::MAX / std::mem::size_of::() { + mul_mono_l(isize::MAX / std::mem::size_of::() + 1, len, std::mem::size_of::()); + assert (isize::MAX / std::mem::size_of::() + 1) * std::mem::size_of::() <= len * std::mem::size_of::(); + assert isize::MAX < (isize::MAX / std::mem::size_of::() + 1) * std::mem::size_of::(); + mul_mono_l(std::mem::size_of::(), stride, capacity); + assert capacity * std::mem::size_of::() <= allocLayout.size(); + mul_mono_l(len, capacity, std::mem::size_of::()); + assert len * std::mem::size_of::() <= allocLayout.size(); + div_rem_nonneg(isize::MAX, allocLayout.align()); + //assert allocLayout.size() <= isize::MAX; + assert false; + } + } + std::mem::MAX_SLICE_LEN_def::(); +} + +pred Vec_share_end_token(k: lifetime_t, t: thread_id_t, l: *Vec, alloc_id: alloc_id_t, ptr: *T, capacity: usize, length: usize) = + raw_vec::RawVec_share_end_token(k, t, &(*l).buf, alloc_id, ptr, capacity) &*& length <= capacity &*& + borrow_end_token(k, Vec_frac_borrow_content(l, length)); + +lem Vec_share__mono(k: lifetime_t, k1: lifetime_t, l: *Vec) + req type_interp::() &*& type_interp::() &*& [_]Vec_share_::(k, ?t, l, ?alloc_id, ?ptr, ?capacity, ?length) &*& lifetime_inclusion(k1, k) == true; + ens type_interp::() &*& type_interp::() &*& [_]Vec_share_::(k1, t, l, alloc_id, ptr, capacity, length); +{ + open Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + raw_vec::RawVec_share__mono(k, k1, t, &(*l).buf); + frac_borrow_mono(k, k1, Vec_frac_borrow_content(l, length)); + close Vec_share_(k1, t, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k1, t, l, alloc_id, ptr, capacity, length); +} + +lem Vec_sync_(t1: thread_id_t) + req type_interp::() &*& [_]Vec_share_::(?k, ?t, ?l, ?alloc_id, ?ptr, ?capacity, ?length) &*& is_Sync(typeid(Vec)) == true; + ens type_interp::() &*& [_]Vec_share_(k, t1, l, alloc_id, ptr, capacity, length); +{ + open Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + raw_vec::RawVec_sync_(t1); + close Vec_share_(k, t1, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k, t1, l, alloc_id, ptr, capacity, length); +} + +lem share_Vec(k: lifetime_t, l: *Vec) + nonghost_callers_only + req [?q]lifetime_token(k) &*& *l |-> ?self_ &*& Vec(?t, self_, ?alloc_id, ?ptr, ?capacity, ?length); + ens [q]lifetime_token(k) &*& [_]Vec_share_(k, t, l, alloc_id, ptr, capacity, length) &*& Vec_share_end_token(k, t, l, alloc_id, ptr, capacity, length); +{ + open Vec(t, self_, alloc_id, ptr, capacity, length); + open_points_to(l); + close_points_to(&(*l).buf); + raw_vec::share_RawVec(k, &(*l).buf); + close Vec_frac_borrow_content::(l, length)(); + borrow(k, Vec_frac_borrow_content(l, length)); + full_borrow_into_frac(k, Vec_frac_borrow_content(l, length)); + close Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + close Vec_share_end_token(k, t, l, alloc_id, ptr, capacity, length); +} + +lem end_share_Vec(l: *Vec) + nonghost_callers_only + req Vec_share_end_token(?k, ?t, l, ?alloc_id, ?ptr, ?capacity, ?length) &*& [_]lifetime_dead_token(k); + ens *l |-> ?self_ &*& Vec(t, self_, alloc_id, ptr, capacity, length); +{ + open Vec_share_end_token(k, t, l, alloc_id, ptr, capacity, length); + raw_vec::end_share_RawVec(&(*l).buf); + borrow_end(k, Vec_frac_borrow_content(l, length)); + open Vec_frac_borrow_content::(l, length)(); + assert *l |-> ?self_; + close Vec(t, self_, alloc_id, ptr, capacity, length); +} + +lem init_ref_Vec_(l: *Vec) + nonghost_callers_only + req ref_init_perm(l, ?l0) &*& [_]Vec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity, ?length) &*& [?q]lifetime_token(k); + ens [q]lifetime_token(k) &*& [_]Vec_share_(k, t, l, alloc_id, ptr, capacity, length) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open Vec_share_::(k, t, l0, alloc_id, ptr, capacity, length); + open_ref_init_perm_Vec(l); + raw_vec::init_ref_RawVec_(&(*l).buf); + frac_borrow_sep(k, ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)); + open_frac_borrow_strong_(k, sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)), q); + open [?f]sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length))(); + open [f]ref_initialized_::>(&(*l).buf)(); + open [f]Vec_frac_borrow_content::(l0, length)(); + init_ref_readonly(&(*l).len, 1/2); + init_ref_padding_Vec(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f]P(); + close_ref_initialized_Vec(l); + open [1 - f]P(); + } + close [f]ref_initialized_::>(l)(); + close scaledp(f, ref_initialized_(l))(); + close [f/2]Vec_frac_borrow_content::(l, length)(); + close scaledp(f/2, Vec_frac_borrow_content(l, length))(); + close sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))(); + { + pred Ctx() = + [f/2](*l0).len |-> length &*& ref_readonly_end_token(&(*l).len, &(*l0).len, f/2) &*& [1 - f]ref_initialized(&(*l).len) &*& + [f/2]struct_Vec_padding(l0) &*& ref_padding_end_token(l, l0, f/2) &*& [1 - f]ref_padding_initialized(l); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow( + Ctx, + sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length))), + f, + sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)) + )() { + open Ctx(); + open sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))(); + open scaledp(f, ref_initialized_(l))(); + open [f]ref_initialized_::>(l)(); + open scaledp(f/2, Vec_frac_borrow_content(l, length))(); + open [f/2]Vec_frac_borrow_content::(l, length)(); + open_ref_initialized_Vec(l); + end_ref_readonly(&(*l).len); + end_ref_padding_Vec(l); + close [f]ref_initialized_::>(&(*l).buf)(); + close [f]Vec_frac_borrow_content::(l0, length)(); + close [f]sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length))(); + } { + close_frac_borrow_strong_(); + } + } + full_borrow_into_frac(k, sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))); + frac_borrow_split(k, scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + frac_borrow_implies_scaled(k, f/2, Vec_frac_borrow_content(l, length)); + ref_origin_min_addr((l as pointer).provenance); + ref_origin_max_addr((l as pointer).provenance); + close Vec_share_::(k, t, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k, t, l, alloc_id, ptr, capacity, length); +} + +lem init_ref_Vec_m(l: *Vec) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(l, ?l0) &*& [_]Vec_share_(?k, ?t, l0, ?alloc_id, ?ptr, ?capacity, ?length) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Vec_share_(k, t, l, alloc_id, ptr, capacity, length) &*& [_]frac_borrow(k, ref_initialized_(l)); +{ + open Vec_share_::(k, t, l0, alloc_id, ptr, capacity, length); + open_ref_init_perm_Vec(l); + raw_vec::init_ref_RawVec_m(&(*l).buf); + frac_borrow_sep(k, ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)); + open_frac_borrow_strong__m(k, sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)), q); + open [?f]sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length))(); + open [f]ref_initialized_::>(&(*l).buf)(); + open [f]Vec_frac_borrow_content::(l0, length)(); + init_ref_readonly(&(*l).len, 1/2); + init_ref_padding_Vec(l, 1/2); + { + pred P() = ref_padding_initialized(l); + close [1 - f]P(); + close_ref_initialized_Vec(l); + open [1 - f]P(); + } + close [f]ref_initialized_::>(l)(); + close scaledp(f, ref_initialized_(l))(); + close [f/2]Vec_frac_borrow_content::(l, length)(); + close scaledp(f/2, Vec_frac_borrow_content(l, length))(); + close sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))(); + { + pred Ctx() = + [f/2](*l0).len |-> length &*& ref_readonly_end_token(&(*l).len, &(*l0).len, f/2) &*& [1 - f]ref_initialized(&(*l).len) &*& + [f/2]struct_Vec_padding(l0) &*& ref_padding_end_token(l, l0, f/2) &*& [1 - f]ref_padding_initialized(l); + close Ctx(); + produce_lem_ptr_chunk restore_frac_borrow( + Ctx, + sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length))), + f, + sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length)) + )() { + open Ctx(); + open sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))(); + open scaledp(f, ref_initialized_(l))(); + open [f]ref_initialized_::>(l)(); + open scaledp(f/2, Vec_frac_borrow_content(l, length))(); + open [f/2]Vec_frac_borrow_content::(l, length)(); + open_ref_initialized_Vec(l); + end_ref_readonly(&(*l).len); + end_ref_padding_Vec(l); + close [f]ref_initialized_::>(&(*l).buf)(); + close [f]Vec_frac_borrow_content::(l0, length)(); + close [f]sep_(ref_initialized_(&(*l).buf), Vec_frac_borrow_content(l0, length))(); + } { + close_frac_borrow_strong__m(); + } + } + full_borrow_into_frac_m(k, sep_(scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length)))); + frac_borrow_split(k, scaledp(f, ref_initialized_(l)), scaledp(f/2, Vec_frac_borrow_content(l, length))); + frac_borrow_implies_scaled(k, f, ref_initialized_(l)); + frac_borrow_implies_scaled(k, f/2, Vec_frac_borrow_content(l, length)); + ref_origin_min_addr((l as pointer).provenance); + ref_origin_max_addr((l as pointer).provenance); + close Vec_share_::(k, t, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k, t, l, alloc_id, ptr, capacity, length); +} + +lem array_share_mono(k: lifetime_t, k1: lifetime_t, l: *T) + req [_]array_share(k, ?t, l, ?length) &*& type_interp::() &*& lifetime_inclusion(k1, k) == true; + ens type_interp::() &*& [_]array_share(k1, t, l, length); +{ + open array_share(k, t, l, length); + if length != 0 { + share_mono(k, k1, t, l); + array_share_mono(k, k1, l + 1); + } + close array_share(k1, t, l, length); + leak array_share(k1, t, l, length); +} + +lem array_sync(t1: thread_id_t, l: *T) + req [_]array_share::(?k, ?t, l, ?length) &*& type_interp::() &*& is_Sync(typeid(T)) == true; + ens type_interp::() &*& [_]array_share(k, t1, l, length); +{ + open array_share(k, t, l, length); + if length != 0 { + Sync::sync::(k, t, t1, l); + array_sync(t1, l + 1); + } + close array_share(k, t1, l, length); + leak array_share(k, t1, l, length); +} + +pred >.share(k, t, l) = + [_]Vec_share_(k, t, l, ?alloc_id, ?ptr, ?capacity, ?length) &*& [_]array_share::(k, t, ptr, length); + +pred_ctor array_at_lft_fbc(k: lifetime_t, t: thread_id_t, p: *T, length: usize)() = + array_at_lft(k, p, length, ?elems) &*& foreach(elems, own(t)); + +lem array_at_lft_share_full(k: lifetime_t, k0: lifetime_t, t: thread_id_t, p: *T, length: usize) + req type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& full_borrow(k, array_at_lft_fbc(k0, t, p, length)) &*& lifetime_inclusion(k, k0) == true; + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& [_]array_share(k, t, p, length); +{ + let n = length; + let p1 = p; + while true + req type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& full_borrow(k, array_at_lft_fbc(k0, t, p1, n)); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& [_]array_share(k, t, old_p1, old_n); + decreases n; + { + if n == 0 { + leak full_borrow(_, _); + close array_share(k, t, p1, n); + leak array_share(k, t, p1, n); + break; + } + let klong = open_full_borrow_strong_m(k, array_at_lft_fbc(k0, t, p1, n), q); + open array_at_lft_fbc::(k0, t, p1, n)(); + open array_at_lft(k0, p1, n, cons(?v, _)); + open foreach(_, _); + open own::(t)(v); + close full_borrow_content_at_lft::(k0, t, p1)(); + close array_at_lft_fbc::(k0, t, p1 + 1, n - 1)(); + close sep(full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1))(); + produce_lem_ptr_chunk full_borrow_convert_strong(True, sep(full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1)), klong, array_at_lft_fbc(k0, t, p1, n))() { + open sep(full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1))(); + open full_borrow_content_at_lft::(k0, t, p1)(); + open array_at_lft_fbc::(k0, t, p1 + 1, n - 1)(); + assert points_to_at_lft(k0, p1, ?elem); + assert foreach(?elems0, own(t)); + close own::(t)(elem); + close foreach(cons(elem, elems0), own(t)); + close array_at_lft_fbc::(k0, t, p1, n)(); + } { + close_full_borrow_strong_m(klong, array_at_lft_fbc(k0, t, p1, n), sep(full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1))); + full_borrow_mono(klong, k, sep(full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1))); + } + full_borrow_split_m(k, full_borrow_content_at_lft::(k0, t, p1), array_at_lft_fbc::(k0, t, p1 + 1, n - 1)); + p1 = p1 + 1; + n = n - 1; + recursive_call(); + full_borrow_at_lft_to_full_borrow(k, k0, t, old_p1); + share_full_borrow_m(k, t, old_p1); + close array_share(k, t, old_p1, old_n); + leak array_share(k, t, old_p1, old_n); + } +} + +lem Vec_share_full(k: lifetime_t, t: thread_id_t, l: *Vec) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& + full_borrow(k, Vec_full_borrow_content::(t, l)) &*& [?q]lifetime_token(k) &*& + ref_origin(l) == l; + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [_]Vec_share::(k, t, l) &*& [q]lifetime_token(k); +{ + assume(lifetime_inclusion(k, lft_of_type::()) && lifetime_inclusion(k, lft_of_type::())); // TODO: Make this a precondition + let klong = open_full_borrow_strong_m(k, Vec_full_borrow_content::(t, l), q); + open Vec_full_borrow_content::(t, l)(); + open_points_to(l); + open >.own(t, ?self_); + open Vec(t, self_, ?alloc_id, ?ptr, ?capacity, ?length); + raw_vec::RawVec_inv(); + close_points_to(&(*l).buf); + raw_vec::close_RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity); + close Vec_frac_borrow_content::(l, length)(); + close array_at_lft_fbc::(alloc_id.lft, t, ptr, length)(); + close sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length))(); + close sep(raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length)))(); + { + pred Ctx() = array_at_lft_(alloc_id.lft, ptr + length, capacity - length, _); + close Ctx(); + + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length))), + klong, + Vec_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length)))(); + raw_vec::open_RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity); + open sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length))(); + open Vec_frac_borrow_content::(l, length)(); + open array_at_lft_fbc::(alloc_id.lft, t, ptr, length)(); + open_points_to(l); + let self1 = *l; + close Vec(t, self1, alloc_id, ptr, capacity, length); + close >.own(t, self1); + close_points_to(&(*l).buf); + close Vec_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m(klong, Vec_full_borrow_content::(t, l), sep(raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length)))); + full_borrow_mono(klong, k, sep(raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length)))); + } + } + full_borrow_split_m(k, raw_vec::RawVec_full_borrow_content_::(t, &(*l).buf, alloc_id, ptr, capacity), sep(Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length))); + full_borrow_split_m(k, Vec_frac_borrow_content(l, length), array_at_lft_fbc::(alloc_id.lft, t, ptr, length)); + raw_vec::close_RawVec_full_borrow(k, t, &(*l).buf, alloc_id, ptr, capacity); + raw_vec::RawVec_share_full_(k, &(*l).buf); + full_borrow_into_frac_m(k, Vec_frac_borrow_content(l, length)); + close Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + leak Vec_share_(k, t, l, alloc_id, ptr, capacity, length); + lifetime_inclusion_trans(k, lft_of_type::(), alloc_id.lft); + array_at_lft_share_full(k, alloc_id.lft, t, ptr, length); + close >.share(k, t, l); + leak >.share(k, t, l); +} + +lem Vec_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *_) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]Vec_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]Vec_share::(k1, t, l); +{ + open Vec_share::(k, t, l); + assert [_]Vec_share_(k, t, l, ?alloc_id, ?ptr, ?capacity, ?length); + Vec_share__mono::(k, k1, l); + array_share_mono(k, k1, ptr); + close Vec_share::(k1, t, l); + leak Vec_share::(k1, t, l); +} + +lem init_ref_Vec(p: *Vec) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Vec_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Vec_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + open >.share(k, t, x); + init_ref_Vec_m(p); + close >.share(k, t, p); + leak >.share(k, t, p); +} + +lem Vec_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& is_Sync(typeid(Vec)) == true &*& [_]Vec_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]Vec_share::(k, t1, l); +{ + open >.share(k, t0, l); + assert [_]Vec_share_(k, t0, l, ?alloc_id, ?ptr, ?capacity, ?length); + Vec_sync_(t1); + array_sync(t1, ptr); + close >.share(k, t1, l); + leak >.share(k, t1, l); +} + + +lem Vec_drop() + req Vec_own::(?_t, ?_v); + ens raw_vec::RawVec_own::(_t, _v.buf) &*& usize_own(_t, _v.len); +{ + open >.own(_t, _v); + open Vec(_t, _v, ?alloc_id, ?ptr, ?capacity, ?length); + array_at_lft_to_array_at_lft_(ptr); + array_at_lft__join(ptr); + leak foreach(_, _); + close raw_vec::RawVec_own::(_t, _v.buf); +} + +lem array_at_lft_snoc(k: lifetime_t, p: *T, n: usize) + req array_at_lft::(k, p, n, ?elems) &*& points_to_at_lft::(k, p + n, ?x) &*& pointer_within_limits(p + n + 1) == true; + ens array_at_lft::(k, p, n + 1, append(elems, [x])); +{ + open array_at_lft::(k, p, n, elems); + if n == 0 { + close array_at_lft::(k, p + 1, 0, []); + close array_at_lft::(k, p, 1, [x]); + } else { + array_at_lft_snoc::(k, p + 1, n - 1); + close array_at_lft::(k, p, n + 1, append(elems, [x])); + } +} + +lem foreach_take_own(t: thread_id_t, xs: list, m: usize) + req foreach(xs, own::(t)) &*& 0 <= m &*& m <= length(xs); + ens foreach(take(m, xs), own::(t)); +{ + open foreach(xs, own::(t)); + if m == 0 { + close foreach([], own::(t)); + close foreach(xs, own::(t)); + leak foreach(xs, own::(t)); + } else { + match xs { + nil => {} + cons(h, tl) => { + foreach_take_own::(t, tl, m - 1); + close foreach(cons(h, take(m - 1, tl)), own::(t)); + } + } + } +} + +lem array_at_lft_uncons(k: lifetime_t, t: thread_id_t, p: *T, n: usize) + req array_at_lft::(k, p, n, ?xs) &*& foreach(xs, own::(t)) &*& 0 < n; + ens points_to_at_lft::(k, p, ?v) &*& .own(t, v) &*& + array_at_lft::(k, p + 1, n - 1, ?rest) &*& foreach(rest, own::(t)) &*& + xs == cons(v, rest); +{ + open array_at_lft::(k, p, n, xs); + assert points_to_at_lft::(k, p, ?v); + open foreach(xs, own::(t)); + open own::(t)(v); +} + +lem array_at_lft_cons(k: lifetime_t, t: thread_id_t, p: *T, n: usize) + req points_to_at_lft::(k, p, ?v) &*& .own(t, v) &*& + array_at_lft::(k, p + 1, n, ?rest) &*& foreach(rest, own::(t)) &*& + pointer_within_limits(p) == true; + ens array_at_lft::(k, p, n + 1, cons(v, rest)) &*& foreach(cons(v, rest), own::(t)); +{ + close own::(t)(v); + close foreach(cons(v, rest), own::(t)); + close array_at_lft::(k, p, n + 1, cons(v, rest)); +} + +lem array_at_lft_unsnoc(k: lifetime_t, t: thread_id_t, p: *T, n: usize) + req array_at_lft::(k, p, n, ?xs) &*& foreach(xs, own::(t)) &*& 0 < n; + ens array_at_lft::(k, p, n - 1, ?pre) &*& foreach(pre, own::(t)) &*& + points_to_at_lft::(k, p + (n - 1), ?v) &*& .own(t, v); +{ + array_at_lft_split(p, n - 1); + foreach_split(xs, own::(t), n - 1); + open array_at_lft::(k, p + (n - 1), 1, ?last_ls); + open array_at_lft::(k, p + (n - 1) + 1, 0, _); + assert points_to_at_lft::(k, p + (n - 1), ?v); + open foreach(last_ls, own::(t)); + open foreach([], own::(t)); + open own::(t)(v); +} + +lem array_at_lft_snoc_own(k: lifetime_t, t: thread_id_t, p: *T, n: usize) + req array_at_lft::(k, p, n, ?pre) &*& foreach(pre, own::(t)) &*& + points_to_at_lft::(k, p + n, ?v) &*& .own(t, v) &*& + pointer_within_limits(p + n + 1) == true; + ens array_at_lft::(k, p, n + 1, append(pre, [v])) &*& foreach(append(pre, [v]), own::(t)); +{ + array_at_lft_snoc::(k, p, n); + close own::(t)(v); + close foreach([], own::(t)); + close foreach([v], own::(t)); + foreach_append(pre, [v]); +} + +lem array_at_lft_join_len(k: lifetime_t, p: *T, n1: usize, n2: usize) + req array_at_lft::(k, p, n1, ?xs1) &*& array_at_lft::(k, p + n1, n2, ?xs2); + ens array_at_lft::(k, p, n1 + n2, append(xs1, xs2)); +{ + open array_at_lft::(k, p, n1, xs1); + match xs1 { + nil => {} + cons(x, xs1_tail) => { + array_at_lft_join_len::(k, p + 1, n1 - 1, n2); + close array_at_lft::(k, p, n1 + n2, cons(x, append(xs1_tail, xs2))); + } + } +} + +@*/ + + +//////////////////////////////////////////////////////////////////////////////// +// Inherent methods +//////////////////////////////////////////////////////////////////////////////// + +impl Vec { + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// # #![allow(unused_mut)] + /// let mut vec: Vec = Vec::new(); + /// ``` + #[inline] + #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] + #[rustc_diagnostic_item = "vec_new"] + #[stable(feature = "rust1", since = "1.0.0")] + #[must_use] + pub const fn new() -> Self { + Vec { buf: RawVec::new(), len: 0 } + } + + /// Constructs a new, empty `Vec` with at least the specified capacity. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, the vector + /// [will not allocate], and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// [will not allocate]: self#memory-layout + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert!(vec.capacity() >= 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert!(vec.capacity() >= 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<()>::with_capacity(10); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[must_use] + #[rustc_diagnostic_item = "vec_with_capacity"] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn with_capacity(capacity: usize) -> Self { + Self::with_capacity_in(capacity, Global) + } + + /// Constructs a new, empty `Vec` with at least the specified capacity. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// # Errors + /// + /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, + /// or if the allocator reports allocation failure. + /// + /// [will not allocate]: self#memory-layout + #[inline] + #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity(capacity: usize) -> Result { + Self::try_with_capacity_in(capacity, Global) + } + + /// Creates a `Vec` directly from a pointer, a length, and a capacity. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section, + /// with allocator [`Global`]. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is normally **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length + /// `size_t`, doing so is only safe if the array was initially allocated by + /// a `Vec` or `String`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. To avoid + /// these issues, it is often preferable to do casting/transmuting using + /// [`slice::from_raw_parts`] instead. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::ptr; + /// + /// let v = vec![1, 2, 3]; + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap) = v.into_raw_parts(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// ptr::write(p.add(i), 4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_raw_parts(p, len, cap); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{alloc, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = alloc(layout).cast::(); + /// if mem.is_null() { + /// return; + /// } + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts(mem, 1, 16) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr, length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } + } + + #[doc(alias = "from_non_null_parts")] + /// Creates a `Vec` directly from a `NonNull` pointer, a length, and a capacity. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section, + /// with allocator [`Global`]. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is normally **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length + /// `size_t`, doing so is only safe if the array was initially allocated by + /// a `Vec` or `String`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. To avoid + /// these issues, it is often preferable to do casting/transmuting using + /// [`NonNull::slice_from_raw_parts`] instead. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// let v = vec![1, 2, 3]; + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap) = v.into_parts(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// p.add(i).write(4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_parts(p, len, cap); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{alloc, Layout}; + /// use std::ptr::NonNull; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let Some(mem) = NonNull::new(alloc(layout).cast::()) else { + /// return; + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_parts(mem, 1, 16) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "box_vec_non_null", since = "1.99.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_parts(ptr: NonNull, length: usize, capacity: usize) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_parts_in(ptr, length, capacity, Global) } + } + + /// Creates a `Vec` where each element is produced by calling `f` with + /// that element's index while walking forward through the `Vec`. + /// + /// This is essentially the same as writing + /// + /// ```text + /// vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)] + /// ``` + /// and is similar to `(0..i).map(f)`, just for `Vec`s not iterators. + /// + /// If `length == 0`, this produces an empty `Vec` without ever calling `f`. + /// + /// # Example + /// + /// ```rust + /// let vec = Vec::from_fn(5, |i| i); + /// + /// // indexes are: 0 1 2 3 4 + /// assert_eq!(vec, [0, 1, 2, 3, 4]); + /// + /// let vec2 = Vec::from_fn(8, |i| i * 2); + /// + /// // indexes are: 0 1 2 3 4 5 6 7 + /// assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]); + /// + /// let bool_vec = Vec::from_fn(5, |i| i % 2 == 0); + /// + /// // indexes are: 0 1 2 3 4 + /// assert_eq!(bool_vec, [true, false, true, false, true]); + /// ``` + /// + /// The `Vec` is generated in ascending index order, starting from the front + /// and going towards the back, so you can use closures with mutable state: + /// ``` + /// let mut state = 1; + /// let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x }); + /// + /// assert_eq!(a, [1, 2, 4, 8, 16, 32]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "vec_from_fn", since = "1.100.0")] + pub fn from_fn(length: usize, f: F) -> Self + where + F: FnMut(usize) -> T, + { + (0..length).map(f).collect() + } + + /// Decomposes a `Vec` into its raw components: `(pointer, length, capacity)`. + /// + /// Returns the raw pointer to the underlying data, the length of + /// the vector (in elements), and the allocated capacity of the + /// data (in elements). These are the same arguments in the same + /// order as the arguments to [`from_raw_parts`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. Most often, one does + /// this by converting the raw pointer, length, and capacity back + /// into a `Vec` with the [`from_raw_parts`] function; more generally, + /// if `T` is non-zero-sized and the capacity is nonzero, one may use + /// any method that calls [`dealloc`] with a layout of + /// `Layout::array::(capacity)`; if `T` is zero-sized or the + /// capacity is zero, nothing needs to be done. + /// + /// [`from_raw_parts`]: Vec::from_raw_parts + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// + /// # Examples + /// + /// ``` + /// let v: Vec = vec![-1, 0, 1]; + /// + /// let (ptr, len, cap) = v.into_raw_parts(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr as *mut u32; + /// + /// Vec::from_raw_parts(ptr, len, cap) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "vec_into_raw_parts", since = "1.93.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_raw_parts(self) -> (*mut T, usize, usize) { + let mut me = ManuallyDrop::new(self); + (me.as_mut_ptr(), me.len(), me.capacity()) + } + + #[doc(alias = "into_non_null_parts")] + /// Decomposes a `Vec` into its raw components: `(NonNull pointer, length, capacity)`. + /// + /// Returns the `NonNull` pointer to the underlying data, the length of + /// the vector (in elements), and the allocated capacity of the + /// data (in elements). These are the same arguments in the same + /// order as the arguments to [`from_parts`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the `NonNull` pointer, length, and capacity back + /// into a `Vec` with the [`from_parts`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_parts`]: Vec::from_parts + /// + /// # Examples + /// + /// ``` + /// let v: Vec = vec![-1, 0, 1]; + /// + /// let (ptr, len, cap) = v.into_parts(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr.cast::(); + /// + /// Vec::from_parts(ptr, len, cap) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "box_vec_non_null", since = "1.99.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_parts(self) -> (NonNull, usize, usize) { + let (ptr, len, capacity) = self.into_raw_parts(); + // SAFETY: A `Vec` always has a non-null pointer. + (unsafe { NonNull::new_unchecked(ptr) }, len, capacity) + } + + /// Interns the `Vec`, making the underlying memory read-only. This method should be + /// called during compile time. (This is a no-op if called during runtime) + /// + /// This method must be called if the memory used by `Vec` needs to appear in the final + /// values of constants. + #[unstable(feature = "const_heap", issue = "79597")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn const_make_global(mut self) -> &'static [T] + where + T: Freeze, + { + // `const_make_global` requires the pointer to point to the beginning of a heap allocation, + // which is not the case when `self.capacity()` is 0, or if `T::IS_ZST`, + // which is why we instead return a new slice in this case. + if self.capacity() == 0 || T::IS_ZST { + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(NonNull::::dangling().as_ptr(), me.len) } + } else { + // ignore-tidy-undocumented-unsafe + unsafe { core::intrinsics::const_make_global(self.as_mut_ptr().cast()) }; + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts(me.as_ptr(), me.len) } + } + } +} + +#[cfg(not(no_global_oom_handling))] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped +const impl Vec { + /// Constructs a new, empty `Vec` with at least the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// It is important to note that although the returned vector has the + /// minimum *capacity* specified, the vector will have a zero *length*. For + /// an explanation of the difference between length and capacity, see + /// *[Capacity and reallocation]*. + /// + /// If it is important to know the exact allocated capacity of a `Vec`, + /// always use the [`capacity`] method after construction. + /// + /// For `Vec` where `T` is a zero-sized type, the vector + /// [will not allocate], and the capacity will always be `usize::MAX`. + /// + /// [Capacity and reallocation]: #capacity-and-reallocation + /// [`capacity`]: Vec::capacity + /// [will not allocate]: self#memory-layout + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut vec = Vec::with_capacity_in(10, System); + /// + /// // The vector contains no items, even though it has capacity for more + /// assert_eq!(vec.len(), 0); + /// assert!(vec.capacity() >= 10); + /// + /// // These are all done without reallocating... + /// for i in 0..10 { + /// vec.push(i); + /// } + /// assert_eq!(vec.len(), 10); + /// assert!(vec.capacity() >= 10); + /// + /// // ...but this may make the vector reallocate + /// vec.push(11); + /// assert_eq!(vec.len(), 11); + /// assert!(vec.capacity() >= 11); + /// + /// // A vector of a zero-sized type will always over-allocate, since no + /// // allocation is necessary + /// let vec_units = Vec::<(), System>::with_capacity_in(10, System); + /// assert_eq!(vec_units.capacity(), usize::MAX); + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { + Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } + } + + /// Appends an element to the back of a collection. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2]; + /// vec.push(3); + /// assert_eq!(vec, [1, 2, 3]); + /// ``` + /// + /// # Time complexity + /// + /// Takes amortized *O*(1) time. If the vector's length would exceed its + /// capacity after the push, *O*(*capacity*) time is taken to copy the + /// vector's elements to a larger allocation. This expensive operation is + /// offset by the *capacity* *O*(1) insertions it allows. + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_confusables("push_back", "put", "append")] + pub fn push(&mut self, value: T) { + let _ = self.push_mut(value); + } + + /// Appends an element to the back of a collection, returning a reference to it. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2]; + /// let last = vec.push_mut(3); + /// assert_eq!(*last, 3); + /// assert_eq!(vec, [1, 2, 3]); + /// + /// let last = vec.push_mut(3); + /// *last += 1; + /// assert_eq!(vec, [1, 2, 3, 4]); + /// ``` + /// + /// # Time complexity + /// + /// Takes amortized *O*(1) time. If the vector's length would exceed its + /// capacity after the push, *O*(*capacity*) time is taken to copy the + /// vector's elements to a larger allocation. This expensive operation is + /// offset by the *capacity* *O*(1) insertions it allows. + #[inline] + #[stable(feature = "push_mut", since = "1.95.0")] + #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"] + pub fn push_mut(&mut self, value: T) -> &mut T { + // Inform codegen that the length does not change across grow_one(). + let len = self.len; + // This will panic or abort if we would allocate > isize::MAX bytes + // or if the length increment would overflow for zero-sized types. + if len == self.buf.capacity() { + self.buf.grow_one(); + } + // ignore-tidy-undocumented-unsafe + unsafe { + let end = self.as_mut_ptr().add(len); + ptr::write(end, value); + self.len = len + 1; + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + &mut *end + } + } +} + +impl Vec { + /// Constructs a new, empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let vec: Vec = Vec::new_in(System); + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")] + pub const fn new_in(alloc: A) -> Self { + Vec { buf: RawVec::new_in(alloc), len: 0 } + } + + /// Constructs a new, empty `Vec` with at least the specified capacity + /// with the provided allocator. + /// + /// The vector will be able to hold at least `capacity` elements without + /// reallocating. This method is allowed to allocate for more elements than + /// `capacity`. If `capacity` is zero, the vector [will not allocate]. + /// + /// # Errors + /// + /// Returns an error if the capacity exceeds `isize::MAX` _bytes_, + /// or if the allocator reports allocation failure. + /// + /// [will not allocate]: self#memory-layout + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + // #[unstable(feature = "try_with_capacity", issue = "91913")] + pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { + Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 }) + } + + /// Creates a `Vec` directly from a pointer, a length, a capacity, + /// and an allocator. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length `size_t`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [`allocate`]: crate::alloc::Allocator::allocate + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// use std::ptr; + /// + /// let mut v = Vec::with_capacity_in(3, System); + /// v.push(1); + /// v.push(2); + /// v.push(3); + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap, alloc) = v.into_raw_parts_with_allocator(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// ptr::write(p.add(i), 4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{AllocError, Allocator, Global, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = match Global.allocate(layout) { + /// Ok(mem) => mem.cast::().as_ptr(), + /// Err(AllocError) => return, + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_raw_parts_in(mem, 1, 16, Global) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const unsafe fn from_raw_parts_in( + ptr: *mut T, + length: usize, + capacity: usize, + alloc: A, + ) -> Self { + ub_checks::assert_unsafe_precondition!( + check_library_ub, + "Vec::from_raw_parts_in requires that length <= capacity", + (length: usize = length, capacity: usize = capacity) => length <= capacity + ); + // SAFETY: Upheld by caller. + unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } + } + + #[doc(alias = "from_non_null_parts_in")] + /// Creates a `Vec` directly from a `NonNull` pointer, a length, a capacity, + /// and an allocator. + /// + /// # Safety + /// + /// The parts must satisfy the invariants described in the [memory layout] section. + /// + /// Violating them may cause problems like corrupting the allocator's + /// internal data structures. For example it is **not** safe + /// to build a `Vec` from a pointer to a C `char` array with length `size_t`. + /// It's also not safe to build one from a `Vec` and its length, because + /// the allocator cares about the alignment, and these two types have different + /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after + /// turning it into a `Vec` it'll be deallocated with alignment 1. + /// + /// The ownership of `ptr` is effectively transferred to the + /// `Vec` which may then deallocate, reallocate or change the + /// contents of memory pointed to by the pointer at will. Ensure + /// that nothing else uses the pointer after calling this + /// function. + /// + /// [`String`]: crate::string::String + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// [memory layout]: self#memory-layout + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v = Vec::with_capacity_in(3, System); + /// v.push(1); + /// v.push(2); + /// v.push(3); + /// + /// // Deconstruct the vector into parts. + /// let (p, len, cap, alloc) = v.into_parts_with_allocator(); + /// + /// unsafe { + /// // Overwrite memory with 4, 5, 6 + /// for i in 0..len { + /// p.add(i).write(4 + i); + /// } + /// + /// // Put everything back together into a Vec + /// let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone()); + /// assert_eq!(rebuilt, [4, 5, 6]); + /// } + /// ``` + /// + /// Using memory that was allocated elsewhere: + /// + /// ```rust + /// use std::alloc::{AllocError, Allocator, Global, Layout}; + /// + /// fn main() { + /// let layout = Layout::array::(16).expect("16 u32s take 64 bytes, so it shouldn't overflow"); + /// + /// let vec = unsafe { + /// let mem = match Global.allocate(layout) { + /// Ok(mem) => mem.cast::(), + /// Err(AllocError) => return, + /// }; + /// + /// mem.write(1_000_000); + /// + /// Vec::from_parts_in(mem, 1, 16, Global) + /// }; + /// + /// assert_eq!(vec, &[1_000_000]); + /// assert_eq!(vec.capacity(), 16); + /// } + /// ``` + #[inline] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))] + #[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })] + pub const unsafe fn from_parts_in( + ptr: NonNull, + length: usize, + capacity: usize, + alloc: A, + ) -> Self { + ub_checks::assert_unsafe_precondition!( + check_library_ub, + "Vec::from_parts_in requires that length <= capacity", + (length: usize = length, capacity: usize = capacity) => length <= capacity + ); + // SAFETY: Upheld by caller. + unsafe { Vec { buf: RawVec::from_nonnull_in(ptr, capacity, alloc), len: length } } + } + + /// Decomposes a `Vec` into its raw components: `(pointer, length, capacity, allocator)`. + /// + /// Returns the raw pointer to the underlying data, the length of the vector (in elements), + /// the allocated capacity of the data (in elements), and the allocator. These are the same + /// arguments in the same order as the arguments to [`from_raw_parts_in`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the raw pointer, length, and capacity back + /// into a `Vec` with the [`from_raw_parts_in`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_raw_parts_in`]: Vec::from_raw_parts_in + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v: Vec = Vec::new_in(System); + /// v.push(-1); + /// v.push(0); + /// v.push(1); + /// + /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr as *mut u32; + /// + /// Vec::from_raw_parts_in(ptr, len, cap, alloc) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_raw_parts_with_allocator(self) -> (*mut T, usize, usize, A) { + let mut me = ManuallyDrop::new(self); + let len = me.len(); + let capacity = me.capacity(); + let ptr = me.as_mut_ptr(); + // ignore-tidy-undocumented-unsafe + let alloc = unsafe { ptr::read(me.allocator()) }; + (ptr, len, capacity, alloc) + } + + #[doc(alias = "into_non_null_parts_with_alloc")] + /// Decomposes a `Vec` into its raw components: `(NonNull pointer, length, capacity, allocator)`. + /// + /// Returns the `NonNull` pointer to the underlying data, the length of the vector (in elements), + /// the allocated capacity of the data (in elements), and the allocator. These are the same + /// arguments in the same order as the arguments to [`from_parts_in`]. + /// + /// After calling this function, the caller is responsible for the + /// memory previously managed by the `Vec`. The only way to do + /// this is to convert the `NonNull` pointer, length, and capacity back + /// into a `Vec` with the [`from_parts_in`] function, allowing + /// the destructor to perform the cleanup. + /// + /// [`from_parts_in`]: Vec::from_parts_in + /// + /// # Examples + /// + /// ``` + /// use std::alloc::System; + /// + /// let mut v: Vec = Vec::new_in(System); + /// v.push(-1); + /// v.push(0); + /// v.push(1); + /// + /// let (ptr, len, cap, alloc) = v.into_parts_with_allocator(); + /// + /// let rebuilt = unsafe { + /// // We can now make changes to the components, such as + /// // transmuting the raw pointer to a compatible type. + /// let ptr = ptr.cast::(); + /// + /// Vec::from_parts_in(ptr, len, cap, alloc) + /// }; + /// assert_eq!(rebuilt, [4294967295, 0, 1]); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + pub const fn into_parts_with_allocator(self) -> (NonNull, usize, usize, A) { + let (ptr, len, capacity, alloc) = self.into_raw_parts_with_allocator(); + // SAFETY: A `Vec` always has a non-null pointer. + (unsafe { NonNull::new_unchecked(ptr) }, len, capacity, alloc) + } + + /// Returns the total number of elements the vector can hold without + /// reallocating. + /// + /// # Examples + /// + /// ``` + /// let mut vec: Vec = Vec::with_capacity(10); + /// vec.push(42); + /// assert!(vec.capacity() >= 10); + /// ``` + /// + /// A vector with zero-sized elements will always have a capacity of usize::MAX: + /// + /// ``` + /// #[derive(Clone)] + /// struct ZeroSized; + /// + /// fn main() { + /// assert_eq!(std::mem::size_of::(), 0); + /// let v = vec![ZeroSized; 0]; + /// assert_eq!(v.capacity(), usize::MAX); + /// } + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn capacity(&self) -> usize + //@ req [_]Vec_share_(?k, currentThread, self, ?alloc_id, ?ptr, ?capacity, ?length) &*& [?q]lifetime_token(k); + //@ ens [q]lifetime_token(k) &*& result == capacity; + /*@ + safety_proof { + open >.share(?k, _t, self); + call(); + } + @*/ + { + //@ open Vec_share_(k, currentThread, self, alloc_id, ptr, capacity, length); + //@ let buf_ref = precreate_ref(&(*self).buf); + //@ raw_vec::init_ref_RawVec_(buf_ref); + //@ open_frac_borrow(k, ref_initialized_(buf_ref), q/2); + //@ open [?f]ref_initialized_::>(buf_ref)(); + let r = self.buf.capacity(); + //@ close [f]ref_initialized_::>(buf_ref)(); + //@ close_frac_borrow(f, ref_initialized_(buf_ref)); + r + } + + /// Reserves capacity for at least `additional` more elements to be inserted + /// in the given `Vec`. The collection may reserve more space to + /// speculatively avoid frequent reallocations. After calling `reserve`, + /// capacity will be greater than or equal to `self.len() + additional`. + /// Does nothing if capacity is already sufficient. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.reserve(10); + /// assert!(vec.capacity() >= 11); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_reserve"] + pub fn reserve(&mut self, additional: usize) + /*@ + req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& + Vec(t, self0, ?alloc_id0, ?ptr0, ?cap0, ?len0) &*& + array_at_lft(alloc_id0.lft, ptr0, len0, ?elems) &*& + array_at_lft_(alloc_id0.lft, ptr0 + len0, cap0 - len0, _); + @*/ + /*@ + ens thread_token(t) &*& *self |-> ?self1 &*& + Vec(t, self1, alloc_id0, ?ptr1, ?cap1, len0) &*& + len0 + additional <= cap1 &*& + array_at_lft(alloc_id0.lft, ptr1, len0, elems) &*& + array_at_lft_(alloc_id0.lft, ptr1 + len0, cap1 - len0, _); + @*/ + /*@ + safety_proof { + open >.own(_t, ?self0); + call(); + close >.own(_t, *self); + } + @*/ + { + //@ open Vec(t, self0, alloc_id0, ptr0, cap0, len0); + //@ open_points_to(self); + //@ close_points_to(&(*self).buf); + //@ assert array_at_lft_(alloc_id0.lft, ptr0 + len0, cap0 - len0, ?spare0); + //@ array_at_lft_to_array_at_lft_(ptr0); + //@ array_at_lft__join(ptr0); + //@ take_append(len0, map(some, elems), spare0); + self.buf.reserve(self.len, additional); + //@ open_points_to(&(*self).buf); + //@ close_points_to(self); + //@ assert *self |-> ?self1 &*& raw_vec::RawVec(t, self1.buf, alloc_id0, ?ptr1, ?cap1); + //@ array_at_lft__split(ptr1, len0); + //@ array_at_lft__to_array_at_lft::(ptr1, elems); + //@ close Vec(t, self1, alloc_id0, ptr1, cap1, len0); + } + + /// Reserves the minimum capacity for at least `additional` more elements to + /// be inserted in the given `Vec`. Unlike [`reserve`], this will not + /// deliberately over-allocate to speculatively avoid frequent allocations. + /// After calling `reserve_exact`, capacity will be greater than or equal to + /// `self.len() + additional`. Does nothing if the capacity is already + /// sufficient. + /// + /// Note that the allocator may give the collection more space than it + /// requests. Therefore, capacity can not be relied upon to be precisely + /// minimal. Prefer [`reserve`] if future insertions are expected. + /// + /// [`reserve`]: Vec::reserve + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.reserve_exact(10); + /// assert!(vec.capacity() >= 11); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn reserve_exact(&mut self, additional: usize) { + self.buf.reserve_exact(self.len, additional); + } + + /// Tries to reserve capacity for at least `additional` more elements to be inserted + /// in the given `Vec`. The collection may reserve more space to speculatively avoid + /// frequent reallocations. After calling `try_reserve`, capacity will be + /// greater than or equal to `self.len() + additional` if it returns + /// `Ok(())`. Does nothing if capacity is already sufficient. This method + /// preserves the contents even if an error occurs. + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use std::collections::TryReserveError; + /// + /// fn process_data(data: &[u32]) -> Result, TryReserveError> { + /// let mut output = Vec::new(); + /// + /// // Pre-reserve the memory, exiting if we can't + /// output.try_reserve(data.len())?; + /// + /// // Now we know this can't OOM in the middle of our complex work + /// output.extend(data.iter().map(|&val| { + /// val * 2 + 5 // very complicated + /// })); + /// + /// Ok(output) + /// } + /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail"); + /// ``` + #[stable(feature = "try_reserve", since = "1.57.0")] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.buf.try_reserve(self.len, additional) + } + + /// Tries to reserve the minimum capacity for at least `additional` + /// elements to be inserted in the given `Vec`. Unlike [`try_reserve`], + /// this will not deliberately over-allocate to speculatively avoid frequent + /// allocations. After calling `try_reserve_exact`, capacity will be greater + /// than or equal to `self.len() + additional` if it returns `Ok(())`. + /// Does nothing if the capacity is already sufficient. + /// + /// Note that the allocator may give the collection more space than it + /// requests. Therefore, capacity can not be relied upon to be precisely + /// minimal. Prefer [`try_reserve`] if future insertions are expected. + /// + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Errors + /// + /// If the capacity overflows, or the allocator reports a failure, then an error + /// is returned. + /// + /// # Examples + /// + /// ``` + /// use std::collections::TryReserveError; + /// + /// fn process_data(data: &[u32]) -> Result, TryReserveError> { + /// let mut output = Vec::new(); + /// + /// // Pre-reserve the memory, exiting if we can't + /// output.try_reserve_exact(data.len())?; + /// + /// // Now we know this can't OOM in the middle of our complex work + /// output.extend(data.iter().map(|&val| { + /// val * 2 + 5 // very complicated + /// })); + /// + /// Ok(output) + /// } + /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail"); + /// ``` + #[stable(feature = "try_reserve", since = "1.57.0")] + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.buf.try_reserve_exact(self.len, additional) + } + + /// Shrinks the capacity of the vector as much as possible. + /// + /// When `vec.len() == vec.capacity()` the allocation is unchanged. Otherwise, the behavior of + /// this method depends on the allocator, which may either shrink the vector in-place or + /// reallocate. The resulting vector might still have some excess capacity, just as + /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details. + /// + /// [`with_capacity`]: Vec::with_capacity + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.shrink_to_fit(); + /// assert!(vec.capacity() >= 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn shrink_to_fit(&mut self) { + // The capacity is never less than the length, and there's nothing to do when + // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` + // by only calling it with a greater capacity. + if self.capacity() > self.len { + self.buf.shrink_to_fit(self.len); + } + } + + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// If the current capacity is less than the lower limit, this is a no-op. + /// + /// # Examples + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.shrink_to(4); + /// assert!(vec.capacity() >= 4); + /// vec.shrink_to(0); + /// assert!(vec.capacity() >= 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "shrink_to", since = "1.56.0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + if self.capacity() > min_capacity { + self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); + } + } + + /// Tries to shrink the capacity of the vector as much as possible + /// + /// The behavior of this method depends on the allocator, which may either shrink the vector + /// in-place or reallocate. The resulting vector might still have some excess capacity, just as + /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details. + /// + /// [`with_capacity`]: Vec::with_capacity + /// + /// # Errors + /// + /// This function returns an error if the allocator fails to shrink the allocation, + /// the vector thereafter is still safe to use, the capacity remains unchanged + /// however. See [`Allocator::shrink`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_fallible_shrink)] + /// + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.try_shrink_to_fit().expect("for this test, shrink shouldn't fail"); + /// assert!(vec.capacity() >= 3); + /// ``` + #[unstable(feature = "vec_fallible_shrink", issue = "152350")] + #[inline] + pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> { + if self.capacity() > self.len { self.buf.try_shrink_to_fit(self.len) } else { Ok(()) } + } + + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// If the current capacity is less than the lower limit, this is a no-op. + /// + /// # Errors + /// + /// This function returns an error if the allocator fails to shrink the allocation, + /// the vector thereafter is still safe to use, the capacity remains unchanged + /// however. See [`Allocator::shrink`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_fallible_shrink)] + /// + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// assert!(vec.capacity() >= 10); + /// vec.try_shrink_to(4).expect("for this test, shrink shouldn't fail"); + /// assert!(vec.capacity() >= 4); + /// vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved."); + /// assert!(vec.capacity() >= 3); + /// ``` + #[unstable(feature = "vec_fallible_shrink", issue = "152350")] + #[inline] + pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), TryReserveError> { + if self.capacity() > min_capacity { + self.buf.try_shrink_to_fit(cmp::max(self.len, min_capacity)) + } else { + Ok(()) + } + } + + /// Converts the vector into a boxed slice. + /// + /// This conversion is in-place if `vec.len() == vec.capacity()`. + /// + /// Before doing the conversion, this method adjusts the vector's allocation as + /// needed so that, if a backing allocation is present, the layout of the returned + /// slice [*fits*] that allocation. Thus, the vector's former capacity is not needed + /// to determine a layout suitable for deallocation. + /// + /// [*fits*]: crate::alloc::Allocator#memory-fitting + /// + /// # Examples + /// + /// ``` + /// let v = vec![1, 2, 3]; + /// + /// let slice = v.into_boxed_slice(); + /// ``` + /// + /// The vector's spare capacity is not retained: + /// + /// ``` + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3]); + /// + /// assert!(vec.capacity() >= 10); + /// let slice = vec.into_boxed_slice(); + /// assert_eq!(slice.into_vec().capacity(), 3); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn into_boxed_slice(mut self) -> Box<[T], A> { + self.shrink_to_fit(); + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { + let buf = ptr::read(&me.buf); + let len = me.len(); + buf.into_box(len).assume_init() + } + } + + /// Converts the Vec into a boxed array. This conversion will discard any spare capacity, + /// if there is any, see [`Vec::into_boxed_slice`]. + /// If you merely wish for a reference to an array, use [`as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array). + /// + /// # Errors + /// + /// Returns the original `Vec` in the `Err` variant if [`Vec::len`] does not equal `N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(alloc_slice_into_array)] + /// let vec: Vec = vec![1, 2, 3]; + /// let box_array: Box<[i32; 3]> = vec.clone().into_array().unwrap(); + /// let not_enough_elements: Result, Vec> = vec.into_array::<4>(); + /// assert_eq!(not_enough_elements, Err(vec![1, 2, 3])); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "alloc_slice_into_array", issue = "148082")] + pub fn into_array(self) -> Result, Self> { + if self.len() == N { + // SAFETY: `Box::into_array` is guaranteed to return `Ok` if the + // length of the slice is equal to `N`. + // `self.into_boxed_slice().len()` is equal to `self.len()`, + // which we just checked. + Ok(unsafe { self.into_boxed_slice().into_array().unwrap_unchecked() }) + } else { + Err(self) + } + } + + /// Shortens the vector, keeping the first `len` elements and dropping + /// the rest. + /// + /// If `len` is greater or equal to the vector's current length, this has + /// no effect. + /// + /// The [`drain`] method can emulate `truncate`, but causes the excess + /// elements to be returned instead of dropped. + /// + /// Note that this method has no effect on the allocated capacity + /// of the vector. + /// + /// # Examples + /// + /// Truncating a five element vector to two elements: + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4, 5]; + /// vec.truncate(2); + /// assert_eq!(vec, [1, 2]); + /// ``` + /// + /// No truncation occurs when `len` is greater than or equal to the + /// vector's current length: + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.truncate(8); + /// assert_eq!(vec, [1, 2, 3]); + /// ``` + /// + /// Truncating when `len == 0` is equivalent to calling the [`clear`] + /// method. + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.truncate(0); + /// assert_eq!(vec, []); + /// ``` + /// + /// [`clear`]: Vec::clear + /// [`drain`]: Vec::drain + #[stable(feature = "rust1", since = "1.0.0")] + pub fn truncate(&mut self, len: usize) { + // SAFETY: `BufWriter::flush_buf` assumes that this will not + // de-initialize any elements of the spare capacity. + + // This is safe because: + // + // * the slice passed to `drop_in_place` is valid; the `len >= self.len` + // case avoids creating an invalid slice, and + // * the `len` of the vector is shrunk before calling `drop_in_place`, + // such that no value will be dropped twice in case `drop_in_place` + // were to panic once (if it panics twice, the program aborts). + unsafe { + if len >= self.len { + return; + } + let remaining_len = self.len - len; + let s = self.as_mut_ptr().add(len).cast_slice(remaining_len); + self.len = len; + ptr::drop_in_place(s); + } + } + + /// Extracts a slice containing the entire vector. + /// + /// Equivalent to `&s[..]`. + /// + /// # Examples + /// + /// ``` + /// use std::io::{self, Write}; + /// let buffer = vec![1, 2, 3, 5, 8]; + /// io::sink().write(buffer.as_slice()).unwrap(); + /// ``` + #[inline] + #[stable(feature = "vec_as_slice", since = "1.7.0")] + #[rustc_diagnostic_item = "vec_as_slice"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn as_slice(&self) -> &[T] { + // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size + // `len` containing properly-initialized `T`s. Data must not be mutated for the returned + // lifetime. Further, `len * size_of::` <= `isize::MAX`, and allocation does not + // "wrap" through overflowing memory addresses. + // + // * Vec API guarantees that self.buf: + // * contains only properly-initialized items within 0..len + // * is aligned, contiguous, and valid for `len` reads + // * obeys size and address-wrapping constraints + // + // * We only construct `&mut` references to `self.buf` through `&mut self` methods; borrow- + // check ensures that it is not possible to mutably alias `self.buf` within the + // returned lifetime. + unsafe { + // normally this would use `slice::from_raw_parts`, but it's + // instantiated often enough that avoiding the UB check is worth it + &*core::intrinsics::aggregate_raw_ptr::<*const [T], _, _>(self.as_ptr(), self.len) + } + } + + /// Extracts a mutable slice of the entire vector. + /// + /// Equivalent to `&mut s[..]`. + /// + /// # Examples + /// + /// ``` + /// use std::io::{self, Read}; + /// let mut buffer = vec![0; 3]; + /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap(); + /// ``` + #[inline] + #[stable(feature = "vec_as_slice", since = "1.7.0")] + #[rustc_diagnostic_item = "vec_as_mut_slice"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn as_mut_slice(&mut self) -> &mut [T] { + // SAFETY: `BufWriter::flush_buf` assumes that this will not + // de-initialize any elements of the spare capacity. + + // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of + // size `len` containing properly-initialized `T`s. Data must not be accessed through any + // other pointer for the returned lifetime. Further, `len * size_of::` <= + // `isize::MAX` and allocation does not "wrap" through overflowing memory addresses. + // + // * Vec API guarantees that self.buf: + // * contains only properly-initialized items within 0..len + // * is aligned, contiguous, and valid for `len` reads + // * obeys size and address-wrapping constraints + // + // * We only construct references to `self.buf` through `&self` and `&mut self` methods; + // borrow-check ensures that it is not possible to construct a reference to `self.buf` + // within the returned lifetime. + unsafe { + // normally this would use `slice::from_raw_parts_mut`, but it's + // instantiated often enough that avoiding the UB check is worth it + &mut *core::intrinsics::aggregate_raw_ptr::<*mut [T], _, _>(self.as_mut_ptr(), self.len) + } + } + + /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer + /// valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// The caller must also ensure that the memory the pointer (non-transitively) points to + /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer + /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`]. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize mutable references to the slice, + /// or mutable references to specific elements you are planning on accessing through this pointer, + /// as well as writing to those elements, may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// + /// # Examples + /// + /// ``` + /// let x = vec![1, 2, 4]; + /// let x_ptr = x.as_ptr(); + /// + /// unsafe { + /// for i in 0..x.len() { + /// assert_eq!(*x_ptr.add(i), 1 << i); + /// } + /// } + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// unsafe { + /// let mut v = vec![0, 1, 2]; + /// let ptr1 = v.as_ptr(); + /// let _ = ptr1.read(); + /// let ptr2 = v.as_mut_ptr().offset(2); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1` + /// // because it mutated a different element: + /// let _ = ptr1.read(); + /// } + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [didn't allocate]: self#memory-layout + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[inline] + #[lint::as_ptr] + #[lint::never_returns_null_ptr] + pub const fn as_ptr(&self) -> *const T { + // We shadow the slice method of the same name to avoid going through + // `deref`, which creates an intermediate reference. + self.buf.ptr() + } + + /// Returns a raw mutable pointer to the vector's buffer, or a dangling + /// raw pointer valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize references to the slice, + /// or references to specific elements you are planning on accessing through this pointer, + /// may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is + /// nonzero, the pointer may be passed into [`dealloc`] with a layout of + /// `Layout::array::(capacity)` in order to deallocate the backing memory. If this is done, + /// be careful not to run the destructor of the `Vec`, as dropping it will result in + /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this. + /// + /// # Examples + /// + /// ``` + /// // Allocate vector big enough for 4 elements. + /// let size = 4; + /// let mut x: Vec = Vec::with_capacity(size); + /// let x_ptr = x.as_mut_ptr(); + /// + /// // Initialize elements via raw pointer writes, then set length. + /// unsafe { + /// for i in 0..size { + /// *x_ptr.add(i) = i as i32; + /// } + /// x.set_len(size); + /// } + /// assert_eq!(&*x, &[0, 1, 2, 3]); + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// unsafe { + /// let mut v = vec![0]; + /// let ptr1 = v.as_mut_ptr(); + /// ptr1.write(1); + /// let ptr2 = v.as_mut_ptr(); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`: + /// ptr1.write(3); + /// } + /// ``` + /// + /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally): + /// + /// ``` + /// use std::mem::{ManuallyDrop, MaybeUninit}; + /// + /// let mut v = ManuallyDrop::new(vec![0, 1, 2]); + /// let ptr = v.as_mut_ptr(); + /// let capacity = v.capacity(); + /// let slice_ptr: *mut [MaybeUninit] = + /// std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity); + /// drop(unsafe { Box::from_raw(slice_ptr) }); + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc + /// [`ManuallyDrop`]: core::mem::ManuallyDrop + /// [didn't allocate]: self#memory-layout + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[lint::as_ptr] + #[lint::never_returns_null_ptr] + #[inline] + pub const fn as_mut_ptr(&mut self) -> *mut T + //@ req *self |-> ?self0 &*& Vec(currentThread, self0, ?alloc_id, ?ptr, ?capacity, ?length); + //@ ens *self |-> ?self1 &*& Vec(currentThread, self1, alloc_id, ptr, capacity, length) &*& result == ptr; + /*@ + safety_proof { + open >.own(_t, ?self0); + call(); + close >.own(_t, *self); + } + @*/ + { + // We shadow the slice method of the same name to avoid going through + // `deref_mut`, which creates an intermediate reference. + //@ open Vec(currentThread, self0, alloc_id, ptr, capacity, length); + //@ let k = begin_lifetime(); + //@ open_points_to(self); + //@ close_points_to(&(*self).buf); + //@ raw_vec::share_RawVec(k, &(*self).buf); + //@ let buf_ref = precreate_ref(&(*self).buf); + //@ raw_vec::init_ref_RawVec_(buf_ref); + //@ open_frac_borrow(k, ref_initialized_(buf_ref), 1/2); + //@ open [?f]ref_initialized_::>(buf_ref)(); + let r = self.buf.ptr(); + //@ close [f]ref_initialized_::>(buf_ref)(); + //@ close_frac_borrow(f, ref_initialized_(buf_ref)); + //@ end_lifetime(k); + //@ raw_vec::end_share_RawVec(&(*self).buf); + //@ close Vec(currentThread, *self, alloc_id, ptr, capacity, length); + r + } + + /// Returns a `NonNull` pointer to the vector's buffer, or a dangling + /// `NonNull` pointer valid for zero sized reads if the vector [didn't allocate]. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up dangling. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// This method guarantees that for the purpose of the aliasing model, this method + /// does not materialize a reference to the underlying slice, and thus the returned pointer + /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], + /// and [`as_non_null`]. + /// Note that calling other methods that materialize references to the slice, + /// or references to specific elements you are planning on accessing through this pointer, + /// may still invalidate this pointer. + /// See the second example below for how this guarantee can be used. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_as_non_null)] + /// + /// // Allocate vector big enough for 4 elements. + /// let size = 4; + /// let mut x: Vec = Vec::with_capacity(size); + /// let x_ptr = x.as_non_null(); + /// + /// // Initialize elements via raw pointer writes, then set length. + /// unsafe { + /// for i in 0..size { + /// x_ptr.add(i).write(i as i32); + /// } + /// x.set_len(size); + /// } + /// assert_eq!(&*x, &[0, 1, 2, 3]); + /// ``` + /// + /// Due to the aliasing guarantee, the following code is legal: + /// + /// ```rust + /// #![feature(vec_as_non_null)] + /// + /// unsafe { + /// let mut v = vec![0]; + /// let ptr1 = v.as_non_null(); + /// ptr1.write(1); + /// let ptr2 = v.as_non_null(); + /// ptr2.write(2); + /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`: + /// ptr1.write(3); + /// } + /// ``` + /// + /// [`as_mut_ptr`]: Vec::as_mut_ptr + /// [`as_ptr`]: Vec::as_ptr + /// [`as_non_null`]: Vec::as_non_null + /// [didn't allocate]: self#memory-layout + #[unstable(feature = "vec_as_non_null", issue = "157843")] + #[rustc_const_unstable(feature = "vec_as_non_null", issue = "157843")] + #[lint::as_ptr] + #[inline] + pub const fn as_non_null(&mut self) -> NonNull { + self.buf.non_null() + } + + /// Returns a reference to the underlying allocator. + #[stable(feature = "allocator_api", since = "1.100.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn allocator(&self) -> &A { + self.buf.allocator() + } + + /// Forces the length of the vector to `new_len`. + /// + /// This is a low-level operation that maintains none of the normal + /// invariants of the type. Normally changing the length of a vector + /// is done using one of the safe operations instead, such as + /// [`truncate`], [`resize`], [`extend`], or [`clear`]. + /// + /// [`truncate`]: Vec::truncate + /// [`resize`]: Vec::resize + /// [`extend`]: Extend::extend + /// [`clear`]: Vec::clear + /// + /// # Safety + /// + /// - `new_len` must be less than or equal to [`capacity()`]. + /// - The elements at `old_len..new_len` must be initialized. + /// + /// [`capacity()`]: Vec::capacity + /// + /// # Examples + /// + /// See [`spare_capacity_mut()`] for an example with safe + /// initialization of capacity elements and use of this method. + /// + /// `set_len()` can be useful for situations in which the vector + /// is serving as a buffer for other code, particularly over FFI: + /// + /// ```no_run + /// # #![allow(dead_code)] + /// # // This is just a minimal skeleton for the doc example; + /// # // don't use this as a starting point for a real library. + /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void } + /// # const Z_OK: i32 = 0; + /// # unsafe extern "C" { + /// # fn deflateGetDictionary( + /// # strm: *mut std::ffi::c_void, + /// # dictionary: *mut u8, + /// # dictLength: *mut usize, + /// # ) -> i32; + /// # } + /// # impl StreamWrapper { + /// pub fn get_dictionary(&self) -> Option> { + /// // Per the FFI method's docs, "32768 bytes is always enough". + /// let mut dict = Vec::with_capacity(32_768); + /// let mut dict_length = 0; + /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that: + /// // 1. `dict_length` elements were initialized. + /// // 2. `dict_length` <= the capacity (32_768) + /// // which makes `set_len` safe to call. + /// unsafe { + /// // Make the FFI call... + /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length); + /// if r == Z_OK { + /// // ...and update the length to what was initialized. + /// dict.set_len(dict_length); + /// Some(dict) + /// } else { + /// None + /// } + /// } + /// } + /// # } + /// ``` + /// + /// While the following example is sound, there is a memory leak since + /// the inner vectors were not freed prior to the `set_len` call: + /// + /// ``` + /// let mut vec = vec![vec![1, 0, 0], + /// vec![0, 1, 0], + /// vec![0, 0, 1]]; + /// // SAFETY: + /// // 1. `old_len..0` is empty so no elements need to be initialized. + /// // 2. `0 <= capacity` always holds whatever `capacity` is. + /// unsafe { + /// vec.set_len(0); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # vec.set_len(3); + /// } + /// ``` + /// + /// Normally, here, one would use [`clear`] instead to correctly drop + /// the contents and thus not leak memory. + /// + /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[requires(new_len <= self.capacity())] + #[requires( + new_len <= self.len + || ub_checks::can_dereference(ptr::slice_from_raw_parts( + self.as_ptr().wrapping_add(self.len), + new_len - self.len, + )) + )] + #[cfg_attr(kani, kani::modifies(&self.len))] + #[ensures(|_| self.len() == new_len)] + pub const unsafe fn set_len(&mut self, new_len: usize) + //@ req *self |-> ?self0 &*& Vec(?t, self0, ?alloc_id, ?ptr, ?capacity, ?length) &*& new_len <= capacity; + //@ ens *self |-> ?self1 &*& Vec(t, self1, alloc_id, ptr, capacity, new_len); + { + const fn precondition_check(new_len: usize, capacity: usize) { + if !(new_len <= capacity) { + let msg = concat!("unsafe precondition(s) violated: ", "Vec::set_len requires that new_len <= capacity()", + " + +This indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety."); + ::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg), false); + } + } + if ::core::ub_checks::check_library_ub() { //~allow_dead_code + precondition_check(new_len, self.capacity()); //~allow_dead_code + } + + //@ open_points_to(self); + self.len = new_len; + //@ open Vec(t, self0, alloc_id, ptr, capacity, length); + //@ let self1 = *self; + //@ close Vec(t, self1, alloc_id, ptr, capacity, new_len); + //@ close_points_to(self); + } + + /// Removes an element from the vector and returns it. + /// + /// The removed element is replaced by the last element of the vector. + /// + /// This does not preserve ordering of the remaining elements, but is *O*(1). + /// If you need to preserve the element order, use [`remove`] instead. + /// + /// [`remove`]: Vec::remove + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec!["foo", "bar", "baz", "qux"]; + /// + /// assert_eq!(v.swap_remove(1), "bar"); + /// assert_eq!(v, ["foo", "qux", "baz"]); + /// + /// assert_eq!(v.swap_remove(0), "foo"); + /// assert_eq!(v, ["baz", "qux"]); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn swap_remove(&mut self, index: usize) -> T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("swap_remove index (is {index}) should be < len (is {len})"); + } + + let len = self.len(); + if index >= len { + assert_failed(index, len); + } + // ignore-tidy-undocumented-unsafe + unsafe { + // We replace self[index] with the last element. Note that if the + // bounds check above succeeds there must be a last element (which + // can be self[index] itself). + let value = ptr::read(self.as_ptr().add(index)); + let base_ptr = self.as_mut_ptr(); + ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); + self.set_len(len - 1); + value + } + } + + /// Inserts an element at position `index` within the vector, shifting all + /// elements after it to the right. + /// + /// # Panics + /// + /// Panics if `index > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!['a', 'b', 'c']; + /// vec.insert(1, 'd'); + /// assert_eq!(vec, ['a', 'd', 'b', 'c']); + /// vec.insert(4, 'e'); + /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be + /// shifted to the right. In the worst case, all elements are shifted when + /// the insertion index is 0. + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "rust1", since = "1.0.0")] + #[track_caller] + pub fn insert(&mut self, index: usize, element: T) { + let _ = self.insert_mut(index, element); + } + + /// Inserts an element at position `index` within the vector, shifting all + /// elements after it to the right, and returning a reference to the new + /// element. + /// + /// # Panics + /// + /// Panics if `index > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 3, 5, 9]; + /// let x = vec.insert_mut(3, 6); + /// *x += 1; + /// assert_eq!(vec, [1, 3, 5, 7, 9]); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be + /// shifted to the right. In the worst case, all elements are shifted when + /// the insertion index is 0. + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "push_mut", since = "1.95.0")] + #[track_caller] + #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"] + pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("insertion index (is {index}) should be <= len (is {len})"); + } + + let len = self.len(); + if index > len { + assert_failed(index, len); + } + + // space for the new element + if len == self.buf.capacity() { + self.buf.grow_one(); + } + + // ignore-tidy-undocumented-unsafe + unsafe { + // infallible + // The spot to put the new value + let p = self.as_mut_ptr().add(index); + { + if index < len { + // Shift everything over to make space. (Duplicating the + // `index`th element into two consecutive places.) + ptr::copy(p, p.add(1), len - index); + } + // Write it in, overwriting the first copy of the `index`th + // element. + ptr::write(p, element); + } + self.set_len(len + 1); + &mut *p + } + } + + /// Removes and returns the element at position `index` within the vector, + /// shifting all elements after it to the left. + /// + /// Note: Because this shifts over the remaining elements, it has a + /// worst-case performance of *O*(*n*). If you don't need the order of elements + /// to be preserved, use [`swap_remove`] instead. If you'd like to remove + /// elements from the beginning of the `Vec`, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`swap_remove`]: Vec::swap_remove + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Panics + /// + /// Panics if `index` is out of bounds. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec!['a', 'b', 'c']; + /// assert_eq!(v.remove(1), 'b'); + /// assert_eq!(v, ['a', 'c']); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[track_caller] + #[rustc_confusables("delete", "take")] + pub fn remove(&mut self, index: usize) -> T { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(index: usize, len: usize) -> ! { + panic!("removal index (is {index}) should be < len (is {len})"); + } + + match self.try_remove(index) { + Some(elem) => elem, + None => assert_failed(index, self.len()), + } + } + + /// Remove and return the element at position `index` within the vector, + /// shifting all elements after it to the left, or [`None`] if it does not + /// exist. + /// + /// Note: Because this shifts over the remaining elements, it has a + /// worst-case performance of *O*(*n*). If you'd like to remove + /// elements from the beginning of the `Vec`, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// assert_eq!(v.try_remove(0), Some(1)); + /// assert_eq!(v.try_remove(2), None); + /// ``` + #[stable(feature = "vec_try_remove", since = "1.101.0")] + #[rustc_confusables("delete", "take", "remove")] + pub fn try_remove(&mut self, index: usize) -> Option { + let len = self.len(); + if index >= len { + return None; + } + // infallible + let ret; + // ignore-tidy-undocumented-unsafe + unsafe { + { + // the place we are taking from. + let ptr = self.as_mut_ptr().add(index); + // copy it out, unsafely having a copy of the value on + // the stack and in the vector at the same time. + ret = ptr::read(ptr); + + // Shift everything down to fill in that spot. + ptr::copy(ptr.add(1), ptr, len - index - 1); + } + self.set_len(len - 1); + } + Some(ret) + } + + /// Retains only the elements specified by the predicate. + /// + /// In other words, remove all elements `e` for which `f(&e)` returns `false`. + /// This method operates in place, visiting each element exactly once in the + /// original order, and preserves the order of the retained elements. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// vec.retain(|&x| x % 2 == 0); + /// assert_eq!(vec, [2, 4]); + /// ``` + /// + /// Because the elements are visited exactly once in the original order, + /// external state may be used to decide which elements to keep. + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4, 5]; + /// let keep = [false, true, true, false, true]; + /// let mut iter = keep.iter(); + /// vec.retain(|_| *iter.next().unwrap()); + /// assert_eq!(vec, [2, 3, 5]); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + pub fn retain(&mut self, mut f: F) + where + F: FnMut(&T) -> bool, + { + self.retain_mut(|elem| f(elem)); + } + + /// Retains only the elements specified by the predicate, passing a mutable reference to it. + /// + /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. + /// This method operates in place, visiting each element exactly once in the + /// original order, and preserves the order of the retained elements. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// vec.retain_mut(|x| if *x <= 3 { + /// *x += 1; + /// true + /// } else { + /// false + /// }); + /// assert_eq!(vec, [2, 3, 4]); + /// ``` + #[stable(feature = "vec_retain_mut", since = "1.61.0")] + pub fn retain_mut(&mut self, mut f: F) + where + F: FnMut(&mut T) -> bool, + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& Vec(t, self0, ?alloc_id, ?base, ?cap, ?len0) &*& + array_at_lft(alloc_id.lft, base, len0, ?elems0) &*& + foreach(elems0, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len0, cap - len0, _) &*& + .own(t, f); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& Vec(t, self1, alloc_id, base, cap, ?len1) &*& + len1 <= len0 &*& + array_at_lft(alloc_id.lft, base, len1, ?elems1) &*& + foreach(elems1, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len1, cap - len1, _); + @*/ + /*@ + safety_proof { + open >.own(_t, ?self0); + call(); + close >.own(_t, *self); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ Vec_inv2(); + //@ let k_len = begin_lifetime(); + //@ share_Vec(k_len, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_Vec_(self_ref); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref), 1/4); + //@ open [?f1]ref_initialized_::>(self_ref)(); + //@ Vec_share__inv(); + //@ open Vec_share_(k_len, t, self_ref, alloc_id, base, cap, len0); + //@ open_frac_borrow(k_len, Vec_frac_borrow_content(self_ref, len0), 1/8); + //@ open [?flen]Vec_frac_borrow_content::(self_ref, len0)(); + let original_len = self.len(); + //@ close [flen]Vec_frac_borrow_content::(self_ref, len0)(); + //@ close_frac_borrow(flen, Vec_frac_borrow_content(self_ref, len0)); + //@ close [f1]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f1, ref_initialized_(self_ref)); + //@ end_lifetime(k_len); + //@ end_share_Vec(self); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + + #[cfg(all(target_arch = "aarch64", target_feature = "sve"))] + { + let long_enough = match mem::size_of::() { + 1 => original_len >= sve_retain::MIN_SVE_SIZE_1, + 2 => original_len >= sve_retain::MIN_SVE_SIZE_2, + 4 => original_len >= sve_retain::MIN_SVE_SIZE_4, + 8 => original_len >= sve_retain::MIN_SVE_SIZE_8, + _ => false, + }; + if long_enough { + // SAFETY: size_of::() is 1, 2, 4 or 8, matching + // the kernel lane widths. + return unsafe { sve_retain::chunked_retain(self, f) }; + } + } + + // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] + // | ^- write ^- read | + // |<- original_len ->| + // Kept: Elements which predicate returns true on. + // Hole: Moved or dropped element slot. + // Unchecked: Unchecked valid elements. + // + // This drop guard will be invoked when predicate or `drop` of element panicked. + // It shifts unchecked elements to cover holes and `set_len` to the correct length. + // In cases when predicate and `drop` never panick, it will be optimized out. + struct PanicGuard<'a, T, A: Allocator> { + v: &'a mut Vec, + read: usize, + write: usize, + original_len: usize, + } + + impl Drop for PanicGuard<'_, T, A> { + #[cold] + fn drop(&mut self) { + let remaining = self.original_len - self.read; + // SAFETY: Trailing unchecked items must be valid since we never touch them. + unsafe { + ptr::copy( + self.v.as_ptr().add(self.read), + self.v.as_mut_ptr().add(self.write), + remaining, + ); + } + // SAFETY: After filling holes, all items are in contiguous memory. + unsafe { + self.v.set_len(self.write + remaining); + } + } + } + + let mut read = 0; + loop { + /*@ + inv thread_token(t) &*& lifetime_token(flft) &*& + 0 <= read &*& read < original_len &*& + *self |-> ?self_cur &*& Vec(t, self_cur, alloc_id, base, cap, original_len) &*& + array_at_lft(alloc_id.lft, base, original_len, ?elems_cur) &*& + foreach(elems_cur, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + original_len, cap - original_len, _) &*& + f |-> ?f_cur &*& .own(t, f_cur); + @*/ + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_lft = lifetime_token_trade(flft, 1/2, alloc_id.lft); + // SAFETY: read < original_len + let cur = unsafe { vec_get_unchecked_mut__VeriFast_wrapper(self, read) }; + //@ assert array_at_lft(alloc_id.lft, base, read, ?pre_e); + let f_ref = &mut f; + let cur_ref = &mut *cur; + let keep = call_fn_mut1__VeriFast_wrapper(f_ref, cur_ref); + //@ close_points_to_at_lft(cur); + //@ lifetime_token_trade_back(q_lft, alloc_id.lft); + //@ array_at_lft_cons::(alloc_id.lft, t, cur, original_len - read - 1); + //@ assert array_at_lft(alloc_id.lft, cur, original_len - read, ?suf1); + //@ array_at_lft_join_len::(alloc_id.lft, base, read, original_len - read); + //@ foreach_append(pre_e, suf1); + if hint_unlikely__VeriFast_wrapper(!keep) { + break; + } + read += 1; + if read == original_len { + // All elements are kept, return early. + return; + } + } + + //@ assert array_at_lft(alloc_id.lft, base, original_len, ?elems_break); + //@ array_at_lft_split::(base, read); + //@ foreach_split(elems_break, own::(t), read); + //@ array_at_lft_uncons::(alloc_id.lft, t, base + read, original_len - read); + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ array_at_lft_inv::(); + //@ mul_mono_l(read, original_len, std::mem::size_of::()); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_drop0 = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(base + read, q_drop0); + // Critical section starts here and at least one element is going to be removed. + // Advance `g.read` early to avoid double drop if `drop_in_place` panicked. + let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len }; + //@ open_points_to(&g); + // SAFETY: previous `read` is always less than original_len. + unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) }; + //@ close_points_to_at_lft_(base + read); + //@ lifetime_token_trade_back(q_drop0, alloc_id.lft); + //@ close array_at_lft_(alloc_id.lft, base + read + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, base + read, 1, _); + //@ close_points_to(&g); + + loop { + /*@ + inv thread_token(t) &*& lifetime_token(flft) &*& + g |-> ?g_cur &*& g_cur.v == self &*& g_cur.original_len == original_len &*& + 0 <= g_cur.write &*& g_cur.write < g_cur.read &*& g_cur.read <= original_len &*& + *self |-> ?self_cur2 &*& Vec(t, self_cur2, alloc_id, base, cap, original_len) &*& + array_at_lft(alloc_id.lft, base, g_cur.write, ?kept) &*& + foreach(kept, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + g_cur.write, g_cur.read - g_cur.write, _) &*& + array_at_lft(alloc_id.lft, base + g_cur.read, original_len - g_cur.read, ?rem) &*& + foreach(rem, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + original_len, cap - original_len, _) &*& + f |-> ?f_cur2 &*& .own(t, f_cur2); + @*/ + //@ open_points_to(&g); + if !(g.read < g.original_len) { + //@ close_points_to(&g); + break; + } + //@ let r_idx = g_cur.read; + //@ let w_idx = g_cur.write; + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ array_at_lft_inv::(); + //@ array_at_lft_uncons::(alloc_id.lft, t, base + r_idx, original_len - r_idx); + //@ array_at_lft_inv::(); + //@ array_at_lft__inv::(); + //@ mul_mono_l(r_idx, original_len, std::mem::size_of::()); + //@ mul_mono_l(w_idx, original_len, std::mem::size_of::()); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_call = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(base + r_idx, q_call / 2); + // SAFETY: `read` is always less than original_len. + let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) }; + let f_ref = &mut f; + let cur_ref = &mut *cur; + let keep = call_fn_mut1__VeriFast_wrapper(f_ref, cur_ref); + //@ assert *(base + r_idx) |-> ?v_cur1; + if !keep { + // Advance `read` early to avoid double drop if `drop_in_place` panicked. + g.read += 1; + // SAFETY: We never touch this element again after dropped. + unsafe { ptr::drop_in_place(cur) }; + //@ close_points_to_at_lft_(base + r_idx); + //@ lifetime_token_trade_back(q_call, alloc_id.lft); + //@ close array_at_lft_(alloc_id.lft, base + r_idx + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, base + r_idx, 1, _); + //@ array_at_lft__join(base + w_idx); + //@ close_points_to(&g); + } else { + // SAFETY: `read` > `write`, so the slots don't overlap. + // We use copy for move, and never touch the source element again. + unsafe { + let hole = g.v.as_mut_ptr().add(g.write); + //@ open array_at_lft_(alloc_id.lft, hole, r_idx - w_idx, _); + //@ open_points_to_at_lft_(hole, q_call / 2); + //@ close array(base + r_idx + 1, 0, []); + //@ close array(base + r_idx, 1, [v_cur1]); + //@ close array_(hole + 1, 0, []); + //@ close array_(hole, 1, _); + ptr::copy_nonoverlapping(cur, hole, 1); + //@ open array(base + r_idx, 1, _); + //@ open array(base + r_idx + 1, 0, _); + //@ open array(hole, 1, _); + //@ open array(hole + 1, 0, _); + //@ close_points_to_at_lft_(base + r_idx); + //@ close_points_to_at_lft(hole); + //@ lifetime_token_trade_back(q_call, alloc_id.lft); + //@ array_at_lft_snoc_own::(alloc_id.lft, t, base, w_idx); + //@ close array_at_lft_(alloc_id.lft, base + r_idx + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, base + r_idx, 1, _); + //@ array_at_lft__join(hole + 1); + } + g.write += 1; + g.read += 1; + //@ close_points_to(&g); + } + } + + //@ array_at_lft__join(base + g_cur.write); + //@ open array_at_lft(alloc_id.lft, base + original_len, 0, _); + //@ open foreach([], own::(t)); + //@ open_points_to(&g); + // We are leaving the critical section and no panic happened, + // Commit the length change and forget the guard. + // SAFETY: `write` is always less than or equal to original_len. + unsafe { g.v.set_len(g.write) }; + //@ let final_len = g_cur.write; + //@ close_points_to(&g); + //@ assert g_cur.v == self &*& g_cur.write == final_len &*& 0 <= g_cur.write &*& g_cur.write <= g_cur.read &*& g_cur.read <= g_cur.original_len; + //@ let k_g = begin_lifetime(); + //@ close Vec_exact_fbc::(t, self, alloc_id, base, cap, final_len)(); + //@ borrow(k_g, Vec_exact_fbc::(t, self, alloc_id, base, cap, final_len)); + //@ close exists::>>(pair(k_g, g_cur.v)); + //@ close exists::>>(pair(alloc_id, pair(base, cap))); + //@ close exists::>>(pair(g_cur.write, pair(g_cur.read, g_cur.original_len))); + unsafe { forget_vec_guard__VeriFast_wrapper::(g) }; + //@ end_lifetime(k_g); + //@ borrow_end(k_g, Vec_exact_fbc::(t, self, alloc_id, base, cap, final_len)); + //@ open Vec_exact_fbc::(t, self, alloc_id, base, cap, final_len)(); + } + + /// Retains only the elements specified by the predicate, passing a mutable reference to it. + /// + /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. + /// This method does not maintain the relative order of the retained elements. If order matters, + /// consider using [`Vec::retain_mut`] instead. However, if no items are removed, then all items + /// are left in their original positions. + /// + /// Generally, this method is faster than [`Vec::retain_mut`] due to its weak ordering guarantees. + /// + /// [`Vec::retain_mut`]: crate::vec::Vec::retain_mut + /// + /// Time complexity: *O*(*n*) + /// + /// + /// # Examples + /// + /// ``` + /// #![feature(retain_unstable)] + /// let mut vec = vec![4, 3, 2, 1]; + /// vec.retain_unstable(|x| if *x <= 3 { + /// *x += 1; + /// true + /// } else { + /// false + /// }); + /// + /// vec.sort(); // it might be in any order, so normalize before asserting + /// assert_eq!(vec, [2, 3, 4]); + /// ``` + #[unstable(feature = "retain_unstable", issue = "164152")] + pub fn retain_unstable(&mut self, mut f: F) + where + F: FnMut(&mut T) -> bool, + { + // Currently this does the following: + // 1) Search backward until you find an element you want to remove + // 2) Swap this element with an element that was kept in the back + // (or if there are no remaining elements, simply truncate the vec) + // 3) Repeat from 1) until there's no element to iterate through + + let original_len = self.len(); + + if original_len == 0 { + // Empty case: explicit return allows better optimization, vs letting compiler infer it + return; + } + + let mut read_back = original_len; + let mut hole = loop { + if read_back == 0 { + // All elements are kept + return; + } + // SAFETY: read_back - 1 < original_len + let cur = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) }; + if hint::unlikely(!f(cur)) { + break cur; + } + read_back -= 1; + }; + + if read_back < self.len { + let swap = self.pop().unwrap(); + *hole = swap; + } else { + self.truncate(self.len - 1); + } + read_back -= 1; + + while read_back > 0 { + // SAFETY: read_back - 1 is always less than current length of + // the vector and the loop condition, read_back > 0, prevents + // read_back from underflowing + hole = unsafe { &mut *self.as_mut_ptr().add(read_back - 1) }; + if !f(hole) { + if read_back < self.len { + let swap = self.pop().unwrap(); + *hole = swap; + } else { + self.truncate(self.len - 1); + } + } + read_back -= 1; + } + } + + /// Removes all but the first of consecutive elements in the vector that resolve to the same + /// key. + /// + /// If the vector is sorted, this removes all duplicates. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![10, 20, 21, 30, 20]; + /// + /// vec.dedup_by_key(|i| *i / 10); + /// + /// assert_eq!(vec, [10, 20, 30, 20]); + /// ``` + #[stable(feature = "dedup_by", since = "1.16.0")] + #[inline] + pub fn dedup_by_key(&mut self, mut key: F) + where + F: FnMut(&mut T) -> K, + K: PartialEq, + { + self.dedup_by(|a, b| key(a) == key(b)) + } + + /// Removes all but the first of consecutive elements in the vector that are + /// "equal" according to the given predicate function. + /// + /// The predicate `same_bucket(x, p)` is passed references to two elements. + /// If it returns `true`, the element `x` is removed from the vector. + /// + /// The element `p` occurs *before* `x` in the vector (`[.., p, .., x, ..]`), + /// so `same_bucket(x, p)` is receiving them in reversed order (unlike [`windows`]). + /// + /// If the vector is sorted, this removes all duplicates. For more complicated predicates + /// however, the order (ascending vs. descending) can matter. + /// + /// [`windows`]: slice::windows + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; + /// vec.dedup_by(|x, p| x.eq_ignore_ascii_case(p)); + /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); + /// ``` + /// + /// Both references passed to `same_bucket` are mutable. + /// This allows merging elements by mutating `p` and returning `true`: + /// + /// ``` + /// let mut ranges = vec![1..2, 2..4, 2..5, 8..9]; + /// + /// // Sort ranges by start, and if equal, by end (lexicographically) + /// // Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail + /// ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end))); + /// + /// // Merge touching (`1..2` and `2..4`) and then overlapping (`1..4` and `2..5`) ranges + /// ranges.dedup_by(|x, p| { + /// if p.end >= x.start { + /// p.end = p.end.max(x.end); + /// true + /// } else { + /// false + /// } + /// }); + /// + /// assert_eq!(ranges, [1..5, 8..9]); + /// ``` + #[stable(feature = "dedup_by", since = "1.16.0")] + pub fn dedup_by(&mut self, mut same_bucket: F) + where + F: FnMut(&mut T, &mut T) -> bool, + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& Vec(t, self0, ?alloc_id, ?base, ?cap, ?len0) &*& + array_at_lft(alloc_id.lft, base, len0, ?elems0) &*& + foreach(elems0, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len0, cap - len0, _) &*& + .own(t, same_bucket); + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& Vec(t, self1, alloc_id, base, cap, ?len1) &*& + len1 <= len0 &*& (len0 == 0 || len1 >= 1) &*& + array_at_lft(alloc_id.lft, base, len1, ?elems1) &*& + foreach(elems1, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len1, cap - len1, _); + @*/ + /*@ + safety_proof { + open >.own(_t, ?self0); + call(); + close >.own(_t, *self); + } + @*/ + { + //@ assert lifetime_token(?flft); + //@ Vec_inv2(); + //@ let k_len = begin_lifetime(); + //@ share_Vec(k_len, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_Vec_(self_ref); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref), 1/4); + //@ open [?f1]ref_initialized_::>(self_ref)(); + //@ Vec_share__inv(); + //@ open Vec_share_(k_len, t, self_ref, alloc_id, base, cap, len0); + //@ open_frac_borrow(k_len, Vec_frac_borrow_content(self_ref, len0), 1/8); + //@ open [?flen]Vec_frac_borrow_content::(self_ref, len0)(); + let len = self.len(); + //@ close [flen]Vec_frac_borrow_content::(self_ref, len0)(); + //@ close_frac_borrow(flen, Vec_frac_borrow_content(self_ref, len0)); + //@ close [f1]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f1, ref_initialized_(self_ref)); + //@ end_lifetime(k_len); + //@ end_share_Vec(self); + if len <= 1 { + return; + } + + // Check if we ever want to remove anything. + // This allows to use copy_non_overlapping in next cycle. + // And avoids any memory writes if we don't need to remove anything. + let mut first_duplicate_idx: usize = 1; + let start = self.as_mut_ptr(); + loop { + /*@ + inv thread_token(t) &*& lifetime_token(flft) &*& + 1 <= first_duplicate_idx &*& first_duplicate_idx <= len &*& + *self |-> ?self_cur &*& Vec(t, self_cur, alloc_id, start, cap, len) &*& + array_at_lft(alloc_id.lft, start, len, ?elems_cur) &*& + foreach(elems_cur, own::(t)) &*& + array_at_lft_(alloc_id.lft, start + len, cap - len, _) &*& + same_bucket |-> ?sb_cur &*& .own(t, sb_cur); + @*/ + if !(first_duplicate_idx != len) { + break; + } + let found_duplicate = { + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ array_at_lft_inv(); + //@ array_at_lft_split(start, first_duplicate_idx); + //@ foreach_split(elems_cur, own::(t), first_duplicate_idx); + //@ array_at_lft_unsnoc::(alloc_id.lft, t, start, first_duplicate_idx); + //@ array_at_lft_uncons::(alloc_id.lft, t, start + first_duplicate_idx, len - first_duplicate_idx); + //@ array_at_lft_inv::(); + //@ mul_mono_l(first_duplicate_idx - 1, len, std::mem::size_of::()); + //@ mul_mono_l(first_duplicate_idx, len, std::mem::size_of::()); + // SAFETY: first_duplicate always in range [1..len). + // Note that we start iteration from 1 so we never overflow. + let prev = unsafe { start.add(first_duplicate_idx.wrapping_sub(1)) }; + // ignore-tidy-undocumented-unsafe + let current = unsafe { start.add(first_duplicate_idx) }; + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_lft = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(prev, q_lft / 2); + //@ open_points_to_at_lft(current, q_lft / 2); + // We explicitly say in docs that references are reversed. + // ignore-tidy-undocumented-unsafe + let f = &mut same_bucket; + let a = unsafe { &mut *current }; + let b = unsafe { &mut *prev }; + let r = call_fn_mut2__VeriFast_wrapper(f, a, b); + //@ close_points_to_at_lft(current); + //@ close_points_to_at_lft(prev); + //@ lifetime_token_trade_back(q_lft, alloc_id.lft); + //@ array_at_lft_cons::(alloc_id.lft, t, current, len - first_duplicate_idx - 1); + //@ array_at_lft_snoc_own::(alloc_id.lft, t, start, first_duplicate_idx - 1); + //@ assert array_at_lft(alloc_id.lft, start, first_duplicate_idx, ?pre1); + //@ assert array_at_lft(alloc_id.lft, current, len - first_duplicate_idx, ?suf1); + //@ array_at_lft_join(start); + //@ foreach_append(pre1, suf1); + r + }; + if found_duplicate { + break; + } + first_duplicate_idx += 1; + } + // Don't need to remove anything. + // We cannot get bigger than len. + if first_duplicate_idx == len { + return; + } + // SAFETY: first_duplicate_idx always in range [1..len) + unsafe { + self.dedup_tail(same_bucket, first_duplicate_idx); + } + } + + /// Continues deduplication after the first duplicate is found. + /// + /// The function treats `self[first_duplicate]` as the first duplicated + /// element and drops it. + /// + /// # Safety + /// + /// `1 <= first_duplicate < self.len()` + unsafe fn dedup_tail(&mut self, mut same_bucket: F, first_duplicate: usize) + where + F: FnMut(&mut T, &mut T) -> bool, + /*@ + req thread_token(?t) &*& t == currentThread &*& + *self |-> ?self0 &*& Vec(t, self0, ?alloc_id, ?base, ?cap, ?len0) &*& + array_at_lft(alloc_id.lft, base, len0, ?elems0) &*& + foreach(elems0, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len0, cap - len0, _) &*& + .own(t, same_bucket) &*& + 1 <= first_duplicate &*& first_duplicate < len0; + @*/ + /*@ + ens thread_token(t) &*& + *self |-> ?self1 &*& Vec(t, self1, alloc_id, base, cap, ?len1) &*& + 1 <= len1 &*& len1 <= len0 &*& + array_at_lft(alloc_id.lft, base, len1, ?elems1) &*& + foreach(elems1, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len1, cap - len1, _); + @*/ + { + //@ assert lifetime_token(?flft); + //@ Vec_inv2(); + /* INVARIANT: vec.len() > read > write > write-1 >= 0 */ + struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { + /* Offset of the element we want to check if it is duplicate */ + read: usize, + + /* Offset of the place where we want to place the non-duplicate + * when we find it. */ + write: usize, + + /* The Vec that would need correction if `same_bucket` panicked */ + vec: &'a mut Vec, + } + + impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> { + fn drop(&mut self) { + /* This code gets executed when `same_bucket` panics */ + + // SAFETY: invariant guarantees that `read - write` + // and `len - read` never overflow and that the copy is always + // in-bounds. + unsafe { + let ptr = self.vec.as_mut_ptr(); + let len = self.vec.len(); + + /* How many items were left when `same_bucket` panicked. + * Basically vec[read..].len() */ + let items_left = len.wrapping_sub(self.read); + + /* Pointer to first item in vec[write..write+items_left] slice */ + let dropped_ptr = ptr.add(self.write); + /* Pointer to first item in vec[read..] slice */ + let valid_ptr = ptr.add(self.read); + + /* Copy `vec[read..]` to `vec[write..write+items_left]`. + * The slices can overlap, so `copy_nonoverlapping` cannot be used */ + ptr::copy(valid_ptr, dropped_ptr, items_left); + + /* How many items have been already dropped + * Basically vec[read..write].len() */ + let dropped = self.read.wrapping_sub(self.write); + + self.vec.set_len(len - dropped); + } + } + } + + let start = self.as_mut_ptr(); + //@ let k_len = begin_lifetime(); + //@ share_Vec(k_len, self); + //@ let self_ref = precreate_ref(self); + //@ init_ref_Vec_(self_ref); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref), 1/4); + //@ open [?f1]ref_initialized_::>(self_ref)(); + //@ Vec_share__inv(); + //@ open Vec_share_(k_len, t, self_ref, alloc_id, start, cap, len0); + //@ open_frac_borrow(k_len, Vec_frac_borrow_content(self_ref, len0), 1/8); + //@ open [?flen]Vec_frac_borrow_content::(self_ref, len0)(); + let len = self.len(); + //@ close [flen]Vec_frac_borrow_content::(self_ref, len0)(); + //@ close_frac_borrow(flen, Vec_frac_borrow_content(self_ref, len0)); + //@ close [f1]ref_initialized_::>(self_ref)(); + //@ close_frac_borrow(f1, ref_initialized_(self_ref)); + //@ end_lifetime(k_len); + //@ end_share_Vec(self); + + /* Drop items while going through Vec, it should be more efficient than + * doing slice partition_dedup + truncate */ + + // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics. + let mut gap = + FillGapOnDrop { read: first_duplicate + 1, write: first_duplicate, vec: self }; + + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ array_at_lft_inv(); + //@ array_at_lft_split(start, first_duplicate); + //@ foreach_split(elems0, own::(t), first_duplicate); + //@ array_at_lft_uncons::(alloc_id.lft, t, start + first_duplicate, len - first_duplicate); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_drop0 = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(start + first_duplicate, q_drop0); + //@ mul_mono_l(first_duplicate, len, std::mem::size_of::()); + // SAFETY: By this function's safety contract, `first_duplicate < self.len()`. + // If drop panics, `gap` would remove this item without drop. + unsafe { + ptr::drop_in_place(start.add(first_duplicate)); + } + //@ close_points_to_at_lft_(start + first_duplicate); + //@ lifetime_token_trade_back(q_drop0, alloc_id.lft); + //@ close array_at_lft_(alloc_id.lft, start + first_duplicate + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, start + first_duplicate, 1, _); + + // SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr + // are always in-bounds and read_ptr never aliases prev_ptr + unsafe { + loop { + /*@ + inv thread_token(t) &*& lifetime_token(flft) &*& + gap |-> ?gap_cur &*& gap_cur.vec == self &*& + 1 <= gap_cur.write &*& gap_cur.write < gap_cur.read &*& gap_cur.read <= len &*& + *self |-> ?self_cur &*& Vec(t, self_cur, alloc_id, start, cap, len) &*& + array_at_lft(alloc_id.lft, start, gap_cur.write, ?kept) &*& + foreach(kept, own::(t)) &*& + array_at_lft_(alloc_id.lft, start + gap_cur.write, gap_cur.read - gap_cur.write, _) &*& + array_at_lft(alloc_id.lft, start + gap_cur.read, len - gap_cur.read, ?rem) &*& + foreach(rem, own::(t)) &*& + array_at_lft_(alloc_id.lft, start + len, cap - len, _) &*& + same_bucket |-> ?sb_cur &*& .own(t, sb_cur); + @*/ + //@ open_points_to(&gap); + if !(gap.read < len) { + //@ close_points_to(&gap); + break; + } + //@ let r_idx = gap_cur.read; + //@ let w_idx = gap_cur.write; + //@ size_align::(); + //@ std::alloc::Layout_inv(std::alloc::Layout::new::()); + //@ array_at_lft_inv::(); + //@ array_at_lft_unsnoc::(alloc_id.lft, t, start, w_idx); + //@ array_at_lft_uncons::(alloc_id.lft, t, start + r_idx, len - r_idx); + //@ array_at_lft_inv::(); + //@ array_at_lft__inv::(); + //@ mul_mono_l(r_idx, len, std::mem::size_of::()); + //@ mul_mono_l(w_idx - 1, len, std::mem::size_of::()); + //@ mul_mono_l(w_idx, len, std::mem::size_of::()); + let read_ptr = start.add(gap.read); + let prev_ptr = start.add(gap.write.wrapping_sub(1)); + + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id.lft); + //@ let q_call = lifetime_token_trade(flft, 1/2, alloc_id.lft); + //@ open_points_to_at_lft(prev_ptr, q_call / 2); + //@ open_points_to_at_lft(read_ptr, q_call / 2); + // We explicitly say in docs that references are reversed. + let f = &mut same_bucket; + let a = unsafe { &mut *read_ptr }; + let b = unsafe { &mut *prev_ptr }; + let found_duplicate = call_fn_mut2__VeriFast_wrapper(f, a, b); + //@ assert *read_ptr |-> ?v_read1; + //@ close_points_to_at_lft(prev_ptr); + //@ array_at_lft_snoc_own::(alloc_id.lft, t, start, w_idx - 1); + //@ assert array_at_lft(alloc_id.lft, start, w_idx, ?kept1); + if found_duplicate { + // Increase `gap.read` now since the drop may panic. + gap.read += 1; + /* We have found duplicate, drop it in-place */ + ptr::drop_in_place(read_ptr); + //@ close_points_to_at_lft_(read_ptr); + //@ lifetime_token_trade_back(q_call, alloc_id.lft); + //@ close array_at_lft_(alloc_id.lft, read_ptr + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, read_ptr, 1, _); + //@ array_at_lft__join(start + w_idx); + //@ close_points_to(&gap); + } else { + let write_ptr = start.add(gap.write); + //@ open array_at_lft_(alloc_id.lft, write_ptr, r_idx - w_idx, _); + //@ open_points_to_at_lft_(write_ptr, q_call / 2); + //@ close array(read_ptr + 1, 0, []); + //@ close array(read_ptr, 1, [v_read1]); + //@ close array_(write_ptr + 1, 0, []); + //@ close array_(write_ptr, 1, _); + /* read_ptr cannot be equal to write_ptr because at this point + * we guaranteed to skip at least one element (before loop starts). + */ + ptr::copy_nonoverlapping(read_ptr, write_ptr, 1); + //@ open array(read_ptr, 1, _); + //@ open array(read_ptr + 1, 0, _); + //@ open array(write_ptr, 1, _); + //@ open array(write_ptr + 1, 0, _); + //@ close_points_to_at_lft_(read_ptr); + //@ close_points_to_at_lft(write_ptr); + //@ lifetime_token_trade_back(q_call, alloc_id.lft); + //@ array_at_lft_snoc_own::(alloc_id.lft, t, start, w_idx); + //@ close array_at_lft_(alloc_id.lft, read_ptr + 1, 0, []); + //@ close array_at_lft_(alloc_id.lft, read_ptr, 1, _); + //@ array_at_lft__join(write_ptr + 1); + + /* We have filled that place, so go further */ + gap.write += 1; + gap.read += 1; + //@ close_points_to(&gap); + } + } + + //@ array_at_lft__join(start + gap_cur.write); + //@ open array_at_lft(alloc_id.lft, start + len, 0, _); + //@ open foreach([], own::(t)); + //@ open_points_to(&gap); + /* Technically we could let `gap` clean up with its Drop, but + * when `same_bucket` is guaranteed to not panic, this bloats a little + * the codegen, so we just do it manually */ + gap.vec.set_len(gap.write); + //@ let final_len = gap_cur.write; + //@ close_points_to(&gap); + //@ assert gap_cur.vec == self &*& gap_cur.write == final_len &*& 1 <= gap_cur.write &*& gap_cur.write <= gap_cur.read &*& gap_cur.read <= len; + //@ let k_gap = begin_lifetime(); + //@ close Vec_exact_fbc::(t, self, alloc_id, start, cap, final_len)(); + //@ borrow(k_gap, Vec_exact_fbc::(t, self, alloc_id, start, cap, final_len)); + //@ close exists::>>(pair(k_gap, gap_cur.vec)); + //@ close exists::>>(pair(alloc_id, pair(start, cap))); + //@ close exists::>>(pair(gap_cur.write, pair(gap_cur.read, len))); + forget_vec_guard__VeriFast_wrapper::(gap); + //@ end_lifetime(k_gap); + //@ borrow_end(k_gap, Vec_exact_fbc::(t, self, alloc_id, start, cap, final_len)); + //@ open Vec_exact_fbc::(t, self, alloc_id, start, cap, final_len)(); + } + } + + /// Appends an element and returns a reference to it if there is sufficient spare capacity, + /// otherwise an error is returned with the element. + /// + /// Unlike [`push`] this method will not reallocate when there's insufficient capacity. + /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. + /// + /// [`push`]: Vec::push + /// [`reserve`]: Vec::reserve + /// [`try_reserve`]: Vec::try_reserve + /// + /// # Examples + /// + /// A manual, panic-free alternative to [`FromIterator`]: + /// + /// ``` + /// #![feature(vec_push_within_capacity)] + /// + /// use std::collections::TryReserveError; + /// fn from_iter_fallible(iter: impl Iterator) -> Result, TryReserveError> { + /// let mut vec = Vec::new(); + /// for value in iter { + /// if let Err(value) = vec.push_within_capacity(value) { + /// vec.try_reserve(1)?; + /// // this cannot fail, the previous line either returned or added at least 1 free slot + /// let _ = vec.push_within_capacity(value); + /// } + /// } + /// Ok(vec) + /// } + /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100))); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*(1) time. + #[inline] + #[unstable(feature = "vec_push_within_capacity", issue = "100486")] + pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> { + if self.len == self.buf.capacity() { + return Err(value); + } + + // ignore-tidy-undocumented-unsafe + let end = unsafe { self.as_mut_ptr().add(self.len) }; + // ignore-tidy-undocumented-unsafe + unsafe { ptr::write(end, value) }; + self.len += 1; + + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + Ok(unsafe { &mut *end }) + } + + /// Removes the last element from a vector and returns it, or [`None`] if it + /// is empty. + /// + /// If you'd like to pop the first element, consider using + /// [`VecDeque::pop_front`] instead. + /// + /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// assert_eq!(vec.pop(), Some(3)); + /// assert_eq!(vec, [1, 2]); + /// ``` + /// + /// # Time complexity + /// + /// Takes *O*(1) time. + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_pop"] + pub fn pop(&mut self) -> Option { + if self.len == 0 { + None + } else { + self.len -= 1; + // ignore-tidy-undocumented-unsafe + unsafe { + core::hint::assert_unchecked(self.len < self.capacity()); + Some(ptr::read(self.as_ptr().add(self.len()))) + } + } + } + + /// Removes and returns the last element from a vector if the predicate + /// returns `true`, or [`None`] if the predicate returns false or the vector + /// is empty (the predicate will not be called in that case). + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3, 4]; + /// let pred = |x: &mut i32| *x % 2 == 0; + /// + /// assert_eq!(vec.pop_if(pred), Some(4)); + /// assert_eq!(vec, [1, 2, 3]); + /// assert_eq!(vec.pop_if(pred), None); + /// ``` + #[stable(feature = "vec_pop_if", since = "1.86.0")] + pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option { + let last = self.last_mut()?; + if predicate(last) { self.pop() } else { None } + } + + /// Returns a mutable reference to the last item in the vector, or + /// `None` if it is empty. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(vec_peek_mut)] + /// let mut vec = Vec::new(); + /// assert!(vec.peek_mut().is_none()); + /// + /// vec.push(1); + /// vec.push(5); + /// vec.push(2); + /// assert_eq!(vec.last(), Some(&2)); + /// if let Some(mut val) = vec.peek_mut() { + /// *val = 0; + /// } + /// assert_eq!(vec.last(), Some(&0)); + /// ``` + #[inline] + #[unstable(feature = "vec_peek_mut", issue = "122742")] + pub fn peek_mut(&mut self) -> Option> + where + A: AllocatorNightly, + { + PeekMut::new(self) + } + + /// Moves all the elements of `other` into `self`, leaving `other` empty. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// let mut vec2 = vec![4, 5, 6]; + /// vec.append(&mut vec2); + /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); + /// assert_eq!(vec2, []); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "append", since = "1.4.0")] + pub fn append(&mut self, other: &mut Self) { + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements(other.as_slice() as _); + other.set_len(0); + } + } + + /// Appends elements to `self` from other buffer. + #[cfg(not(no_global_oom_handling))] + #[inline] + unsafe fn append_elements(&mut self, other: *const [T]) { + self.reserve(other.len()); + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements_unreserved(other); + } + } + + /// Appends elements to `self` from other buffer, returning [`TryReserveError`] on OOM. + #[inline] + unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> { + self.try_reserve(other.len())?; + // ignore-tidy-undocumented-unsafe + unsafe { + self.append_elements_unreserved(other); + } + Ok(()) + } + + /// Appends elements to `self` from other buffer without reserving additional capacity. + #[inline] + unsafe fn append_elements_unreserved(&mut self, other: *const [T]) { + let count = other.len(); + let len = self.len(); + if count > 0 { + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) + }; + } + self.len += count; + } + + /// Removes the subslice indicated by the given range from the vector, + /// returning a double-ended iterator over the removed subslice. + /// + /// If the iterator is dropped before being fully consumed, + /// it drops the remaining removed elements. + /// + /// The returned iterator keeps a mutable borrow on the vector to optimize + /// its implementation. + /// + /// # Panics + /// + /// Panics if the range has `start_bound > end_bound`, or, if the range is + /// bounded on either end and past the length of the vector. + /// + /// # Leaking + /// + /// If the returned iterator goes out of scope without being dropped (due to + /// [`mem::forget`], for example), the vector may have lost and leaked + /// elements arbitrarily, including elements outside the range. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// let u: Vec<_> = v.drain(1..).collect(); + /// assert_eq!(v, &[1]); + /// assert_eq!(u, &[2, 3]); + /// + /// // A full range clears the vector, like `clear()` does + /// v.drain(..); + /// assert_eq!(v, &[]); + /// ``` + #[stable(feature = "drain", since = "1.6.0")] + pub fn drain(&mut self, range: R) -> Drain<'_, T, A> + where + A: AllocatorNightly, + R: RangeBounds, + { + // Memory safety + // + // When the Drain is first created, it shortens the length of + // the source vector to make sure no uninitialized or moved-from elements + // are accessible at all if the Drain's destructor never gets to run. + // + // Drain will ptr::read out the values to remove. + // When finished, remaining tail of the vec is copied back to cover + // the hole, and the vector length is restored to the new length. + // + let len = self.len(); + let Range { start, end } = slice::range(range, ..len); + + // ignore-tidy-undocumented-unsafe + unsafe { + // set self.vec length's to start, to be safe in case Drain is leaked + self.set_len(start); + let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start); + Drain { + tail_start: end, + tail_len: len - end, + iter: range_slice.iter(), + vec: NonNull::from(self), + } + } + } + + /// Clears the vector, removing all values. + /// + /// Note that this method has no effect on the allocated capacity + /// of the vector. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3]; + /// + /// v.clear(); + /// + /// assert!(v.is_empty()); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn clear(&mut self) { + // Though this is equivalent to `truncate(0)`, the manual version + // optimizes better, justifying the additional complexity + // (see #96002 and #154095 for context). + + let elems: *mut [T] = self.as_mut_slice(); + + // SAFETY: + // - `elems` comes directly from `as_mut_slice` and is therefore valid. + // - Setting `self.len` before calling `drop_in_place` means that, + // if an element's `Drop` impl panics, the vector's `Drop` impl will + // do nothing (leaking the rest of the elements) instead of dropping + // some twice. + unsafe { + self.len = 0; + ptr::drop_in_place(elems); + } + } + + /// Returns the number of elements in the vector, also referred to + /// as its 'length'. + /// + /// # Examples + /// + /// ``` + /// let a = vec![1, 2, 3]; + /// assert_eq!(a.len(), 3); + /// ``` + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + #[rustc_confusables("length", "size")] + pub const fn len<'a>(&'a self) -> usize + //@ req [?f](*self).len |-> ?length &*& length <= std::mem::MAX_SLICE_LEN::(); + //@ ens [f](*self).len |-> length &*& result == length; + /*@ + safety_proof { + open >.share('a, _t, self); + Vec_share__inv(); + open Vec_share_('a, currentThread, self, ?alloc_id, ?ptr, ?capacity, ?length); + open_frac_borrow('a, Vec_frac_borrow_content(self, length), _q_a); + open [?f]Vec_frac_borrow_content::(self, length)(); + let result = call(); + close [f]Vec_frac_borrow_content::(self, length)(); + close_frac_borrow(f, Vec_frac_borrow_content(self, length)); + } + @*/ + { + let len = self.len; + + // SAFETY: The maximum capacity of `Vec` is `isize::MAX` bytes, so the maximum value can + // be returned is `usize::checked_div(size_of::()).unwrap_or(usize::MAX)`, which + // matches the definition of `T::MAX_SLICE_LEN`. + unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) }; + + len + } + + /// Returns `true` if the vector contains no elements. + /// + /// # Examples + /// + /// ``` + /// let mut v = Vec::new(); + /// assert!(v.is_empty()); + /// + /// v.push(1); + /// assert!(!v.is_empty()); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_diagnostic_item = "vec_is_empty"] + #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")] + pub const fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Splits the collection into two at the given index. + /// + /// Returns a newly allocated vector containing the elements in the range + /// `[at, len)`. After the call, the original vector will be left containing + /// the elements `[0, at)` with its previous capacity unchanged. + /// + /// - If you want to take ownership of the entire contents and capacity of + /// the vector, see [`mem::take`] or [`mem::replace`]. + /// - If you don't need the returned vector at all, see [`Vec::truncate`]. + /// - If you want to take ownership of an arbitrary subslice, or you don't + /// necessarily want to store the removed items in a vector, see [`Vec::drain`]. + /// + /// # Panics + /// + /// Panics if `at > len`. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!['a', 'b', 'c']; + /// let vec2 = vec.split_off(1); + /// assert_eq!(vec, ['a']); + /// assert_eq!(vec2, ['b', 'c']); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[must_use = "use `.truncate()` if you don't need the other half"] + #[stable(feature = "split_off", since = "1.4.0")] + #[track_caller] + pub fn split_off(&mut self, at: usize) -> Self + where + A: Clone, + { + #[cold] + #[cfg_attr(not(panic = "immediate-abort"), inline(never))] + #[track_caller] + #[optimize(size)] + fn assert_failed(at: usize, len: usize) -> ! { + panic!("`at` split index (is {at}) should be <= len (is {len})"); + } + + if at > self.len() { + assert_failed(at, self.len()); + } + + let other_len = self.len - at; + let mut other = Vec::with_capacity_in(other_len, self.allocator().clone()); + + // Unsafely `set_len` and copy items to `other`. + // ignore-tidy-undocumented-unsafe + unsafe { + self.set_len(at); + other.set_len(other_len); + + ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); + } + other + } + + /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the `Vec` is extended by the + /// difference, with each additional slot filled with the result of + /// calling the closure `f`. The return values from `f` will end up + /// in the `Vec` in the order they have been generated. + /// + /// If `new_len` is less than or equal to `len`, the `Vec` is simply + /// truncated. + /// + /// This method uses a closure to create new values on every push. If + /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you + /// want to use the [`Default`] trait to generate values, you can + /// pass [`Default::default`] as the second argument. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 3]; + /// vec.resize_with(5, Default::default); + /// assert_eq!(vec, [1, 2, 3, 0, 0]); + /// + /// let mut vec = vec![]; + /// let mut p = 1; + /// vec.resize_with(4, || { p *= 2; p }); + /// assert_eq!(vec, [2, 4, 8, 16]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_resize_with", since = "1.33.0")] + pub fn resize_with(&mut self, new_len: usize, f: F) + where + F: FnMut() -> T, + { + let len = self.len(); + if new_len > len { + self.extend_trusted(iter::repeat_with(f).take(new_len - len)); + } else { + self.truncate(new_len); + } + } + + /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, + /// `&'a mut [T]`. + /// + /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type + /// has only static references, or none at all, then this may be chosen to be + /// `'static`. + /// + /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, + /// so the leaked allocation may include unused capacity that is not part + /// of the returned slice. + /// + /// This function is mainly useful for data that lives for the remainder of + /// the program's life. Dropping the returned reference will cause a memory + /// leak. + /// + /// # Examples + /// + /// Simple usage: + /// + /// ``` + /// let x = vec![1, 2, 3]; + /// let static_ref: &'static mut [usize] = x.leak(); + /// static_ref[0] += 1; + /// assert_eq!(static_ref, &[2, 2, 3]); + /// # // FIXME(https://github.com/rust-lang/miri/issues/3670): + /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak. + /// # drop(unsafe { Box::from_raw(static_ref) }); + /// ``` + #[stable(feature = "vec_leak", since = "1.47.0")] + #[inline] + pub fn leak<'a>(self) -> &'a mut [T] + where + A: 'a, + { + let mut me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) } + } + + /// Returns the remaining spare capacity of the vector as a slice of + /// `MaybeUninit`. + /// + /// The returned slice can be used to fill the vector with data (e.g. by + /// reading from a file) before marking the data as initialized using the + /// [`set_len`] method. + /// + /// [`set_len`]: Vec::set_len + /// + /// # Examples + /// + /// ``` + /// // Allocate vector big enough for 10 elements. + /// let mut v = Vec::with_capacity(10); + /// + /// // Fill in the first 3 elements. + /// let uninit = v.spare_capacity_mut(); + /// uninit[0].write(0); + /// uninit[1].write(1); + /// uninit[2].write(2); + /// + /// // Mark the first 3 elements of the vector as being initialized. + /// unsafe { + /// v.set_len(3); + /// } + /// + /// assert_eq!(&v, &[0, 1, 2]); + /// ``` + #[stable(feature = "vec_spare_capacity", since = "1.60.0")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + // Note: + // This method is not implemented in terms of `split_at_spare_mut`, + // to prevent invalidation of pointers to the buffer. + // ignore-tidy-undocumented-unsafe + unsafe { + slice::from_raw_parts_mut( + self.as_mut_ptr().add(self.len) as *mut MaybeUninit, + self.buf.capacity() - self.len, + ) + } + } + + /// Returns vector content as a slice of `T`, along with the remaining spare + /// capacity of the vector as a slice of `MaybeUninit`. + /// + /// The returned spare capacity slice can be used to fill the vector with data + /// (e.g. by reading from a file) before marking the data as initialized using + /// the [`set_len`] method. + /// + /// [`set_len`]: Vec::set_len + /// + /// Note that this is a low-level API, which should be used with care for + /// optimization purposes. If you need to append data to a `Vec` + /// you can use [`push`], [`extend`], [`extend_from_slice`], + /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or + /// [`resize_with`], depending on your exact needs. + /// + /// [`push`]: Vec::push + /// [`extend`]: Vec::extend + /// [`extend_from_slice`]: Vec::extend_from_slice + /// [`extend_from_within`]: Vec::extend_from_within + /// [`insert`]: Vec::insert + /// [`append`]: Vec::append + /// [`resize`]: Vec::resize + /// [`resize_with`]: Vec::resize_with + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_split_at_spare)] + /// + /// let mut v = vec![1, 1, 2]; + /// + /// // Reserve additional space big enough for 10 elements. + /// v.reserve(10); + /// + /// let (init, uninit) = v.split_at_spare_mut(); + /// let sum = init.iter().copied().sum::(); + /// + /// // Fill in the next 4 elements. + /// uninit[0].write(sum); + /// uninit[1].write(sum * 2); + /// uninit[2].write(sum * 3); + /// uninit[3].write(sum * 4); + /// + /// // Mark the 4 elements of the vector as being initialized. + /// unsafe { + /// let len = v.len(); + /// v.set_len(len + 4); + /// } + /// + /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]); + /// ``` + #[unstable(feature = "vec_split_at_spare", issue = "81944")] + #[rustc_const_unstable(feature = "const_heap", issue = "79597")] + #[inline] + pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit]) { + // SAFETY: + // - len is ignored and so never changed + let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() }; + (init, spare) + } + + /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`. + /// + /// This method provides unique access to all vec parts at once in `extend_from_within`. + #[requires(self.len <= self.buf.capacity())] + #[ensures(|result| result.0.len() == *result.2 && result.0.len() + result.1.len() == old(self.capacity()))] + const unsafe fn split_at_spare_mut_with_len( + &mut self, + ) -> (&mut [T], &mut [MaybeUninit], &mut usize) { + let ptr = self.as_mut_ptr(); + // SAFETY: + // - `ptr` is guaranteed to be valid for `self.len` elements + // - but the allocation extends out to `self.buf.capacity()` elements, possibly + // uninitialized + let spare_ptr = unsafe { ptr.add(self.len) }; + let spare_ptr = spare_ptr.cast_uninit(); + let spare_len = self.buf.capacity() - self.len; + + // SAFETY: + // - `ptr` is guaranteed to be valid for `self.len` elements + // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized` + unsafe { + let initialized = slice::from_raw_parts_mut(ptr, self.len); + let spare = slice::from_raw_parts_mut(spare_ptr, spare_len); + + (initialized, spare, &mut self.len) + } + } + + /// Groups every `N` elements in the `Vec` into chunks to produce a `Vec<[T; N]>`, dropping + /// elements in the remainder. `N` must be greater than zero. + /// + /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the + /// nearest multiple with a reallocation or deallocation. + /// + /// This function can be used to reverse [`Vec::into_flattened`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_into_chunks)] + /// + /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7]; + /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]); + /// + /// let vec = vec![0, 1, 2, 3]; + /// let chunks: Vec<[u8; 10]> = vec.into_chunks(); + /// assert!(chunks.is_empty()); + /// + /// let flat = vec![0; 8 * 8 * 8]; + /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks(); + /// assert_eq!(reshaped.len(), 1); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_into_chunks", issue = "142137")] + pub fn into_chunks(mut self) -> Vec<[T; N], A> { + const { + assert!(N != 0, "chunk size must be greater than zero"); + } + + let (len, cap) = (self.len(), self.capacity()); + + let len_remainder = len % N; + if len_remainder != 0 { + self.truncate(len - len_remainder); + } + + let cap_remainder = cap % N; + if !T::IS_ZST && cap_remainder != 0 { + self.buf.shrink_to_fit(cap - cap_remainder); + } + + let (ptr, _, _, alloc) = self.into_raw_parts_with_allocator(); + + // SAFETY: + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` + // - `[T; N]` has the same alignment as `T` + // - `size_of::<[T; N]>() * cap / N == size_of::() * cap` + // - `len / N <= cap / N` because `len <= cap` + // - the allocated memory consists of `len / N` valid values of type `[T; N]` + // - `cap / N` fits the size of the allocated memory after shrinking + unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) } + } + + /// This clears out this `Vec` and recycles the allocation into a new `Vec`. + /// The item type of the resulting `Vec` needs to have the same size and + /// alignment as the item type of the original `Vec`. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_recycle, transmutability)] + /// let a: Vec = vec![0; 100]; + /// let capacity = a.capacity(); + /// let addr = a.as_ptr().addr(); + /// let b: Vec = a.recycle(); + /// assert_eq!(b.len(), 0); + /// assert_eq!(b.capacity(), capacity); + /// assert_eq!(b.as_ptr().addr(), addr); + /// ``` + /// + /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// let vec: Vec<[u8; 2]> = Vec::new(); + /// let _: Vec<[u8; 1]> = vec.recycle(); + /// ``` + /// ...or different alignments: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// let vec: Vec<[u16; 0]> = Vec::new(); + /// let _: Vec<[u8; 0]> = vec.recycle(); + /// ``` + /// + /// However, due to temporary implementation limitations of `Recyclable`, + /// this method is not yet callable when `T` or `U` are slices, trait objects, + /// or other exotic types; e.g.: + /// + /// ```compile_fail,E0277 + /// #![feature(vec_recycle, transmutability)] + /// # let inputs = ["a b c", "d e f"]; + /// # fn process(_: &[&str]) {} + /// let mut storage: Vec<&[&str]> = Vec::new(); + /// + /// for input in inputs { + /// let mut buffer: Vec<&str> = storage.recycle(); + /// buffer.extend(input.split(" ")); + /// process(&buffer); + /// storage = buffer.recycle(); + /// } + /// ``` + #[unstable(feature = "vec_recycle", issue = "148227")] + #[expect(private_bounds)] + pub fn recycle(mut self) -> Vec + where + U: Recyclable, + { + self.clear(); + const { + // FIXME(const-hack, 146097): compare `Layout`s + assert!(size_of::() == size_of::()); + assert!(align_of::() == align_of::()); + }; + let (ptr, length, capacity, alloc) = self.into_parts_with_allocator(); + debug_assert_eq!(length, 0); + // SAFETY: + // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()` + // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later + // - the original vector was cleared, so there is no problem with "transmuting" the stored values + unsafe { Vec::from_parts_in(ptr.cast::(), length, capacity, alloc) } + } +} + +/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`. +/// +/// # Safety +/// +/// `Self` is `Recyclable` if `Layout::new::() == Layout::new::()`. +unsafe trait Recyclable: Sized {} + +#[unstable_feature_bound(transmutability)] +// SAFETY: enforced by `TransmuteFrom` +unsafe impl Recyclable for To +where + for<'a> &'a MaybeUninit: TransmuteFrom<&'a MaybeUninit, { Assume::SAFETY }>, + for<'a> &'a MaybeUninit: TransmuteFrom<&'a MaybeUninit, { Assume::SAFETY }>, +{ +} + +impl Vec { + /// Create a new `Vec` that contains `elem` `n` times. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// + /// If `n` is zero, the vector will not allocate. + /// + /// # Panics + /// + /// Panics if `size_of::() * n` exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_repeat)] + /// let vec = Vec::repeat(0, 3); + /// assert_eq!(vec, [0; 3]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_repeat", issue = "164215")] + #[inline] + pub fn repeat(elem: T, n: usize) -> Self { + ::from_elem(elem, n, Global) + } +} + +impl Vec { + /// Create a new `Vec` with the provided allocator that contains `elem` `n` times. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// + /// If `n` is zero, the vector will not allocate. + /// + /// # Panics + /// + /// Panics if `size_of::() * n` exceeds `isize::MAX` bytes. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_repeat)] + /// use std::alloc::System; + /// + /// let vec = Vec::repeat_in(0, 3, System); + /// assert_eq!(vec, [0; 3]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "vec_repeat", issue = "164215")] + #[inline] + pub fn repeat_in(elem: T, n: usize, alloc: A) -> Self { + ::from_elem(elem, n, alloc) + } + + /// Resizes the `Vec` in-place so that `len` is equal to `new_len`. + /// + /// If `new_len` is greater than `len`, the `Vec` is extended by the + /// difference, with each additional slot filled with `value`. + /// If `new_len` is less than or equal to `len`, the `Vec` is simply + /// truncated. + /// + /// This method requires `T` to implement [`Clone`], + /// in order to be able to clone the passed value. + /// If you need more flexibility (or want to rely on [`Default`] instead of + /// [`Clone`]), use [`Vec::resize_with`]. + /// If you only need to resize to a smaller size, use [`Vec::truncate`]. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec!["hello"]; + /// vec.resize(3, "world"); + /// assert_eq!(vec, ["hello", "world", "world"]); + /// + /// let mut vec = vec!['a', 'b', 'c', 'd']; + /// vec.resize(2, '_'); + /// assert_eq!(vec, ['a', 'b']); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_resize", since = "1.5.0")] + pub fn resize(&mut self, new_len: usize, value: T) { + let len = self.len(); + + if new_len > len { + self.extend_with(new_len - len, value) + } else { + self.truncate(new_len); + } + } + + /// Clones and appends all elements in a slice to the `Vec`. + /// + /// Iterates over the slice `other`, clones each element, and then appends + /// it to this `Vec`. The `other` slice is traversed in-order. + /// + /// Note that this function is the same as [`extend`], + /// except that it also works with slice elements that are Clone but not Copy. + /// If Rust gets specialization this function may be deprecated. + /// + /// # Panics + /// + /// Panics if the new capacity exceeds `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1]; + /// vec.extend_from_slice(&[2, 3, 4]); + /// assert_eq!(vec, [1, 2, 3, 4]); + /// ``` + /// + /// [`extend`]: Vec::extend + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] + pub fn extend_from_slice(&mut self, other: &[T]) { + self.spec_extend(other.iter()) + } + + /// Given a range `src`, clones a slice of elements in that range and appends it to the end. + /// + /// `src` must be a range that can form a valid subslice of the `Vec`. + /// + /// # Panics + /// + /// Panics if starting index is greater than the end index, if the index is + /// greater than the length of the vector, or if the new capacity exceeds + /// `isize::MAX` _bytes_. + /// + /// # Examples + /// + /// ``` + /// let mut characters = vec!['a', 'b', 'c', 'd', 'e']; + /// characters.extend_from_within(2..); + /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']); + /// + /// let mut numbers = vec![0, 1, 2, 3, 4]; + /// numbers.extend_from_within(..2); + /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]); + /// + /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")]; + /// strings.extend_from_within(1..=2); + /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "vec_extend_from_within", since = "1.53.0")] + pub fn extend_from_within(&mut self, src: R) + where + R: RangeBounds, + { + let range = slice::range(src, ..self.len()); + self.reserve(range.len()); + + // SAFETY: + // - `slice::range` guarantees that the given range is valid for indexing self + unsafe { + self.spec_extend_from_within(range); + } + } +} + +impl Vec { + #[cfg_attr( + not(no_global_oom_handling), + expect( + dead_code, + reason = "currently only used in IO module when global OOM handling is disabled" + ) + )] + pub(crate) fn try_extend_from_slice_of_bytes( + &mut self, + other: &[u8], + ) -> Result<(), TryReserveError> { + // ignore-tidy-undocumented-unsafe + unsafe { self.try_append_elements(other) } + } +} + +impl Vec<[T; N], A> { + /// Takes a `Vec<[T; N]>` and flattens it into a `Vec`. + /// + /// # Panics + /// + /// Panics if the length of the resulting vector would overflow a `usize`. + /// + /// This is only possible when flattening a vector of arrays of zero-sized + /// types, and thus tends to be irrelevant in practice. If + /// `size_of::() > 0`, this will never panic. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + /// assert_eq!(vec.pop(), Some([7, 8, 9])); + /// + /// let mut flattened = vec.into_flattened(); + /// assert_eq!(flattened.pop(), Some(6)); + /// ``` + #[stable(feature = "slice_flatten", since = "1.80.0")] + pub fn into_flattened(self) -> Vec { + let (ptr, len, cap, alloc) = self.into_raw_parts_with_allocator(); + let (new_len, new_cap) = if T::IS_ZST { + ( + len.checked_mul(N).expect("the product of vec len and N shouldn't overflow"), + usize::MAX, + ) + } else { + // SAFETY: + // - `cap * N` cannot overflow because the allocation is already in + // the address space. + // - Each `[T; N]` has `N` valid elements, so there are `len * N` + // valid elements in the allocation. + unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) } + }; + // SAFETY: + // - `ptr` was allocated by `self` + // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`. + // - `new_cap` refers to the same sized allocation as `cap` because + // `new_cap * size_of::()` == `cap * size_of::<[T; N]>()` + // - `len` <= `cap`, so `len * N` <= `cap * N`. + unsafe { Vec::::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) } + } +} + +impl Vec { + #[cfg(not(no_global_oom_handling))] + /// Extend the vector by `n` clones of value. + fn extend_with(&mut self, n: usize, value: T) { + self.spec_extend_with(n, value); + } +} + +impl Vec { + /// Removes consecutive repeated elements in the vector according to the + /// [`PartialEq`] trait implementation. + /// + /// If the vector is sorted, this removes all duplicates. + /// + /// # Examples + /// + /// ``` + /// let mut vec = vec![1, 2, 2, 3, 2]; + /// + /// vec.dedup(); + /// + /// assert_eq!(vec, [1, 2, 3, 2]); + /// ``` + #[stable(feature = "rust1", since = "1.0.0")] + #[inline] + pub fn dedup(&mut self) { + // Vectorize the process of finding first duplicate if possible + if let Some(chunk_size) = dedup_simd_chunk_size::() { + // Unlike dedup_by, we don't guarantee the order + // and time in which we call `PartialEq::eq`. + let Some(first_duplicate) = find_first_duplicate(self.as_slice(), chunk_size) else { + return; + }; + + // SAFETY: `1 <= first_duplicate < self.len()` + unsafe { + self.dedup_tail(|a, b| a == b, first_duplicate); + } + } else { + self.dedup_by(|a, b| a == b); + } + } +} + +const fn dedup_simd_chunk_size() -> Option { + // The minimal SIMD width on supported platforms + #[allow(unused)] + const SIMD_WIDTH: usize = 16; + let size = size_of::(); + + // We only have SIMD implementations for these element sizes. + if !matches!(size, 1 | 2 | 4 | 8) { + return None; + } + + let simd_width: Option = cfg_select! { + all(target_arch = "arm", target_feature = "neon") => { + // Packed 64-bit integer lane equality is unavailable on arm neon + if size == 8 { None } else { Some(SIMD_WIDTH) } + } + + all(target_arch = "aarch64", target_feature = "neon") => Some(SIMD_WIDTH), + + all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse4.1") => { + Some(SIMD_WIDTH) + } + + all(any(target_arch = "x86", target_arch = "x86_64"), target_feature = "sse2") => { + // Packed 64-bit integer lane equality is only available on sse4.1 + if size == 8 { None } else { Some(SIMD_WIDTH) } + } + + all(any(target_arch = "riscv32", target_arch = "riscv64"), target_feature = "v") => { + Some(SIMD_WIDTH) + } + + all(any(target_arch = "loongarch32", target_arch = "loongarch64"), target_feature = "lsx") => { + Some(SIMD_WIDTH) + } + + _ => None, + }; + + if let Some(simd_width) = simd_width { Some(simd_width * 2 / size) } else { None } +} + +fn find_first_duplicate(v: &[T], chunk_size: usize) -> Option { + let len = v.len(); + if len <= 1 { + return None; + } + + let mut i = 1; + + // The scalar fallback path if the length is not long enough + if len < chunk_size + 1 { + while i < len { + // It keeps the same comparison order as `dedup_tail` + // + // SAFETY: i always in range [1..len) + if unsafe { v.get_unchecked(i) == v.get_unchecked(i - 1) } { + return Some(i); + } + i += 1; + } + return None; + } + + /// # Safety + /// - `start > 0` and `start + chunk_size <= v.len()` + /// - `0 < chunk_size <= 32` + #[inline(always)] + unsafe fn find_duplicate( + v: &[T], + start: usize, + chunk_size: usize, + ) -> Option { + let mut mask: u32 = 0; + debug_assert!( + u32::BITS as usize >= chunk_size, + "the bit width of mask must be greater than or equal to chunk_size" + ); + for j in 0..chunk_size { + // SAFETY: start + j always in range [1..v.len()) + let eq = unsafe { v.get_unchecked(start + j) == v.get_unchecked(start + j - 1) }; + mask |= (eq as u32) << j; + } + if mask != 0 { + return Some(start + mask.trailing_zeros() as usize); + } + None + } + + // This loop performs chunk_size comparisons in parallel without early exit, + // which is what allows for SIMD optimization. + while i + chunk_size <= len { + // SAFETY: `i >= 1` and `i + chunk_size <= len` + if let Some(duplicate) = unsafe { find_duplicate(v, i, chunk_size) } { + return Some(duplicate); + } + i += chunk_size; + } + + // This may check the same elements multiple times. + // However we don't guarantee `PartialEq::eq` is only called once per pair. + if i < len { + let start = len - chunk_size; + // SAFETY: `len - chunk_size >= 1` and `start + chunk_size <= len` + if let Some(duplicate) = unsafe { find_duplicate(v, start, chunk_size) } { + return Some(duplicate); + } + } + + None +} + +//////////////////////////////////////////////////////////////////////////////// +// Internal methods and functions +//////////////////////////////////////////////////////////////////////////////// + +// This function is no longer used internally (`from_elem_global` is used instead). +// It is only kept so as not to break a few crates who mistakenly used it at a +// time when we didn't have the ability to gate internal methods used by public macros. +#[doc(hidden)] +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +// NOTE: the real deprecation version is the same as the stabilization version. +// I.e. it should never have been used even in version 1.0. +#[deprecated(since = "1.101.0", note = "use the `vec!` macro instead")] +pub fn from_elem(elem: T, n: usize) -> Vec { + vec![elem; n] +} + +// This function is required because it ensures the `vec_from_elem` diagnostic +// item is emitted, which is consumed by Clippy to detect calls to +// `vec![elem; n]`. We cannot add the item to `Vec::repeat` because then we +// would end up confusing Clippy. +#[doc(hidden)] +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "liballoc_internals", issue = "none")] +#[rustc_diagnostic_item = "vec_from_elem"] +pub fn from_elem_global(elem: T, n: usize) -> Vec { + Vec::repeat(elem, n) +} + +#[cfg(not(no_global_oom_handling))] +trait ExtendFromWithinSpec { + /// # Safety + /// + /// - `src` needs to be valid index + /// - `self.capacity() - self.len()` must be `>= src.len()` + unsafe fn spec_extend_from_within(&mut self, src: Range); +} + +#[cfg(not(no_global_oom_handling))] +impl ExtendFromWithinSpec for Vec { + default unsafe fn spec_extend_from_within(&mut self, src: Range) { + // SAFETY: + // - len is increased only after initializing elements + let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() }; + + // SAFETY: + // - caller guarantees that src is a valid index + let to_clone = unsafe { this.get_unchecked(src) }; + + iter::zip(to_clone, spare) + .map(|(src, dst)| dst.write(src.clone())) + // Note: + // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len + // - len is increased after each element to prevent leaks (see issue #82533) + .for_each(|_| *len += 1); + } +} + +#[cfg(not(no_global_oom_handling))] +impl ExtendFromWithinSpec for Vec { + #[requires(src.start <= src.end && src.end <= self.len())] + #[requires(src.end - src.start <= self.capacity() - self.len())] + #[ensures(|_| self.len() == old(self.len()) + old(src.end - src.start))] + #[ensures(|_| self.capacity() == old(self.capacity()))] + #[ensures(|_| self.as_ptr() == old(self.as_ptr()))] + #[cfg_attr( + kani, + kani::modifies( + &self.len, + ptr::slice_from_raw_parts(self.as_ptr().wrapping_add(self.len()), src.end - src.start), + ) + )] + unsafe fn spec_extend_from_within(&mut self, src: Range) { + let count = src.len(); + { + let (init, spare) = self.split_at_spare_mut(); + + // SAFETY: + // - caller guarantees that `src` is a valid index + let source = unsafe { init.get_unchecked(src) }; + + // SAFETY: + // - Both pointers are created from unique slice references (`&mut [_]`) + // so they are valid and do not overlap. + // - Elements implement `TrivialClone` so this is equivalent to calling + // `clone` on every one of them. + // - `count` is equal to the len of `source`, so source is valid for + // `count` reads + // - `.reserve(count)` guarantees that `spare.len() >= count` so spare + // is valid for `count` writes + unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) }; + } + + // SAFETY: + // - The elements were just initialized by `copy_nonoverlapping` + self.len += count; + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Common trait implementations for Vec +//////////////////////////////////////////////////////////////////////////////// + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl ops::Deref for Vec { + type Target = [T]; + + #[inline] + fn deref(&self) -> &[T] { + self.as_slice() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl ops::DerefMut for Vec { + #[inline] + fn deref_mut(&mut self) -> &mut [T] { + self.as_mut_slice() + } +} + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl ops::DerefPure for Vec {} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Clone for Vec { + /// Creates a new `Vec` by deep-copying the contents of an existing `Vec`. + /// + /// This method will allocate a new `Vec` and `clone` all of `self`'s contents + /// into it. The capacity of the duplicate `Vec` is not forced to match the + /// capacity of the original. + fn clone(&self) -> Self { + let alloc = self.allocator().clone(); + <[T]>::to_vec_in(self, alloc) + } + + /// Overwrites the contents of `self` with a clone of the contents of `source`. + /// + /// This method is preferred over simply assigning `source.clone()` to `self`, + /// as it avoids reallocation if possible. Additionally, if the element type + /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s + /// elements as well. + /// + /// # Examples + /// + /// ``` + /// let x = vec![5, 6, 7]; + /// let mut y = vec![8, 9, 10]; + /// let yp: *const i32 = y.as_ptr(); + /// + /// y.clone_from(&x); + /// + /// // The value is the same + /// assert_eq!(x, y); + /// + /// // And no reallocation occurred + /// assert_eq!(yp, y.as_ptr()); + /// ``` + fn clone_from(&mut self, source: &Self) { + crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self); + } +} + +/// The hash of a vector is the same as that of the corresponding slice, +/// as required by the `core::borrow::Borrow` implementation. +/// +/// ``` +/// use std::hash::BuildHasher; +/// +/// let b = std::hash::RandomState::new(); +/// let v: Vec = vec![0xa8, 0x3c, 0x09]; +/// let s: &[u8] = &[0xa8, 0x3c, 0x09]; +/// assert_eq!(b.hash_one(v), b.hash_one(s)); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +impl Hash for Vec { + #[inline] + fn hash(&self, state: &mut H) { + Hash::hash(&**self, state) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_index", issue = "143775")] +const impl, A: Allocator> Index for Vec { + type Output = I::Output; + + #[inline] + fn index(&self, index: I) -> &Self::Output { + Index::index(&**self, index) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_index", issue = "143775")] +const impl, A: Allocator> IndexMut for Vec { + #[inline] + fn index_mut(&mut self, index: I) -> &mut Self::Output { + IndexMut::index_mut(&mut **self, index) + } +} + +/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`] +/// +/// # Allocation behavior +/// +/// In general `Vec` does not guarantee any particular growth or allocation strategy. +/// That also applies to this trait impl. +/// +/// **Note:** This section covers implementation details and is therefore exempt from +/// stability guarantees. +/// +/// Vec may use any or none of the following strategies, +/// depending on the supplied iterator: +/// +/// * preallocate based on [`Iterator::size_hint()`] +/// * and panic if the number of items is outside the provided lower/upper bounds +/// * use an amortized growth strategy similar to `pushing` one item at a time +/// * perform the iteration in-place on the original allocation backing the iterator +/// +/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory +/// consumption and improves cache locality. But when big, short-lived allocations are created, +/// only a small fraction of their items get collected, no further use is made of the spare capacity +/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large +/// allocations having their lifetimes unnecessarily extended which can result in increased memory +/// footprint. +/// +/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`], +/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces +/// the size of the long-lived struct. +/// +/// [owned slice]: Box +/// +/// ```rust +/// # use std::sync::Mutex; +/// static LONG_LIVED: Mutex>> = Mutex::new(Vec::new()); +/// +/// for i in 0..10 { +/// let big_temporary: Vec = (0..1024).collect(); +/// // discard most items +/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect(); +/// // without this a lot of unused capacity might be moved into the global +/// result.shrink_to_fit(); +/// LONG_LIVED.lock().unwrap().push(result); +/// } +/// ``` +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl FromIterator for Vec { + #[inline] + fn from_iter>(iter: I) -> Vec { + >::from_iter(iter.into_iter()) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; + + /// Creates a consuming iterator, that is, one that moves each value out of + /// the vector (from start to end). The vector cannot be used after calling + /// this. + /// + /// # Examples + /// + /// ``` + /// let v = vec!["a".to_string(), "b".to_string()]; + /// let mut v_iter = v.into_iter(); + /// + /// let first_element: Option = v_iter.next(); + /// + /// assert_eq!(first_element, Some("a".to_string())); + /// assert_eq!(v_iter.next(), Some("b".to_string())); + /// assert_eq!(v_iter.next(), None); + /// ``` + #[inline] + fn into_iter(self) -> Self::IntoIter { + let me = ManuallyDrop::new(self); + // ignore-tidy-undocumented-unsafe + unsafe { + let alloc = ManuallyDrop::new(ptr::read(me.allocator())); + let buf = me.buf.non_null(); + let begin = buf.as_ptr(); + let end = if T::IS_ZST { + begin.wrapping_byte_add(me.len()) + } else { + begin.add(me.len()) as *const T + }; + let cap = me.buf.capacity(); + IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end } + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T, A: Allocator> IntoIterator for &'a Vec { + type Item = &'a T; + type IntoIter = slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { + type Item = &'a mut T; + type IntoIter = slice::IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter_mut() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Extend for Vec { + #[inline] + fn extend>(&mut self, iter: I) { + >::spec_extend(self, iter.into_iter()) + } + + #[inline] + fn extend_one(&mut self, item: T) { + self.push(item); + } + + #[inline] + fn extend_reserve(&mut self, additional: usize) { + self.reserve(additional); + } + + #[inline] + unsafe fn extend_one_unchecked(&mut self, item: T) { + // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly. + unsafe { + let len = self.len(); + ptr::write(self.as_mut_ptr().add(len), item); + self.set_len(len + 1); + } + } +} + + +fn size_hint_lower__VeriFast_wrapper(it: &I) -> usize +//@ req thread_token(?t) &*& [_](.share(?k, t, it)) &*& [?q]lifetime_token(k); +//@ ens thread_token(t) &*& [q]lifetime_token(k); +//@ assume_correct +{ + let (lower, _) = it.size_hint(); + lower +} + +fn saturating_add_one_usize__VeriFast_wrapper(a: usize) -> usize +//@ req true; +//@ ens result == if a + 1 <= usize::MAX { a + 1 } else { usize::MAX }; +//@ on_unwind_ens false; +//@ assume_correct +{ + a.saturating_add(1) +} + +fn call_fn_mut1__VeriFast_wrapper bool>(f: &mut F, a: &mut T) -> bool +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& *a |-> ?a0 &*& .own(t, a0); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& *a |-> ?a1 &*& .own(t, a1); +//@ assume_correct +{ + f(a) +} + +fn call_fn_mut2__VeriFast_wrapper bool>( + f: &mut F, + a: &mut T, + b: &mut T, +) -> bool +//@ req thread_token(?t) &*& *f |-> ?f0 &*& .own(t, f0) &*& *a |-> ?a0 &*& .own(t, a0) &*& *b |-> ?b0 &*& .own(t, b0); +//@ ens thread_token(t) &*& *f |-> ?f1 &*& .own(t, f1) &*& *a |-> ?a1 &*& .own(t, a1) &*& *b |-> ?b1 &*& .own(t, b1); +//@ assume_correct +{ + f(a, b) +} + +fn hint_unlikely__VeriFast_wrapper(b: bool) -> bool +//@ req true; +//@ ens result == b; +//@ on_unwind_ens false; +//@ assume_correct +{ + hint::unlikely(b) +} + +/*@ +pred_ctor Vec_exact_fbc( + t: thread_id_t, + vp: *Vec, + alloc_id: std::alloc::alloc_id_t, + base: *T, + cap: usize, + len: usize +)() = + *vp |-> ?v &*& + Vec(t, v, alloc_id, base, cap, len) &*& + array_at_lft(alloc_id.lft, base, len, ?elems) &*& + foreach(elems, own::(t)) &*& + array_at_lft_(alloc_id.lft, base + len, cap - len, _); +@*/ + +// Bridges `Vec::get_unchecked_mut(index)` (which traverses `DerefMut` to form a +// mutable slice over all `0..len` elements and then projects `&mut [T]::get_unchecked_mut`) +// by requiring full initialized-prefix ownership (`array_at_lft` + `foreach(elems, own)`) +// and an exclusive lifetime token `[q]lifetime_token(alloc_id.lft)` in addition to +// `index < len`, and handing out a scoped exclusive borrow `*result |-> nth(index, elems)` +// paired with `close_points_to_at_lft_token(1, alloc_id.lft, result, q)` to be restored +// after the caller finishes using `&mut T`. +unsafe fn vec_get_unchecked_mut__VeriFast_wrapper<'a, T, A: Allocator>( + v: &'a mut Vec, + index: usize, +) -> &'a mut T +/*@ +req thread_token(?t) &*& + *v |-> ?v0 &*& Vec(t, v0, ?alloc_id, ?base, ?cap, ?len) &*& + [?q]lifetime_token(alloc_id.lft) &*& + array_at_lft(alloc_id.lft, base, len, ?elems) &*& + foreach(elems, own::(t)) &*& + index < len; +@*/ +/*@ +ens thread_token(t) &*& + *v |-> v0 &*& Vec(t, v0, alloc_id, base, cap, len) &*& + result == base + index &*& + pointer_within_limits(result) == true &*& + array_at_lft(alloc_id.lft, base, index, take(index, elems)) &*& + foreach(take(index, elems), own::(t)) &*& + *result |-> nth(index, elems) &*& .own(t, nth(index, elems)) &*& + close_points_to_at_lft_token(1, alloc_id.lft, result, q) &*& + array_at_lft(alloc_id.lft, base + index + 1, len - index - 1, drop(index + 1, elems)) &*& + foreach(drop(index + 1, elems), own::(t)); +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { v.get_unchecked_mut(index) } +} + +// Bridges `core::mem::forget(guard)` for function-local `Vec` drop guards (`PanicGuard`, +// `FillGapOnDrop`) whose `impl Drop` suppresses default `.own` synthesis and whose +// impl-method-scoped type path (`vec::Vec::fn::Guard`) cannot be parsed in a +// module-level VeriFast `pred` declaration (while `refinement-checker` rejects moving the +// struct out of the method). Unlike a `req true` stub, this contract requires a thread +// token, a live exclusive `full_borrow(k, Vec_exact_fbc(...))` proving the guard's `&mut Vec` +// reference points to a valid owned `Vec`, and valid cursor bounds (`0 <= write <= read <= orig_len`). +unsafe fn forget_vec_guard__VeriFast_wrapper(g: G) +/*@ +req thread_token(?t) &*& + exists::>>(?kv) &*& + exists::>>(?abc) &*& + exists::>>(?wro) &*& + full_borrow(fst(kv), Vec_exact_fbc::(t, snd(kv), fst(abc), fst(snd(abc)), snd(snd(abc)), fst(wro))) &*& + 0 <= fst(wro) &*& fst(wro) <= fst(snd(wro)) &*& fst(snd(wro)) <= snd(snd(wro)); +@*/ +//@ ens thread_token(t); +//@ on_unwind_ens false; +//@ assume_correct +{ + mem::forget(g); +} + +impl Vec { + // leaf method to which various SpecFrom/SpecExtend implementations delegate when + // they have no further optimizations to apply + #[cfg(not(no_global_oom_handling))] + fn extend_desugared>(&mut self, mut iterator: I) + //@ req thread_token(?t) &*& t == currentThread &*& *self |-> ?self0 &*& >.own(t, self0) &*& .own(t, iterator); + //@ ens thread_token(t) &*& *self |-> ?self1 &*& >.own(t, self1); + { + //@ assert lifetime_token(?flft); + loop { + //@ inv thread_token(t) &*& lifetime_token(flft) &*& *self |-> ?self_cur &*& >.own(t, self_cur) &*& iterator |-> ?it_cur &*& .own(t, it_cur); + let next_opt = iterator.next(); + let Some(element) = next_opt else { + //@ open >.own(t, next_opt); + break; + }; + //@ open >.own(t, next_opt); + //@ open >.own(t, self_cur); + //@ Vec_inv2(); + //@ assert Vec(t, self_cur, ?alloc_id, ?ptr, ?cap, ?length); + //@ let k_len = begin_lifetime(); + //@ share_Vec(k_len, self); + //@ let self_ref1 = precreate_ref(self); + //@ init_ref_Vec_(self_ref1); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref1), 1/4); + //@ open [?f1]ref_initialized_::>(self_ref1)(); + //@ Vec_share__inv(); + //@ open Vec_share_(k_len, t, self_ref1, alloc_id, ptr, cap, length); + //@ open_frac_borrow(k_len, Vec_frac_borrow_content(self_ref1, length), 1/8); + //@ open [?flen]Vec_frac_borrow_content::(self_ref1, length)(); + let len = self.len(); + //@ close [flen]Vec_frac_borrow_content::(self_ref1, length)(); + //@ close_frac_borrow(flen, Vec_frac_borrow_content(self_ref1, length)); + //@ close [f1]ref_initialized_::>(self_ref1)(); + //@ close_frac_borrow(f1, ref_initialized_(self_ref1)); + //@ let self_ref2 = precreate_ref(self); + //@ init_ref_Vec_(self_ref2); + //@ open_frac_borrow(k_len, ref_initialized_(self_ref2), 1/4); + //@ open [?f2]ref_initialized_::>(self_ref2)(); + let cur_cap = self.capacity(); + //@ close [f2]ref_initialized_::>(self_ref2)(); + //@ close_frac_borrow(f2, ref_initialized_(self_ref2)); + //@ end_lifetime(k_len); + //@ end_share_Vec(self); + if len == cur_cap { + //@ let k_it = begin_lifetime(); + //@ close_full_borrow_content::(t, &iterator); + //@ borrow(k_it, .full_borrow_content(t, &iterator)); + //@ produce_type_interp::(); + //@ share_full_borrow::(k_it, t, &iterator); + //@ let it_ref = precreate_ref(&iterator); + //@ init_ref_share::(k_it, t, it_ref); + //@ leak type_interp::(); + //@ open_frac_borrow(k_it, ref_initialized_(it_ref), 1/2); + //@ open [?fit]ref_initialized_::(it_ref)(); + let lower = size_hint_lower__VeriFast_wrapper(&iterator); + //@ close [fit]ref_initialized_::(it_ref)(); + //@ close_frac_borrow(fit, ref_initialized_(it_ref)); + //@ end_lifetime(k_it); + //@ borrow_end(k_it, .full_borrow_content(t, &iterator)); + //@ open_full_borrow_content::(t, &iterator); + self.reserve(saturating_add_one_usize__VeriFast_wrapper(lower)); + } + //@ Vec_inv2(); + //@ assert Vec(t, ?self_res, ?alloc_id1, ?ptr1, ?cap1, len); + //@ assert array_at_lft(alloc_id1.lft, ptr1, len, ?elems1); + // ignore-tidy-undocumented-unsafe + unsafe { + let base_ptr = self.as_mut_ptr(); + //@ open array_at_lft_(alloc_id1.lft, ptr1 + len, cap1 - len, _); + let dst = base_ptr.add(len); + //@ lifetime_inclusion_trans(flft, lft_of_type::(), alloc_id1.lft); + //@ let q_lft = lifetime_token_trade(flft, 1/2, alloc_id1.lft); + //@ open_points_to_at_lft_(dst, q_lft); + ptr::write(dst, element); + //@ close_points_to_at_lft(dst); + //@ lifetime_token_trade_back(q_lft, alloc_id1.lft); + //@ array_at_lft_snoc::(alloc_id1.lft, ptr1, len); + //@ close own::(t)(element); + //@ close foreach([], own::(t)); + //@ close foreach([element], own::(t)); + //@ foreach_append(elems1, [element]); + // Since next() executes user code which can panic we have to bump the length + // after each step. + // NB can't overflow since we would have had to alloc the address space + self.set_len(len + 1); + } + //@ close >.own(t, *self); + } + } + + // specific extend for `TrustedLen` iterators, called both by the specializations + // and internal places where resolving specialization makes compilation slower + #[cfg(not(no_global_oom_handling))] + fn extend_trusted(&mut self, iterator: impl iter::TrustedLen) { + let (low, high) = iterator.size_hint(); + if let Some(additional) = high { + debug_assert_eq!( + low, + additional, + "TrustedLen iterator's size hint is not exact: {:?}", + (low, high) + ); + self.reserve(additional); + let ptr = self.as_mut_ptr(); + let mut local_len = SetLenOnDrop::new(&mut self.len); + // ignore-tidy-undocumented-unsafe + unsafe { + iterator.for_each(move |element| { + ptr::write(ptr.add(local_len.current_len()), element); + // Since the loop executes user code which can panic we have to update + // the length every step to correctly drop what we've written. + // NB can't overflow since we would have had to alloc the address space + local_len.increment_len(1); + }); + } + } else { + // Per TrustedLen contract a `None` upper bound means that the iterator length + // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway. + // Since the other branch already panics eagerly (via `reserve()`) we do the same here. + // This avoids additional codegen for a fallback code path which would eventually + // panic anyway. + panic!("capacity overflow"); + } + } + + /// Creates a splicing iterator that replaces the specified range in the vector + /// with the given `replace_with` iterator and yields the removed items. + /// `replace_with` does not need to be the same length as `range`. + /// + /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped. + /// + /// It is unspecified how many elements are removed from the vector + /// if the `Splice` value is leaked. + /// + /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped. + /// + /// This is optimal if: + /// + /// * The tail (elements in the vector after `range`) is empty, + /// * or `replace_with` yields fewer or equal elements than `range`'s length + /// * or the lower bound of its `size_hint()` is exact. + /// + /// Otherwise, a temporary vector is allocated and the tail is moved twice. + /// + /// # Panics + /// + /// Panics if the range has `start_bound > end_bound`, or, if the range is + /// bounded on either end and past the length of the vector. + /// + /// # Examples + /// + /// ``` + /// let mut v = vec![1, 2, 3, 4]; + /// let new = [7, 8, 9]; + /// let u: Vec<_> = v.splice(1..3, new).collect(); + /// assert_eq!(v, [1, 7, 8, 9, 4]); + /// assert_eq!(u, [2, 3]); + /// ``` + /// + /// Using `splice` to insert new items into a vector efficiently at a specific position + /// indicated by an empty range: + /// + /// ``` + /// let mut v = vec![1, 5]; + /// let new = [2, 3, 4]; + /// v.splice(1..1, new); + /// assert_eq!(v, [1, 2, 3, 4, 5]); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "vec_splice", since = "1.21.0")] + pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> + where + A: AllocatorNightly, + R: RangeBounds, + I: IntoIterator, + { + Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } + } + + /// Creates an iterator which uses a closure to determine if an element in the range should be removed. + /// + /// If the closure returns `true`, the element is removed from the vector + /// and yielded. If the closure returns `false`, or panics, the element + /// remains in the vector and will not be yielded. + /// + /// Only elements that fall in the provided range are considered for extraction, but any elements + /// after the range will still have to be moved if any element has been extracted. + /// + /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating + /// or the iteration short-circuits, then the remaining elements will be retained. + /// Use `extract_if().for_each(drop)` if you do not need the returned iterator, + /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range. + /// + /// [`retain_mut`]: Vec::retain_mut + /// + /// Using this method is equivalent to the following code: + /// + /// ``` + /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 }; + /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6]; + /// # let mut vec2 = vec.clone(); + /// # let range = 1..5; + /// let mut i = range.start; + /// let end_items = vec.len() - range.end; + /// # let mut extracted = vec![]; + /// + /// while i < vec.len() - end_items { + /// if some_predicate(&mut vec[i]) { + /// let val = vec.remove(i); + /// // your code here + /// # extracted.push(val); + /// } else { + /// i += 1; + /// } + /// } + /// + /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect(); + /// # assert_eq!(vec, vec2); + /// # assert_eq!(extracted, extracted2); + /// ``` + /// + /// But `extract_if` is easier to use. `extract_if` is also more efficient, + /// because it can backshift the elements of the array in bulk. + /// + /// The iterator also lets you mutate the value of each element in the + /// closure, regardless of whether you choose to keep or remove it. + /// + /// # Panics + /// + /// If `range` is out of bounds. + /// + /// # Examples + /// + /// Splitting a vector into even and odd values, reusing the original vector: + /// + /// ``` + /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]; + /// + /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::>(); + /// let odds = numbers; + /// + /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); + /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); + /// ``` + /// + /// Using the range argument to only process a part of the vector: + /// + /// ``` + /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]; + /// let ones = items.extract_if(7.., |x| *x == 1).collect::>(); + /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]); + /// assert_eq!(ones.len(), 3); + /// ``` + #[stable(feature = "extract_if", since = "1.87.0")] + pub fn extract_if(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A> + where + A: AllocatorNightly, + F: FnMut(&mut T) -> bool, + R: RangeBounds, + { + ExtractIf::new(self, filter, range) + } +} + +/// Extend implementation that copies elements out of references before pushing them onto the Vec. +/// +/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to +/// append the entire slice at once. +/// +/// [`copy_from_slice`]: slice::copy_from_slice +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "extend_ref", since = "1.2.0")] +impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec { + fn extend>(&mut self, iter: I) { + self.spec_extend(iter.into_iter()) + } + + #[inline] + fn extend_one(&mut self, &item: &'a T) { + self.push(item); + } + + #[inline] + fn extend_reserve(&mut self, additional: usize) { + self.reserve(additional); + } + + #[inline] + unsafe fn extend_one_unchecked(&mut self, &item: &'a T) { + // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly. + unsafe { + let len = self.len(); + ptr::write(self.as_mut_ptr().add(len), item); + self.set_len(len + 1); + } + } +} + +/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison). +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd> for Vec +where + T: PartialOrd, + A1: Allocator, + A2: Allocator, +{ + #[inline] + fn partial_cmp(&self, other: &Vec) -> Option { + PartialOrd::partial_cmp(&**self, &**other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Eq for Vec {} + +/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison). +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Vec { + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + Ord::cmp(&**self, &**other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_heap", issue = "79597")] +const unsafe impl<#[may_dangle] T: [const] Destruct, A: [const] Allocator + [const] Destruct> Drop + for Vec +{ + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + // use drop for [T] + // use a raw slice to refer to the elements of the vector as weakest necessary type; + // could avoid questions of validity in certain cases + self.as_mut_ptr().cast_slice(self.len).drop_in_place() + } + // RawVec handles deallocation + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_const_unstable(feature = "const_default", issue = "143894")] +const impl Default for Vec { + /// Creates an empty `Vec`. + /// + /// The vector will not allocate until elements are pushed onto it. + fn default() -> Vec { + Vec::new() + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Vec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef> for Vec { + fn as_ref(&self) -> &Vec { + self + } +} + +#[stable(feature = "vec_as_mut", since = "1.5.0")] +impl AsMut> for Vec { + fn as_mut(&mut self) -> &mut Vec { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef<[T]> for Vec { + fn as_ref(&self) -> &[T] { + self + } +} + +#[stable(feature = "vec_as_mut", since = "1.5.0")] +impl AsMut<[T]> for Vec { + fn as_mut(&mut self) -> &mut [T] { + self + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl From<&[T]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]); + /// ``` + fn from(s: &[T]) -> Vec { + s.to_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_mut", since = "1.19.0")] +impl From<&mut [T]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]); + /// ``` + fn from(s: &mut [T]) -> Vec { + s.to_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array_ref", since = "1.74.0")] +impl From<&[T; N]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: &[T; N]) -> Vec { + Self::from(s.as_slice()) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array_ref", since = "1.74.0")] +impl From<&mut [T; N]> for Vec { + /// Allocates a `Vec` and fills it by cloning `s`'s items. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: &mut [T; N]) -> Vec { + Self::from(s.as_mut_slice()) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "vec_from_array", since = "1.44.0")] +impl From<[T; N]> for Vec { + /// Allocates a `Vec` and moves `s`'s items into it. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]); + /// ``` + fn from(s: [T; N]) -> Vec { + <[T]>::into_vec(Box::new(s)) + } +} + +#[stable(feature = "vec_from_cow_slice", since = "1.14.0")] +impl<'a, T> From> for Vec +where + [T]: ToOwned>, +{ + /// Converts a clone-on-write slice into a vector. + /// + /// If `s` already owns a `Vec`, it will be returned directly. + /// If `s` is borrowing a slice, a new `Vec` will be allocated and + /// filled by cloning `s`'s items into it. + /// + /// # Examples + /// + /// ``` + /// # use std::borrow::Cow; + /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]); + /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]); + /// assert_eq!(Vec::from(o), Vec::from(b)); + /// ``` + fn from(s: Cow<'a, [T]>) -> Vec { + s.into_owned() + } +} + +#[stable(feature = "vec_from_box", since = "1.18.0")] +impl From> for Vec { + /// Converts a boxed slice into a vector by transferring ownership of + /// the existing heap allocation. + /// + /// # Examples + /// + /// ``` + /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice(); + /// assert_eq!(Vec::from(b), vec![1, 2, 3]); + /// ``` + fn from(s: Box<[T], A>) -> Self { + s.into_vec() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "box_from_vec", since = "1.20.0")] +impl From> for Box<[T], A> { + /// Converts a vector into a boxed slice. + /// + /// This is equivalent to [`Vec::into_boxed_slice`]. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); + /// ``` + fn from(v: Vec) -> Self { + v.into_boxed_slice() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl From<&str> for Vec { + /// Allocates a `Vec` and fills it with a UTF-8 string. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']); + /// ``` + fn from(s: &str) -> Vec { + From::from(s.as_bytes()) + } +} + +#[stable(feature = "array_try_from_vec", since = "1.48.0")] +#[rustc_const_unstable(feature = "const_convert", issue = "143773")] +const impl + TryFrom> for [T; N] +{ + type Error = Vec; + + /// Gets the entire contents of the `Vec` as an array, + /// if its size exactly matches that of the requested array. + /// + /// # Examples + /// + /// ``` + /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3])); + /// assert_eq!(>::new().try_into(), Ok([])); + /// ``` + /// + /// If the length doesn't match, the input comes back in `Err`: + /// ``` + /// let r: Result<[i32; 4], _> = (0..10).collect::>().try_into(); + /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9])); + /// ``` + /// + /// If you're fine with just getting a prefix of the `Vec`, + /// you can call [`.truncate(N)`](Vec::truncate) first. + /// ``` + /// let mut v = String::from("hello world").into_bytes(); + /// v.sort(); + /// v.truncate(2); + /// let [a, b]: [_; 2] = v.try_into().unwrap(); + /// assert_eq!(a, b' '); + /// assert_eq!(b, b'd'); + /// ``` + fn try_from(mut vec: Vec) -> Result<[T; N], Vec> { + if vec.len() != N { + return Err(vec); + } + + // SAFETY: `.set_len(0)` is always sound. + unsafe { vec.set_len(0) }; + + // SAFETY: A `Vec`'s pointer is always aligned properly, and + // the alignment the array needs is the same as the items. + // We checked earlier that we have sufficient items. + // The items will not double-drop as the `set_len` + // tells the `Vec` not to also drop them. + let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) }; + Ok(array) + } +} + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use core::kani; + + use crate::vec::Vec; + + // Size chosen for testing the empty vector (0), middle element removal (1) + // and last element removal (2) cases while keeping verification tractable + const ARRAY_LEN: usize = 3; + + #[kani::proof] + pub fn verify_swap_remove() { + // Creating a vector directly from a fixed length arbitrary array + let mut arr: [i32; ARRAY_LEN] = kani::Arbitrary::any_array(); + let mut vect = Vec::from(&arr); + + // Recording the original length and a copy of the vector for validation + let original_len = vect.len(); + let original_vec = vect.clone(); + + // Generating a nondeterministic index which is guaranteed to be within bounds + let index: usize = kani::any_where(|x| *x < original_len); + + let removed = vect.swap_remove(index); + + // Verifying that the length of the vector decreases by one after the operation is performed + assert!(vect.len() == original_len - 1, "Length should decrease by 1"); + + // Verifying that the removed element matches the original element at the index + assert!(removed == original_vec[index], "Removed element should match original"); + + // Verifying that the removed index now contains the element originally at the vector's last index if applicable + if index < original_len - 1 { + assert!( + vect[index] == original_vec[original_len - 1], + "Index should contain last element" + ); + } + + // Check that all other unaffected elements remain unchanged + let k = kani::any_where(|&x: &usize| x < original_len - 1); + if k != index { + assert!(vect[k] == arr[k]); + } + } +} diff --git a/verifast-proofs/alloc/vec/mod.rs/verify.sh b/verifast-proofs/alloc/vec/mod.rs/verify.sh new file mode 100755 index 0000000000000..f7afa7918019a --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/verify.sh @@ -0,0 +1,159 @@ +set -e -x + +export VFVERSION=26.10 + +# Ensure VeriFast toolchain is available; also ensure pinned rustc (nightly-2026-09-25) +# is installed even when $VERIFAST_HOME was restored from a cache. +. ../../../setup-verifast-home +if ! rustup toolchain list | grep -q '^nightly-2026-09-25'; then + rustup toolchain install nightly-2026-09-25 +fi + +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT + +if [[ "$(uname)" == "Darwin" ]]; then + SO_EXT="dylib" +else + SO_EXT="so" +fi + +rustc +nightly-2026-09-25 --edition 2021 --crate-type proc-macro --crate-name safety \ + -o "$STAGE/libsafety.$SO_EXT" safety_stub.rs + +ALLOC_SRC="../../../../library/alloc/src" +VF_ORIG="$VERIFAST_HOME/tests/rust/safe_abstraction/vec/original" + +stage_tree() { + local dst="$1" + mkdir -p "$dst/boxed" "$dst/collections/vec_deque" "$dst/raw_vec" "$dst/vec" + cp lib.rs "$dst/lib.rs" + for f in alloc.rs borrow.rs boxed.rs fmt.rs intrinsics.rs macros.rs panicking.rs slice.rs str.rs string.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$VF_ORIG/$f" > "$dst/$f" + done + for f in "$VF_ORIG/boxed/"*.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$f" > "$dst/boxed/$(basename "$f")" + done + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$VF_ORIG/collections/mod.rs" > "$dst/collections/mod.rs" + for f in "$VF_ORIG/collections/vec_deque/"*.rs; do + sed 's/CURRENT_RUSTC_VERSION/1.100.0/g' "$f" > "$dst/collections/vec_deque/$(basename "$f")" + done + cp "$ALLOC_SRC/raw_vec/mod.rs" "$dst/raw_vec/mod.rs" + for f in "$ALLOC_SRC/vec/"*.rs; do + base="$(basename "$f")" + case "$base" in + verify*.rs) ;; + *) cp "$f" "$dst/vec/$base" ;; + esac + done +} + +stage_tree "$STAGE/original" +cp original/vec_mod.rs "$STAGE/original/vec/mod.rs" +cp original/spec_extend_with.rs "$STAGE/original/vec/spec_extend_with.rs" +cp original/set_len_on_drop.rs "$STAGE/original/vec/set_len_on_drop.rs" + +cp -a "$STAGE/original" "$STAGE/with-directives" +cp ../../raw_vec/mod.rs/with-directives/raw_vec.rs "$STAGE/with-directives/raw_vec/mod.rs" +cp with-directives/spec_extend_with.rs "$STAGE/with-directives/vec/spec_extend_with.rs" + +cp -a "$STAGE/with-directives" "$STAGE/verified" +cp verified/raw_vec_mod.rs "$STAGE/verified/raw_vec/mod.rs" +cp verified/vec_mod.rs "$STAGE/verified/vec/mod.rs" +cp verified/spec_extend_with.rs "$STAGE/verified/vec/spec_extend_with.rs" +cp verified/set_len_on_drop.rs "$STAGE/verified/vec/set_len_on_drop.rs" + +RUSTC_ARGS="--crate-name alloc --edition 2024 --extern safety=$STAGE/libsafety.$SO_EXT" + +verifast -rustc_args "$RUSTC_ARGS" -skip_specless_fns -ignore_unwind_paths -allow_assume "$STAGE/verified/lib.rs" +# Companion zero-`assume` proof of `SetLenOnDrop::{new, increment_len, drop}` (no `-allow_assume`!): +verifast -rustc_args "--edition 2024" -ignore_unwind_paths set_len_on_drop_proof.rs +python3 - "$ALLOC_SRC/vec/set_len_on_drop.rs" set_len_on_drop_proof.rs << 'PY' +import re, sys + +def strip_comments(code: str) -> str: + # Remove block comments (including VeriFast /*@ ... @*/) and line comments (including //@) + code = re.sub(r"/\*.*?\*/", "", code, flags=re.S) + code = re.sub(r"//[^\n]*", "", code) + return re.sub(r"\s+", " ", code).strip() + +def extract_fn_body(src: str, header_re: str) -> str: + m = re.search(header_re, src, flags=re.S) + assert m, f"Could not locate function header matching {header_re!r}" + # Find opening brace of the function body (skipping ghost blocks /*@ ... @*/ and //@ lines) + i = m.end() + n = len(src) + while i < n: + if src.startswith("/*", i): + end = src.find("*/", i + 2) + assert end != -1 + i = end + 2 + elif src.startswith("//", i): + end = src.find("\n", i + 2) + i = n if end == -1 else end + 1 + elif src[i] == "{": + break + else: + i += 1 + assert i < n and src[i] == "{", f"Missing body brace for {header_re!r}" + depth = 0 + start = i + while i < n: + if src.startswith("/*", i): + end = src.find("*/", i + 2) + assert end != -1 + i = end + 2 + continue + if src.startswith("//", i): + end = src.find("\n", i + 2) + i = n if end == -1 else end + 1 + continue + if src[i] == "{": + depth += 1 + elif src[i] == "}": + depth -= 1 + if depth == 0: + return strip_comments(src[start + 1 : i]) + i += 1 + raise AssertionError(f"Unclosed body brace for {header_re!r}") + +src = open(sys.argv[1]).read() +prf = open(sys.argv[2]).read() + +prod_new = extract_fn_body(src, r"pub\(super\)\s+fn\s+new\s*\([^)]*\)\s*->\s*Self") +prod_inc = extract_fn_body(src, r"pub\(super\)\s+fn\s+increment_len\s*\([^)]*\)") +prod_drop = extract_fn_body(src, r"impl\s+Drop\s+for\s+SetLenOnDrop<'_>\s*\{.*?fn\s+drop\s*\(&mut\s+self\)") + +checks = [ + ("new_checked", r"pub\s+unsafe\s+fn\s+new_checked\s*\([^)]*\)\s*->\s*Self", prod_new), + ("increment_len_checked", r"pub\s+unsafe\s+fn\s+increment_len_checked\s*\([^)]*\)", prod_inc), + ("increment_len_preserves_bound", r"pub\s+unsafe\s+fn\s+increment_len_preserves_bound\s*\([^)]*\)", prod_inc), + ("drop_writeback_preserves_fbc", r"pub\s+unsafe\s+fn\s+drop_writeback_preserves_fbc\s*\([^)]*\)", prod_drop), + ("drop_writeback_exact", r"pub\s+unsafe\s+fn\s+drop_writeback_exact\s*\([^)]*\)", prod_drop), + ("SetLenOnDropTrait::increment_len", r"impl<'a>\s+SetLenOnDropTrait<'a>\s*\{.*?pub\s+unsafe\s+fn\s+increment_len\s*\([^)]*\)", prod_inc), + ("SetLenOnDropTrait::drop", r"impl<'a>\s+Drop\s+for\s+SetLenOnDropTrait<'a>\s*\{.*?fn\s+drop\s*\(&mut\s+self\)", f"unsafe {{ {prod_drop} }}"), +] +for name, pat, expected in checks: + got = extract_fn_body(prf, pat) + assert got == expected, f"Body mismatch for {name}: got {got!r}, expected {expected!r}" +trait_new = extract_fn_body(prf, r"impl<'a>\s+SetLenOnDropTrait<'a>\s*\{.*?pub\s+unsafe\s+fn\s+new\s*\([^)]*\)\s*->\s*Self") +assert trait_new == "let local_len = *len; let res = SetLenOnDropTrait { local_len, len: len as *mut usize, _marker: PhantomData }; res", f"Unexpected SetLenOnDropTrait::new body: {trait_new!r}" +assert "assume(" not in prf, "set_len_on_drop_proof.rs must contain zero assume() statements" +print(f"set_len_on_drop_proof.rs scoped method-body sync check ({len(checks) + 1}/8 methods, 0 assume): OK") +PY +refinement-checker --ignore-directives --rustc-args "$RUSTC_ARGS" "$STAGE/original/lib.rs" "$STAGE/with-directives/lib.rs" > /dev/null +refinement-checker --rustc-args "$RUSTC_ARGS" "$STAGE/with-directives/lib.rs" "$STAGE/verified/lib.rs" > /dev/null + +if ! diff original/vec_mod.rs "$ALLOC_SRC/vec/mod.rs"; then + echo "::error title=VeriFast proof out of date::original/vec_mod.rs differs from library/alloc/src/vec/mod.rs" + false +fi +if ! diff original/spec_extend_with.rs "$ALLOC_SRC/vec/spec_extend_with.rs"; then + echo "::error title=VeriFast proof out of date::original/spec_extend_with.rs differs from library/alloc/src/vec/spec_extend_with.rs" + false +fi +if ! diff original/set_len_on_drop.rs "$ALLOC_SRC/vec/set_len_on_drop.rs"; then + echo "::error title=VeriFast proof out of date::original/set_len_on_drop.rs differs from library/alloc/src/vec/set_len_on_drop.rs" + false +fi +python3 sync_raw_vec.py --check diff --git a/verifast-proofs/alloc/vec/mod.rs/with-directives/spec_extend_with.rs b/verifast-proofs/alloc/vec/mod.rs/with-directives/spec_extend_with.rs new file mode 100644 index 0000000000000..8b291a398b496 --- /dev/null +++ b/verifast-proofs/alloc/vec/mod.rs/with-directives/spec_extend_with.rs @@ -0,0 +1,114 @@ +use core::clone::TrivialClone; +#[cfg(kani)] +use core::kani; +use core::{mem, ptr}; + +use crate::alloc::Allocator; +use crate::vec::{SetLenOnDrop, Vec}; + +pub(super) trait SpecExtendWith { + /// Extend the vector by `n` clones of value. + fn spec_extend_with(&mut self, n: usize, value: T); +} + +impl SpecExtendWith for Vec { + default fn spec_extend_with(&mut self, n: usize, /*@~mut@*/ value: T) { + self.reserve(n); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let mut ptr = unsafe { self.as_mut_ptr().add(self.len()) }; + // Use SetLenOnDrop to work around bug where compiler + // might not realize the store through `ptr` through self.set_len() + // don't alias. + let mut local_len = SetLenOnDrop::new(&mut self.len); + + // Write all elements except the last one + for _ in 1..n { + // three things have been taken into consideration: + // - `T::clone` can be provided by the user, and can panic. + // - `T` may implement Drop. + // - Since we already have a `value: T`, we can clone `n - 1` times. + + // This loop runs at most `n - 1` times, for all slots except the last one. + // As per the guarantee of `reserve`, increments to `ptr` within this range won't wrap around. + + // if clone() panics and starts unwinding; + // - the write has not been done yet + // - the length will be set by SetLenOnDrop, to the amount of initialized elements + // - later, when the Vec is dropped, only initialized elements are dropped. + // SAFETY: According to the diagram above, this write is within bounds. + unsafe { ptr::write(ptr, value.clone()) }; + // SAFETY: According to the diagram above, this increment is within bounds of the + // allocation and won't wrap around + ptr = unsafe { ptr.add(1) }; + // Increment the length of SetLenOnDrop in every step in case clone() panics to drop the + // already-initialized elements. + local_len.increment_len(1); + } + + if n > 0 { + // We can write the last element directly without cloning needlessly + + // SAFETY: According to the diagram above, the last element is not yet written, + // so this write is within bounds. + unsafe { ptr::write(ptr, value) }; + local_len.increment_len(1); + } + + // len set by scope guard + } +} + +impl SpecExtendWith for Vec { + fn spec_extend_with(&mut self, n: usize, value: T) { + // The `n == 0` check is already being inserted by the loop canonicalization pass, + // so this costs nothing. + // https://llvm.org/docs/LoopTerminology.html#more-canonical-loops + if n == 0 { + // three things: + // `self.reserve(0)` does not need to be run, since reserving space for 0 elements + // is a no-op. since the `value` argument did not have anywhere to be moved to, it is + // dropped here. with this branch present here, we can elide the write through self.len, + // since `self.len += 0` would be a no-op. + return; + } + + self.reserve(n); + + // SAFETY: Since `reserve` guarantees `self.len() + n` <= `capacity`, this + // pointer is always within bounds, and valid for writes for the next `n` items. + let ptr = unsafe { self.as_mut_ptr().add(self.len()) }; + + let mut i = 0; + // Write all the elements by copying `value`. + // We use an incrementing index here instead of incrementing pointer because the former + // has been observed to have less register pressure in the loop initialization. + // https://llvm.org/docs/Vectorizers.html#inductions + #[cfg_attr(kani, kani::loop_invariant(i <= n))] + #[cfg_attr(kani, kani::loop_modifies(&i, ptr::slice_from_raw_parts_mut(ptr, n)))] + while i < n { + // SAFETY: `TrivialClone` indicates that copying `value` is equivalent to + // calling `Clone::clone` for `T`. As per the safety comment for `ptr`, this pointer + // is within bounds, won't wrap around while `i < n`, and valid for writes. The values + // do not overlap since `value` is stored as a function argument, and the target is + // in the Vec. + unsafe { ptr.add(i).copy_from_nonoverlapping(&value, 1) }; + + // Because above is infallible, we don't need to worry about setting the len + // in this loop, and instead we just increment the loop induction variable. + i += 1; + } + + // Above, `n` items have been infallibly copied into the vector + self.len += n; + + // The reason we did not treat the last position in the vector specially by doing + // `n - 1` copies and semantically moving `value` into it is that we are forced to do `n` + // copies of the value no matter what, and it's better to do it in the above loop than + // by manually writing since it can be vectorized. + // Then, `value` was never semantically moved into the vec, only copied from, + // so we forget it here to prevent the Drop. + mem::forget(value); + } +} diff --git a/verifast-proofs/check-verifast-proofs-negative.sh b/verifast-proofs/check-verifast-proofs-negative.sh index 89fa996463136..d79ba794d3696 100755 --- a/verifast-proofs/check-verifast-proofs-negative.sh +++ b/verifast-proofs/check-verifast-proofs-negative.sh @@ -11,4 +11,9 @@ cd alloc bash verify.sh cd .. cd .. + cd vec + cd mod.rs-negative + bash verify.sh + cd .. + cd .. cd .. diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 23bd82948efbd..bdad80416c743 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -17,4 +17,9 @@ cd alloc bash verify.sh cd .. cd .. + cd vec + cd mod.rs + bash verify.sh + cd .. + cd .. cd .. diff --git a/verifast-proofs/patch-verifast-proofs.sh b/verifast-proofs/patch-verifast-proofs.sh index 802b68ba7b68a..406ba909bfdc3 100755 --- a/verifast-proofs/patch-verifast-proofs.sh +++ b/verifast-proofs/patch-verifast-proofs.sh @@ -22,3 +22,9 @@ popd pushd alloc/raw_vec/mod.rs patch_proof popd +pushd alloc/vec/mod.rs + patch_proof +popd +pushd alloc/vec/mod.rs-negative + patch_proof +popd