Skip to main content

vortex_buffer/
buffer_mut.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use core::mem::MaybeUninit;
5use std::alloc::Layout;
6use std::any::type_name;
7use std::cmp::max;
8use std::fmt::Debug;
9use std::fmt::Formatter;
10use std::ops::Deref;
11use std::ops::DerefMut;
12
13use itertools::Itertools;
14use vortex_error::VortexExpect;
15use vortex_error::vortex_panic;
16
17use crate::Alignment;
18use crate::Allocation;
19use crate::Buffer;
20use crate::BufferAllocatorRef;
21use crate::ByteBufferMut;
22use crate::debug::TruncatedDebug;
23use crate::trusted_len::TrustedLen;
24
25/// A mutable buffer that maintains a runtime-defined alignment through resizing operations.
26///
27/// Zero-sized element types are rejected at compile time when constructing a buffer.
28///
29/// ```compile_fail
30/// use vortex_buffer::BufferMut;
31/// let _ = BufferMut::<()>::empty();
32/// ```
33///
34/// ```compile_fail
35/// use vortex_buffer::BufferMut;
36/// let _ = BufferMut::<()>::zeroed(3);
37/// ```
38pub struct BufferMut<T> {
39    /// The owned allocation, including any bytes before `ptr` used for alignment.
40    pub(crate) allocation: Allocation,
41    /// The first element, aligned to `alignment`; it may dangle for an empty buffer.
42    pub(crate) ptr: std::ptr::NonNull<T>,
43    /// The number of initialized `T` values starting at `ptr`.
44    pub(crate) length: usize,
45    /// The number of `T` values that fit from `ptr`.
46    pub(crate) capacity: usize,
47    /// The minimum alignment maintained for `ptr` across reallocations.
48    pub(crate) alignment: Alignment,
49    /// Marks the buffer as logically owning values of `T` despite storing an erased allocation.
50    pub(crate) _marker: std::marker::PhantomData<T>,
51}
52
53// SAFETY: BufferMut uniquely owns its allocation and only exposes T across threads.
54unsafe impl<T: Send> Send for BufferMut<T> {}
55// SAFETY: shared access to BufferMut only exposes shared access to T.
56unsafe impl<T: Sync> Sync for BufferMut<T> {}
57
58impl<T> BufferMut<T> {
59    /// Create a new `BufferMut` with the requested alignment and capacity.
60    pub fn with_capacity(capacity: usize) -> Self {
61        Self::with_capacity_in(capacity, BufferAllocatorRef::statically_allocated())
62    }
63
64    /// Create a new `BufferMut` with the requested capacity and allocator.
65    pub fn with_capacity_in(capacity: usize, allocator: BufferAllocatorRef) -> Self {
66        Self::with_capacity_aligned_in(capacity, Alignment::of::<T>(), allocator)
67    }
68
69    /// Create a new `BufferMut` with the requested alignment and capacity.
70    ///
71    /// The allocation is over-aligned to [`Alignment::DEFAULT_ALIGNMENT`] when that is larger than
72    /// `alignment`. Use [`with_capacity_preferred_aligned`] to control the over-alignment.
73    ///
74    /// [`with_capacity_preferred_aligned`]: Self::with_capacity_preferred_aligned
75    pub fn with_capacity_aligned(capacity: usize, alignment: Alignment) -> Self {
76        Self::with_capacity_aligned_in(
77            capacity,
78            alignment,
79            BufferAllocatorRef::statically_allocated(),
80        )
81    }
82
83    /// Create a new `BufferMut` with the requested alignment, capacity, and allocator.
84    pub fn with_capacity_aligned_in(
85        capacity: usize,
86        alignment: Alignment,
87        allocator: BufferAllocatorRef,
88    ) -> Self {
89        Self::with_capacity_preferred_aligned_in(
90            capacity,
91            alignment,
92            Some(Alignment::DEFAULT_ALIGNMENT),
93            allocator,
94        )
95    }
96
97    /// Create a new `BufferMut` with the requested alignment and capacity.
98    ///
99    /// The buffer reports `alignment`, but the underlying allocation is over-aligned to the larger
100    /// of `alignment` and `preferred_alignment`.
101    pub fn with_capacity_preferred_aligned(
102        capacity: usize,
103        alignment: Alignment,
104        preferred_alignment: Option<Alignment>,
105    ) -> Self {
106        Self::with_capacity_preferred_aligned_in(
107            capacity,
108            alignment,
109            preferred_alignment,
110            BufferAllocatorRef::statically_allocated(),
111        )
112    }
113
114    /// Create a new allocator-backed `BufferMut` with a requested and preferred alignment.
115    pub fn with_capacity_preferred_aligned_in(
116        capacity: usize,
117        alignment: Alignment,
118        preferred_alignment: Option<Alignment>,
119        allocator: BufferAllocatorRef,
120    ) -> Self {
121        const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
122        let actual = max(
123            alignment,
124            preferred_alignment.unwrap_or(Alignment::of::<u8>()),
125        );
126
127        if !alignment.is_aligned_to(Alignment::of::<T>()) {
128            misaligned_scalar_type(alignment, Alignment::of::<T>());
129        }
130
131        let size = capacity
132            .checked_mul(size_of::<T>())
133            .vortex_expect("buffer capacity overflow");
134        let layout = if size == 0 {
135            Layout::from_size_align(0, actual.as_usize())
136                .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
137        } else {
138            let allocation_size = size
139                .checked_add(actual.as_usize())
140                .vortex_expect("buffer capacity overflow");
141            Layout::from_size_align(allocation_size, 1).unwrap_or_else(|_| {
142                vortex_panic!("buffer capacity exceeds maximum allocation size")
143            })
144        };
145        let allocation = Allocation::allocate(layout, allocator);
146        let offset = allocation.ptr().as_ptr().align_offset(actual.as_usize());
147        // SAFETY: the allocation includes enough padding to reach this aligned pointer.
148        let ptr = unsafe { allocation.ptr().add(offset).cast() };
149        let capacity = (allocation.size() - offset) / size_of::<T>();
150        Self {
151            allocation,
152            ptr,
153            length: 0,
154            capacity,
155            alignment,
156            _marker: Default::default(),
157        }
158    }
159
160    /// Create a new zeroed `BufferMut`.
161    pub fn zeroed(len: usize) -> Self {
162        Self::zeroed_in(len, BufferAllocatorRef::statically_allocated())
163    }
164
165    /// Create a new zeroed `BufferMut` with the requested allocator.
166    pub fn zeroed_in(len: usize, allocator: BufferAllocatorRef) -> Self {
167        Self::zeroed_aligned_in(len, Alignment::of::<T>(), allocator)
168    }
169
170    /// Create a new zeroed `BufferMut` with the requested alignment.
171    ///
172    /// The allocation is over-aligned to [`Alignment::DEFAULT_ALIGNMENT`] when that is larger than
173    /// `alignment`. Use [`zeroed_preferred_aligned`] to control the over-alignment.
174    ///
175    /// [`zeroed_preferred_aligned`]: Self::zeroed_preferred_aligned
176    pub fn zeroed_aligned(len: usize, alignment: Alignment) -> Self {
177        Self::zeroed_aligned_in(len, alignment, BufferAllocatorRef::statically_allocated())
178    }
179
180    /// Create a zeroed `BufferMut` with an alignment and allocator.
181    pub fn zeroed_aligned_in(
182        len: usize,
183        alignment: Alignment,
184        allocator: BufferAllocatorRef,
185    ) -> Self {
186        Self::zeroed_preferred_aligned_in(
187            len,
188            alignment,
189            Some(Alignment::DEFAULT_ALIGNMENT),
190            allocator,
191        )
192    }
193
194    /// Create a new zeroed `BufferMut` with the requested alignment.
195    ///
196    /// The buffer reports `alignment`, but the underlying allocation is over-aligned to the larger
197    /// of `alignment` and `preferred_alignment`.
198    pub fn zeroed_preferred_aligned(
199        len: usize,
200        alignment: Alignment,
201        preferred_alignment: Option<Alignment>,
202    ) -> Self {
203        Self::zeroed_preferred_aligned_in(
204            len,
205            alignment,
206            preferred_alignment,
207            BufferAllocatorRef::statically_allocated(),
208        )
209    }
210
211    /// Create a zeroed allocator-backed buffer with a requested and preferred alignment.
212    pub fn zeroed_preferred_aligned_in(
213        len: usize,
214        alignment: Alignment,
215        preferred_alignment: Option<Alignment>,
216        allocator: BufferAllocatorRef,
217    ) -> Self {
218        const { assert!(size_of::<T>() != 0, "ZSTs are not supported") };
219        let preferred_alignment = preferred_alignment.unwrap_or(Alignment::of::<u8>());
220        let actual_alignment = max(preferred_alignment, alignment);
221        let size = len
222            .checked_mul(size_of::<T>())
223            .vortex_expect("buffer length overflow");
224        let layout = if size == 0 {
225            Layout::from_size_align(0, actual_alignment.as_usize())
226                .unwrap_or_else(|_| vortex_panic!("invalid empty buffer alignment"))
227        } else {
228            let allocation_size = size
229                .checked_add(actual_alignment.as_usize())
230                .vortex_expect("buffer length overflow");
231            Layout::from_size_align(allocation_size, 1)
232                .unwrap_or_else(|_| vortex_panic!("buffer length exceeds maximum allocation size"))
233        };
234        let allocation = Allocation::allocate_zeroed(layout, allocator);
235        let offset = allocation
236            .ptr()
237            .as_ptr()
238            .align_offset(actual_alignment.as_usize());
239        // SAFETY: the allocation includes enough padding to reach this aligned pointer.
240        let ptr = unsafe { allocation.ptr().add(offset).cast() };
241        let capacity = (allocation.size() - offset) / size_of::<T>();
242        Self {
243            allocation,
244            ptr,
245            length: len,
246            capacity,
247            alignment,
248            _marker: Default::default(),
249        }
250    }
251
252    /// Create a new empty `BufferMut` with the provided alignment.
253    pub fn empty() -> Self {
254        Self::empty_aligned(Alignment::of::<T>())
255    }
256
257    /// Create a new empty `BufferMut` with the provided alignment.
258    ///
259    /// The allocation is over-aligned to [`Alignment::DEFAULT_ALIGNMENT`] when that is larger than
260    /// `alignment`. Use [`empty_preferred_aligned`] to control the over-alignment.
261    ///
262    /// [`empty_preferred_aligned`]: Self::empty_preferred_aligned
263    pub fn empty_aligned(alignment: Alignment) -> Self {
264        Self::empty_aligned_in(alignment, BufferAllocatorRef::statically_allocated())
265    }
266
267    /// Create an empty `BufferMut` with an alignment and allocator.
268    pub fn empty_aligned_in(alignment: Alignment, allocator: BufferAllocatorRef) -> Self {
269        Self::with_capacity_aligned_in(0, alignment, allocator)
270    }
271
272    /// Create a new empty `BufferMut` with the provided alignment.
273    ///
274    /// The buffer reports `alignment`, but the underlying allocation is over-aligned to the larger
275    /// of `alignment` and `preferred_alignment`.
276    pub fn empty_preferred_aligned(
277        alignment: Alignment,
278        preferred_alignment: Option<Alignment>,
279    ) -> Self {
280        BufferMut::with_capacity_preferred_aligned_in(
281            0,
282            alignment,
283            preferred_alignment,
284            BufferAllocatorRef::statically_allocated(),
285        )
286    }
287
288    /// Create a new full `BufferMut` with the given value.
289    pub fn full(item: T, len: usize) -> Self
290    where
291        T: Copy,
292    {
293        Self::full_in(item, len, BufferAllocatorRef::statically_allocated())
294    }
295
296    /// Create a full `BufferMut` with the given value and allocator.
297    pub fn full_in(item: T, len: usize, allocator: BufferAllocatorRef) -> Self
298    where
299        T: Copy,
300    {
301        let mut buffer = BufferMut::<T>::with_capacity_in(len, allocator);
302        buffer.push_n(item, len);
303        buffer
304    }
305
306    /// Create a mutable scalar buffer by copying the contents of the slice.
307    pub fn copy_from(other: impl AsRef<[T]>) -> Self
308    where
309        T: Copy,
310    {
311        Self::copy_from_in(other, BufferAllocatorRef::statically_allocated())
312    }
313
314    /// Create a mutable scalar buffer by copying with the given allocator.
315    pub fn copy_from_in(other: impl AsRef<[T]>, allocator: BufferAllocatorRef) -> Self
316    where
317        T: Copy,
318    {
319        Self::copy_from_aligned_in(other, Alignment::of::<T>(), allocator)
320    }
321
322    /// Create a mutable scalar buffer with the alignment by copying the contents of the slice.
323    ///
324    /// The allocation is over-aligned to [`Alignment::DEFAULT_ALIGNMENT`] when that is larger than
325    /// `alignment`. Use [`copy_from_preferred_aligned`] to control the over-alignment.
326    ///
327    /// [`copy_from_preferred_aligned`]: Self::copy_from_preferred_aligned
328    ///
329    /// ## Panics
330    ///
331    /// Panics when the requested alignment isn't itself aligned to type T.
332    pub fn copy_from_aligned(other: impl AsRef<[T]>, alignment: Alignment) -> Self
333    where
334        T: Copy,
335    {
336        Self::copy_from_aligned_in(other, alignment, BufferAllocatorRef::statically_allocated())
337    }
338
339    /// Copy values into a mutable buffer with the given alignment and allocator.
340    pub fn copy_from_aligned_in(
341        other: impl AsRef<[T]>,
342        alignment: Alignment,
343        allocator: BufferAllocatorRef,
344    ) -> Self
345    where
346        T: Copy,
347    {
348        Self::copy_from_preferred_aligned_in(
349            other,
350            alignment,
351            Some(Alignment::DEFAULT_ALIGNMENT),
352            allocator,
353        )
354    }
355
356    /// Create a mutable scalar buffer with the alignment by copying the contents of the slice.
357    ///
358    /// The buffer reports `alignment`, but the underlying allocation is over-aligned to the larger
359    /// of `alignment` and `preferred_alignment`.
360    ///
361    /// ## Panics
362    ///
363    /// Panics when the requested alignment isn't itself aligned to type T.
364    pub fn copy_from_preferred_aligned(
365        other: impl AsRef<[T]>,
366        alignment: Alignment,
367        preferred_alignment: Option<Alignment>,
368    ) -> Self
369    where
370        T: Copy,
371    {
372        Self::copy_from_preferred_aligned_in(
373            other,
374            alignment,
375            preferred_alignment,
376            BufferAllocatorRef::statically_allocated(),
377        )
378    }
379
380    /// Copy values with the given allocator, requested alignment, and preferred alignment.
381    pub fn copy_from_preferred_aligned_in(
382        other: impl AsRef<[T]>,
383        alignment: Alignment,
384        preferred_alignment: Option<Alignment>,
385        allocator: BufferAllocatorRef,
386    ) -> Self
387    where
388        T: Copy,
389    {
390        if !alignment.is_aligned_to(Alignment::of::<T>()) {
391            vortex_panic!("Given alignment is not aligned to type T")
392        }
393        let other = other.as_ref();
394        let mut buffer = Self::with_capacity_preferred_aligned_in(
395            other.len(),
396            alignment,
397            preferred_alignment,
398            allocator,
399        );
400        buffer.extend_from_slice(other);
401        debug_assert_eq!(buffer.alignment(), alignment);
402        buffer
403    }
404
405    /// Get the alignment of the buffer.
406    #[allow(clippy::inline_always)]
407    #[inline(always)]
408    pub fn alignment(&self) -> Alignment {
409        self.alignment
410    }
411
412    /// Takes the buffer, leaving an empty buffer with the same alignment and allocator.
413    pub fn take(&mut self) -> Self {
414        let replacement =
415            Self::empty_aligned_in(self.alignment, self.allocation.allocator().clone());
416        std::mem::replace(self, replacement)
417    }
418
419    /// Returns the length of the buffer.
420    #[allow(clippy::inline_always)]
421    #[inline(always)]
422    pub fn len(&self) -> usize {
423        self.length
424    }
425
426    /// Returns whether the buffer is empty.
427    #[allow(clippy::inline_always)]
428    #[inline(always)]
429    pub fn is_empty(&self) -> bool {
430        self.length == 0
431    }
432
433    /// Returns the capacity of the buffer.
434    #[inline]
435    pub fn capacity(&self) -> usize {
436        self.capacity
437    }
438
439    /// Returns a raw pointer to the buffer's data.
440    #[allow(clippy::inline_always)]
441    #[inline(always)]
442    pub fn as_ptr(&self) -> *const T {
443        self.ptr.as_ptr()
444    }
445
446    /// Returns a mutable raw pointer to the buffer's data.
447    #[allow(clippy::inline_always)]
448    #[inline(always)]
449    pub fn as_mut_ptr(&mut self) -> *mut T {
450        self.ptr.as_ptr()
451    }
452
453    /// Returns a slice over the buffer of elements of type T.
454    #[inline]
455    pub fn as_slice(&self) -> &[T] {
456        // SAFETY: ptr is in the live allocation and construction checks its alignment.
457        unsafe { std::slice::from_raw_parts(self.as_ptr(), self.length) }
458    }
459
460    /// Returns a slice over the buffer of elements of type T.
461    #[inline]
462    pub fn as_mut_slice(&mut self) -> &mut [T] {
463        // SAFETY: BufferMut uniquely owns the allocation and the initialized range is in bounds.
464        unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.length) }
465    }
466
467    /// Clear the buffer, retaining any existing capacity.
468    #[inline]
469    pub fn clear(&mut self) {
470        self.length = 0;
471    }
472
473    /// Shortens the buffer, keeping the first `len` bytes and dropping the
474    /// rest.
475    ///
476    /// If `len` is greater than the buffer's current length, this has no
477    /// effect.
478    ///
479    /// Existing underlying capacity is preserved.
480    #[inline]
481    pub fn truncate(&mut self, len: usize) {
482        if len <= self.len() {
483            // SAFETY: Shrinking the buffer cannot expose uninitialized bytes.
484            unsafe { self.set_len(len) };
485        }
486    }
487
488    /// Reserves capacity for at least `additional` more elements to be inserted in the buffer.
489    #[inline]
490    pub fn reserve(&mut self, additional: usize) {
491        if additional <= self.capacity() - self.length {
492            // We can fit the additional bytes in the remaining capacity. Nothing to do.
493            return;
494        }
495
496        // Otherwise, reserve additional + alignment bytes in case we need to realign the buffer.
497        self.reserve_allocate(additional);
498    }
499
500    /// Keeps allocation work out of the inline fast path in [`Self::reserve`].
501    ///
502    /// Buffer capacity measures the space available from the data pointer. The allocation also
503    /// includes any bytes before that pointer, which can come from alignment padding or slicing.
504    /// The new layout follows the buffer growth policy without retaining that old prefix.
505    ///
506    /// For a byte buffer:
507    ///
508    /// ```text
509    /// Before reserve(100): allocation = 1,000 bytes, capacity = 100 bytes.
510    /// | 900 bytes before slice | 100 data |
511    ///                          ^ data pointer
512    ///
513    /// After reserve(100): allocation = 257 bytes, capacity = 256 bytes.
514    /// | 100 data | 156 spare | 1 unused |
515    /// ^ data pointer
516    /// ```
517    ///
518    /// [`Allocator::grow`] requires the new allocation to be at least as large as the entire old
519    /// allocation. If the new layout is smaller, allocate a separate block and copy the initialized
520    /// data instead of violating that safety contract.
521    ///
522    /// [`Allocator::grow`]: allocator_api2::alloc::Allocator::grow
523    fn reserve_allocate(&mut self, additional: usize) {
524        let required_capacity = self
525            .length
526            .checked_add(additional)
527            .vortex_expect("buffer capacity overflow");
528        let required_bytes = required_capacity
529            .checked_mul(size_of::<T>())
530            .vortex_expect("buffer capacity overflow");
531        let capacity_bytes = self
532            .capacity
533            .checked_mul(size_of::<T>())
534            .vortex_expect("buffer capacity overflow");
535        let new_capacity_bytes = required_bytes
536            .max(capacity_bytes.saturating_mul(2))
537            .max(Alignment::DEFAULT_ALIGNMENT.as_usize());
538
539        // Reserve space before the data so its pointer can satisfy the buffer's alignment.
540        let data_alignment = self.alignment.as_usize();
541        let new_allocation_bytes = new_capacity_bytes
542            .checked_add(data_alignment)
543            .vortex_expect("buffer capacity overflow");
544        let allocation_alignment = if self.allocation.size() == 0 {
545            1
546        } else {
547            self.allocation.alignment()
548        };
549        let new_layout = Layout::from_size_align(new_allocation_bytes, allocation_alignment)
550            .unwrap_or_else(|_| vortex_panic!("buffer capacity exceeds maximum allocation size"));
551        let initialized_bytes = self.length * size_of::<T>();
552
553        // The default global allocator (`is_statically_allocated`) uses allocate-and-copy. Custom
554        // allocators must also allocate and copy when the new layout is smaller, because
555        // `Allocator::grow` forbids shrinking.
556        let needs_new_allocation = self.allocation.allocator().is_statically_allocated()
557            || new_layout.size() < self.allocation.size();
558
559        let data_offset = if needs_new_allocation {
560            let new_allocation =
561                Allocation::allocate(new_layout, self.allocation.allocator().clone());
562            let new_data_offset = new_allocation.ptr().as_ptr().align_offset(data_alignment);
563
564            // SAFETY: self.ptr addresses initialized_bytes of live data. The new allocation has
565            // room for those bytes after alignment padding and is disjoint from the old allocation.
566            unsafe {
567                std::ptr::copy_nonoverlapping(
568                    self.ptr.cast::<u8>().as_ptr(),
569                    new_allocation.ptr().as_ptr().add(new_data_offset),
570                    initialized_bytes,
571                );
572            }
573
574            self.allocation = new_allocation;
575
576            new_data_offset
577        } else {
578            let old_data_offset =
579                self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
580            self.allocation.grow(new_layout);
581
582            let new_data_offset = self.allocation.ptr().as_ptr().align_offset(data_alignment);
583
584            if new_data_offset != old_data_offset {
585                // SAFETY: grow preserved initialized_bytes at old_data_offset. The reserved padding
586                // leaves room for the data at new_data_offset, and copy permits overlap.
587                unsafe {
588                    std::ptr::copy(
589                        self.allocation.ptr().as_ptr().add(old_data_offset),
590                        self.allocation.ptr().as_ptr().add(new_data_offset),
591                        initialized_bytes,
592                    );
593                }
594            }
595
596            new_data_offset
597        };
598
599        // SAFETY: data_offset satisfies the required alignment and leaves new_capacity_bytes
600        // available within the allocation.
601        self.ptr = unsafe { self.allocation.ptr().add(data_offset).cast() };
602        self.capacity = new_capacity_bytes / size_of::<T>();
603    }
604
605    /// Returns the spare capacity of the buffer as a slice of `MaybeUninit<T>`.
606    /// Has identical semantics to [`Vec::spare_capacity_mut`].
607    ///
608    /// The returned slice can be used to fill the buffer with data (e.g. by
609    /// reading from a file) before marking the data as initialized using the
610    /// [`set_len`] method.
611    ///
612    /// Note that the returned slice may be larger than the capacity requested at
613    /// construction, since the underlying allocation can be rounded up (e.g. to
614    /// satisfy alignment requirements).
615    ///
616    /// [`set_len`]: BufferMut::set_len
617    /// [`Vec::spare_capacity_mut`]: Vec::spare_capacity_mut
618    ///
619    /// # Examples
620    ///
621    /// ```
622    /// use vortex_buffer::BufferMut;
623    ///
624    /// // Allocate vector big enough for 10 elements.
625    /// let mut b = BufferMut::<u64>::with_capacity(10);
626    ///
627    /// // Fill in the first 3 elements.
628    /// let uninit = b.spare_capacity_mut();
629    /// uninit[0].write(0);
630    /// uninit[1].write(1);
631    /// uninit[2].write(2);
632    ///
633    /// // Mark the first 3 elements of the vector as being initialized.
634    /// unsafe {
635    ///     b.set_len(3);
636    /// }
637    ///
638    /// assert_eq!(b.as_slice(), &[0u64, 1, 2]);
639    /// ```
640    #[inline]
641    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
642        // SAFETY: offset + length is within the allocation and points at spare capacity.
643        let dst = unsafe { self.as_mut_ptr().add(self.length) }.cast::<MaybeUninit<T>>();
644        unsafe { std::slice::from_raw_parts_mut(dst, self.capacity() - self.length) }
645    }
646
647    /// Sets the length of the buffer.
648    ///
649    /// # Safety
650    ///
651    /// - `new_len` must be less than or equal to [`capacity()`].
652    /// - The elements at `old_len..new_len` must be initialized.
653    ///
654    /// [`capacity()`]: Self::capacity
655    #[inline]
656    pub unsafe fn set_len(&mut self, len: usize) {
657        debug_assert!(len <= self.capacity());
658        self.length = len;
659    }
660
661    /// Appends a scalar to the buffer.
662    #[inline]
663    pub fn push(&mut self, value: T) {
664        self.reserve(1);
665        unsafe { self.push_unchecked(value) }
666    }
667
668    /// Appends a scalar to the buffer without checking for sufficient capacity.
669    ///
670    /// ## Safety
671    ///
672    /// The caller must ensure there is sufficient capacity in the array.
673    #[inline]
674    pub unsafe fn push_unchecked(&mut self, item: T) {
675        // SAFETY: the caller ensures we have sufficient capacity
676        unsafe {
677            let dst = self.as_mut_ptr().add(self.length);
678            dst.write(item);
679        }
680        self.length += 1;
681    }
682
683    /// Appends n scalars to the buffer.
684    ///
685    /// This function is slightly more optimized than `extend(iter::repeat_n(item, b))`.
686    #[inline]
687    pub fn push_n(&mut self, item: T, n: usize)
688    where
689        T: Copy,
690    {
691        self.reserve(n);
692        unsafe { self.push_n_unchecked(item, n) }
693    }
694
695    /// Appends n scalars to the buffer.
696    ///
697    /// ## Safety
698    ///
699    /// The caller must ensure there is sufficient capacity in the array.
700    #[inline]
701    pub unsafe fn push_n_unchecked(&mut self, item: T, n: usize)
702    where
703        T: Copy,
704    {
705        // SAFETY: the caller guarantees enough spare capacity.
706        let mut dst = unsafe { self.as_mut_ptr().add(self.length) };
707        // SAFETY: we checked the capacity in the reserve call
708        unsafe {
709            let end = dst.add(n);
710            while dst < end {
711                dst.write(item);
712                dst = dst.add(1);
713            }
714        }
715        self.length += n;
716    }
717
718    /// Appends a slice by copying its elements, growing the internal buffer as needed.
719    ///
720    /// This does not call [`Clone::clone`].
721    ///
722    /// # Example
723    ///
724    /// ```
725    /// use vortex_buffer::BufferMut;
726    ///
727    /// let mut buffer = BufferMut::from_iter([1, 2]);
728    /// buffer.extend_from_slice(&[3, 4]);
729    /// assert_eq!(buffer.as_slice(), &[1, 2, 3, 4]);
730    /// ```
731    ///
732    /// Elements must implement `Copy`, even when they implement `Clone`.
733    ///
734    /// ```compile_fail,E0277
735    /// use vortex_buffer::BufferMut;
736    ///
737    /// #[derive(Clone)]
738    /// struct NotCopy(u32);
739    ///
740    /// let mut buffer = BufferMut::with_capacity(1);
741    /// buffer.extend_from_slice(&[NotCopy(1)]);
742    /// ```
743    #[inline]
744    pub fn extend_from_slice(&mut self, slice: &[T])
745    where
746        T: Copy,
747    {
748        self.reserve(slice.len());
749        let dst = self
750            .spare_capacity_mut()
751            .get_mut(..slice.len())
752            .vortex_expect("reserve guarantees sufficient spare capacity");
753        dst.write_copy_of_slice(slice);
754        self.length += slice.len();
755    }
756
757    /// Return the [`ByteBufferMut`] for this [`BufferMut`].
758    pub fn into_byte_buffer(self) -> ByteBufferMut {
759        let capacity = self
760            .capacity
761            .checked_mul(size_of::<T>())
762            .vortex_expect("buffer capacity overflow");
763        ByteBufferMut {
764            allocation: self.allocation,
765            ptr: self.ptr.cast(),
766            length: self.length * size_of::<T>(),
767            capacity,
768            alignment: self.alignment,
769            _marker: Default::default(),
770        }
771    }
772
773    /// Freeze the `BufferMut` into a `Buffer`.
774    pub fn freeze(self) -> Buffer<T> {
775        let offset = self.ptr.cast::<u8>().addr().get() - self.allocation.ptr().addr().get();
776        Buffer::from_allocation(self.allocation, offset, self.length, self.alignment)
777    }
778
779    /// Return a `BufferMut<T>` with the same data as this one with the given alignment.
780    ///
781    /// If the data is already properly aligned, this is a metadata-only operation.
782    ///
783    /// If the data is not aligned, we copy it into a new allocation.
784    pub fn aligned(self, alignment: Alignment) -> Self
785    where
786        T: Copy,
787    {
788        if self.as_ptr().align_offset(alignment.as_usize()) == 0 {
789            Self { alignment, ..self }
790        } else {
791            let capacity = self.capacity();
792            let allocator = self.allocation.allocator().clone();
793            let mut aligned = Self::with_capacity_aligned_in(capacity, alignment, allocator);
794            aligned.extend_from_slice(&self);
795            aligned.capacity = capacity;
796            aligned
797        }
798    }
799
800    /// Transmute a `Buffer<T>` into a `Buffer<U>`.
801    ///
802    /// # Safety
803    ///
804    /// The caller must ensure that all possible bit representations of type `T` are valid when
805    /// interpreted as type `U`.
806    /// See [`std::mem::transmute`] for more details.
807    ///
808    /// # Panics
809    ///
810    /// Panics if the type `U` does not have the same size and alignment as `T`.
811    pub unsafe fn transmute<U>(self) -> BufferMut<U> {
812        assert_eq!(size_of::<T>(), size_of::<U>(), "Buffer type size mismatch");
813        assert_eq!(
814            align_of::<T>(),
815            align_of::<U>(),
816            "Buffer type alignment mismatch"
817        );
818
819        BufferMut {
820            allocation: self.allocation,
821            ptr: self.ptr.cast(),
822            length: self.length,
823            capacity: self.capacity,
824            alignment: self.alignment,
825            _marker: std::marker::PhantomData,
826        }
827    }
828}
829
830impl<T: Copy> Clone for BufferMut<T> {
831    fn clone(&self) -> Self {
832        let mut buffer = BufferMut::<T>::with_capacity_aligned_in(
833            self.capacity(),
834            self.alignment,
835            self.allocation.allocator().clone(),
836        );
837        buffer.extend_from_slice(self.as_slice());
838        buffer
839    }
840}
841
842impl<T: PartialEq> PartialEq for BufferMut<T> {
843    fn eq(&self, other: &Self) -> bool {
844        self.as_slice() == other.as_slice()
845    }
846}
847
848impl<T: Eq> Eq for BufferMut<T> {}
849
850impl<T: Debug> Debug for BufferMut<T> {
851    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
852        f.debug_struct(&format!("BufferMut<{}>", type_name::<T>()))
853            .field("length", &self.length)
854            .field("alignment", &self.alignment)
855            .field("as_slice", &TruncatedDebug(self.as_slice()))
856            .finish()
857    }
858}
859
860impl<T> Default for BufferMut<T> {
861    fn default() -> Self {
862        Self::empty()
863    }
864}
865
866impl<T> Deref for BufferMut<T> {
867    type Target = [T];
868
869    #[inline]
870    fn deref(&self) -> &Self::Target {
871        self.as_slice()
872    }
873}
874
875impl<T> DerefMut for BufferMut<T> {
876    #[inline]
877    fn deref_mut(&mut self) -> &mut Self::Target {
878        self.as_mut_slice()
879    }
880}
881
882impl<T> AsRef<[T]> for BufferMut<T> {
883    #[inline]
884    fn as_ref(&self) -> &[T] {
885        self.as_slice()
886    }
887}
888
889impl<T> AsMut<[T]> for BufferMut<T> {
890    #[inline]
891    fn as_mut(&mut self) -> &mut [T] {
892        self.as_mut_slice()
893    }
894}
895
896impl<T> BufferMut<T> {
897    /// A helper method for the two [`Extend`] implementations.
898    ///
899    /// We use the lower bound hint on the iterator to manually write data, and then we continue to
900    /// push items normally past the lower bound.
901    fn extend_iter(&mut self, mut iter: impl Iterator<Item = T>) {
902        // Since we do not know the length of the iterator, we can only guess how much memory we
903        // need to reserve. Note that these hints may be inaccurate.
904        let (lower_bound, _) = iter.size_hint();
905
906        // We choose not to use the optional upper bound size hint to match the standard library.
907
908        self.reserve(lower_bound);
909
910        let unwritten = self.capacity() - self.len();
911
912        // We store `begin` in the case that the lower bound hint is incorrect.
913        let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
914        let mut dst: *mut T = begin.cast_mut();
915
916        // As a first step, we manually iterate the iterator up to the known capacity.
917        for _ in 0..unwritten {
918            let Some(item) = iter.next() else {
919                // The lower bound hint may be incorrect.
920                break;
921            };
922
923            // SAFETY: We have reserved enough capacity to hold this item, and `dst` is a pointer
924            // derived from a valid reference to byte data.
925            unsafe { dst.write(item) };
926
927            // Note: We used to have `dst.add(iteration).write(item)`, here. However this was much
928            // slower than just incrementing `dst`.
929            // SAFETY: The offsets fits in `isize`, and because we were able to reserve the memory
930            // we know that `add` will not overflow.
931            unsafe { dst = dst.add(1) };
932        }
933
934        // SAFETY: `dst` was derived from `begin`, which were both valid references to byte data,
935        // and since the only operation that `dst` has is `add`, we know that `dst >= begin`.
936        let items_written = unsafe { dst.offset_from_unsigned(begin) };
937        let length = self.len() + items_written;
938
939        // SAFETY: We have written valid items between the old length and the new length.
940        unsafe { self.set_len(length) };
941
942        // Finally, since the iterator will have arbitrarily more items to yield, we push the
943        // remaining items normally.
944        iter.for_each(|item| self.push(item));
945    }
946
947    /// Extends the `BufferMut` with an iterator with `TrustedLen`.
948    ///
949    /// The caller guarantees that the iterator will have a trusted upper bound, which allows the
950    /// implementation to reserve all of the memory needed up front.
951    pub fn extend_trusted<I: TrustedLen<Item = T>>(&mut self, iter: I) {
952        let (_, upper_bound) = iter.size_hint();
953        self.reserve(
954            upper_bound
955                .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
956        );
957
958        let begin: *const T = self.spare_capacity_mut().as_mut_ptr().cast();
959        let mut dst: *mut T = begin.cast_mut();
960
961        iter.for_each(|item| {
962            // SAFETY: We have reserved enough capacity to hold this item, and `dst` is a pointer
963            // derived from a valid reference to byte data.
964            unsafe { dst.write(item) };
965
966            // Note: We used to have `dst.add(iteration).write(item)`, here. However this was much
967            // slower than just incrementing `dst`.
968            // SAFETY: The offset fits in `isize`, and because we were able to reserve the memory
969            // we know that `add` will not overflow.
970            unsafe { dst = dst.add(1) };
971        });
972
973        // SAFETY: `dst` starts at `begin` and advances by one for each item, so both pointers refer
974        // to the same allocation and `dst` is at or after `begin`.
975        let items_written = unsafe { dst.offset_from_unsigned(begin) };
976        let length = self.len() + items_written;
977
978        // SAFETY: We have written valid items between the old length and the new length.
979        unsafe { self.set_len(length) };
980    }
981
982    /// Creates a `BufferMut` from an iterator with a trusted length.
983    ///
984    /// Internally, this calls [`extend_trusted()`](Self::extend_trusted).
985    pub fn from_trusted_len_iter<I>(iter: I) -> Self
986    where
987        I: TrustedLen<Item = T>,
988    {
989        let (_, upper_bound) = iter.size_hint();
990        let mut buffer = Self::with_capacity(
991            upper_bound
992                .vortex_expect("`TrustedLen` iterator somehow didn't have valid upper bound"),
993        );
994
995        buffer.extend_trusted(iter);
996        buffer
997    }
998
999    /// Like [`extend_trusted()`](Self::extend_trusted), but the iterator yields `Result<T, E>`
1000    /// and the extension short-circuits on the first `Err`.
1001    ///
1002    /// On error, items written before the failure remain in the buffer.
1003    pub fn try_extend_trusted<E, I>(&mut self, iter: I) -> Result<(), E>
1004    where
1005        I: TrustedLen<Item = Result<T, E>>,
1006    {
1007        iter.process_results(|values| self.extend_trusted(values))
1008    }
1009
1010    /// Like [`from_trusted_len_iter()`](Self::from_trusted_len_iter), but the iterator yields
1011    /// `Result<T, E>` and construction short-circuits on the first `Err`.
1012    pub fn try_from_trusted_len_iter<E, I>(iter: I) -> Result<Self, E>
1013    where
1014        I: TrustedLen<Item = Result<T, E>>,
1015    {
1016        iter.process_results(|values| Self::from_trusted_len_iter(values))
1017    }
1018}
1019
1020impl<T> Extend<T> for BufferMut<T> {
1021    #[inline]
1022    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1023        self.extend_iter(iter.into_iter())
1024    }
1025}
1026
1027impl<'a, T> Extend<&'a T> for BufferMut<T>
1028where
1029    T: Copy + 'a,
1030{
1031    #[inline]
1032    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1033        self.extend_iter(iter.into_iter().copied())
1034    }
1035}
1036
1037impl<T> FromIterator<T> for BufferMut<T> {
1038    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1039        let iter = iter.into_iter();
1040        let mut buffer = Self::with_capacity(iter.size_hint().0);
1041        buffer.extend(iter);
1042        buffer
1043    }
1044}
1045
1046#[cold]
1047#[inline(never)]
1048fn misaligned_scalar_type(alignment: Alignment, scalar_align: Alignment) -> ! {
1049    vortex_panic!("Alignment {alignment} must align to the scalar type's alignment {scalar_align}")
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054    use std::cell::Cell;
1055
1056    use allocator_api2::alloc::Global;
1057
1058    use crate::Alignment;
1059    use crate::BufferAllocatorRef;
1060    use crate::BufferMut;
1061    use crate::buffer_mut;
1062
1063    #[derive(Copy, Debug, PartialEq)]
1064    struct CopyWithCloneCounter<'a> {
1065        value: u32,
1066        clones: &'a Cell<usize>,
1067    }
1068
1069    #[allow(clippy::non_canonical_clone_impl)]
1070    impl Clone for CopyWithCloneCounter<'_> {
1071        fn clone(&self) -> Self {
1072            self.clones.set(self.clones.get() + 1);
1073            *self
1074        }
1075    }
1076
1077    #[test]
1078    fn extend_from_slice_skips_clone() {
1079        let clones = Cell::new(0);
1080        let source = [CopyWithCloneCounter {
1081            value: 42,
1082            clones: &clones,
1083        }];
1084        let mut buffer = BufferMut::empty();
1085        buffer.extend_from_slice(&source);
1086        buffer.extend_from_slice(&source);
1087        buffer.extend_from_slice(&[]);
1088        assert_eq!(clones.get(), 0);
1089        assert_eq!(buffer.as_slice(), &[source[0], source[0]]);
1090        assert_eq!(buffer.clone().as_slice(), buffer.as_slice());
1091        assert_eq!(clones.get(), 0);
1092    }
1093
1094    #[test]
1095    fn capacity() {
1096        let mut n = 57;
1097        let mut buf = BufferMut::<i32>::with_capacity_aligned(n, Alignment::new(1024));
1098        assert!(buf.capacity() >= 57);
1099
1100        while n > 0 {
1101            buf.push(0);
1102            assert!(buf.capacity() >= n);
1103            n -= 1
1104        }
1105
1106        assert_eq!(buf.alignment(), Alignment::new(1024));
1107    }
1108
1109    #[test]
1110    fn take_preserves_alignment_and_allocator() {
1111        let alignment = Alignment::new(1024);
1112        let allocator = BufferAllocatorRef::new(Global);
1113        let mut buffer = BufferMut::with_capacity_aligned_in(4, alignment, allocator.clone());
1114        buffer.extend([1u32, 2, 3]);
1115
1116        let taken = buffer.take();
1117
1118        assert_eq!(taken.as_slice(), [1, 2, 3]);
1119        assert!(taken.allocation.allocator().ptr_eq(&allocator));
1120        assert!(buffer.is_empty());
1121        assert_eq!(buffer.alignment(), alignment);
1122        assert!(buffer.allocation.allocator().ptr_eq(&allocator));
1123    }
1124
1125    #[test]
1126    fn growth_preserves_alignment_and_values() {
1127        let alignment = Alignment::new(4096);
1128        let mut buffer = BufferMut::<u64>::with_capacity_aligned(1, alignment);
1129
1130        for value in 0..10_000 {
1131            buffer.push(value);
1132            assert!(alignment.is_offset_aligned(buffer.as_ptr().addr()));
1133        }
1134
1135        assert_eq!(buffer.as_slice(), (0..10_000).collect::<Vec<_>>());
1136    }
1137
1138    #[test]
1139    fn growth_seeds_and_doubles_logical_capacity() {
1140        let alignment = Alignment::new(64);
1141        let mut buffer = BufferMut::<u8>::empty_aligned(alignment);
1142
1143        buffer.push(0);
1144        let capacity = buffer.capacity();
1145        assert_eq!(capacity, Alignment::DEFAULT_ALIGNMENT.as_usize());
1146
1147        buffer.reserve(capacity);
1148        assert_eq!(buffer.capacity(), capacity * 2);
1149    }
1150
1151    #[test]
1152    fn static_growth_copies_live_data() {
1153        let mut buffer = BufferMut::<u32>::with_capacity(1);
1154        let capacity = buffer.capacity();
1155        buffer.extend(std::iter::repeat_n(7, capacity));
1156        let old_ptr = buffer.as_ptr();
1157
1158        buffer.push(u32::MAX);
1159
1160        assert_ne!(buffer.as_ptr(), old_ptr);
1161        assert_eq!(&buffer[..capacity], vec![7; capacity]);
1162        assert_eq!(buffer[capacity], u32::MAX);
1163    }
1164
1165    #[test]
1166    fn growth_of_sliced_buffer_preserves_allocator_and_values() {
1167        let allocator = BufferAllocatorRef::new(Global);
1168        let mut buffer = BufferMut::<u32>::with_capacity_preferred_aligned_in(
1169            1024,
1170            Alignment::of::<u32>(),
1171            None,
1172            allocator.clone(),
1173        );
1174        buffer.extend_from_slice(&[7; 1024]);
1175        let sliced_ptr = buffer.as_ptr().wrapping_add(1016);
1176        let sliced = buffer.freeze().slice(1016..);
1177        let mut buffer = sliced.try_into_mut().unwrap();
1178        assert_eq!(buffer.as_ptr(), sliced_ptr);
1179
1180        // The slice retains a large backing allocation, but needs only a small capacity increase.
1181        buffer.extend_from_slice(&[8; 16]);
1182
1183        assert!(buffer.allocation.allocator().ptr_eq(&allocator));
1184        assert_eq!(&buffer[..8], &[7; 8]);
1185        assert_eq!(&buffer[8..], &[8; 16]);
1186    }
1187
1188    #[test]
1189    fn raising_logical_alignment_preserves_capacity() {
1190        let buffer =
1191            BufferMut::<u8>::with_capacity_preferred_aligned(1, Alignment::of::<u8>(), None);
1192        let capacity = buffer.capacity();
1193
1194        let mut buffer = buffer.aligned(Alignment::new(2));
1195
1196        assert_eq!(buffer.capacity(), capacity);
1197        buffer.extend(0..100);
1198        assert!(Alignment::new(2).is_ptr_aligned(buffer.as_ptr()));
1199        assert_eq!(buffer.as_slice(), (0..100).collect::<Vec<_>>());
1200    }
1201
1202    #[test]
1203    fn from_iter() {
1204        let buf = BufferMut::from_iter([0, 10, 20, 30]);
1205        assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1206    }
1207
1208    #[test]
1209    fn try_from_trusted_len_iter_ok() {
1210        let buf = BufferMut::<i32>::try_from_trusted_len_iter(
1211            [0, 10, 20, 30].iter().map(|&v| Ok::<_, ()>(v)),
1212        )
1213        .unwrap();
1214        assert_eq!(buf.as_slice(), &[0, 10, 20, 30]);
1215    }
1216
1217    #[test]
1218    fn try_from_trusted_len_iter_err() {
1219        let result: Result<BufferMut<i32>, &'static str> = BufferMut::try_from_trusted_len_iter(
1220            [0, 10, 20, 30]
1221                .iter()
1222                .map(|&v| if v == 20 { Err("bad") } else { Ok(v) }),
1223        );
1224        assert_eq!(result.err(), Some("bad"));
1225    }
1226
1227    #[test]
1228    fn try_extend_trusted_retains_values_before_error() {
1229        let mut buf = BufferMut::from_iter([0, 10]);
1230        let result = buf.try_extend_trusted([Ok(20), Err("bad"), Ok(30)].into_iter());
1231
1232        assert_eq!(result, Err("bad"));
1233        assert_eq!(buf.as_slice(), &[0, 10, 20]);
1234    }
1235
1236    #[test]
1237    fn extend() {
1238        let mut buf = BufferMut::empty();
1239        buf.extend([0i32, 10, 20, 30]);
1240        buf.extend([40, 50, 60]);
1241        assert_eq!(buf.as_slice(), &[0, 10, 20, 30, 40, 50, 60]);
1242    }
1243
1244    #[test]
1245    fn push() {
1246        let mut buf = BufferMut::empty();
1247        buf.push(1);
1248        buf.push(2);
1249        buf.push(3);
1250        assert_eq!(buf.as_slice(), &[1, 2, 3]);
1251    }
1252
1253    #[test]
1254    fn push_n() {
1255        let mut buf = BufferMut::empty();
1256        buf.push_n(0, 100);
1257        assert_eq!(buf.as_slice(), &[0; 100]);
1258    }
1259
1260    #[test]
1261    fn as_mut() {
1262        let mut buf = buffer_mut![0, 1, 2];
1263        // Uses DerefMut
1264        buf[1] = 0;
1265        // Uses as_mut
1266        buf.as_mut()[2] = 0;
1267        assert_eq!(buf.as_slice(), &[0, 0, 0]);
1268    }
1269
1270    #[test]
1271    fn buffer_mut_zeroed() {
1272        const LEN: usize = 17;
1273
1274        let mut buf = BufferMut::<u32>::zeroed(LEN);
1275
1276        assert_eq!(
1277            buf.as_ptr().align_offset(Alignment::of::<u32>().as_usize()),
1278            0
1279        );
1280        assert_eq!(buf.as_slice(), &[0; LEN]);
1281
1282        buf[3] = 7;
1283        assert_eq!(buf.as_slice()[3], 7);
1284    }
1285
1286    #[test]
1287    fn buffer_mut_zeroed_aligned() {
1288        const LEN: usize = 17;
1289        let alignment = Alignment::new(64);
1290
1291        let mut buf = BufferMut::<u32>::zeroed_aligned(LEN, alignment);
1292
1293        assert_eq!(buf.as_ptr().align_offset(alignment.as_usize()), 0);
1294        assert_eq!(buf.as_slice(), &[0; LEN]);
1295
1296        buf[3] = 7;
1297        assert_eq!(buf.as_slice()[3], 7);
1298    }
1299}