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