Skip to main content

arrow_buffer/buffer/
mutable.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::alloc::Layout;
6use std::mem;
7use std::ptr::NonNull;
8
9use crate::alloc::{ALIGNMENT, Deallocation};
10use crate::{
11    bytes::Bytes,
12    native::{ArrowNativeType, ToByteSlice},
13    util::bit_util,
14};
15
16#[cfg(feature = "pool")]
17use crate::pool::{MemoryPool, TrackedReservation};
18
19use super::Buffer;
20
21/// Error returned by fallible [`MutableBuffer`] operations.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum MutableBufferError {
24    /// Arithmetic overflow when computing the required buffer length or capacity.
25    LengthOverflow,
26    /// The requested capacity cannot be represented as a valid allocation layout.
27    LayoutError,
28    /// An allocation failed due to insufficient memory.
29    AllocationError(Layout),
30}
31
32impl std::fmt::Display for MutableBufferError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        match self {
35            Self::LengthOverflow => write!(f, "buffer length overflow"),
36            Self::LayoutError => write!(f, "invalid allocation layout for requested capacity"),
37            Self::AllocationError(layout) => {
38                write!(f, "failed to allocate memory for layout {layout:?}")
39            }
40        }
41    }
42}
43
44impl std::error::Error for MutableBufferError {}
45
46/// A [`MutableBuffer`] is a wrapper over memory regions, used to build
47/// [`Buffer`]s out of items or slices of items.
48///
49/// [`Buffer`]s created from [`MutableBuffer`] (via `into`) are guaranteed to be
50/// aligned along cache lines and in multiples of 64 bytes.
51///
52/// Use [MutableBuffer::push] to insert an item, [MutableBuffer::extend_from_slice]
53/// to insert many items, and `into` to convert it to [`Buffer`]. For typed data,
54/// it is often more efficient to use [`Vec`] and convert it to [`Buffer`] rather
55/// than using [`MutableBuffer`] (see examples below).
56///
57/// # See Also
58/// * For a safe, strongly typed API consider using [`Vec`] and [`ScalarBuffer`](crate::ScalarBuffer)
59/// * To apply bitwise operations, see [`apply_bitwise_binary_op`] and [`apply_bitwise_unary_op`]
60///
61/// [`apply_bitwise_binary_op`]: crate::bit_util::apply_bitwise_binary_op
62/// [`apply_bitwise_unary_op`]: crate::bit_util::apply_bitwise_unary_op
63///
64/// # Example: Creating a [`Buffer`] from a [`MutableBuffer`]
65/// ```
66/// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
67/// let mut buffer = MutableBuffer::new(0);
68/// buffer.push(256u32);
69/// buffer.extend_from_slice(&[1u32]);
70/// let buffer = Buffer::from(buffer);
71/// assert_eq!(buffer.as_slice(), &[0u8, 1, 0, 0, 1, 0, 0, 0])
72/// ```
73///
74/// The same can be achieved more efficiently by using a `Vec<u32>`
75/// ```
76/// # use arrow_buffer::buffer::Buffer;
77/// let mut vec = Vec::new();
78/// vec.push(256u32);
79/// vec.extend_from_slice(&[1u32]);
80/// let buffer = Buffer::from(vec);
81/// assert_eq!(buffer.as_slice(), &[0u8, 1, 0, 0, 1, 0, 0, 0]);
82/// ```
83///
84/// # Example: Creating a [`MutableBuffer`] from a `Vec<T>`
85/// ```
86/// # use arrow_buffer::buffer::MutableBuffer;
87/// let vec = vec![1u32, 2, 3];
88/// let mutable_buffer = MutableBuffer::from(vec); // reuses the allocation from vec
89/// assert_eq!(mutable_buffer.len(), 12); // 3 * 4 bytes
90/// ```
91///
92/// # Example: Creating a [`MutableBuffer`] from a [`Buffer`]
93/// ```
94/// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
95/// let buffer: Buffer = Buffer::from(&[1u8, 2, 3, 4][..]);
96/// // Only possible to convert a Buffer into a MutableBuffer if uniquely owned
97/// // (i.e., there are no other references to it).
98/// let mut mutable_buffer = match buffer.into_mutable() {
99///    Ok(mutable) => mutable,
100///    Err(orig_buffer) => {
101///      panic!("buffer was not uniquely owned");
102///    }
103/// };
104/// mutable_buffer.push(5u8);
105/// let buffer = Buffer::from(mutable_buffer);
106/// assert_eq!(buffer.as_slice(), &[1u8, 2, 3, 4, 5])
107/// ```
108#[derive(Debug)]
109pub struct MutableBuffer {
110    // dangling iff capacity = 0
111    data: NonNull<u8>,
112    // invariant: len <= capacity
113    len: usize,
114    layout: Layout,
115
116    /// Memory reservation for tracking memory usage
117    #[cfg(feature = "pool")]
118    reservation: TrackedReservation,
119}
120
121impl MutableBuffer {
122    /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`.
123    ///
124    /// See [`MutableBuffer::with_capacity`].
125    ///
126    /// # Panics
127    ///
128    /// See [`MutableBuffer::with_capacity`].
129    #[inline]
130    pub fn new(capacity: usize) -> Self {
131        Self::try_with_capacity(capacity).unwrap_or_else(|e| panic!("{e}"))
132    }
133
134    /// Allocate a new [MutableBuffer] with initial capacity to be at least `capacity`.
135    ///
136    /// # Panics
137    ///
138    /// If `capacity`, when rounded up to the nearest multiple of [`ALIGNMENT`], is greater
139    /// then `isize::MAX`, then this function will panic.
140    #[inline]
141    pub fn with_capacity(capacity: usize) -> Self {
142        Self::try_with_capacity(capacity).unwrap_or_else(|e| panic!("{e}"))
143    }
144
145    /// Fallible version of [`MutableBuffer::with_capacity`].
146    #[inline]
147    pub fn try_with_capacity(capacity: usize) -> Result<Self, MutableBufferError> {
148        let capacity = capacity
149            .checked_next_multiple_of(64)
150            .ok_or(MutableBufferError::LayoutError)?;
151        let layout = Layout::from_size_align(capacity, ALIGNMENT)
152            .map_err(|_| MutableBufferError::LayoutError)?;
153        let data = match layout.size() {
154            0 => dangling_ptr(),
155            _ => {
156                // Safety: Verified size != 0
157                let raw_ptr = unsafe { std::alloc::alloc(layout) };
158                match NonNull::new(raw_ptr) {
159                    Some(ptr) => ptr,
160                    None => return Err(MutableBufferError::AllocationError(layout)),
161                }
162            }
163        };
164        Ok(Self {
165            data,
166            len: 0,
167            layout,
168            #[cfg(feature = "pool")]
169            reservation: TrackedReservation::default(),
170        })
171    }
172
173    /// Allocates a new [MutableBuffer] with `len` and capacity to be at least `len` where
174    /// all bytes are guaranteed to be `0u8`.
175    /// # Example
176    /// ```
177    /// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
178    /// let mut buffer = MutableBuffer::from_len_zeroed(127);
179    /// assert_eq!(buffer.len(), 127);
180    /// assert!(buffer.capacity() >= 127);
181    /// let data = buffer.as_slice_mut();
182    /// assert_eq!(data[126], 0u8);
183    /// ```
184    ///
185    /// # Panics
186    ///
187    /// Panics if `len` is too large to construct a valid allocation [`Layout`]
188    pub fn from_len_zeroed(len: usize) -> Self {
189        Self::try_from_len_zeroed(len).unwrap_or_else(|e| panic!("{e}"))
190    }
191
192    /// Fallible version of [`MutableBuffer::from_len_zeroed`].
193    pub fn try_from_len_zeroed(len: usize) -> Result<Self, MutableBufferError> {
194        let layout =
195            Layout::from_size_align(len, ALIGNMENT).map_err(|_| MutableBufferError::LayoutError)?;
196        let data = match layout.size() {
197            0 => dangling_ptr(),
198            _ => {
199                // Safety: Verified size != 0
200                let raw_ptr = unsafe { std::alloc::alloc_zeroed(layout) };
201                match NonNull::new(raw_ptr) {
202                    Some(ptr) => ptr,
203                    None => return Err(MutableBufferError::AllocationError(layout)),
204                }
205            }
206        };
207        Ok(Self {
208            data,
209            len,
210            layout,
211            #[cfg(feature = "pool")]
212            reservation: TrackedReservation::default(),
213        })
214    }
215
216    /// Allocates a new [MutableBuffer] from given `Bytes`.
217    pub(crate) fn from_bytes(bytes: Bytes) -> Result<Self, Bytes> {
218        let layout = match bytes.deallocation() {
219            Deallocation::Standard(layout) => *layout,
220            Deallocation::Custom(..) => return Err(bytes),
221        };
222
223        let len = bytes.len();
224        let data = bytes.ptr();
225        #[cfg(feature = "pool")]
226        let reservation = bytes.reservation.take();
227
228        mem::forget(bytes);
229
230        Ok(Self {
231            data,
232            len,
233            layout,
234            #[cfg(feature = "pool")]
235            reservation,
236        })
237    }
238
239    /// creates a new [MutableBuffer] with capacity and length capable of holding `len` bits.
240    /// This is useful to create a buffer for packed bitmaps.
241    ///
242    /// # Panics
243    ///
244    /// See [`MutableBuffer::from_len_zeroed`].
245    pub fn new_null(len: usize) -> Self {
246        let num_bytes = bit_util::ceil(len, 8);
247        MutableBuffer::from_len_zeroed(num_bytes)
248    }
249
250    /// Fallible version of [`MutableBuffer::new_null`].
251    pub fn try_new_null(len: usize) -> Result<Self, MutableBufferError> {
252        let num_bytes = bit_util::ceil(len, 8);
253        MutableBuffer::try_from_len_zeroed(num_bytes)
254    }
255
256    /// Set the bits in the range of `[0, end)` to 0 (if `val` is false), or 1 (if `val`
257    /// is true). Also extend the length of this buffer to be `end`.
258    ///
259    /// This is useful when one wants to clear (or set) the bits and then manipulate
260    /// the buffer directly (e.g., modifying the buffer by holding a mutable reference
261    /// from `data_mut()`).
262    ///
263    /// # Panics
264    ///
265    /// Panics if `end` exceeds the buffer capacity.
266    pub fn with_bitset(mut self, end: usize, val: bool) -> Self {
267        assert!(end <= self.layout.size());
268        let v = if val { 255 } else { 0 };
269        unsafe {
270            std::ptr::write_bytes(self.data.as_ptr(), v, end);
271            self.len = end;
272        }
273        self
274    }
275
276    /// Ensure that `count` bytes from `start` contain zero bits
277    ///
278    /// This is used to initialize the bits in a buffer, however, it has no impact on the
279    /// `len` of the buffer and so can be used to initialize the memory region from
280    /// `len` to `capacity`.
281    ///
282    /// # Panics
283    ///
284    /// Panics if the byte range `start..start + count` exceeds the buffer capacity.
285    pub fn set_null_bits(&mut self, start: usize, count: usize) {
286        assert!(
287            start.saturating_add(count) <= self.layout.size(),
288            "range start index {start} and count {count} out of bounds for \
289            buffer of length {}",
290            self.layout.size(),
291        );
292
293        // Safety: `self.data[start..][..count]` is in-bounds and well-aligned for `u8`
294        unsafe {
295            std::ptr::write_bytes(self.data.as_ptr().add(start), 0, count);
296        }
297    }
298
299    /// Fallible version of [`MutableBuffer::reserve`].
300    #[inline]
301    pub fn try_reserve(&mut self, additional: usize) -> Result<(), MutableBufferError> {
302        let required_cap = self
303            .len
304            .checked_add(additional)
305            .ok_or(MutableBufferError::LengthOverflow)?;
306        if required_cap > self.layout.size() {
307            let new_capacity = required_cap
308                .checked_next_multiple_of(64)
309                .ok_or(MutableBufferError::LayoutError)?;
310            let new_capacity = std::cmp::max(new_capacity, self.layout.size().saturating_mul(2));
311            self.try_reallocate(new_capacity)?;
312        }
313        Ok(())
314    }
315    /// Ensures that this buffer has at least `self.len + additional` bytes. This re-allocates iff
316    /// `self.len + additional > capacity`.
317    /// # Example
318    /// ```
319    /// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
320    /// let mut buffer = MutableBuffer::new(0);
321    /// buffer.reserve(253); // allocates for the first time
322    /// (0..253u8).for_each(|i| buffer.push(i)); // no reallocation
323    /// let buffer: Buffer = buffer.into();
324    /// assert_eq!(buffer.len(), 253);
325    /// ```
326    ///
327    /// # Panics
328    ///
329    /// Panics if `self.len + additional` overflows `usize`, or if the required capacity is too
330    /// large to round up to the next 64-byte boundary and construct a valid allocation layout.
331    // For performance reasons, this must be inlined so that the `if` is executed inside the caller, and not as an extra call that just
332    // exits.
333    #[inline(always)]
334    pub fn reserve(&mut self, additional: usize) {
335        self.try_reserve(additional)
336            .unwrap_or_else(|e| panic!("{e}"))
337    }
338
339    /// Fallible version of [`MutableBuffer::repeat_slice_n_times`].
340    pub fn try_repeat_slice_n_times<T: ArrowNativeType>(
341        &mut self,
342        slice_to_repeat: &[T],
343        repeat_count: usize,
344    ) -> Result<(), MutableBufferError> {
345        if repeat_count == 0 || slice_to_repeat.is_empty() {
346            return Ok(());
347        }
348        let bytes_per_copy = size_of_val(slice_to_repeat);
349        let total_bytes = repeat_count
350            .checked_mul(bytes_per_copy)
351            .ok_or(MutableBufferError::LengthOverflow)?;
352        self.len
353            .checked_add(total_bytes)
354            .ok_or(MutableBufferError::LengthOverflow)?;
355
356        // Ensure capacity
357        self.try_reserve(total_bytes)?;
358
359        // Save the length before we do all the copies to know where to start from
360        let length_before = self.len;
361
362        // Copy the initial slice once so we can use doubling strategy on it
363        self.try_extend_from_slice(slice_to_repeat)?;
364
365        // Number of times the slice was repeated
366        let mut already_repeated = 1usize;
367
368        // We will use doubling strategy to fill the buffer in log(repeat_count) steps
369        while already_repeated < repeat_count {
370            // How many slices can we copy in this iteration
371            // (either double what we have, or just the remaining ones)
372            let to_copy = already_repeated.min(repeat_count - already_repeated);
373            let byte_count = to_copy * bytes_per_copy;
374            unsafe {
375                // Get to the start of the data before we started copying anything
376                let src = self.data.as_ptr().add(length_before).cast_const();
377                // Go to the current location to copy to (end of current data)
378                let dst = self.data.as_ptr().add(self.len);
379                // SAFETY: the pointers are not overlapping as there is `byte_count` or less between them
380                std::ptr::copy_nonoverlapping(src, dst, byte_count);
381            }
382            // Advance the length by the amount of data we just copied (doubled)
383            self.len += byte_count;
384            already_repeated += to_copy;
385        }
386        Ok(())
387    }
388    /// Adding to this mutable buffer `slice_to_repeat` repeated `repeat_count` times.
389    ///
390    /// # Example
391    ///
392    /// ## Repeat the same string bytes multiple times
393    /// ```
394    /// # use arrow_buffer::buffer::MutableBuffer;
395    /// let mut buffer = MutableBuffer::new(0);
396    /// let bytes_to_repeat = b"ab";
397    /// buffer.repeat_slice_n_times(bytes_to_repeat, 3);
398    /// assert_eq!(buffer.as_slice(), b"ababab");
399    /// ```
400    ///
401    /// # Panics
402    ///
403    /// Panics if the repeated slice byte length overflows `usize`, if the resulting buffer
404    /// length overflows `usize`, or if reserving the required capacity fails for the same
405    /// reasons as [`MutableBuffer::reserve`].
406    pub fn repeat_slice_n_times<T: ArrowNativeType>(
407        &mut self,
408        slice_to_repeat: &[T],
409        repeat_count: usize,
410    ) {
411        self.try_repeat_slice_n_times(slice_to_repeat, repeat_count)
412            .unwrap_or_else(|e| panic!("{e}"))
413    }
414
415    #[cold]
416    fn try_reallocate(&mut self, capacity: usize) -> Result<(), MutableBufferError> {
417        let new_layout = Layout::from_size_align(capacity, self.layout.align())
418            .map_err(|_| MutableBufferError::LayoutError)?;
419
420        if new_layout.size() == 0 {
421            if self.layout.size() != 0 {
422                // Safety: data was allocated with layout
423                unsafe { std::alloc::dealloc(self.as_mut_ptr(), self.layout) };
424                self.layout = new_layout;
425            }
426            return Ok(());
427        }
428
429        let data = match self.layout.size() {
430            // Safety: new_layout is not empty
431            0 => unsafe { std::alloc::alloc(new_layout) },
432            // Safety: verified new layout is valid and not empty
433            _ => unsafe { std::alloc::realloc(self.as_mut_ptr(), self.layout, capacity) },
434        };
435        self.data = match NonNull::new(data) {
436            Some(ptr) => ptr,
437            None => return Err(MutableBufferError::AllocationError(new_layout)),
438        };
439        self.layout = new_layout;
440        #[cfg(feature = "pool")]
441        self.reservation.resize(self.layout.size());
442        Ok(())
443    }
444    /// Truncates this buffer to `len` bytes
445    ///
446    /// If `len` is greater than the buffer's current length, this has no effect
447    #[inline(always)]
448    pub fn truncate(&mut self, len: usize) {
449        if len > self.len {
450            return;
451        }
452        self.len = len;
453        #[cfg(feature = "pool")]
454        self.reservation.resize(self.len);
455    }
456
457    /// Fallible version of [`MutableBuffer::resize`].
458    #[inline]
459    pub fn try_resize(&mut self, new_len: usize, value: u8) -> Result<(), MutableBufferError> {
460        if new_len > self.len {
461            let diff = new_len - self.len;
462            self.try_reserve(diff)?;
463            // Safety: try_reserve ensured capacity >= new_len.
464            // write the value
465            unsafe { self.data.as_ptr().add(self.len).write_bytes(value, diff) };
466        }
467        // this truncates the buffer when new_len < self.len
468        self.len = new_len;
469        #[cfg(feature = "pool")]
470        self.reservation.resize(self.len);
471        Ok(())
472    }
473    /// Resizes the buffer, either truncating its contents (with no change in capacity), or
474    /// growing it (potentially reallocating it) and writing `value` in the newly available bytes.
475    /// # Example
476    /// ```
477    /// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
478    /// let mut buffer = MutableBuffer::new(0);
479    /// buffer.resize(253, 2); // allocates for the first time
480    /// assert_eq!(buffer.as_slice()[252], 2u8);
481    /// ```
482    ///
483    /// # Panics
484    ///
485    /// Panics if growing the buffer requires reserving a capacity that fails for the same
486    /// reasons as [`MutableBuffer::reserve`].
487    // For performance reasons, this must be inlined so that the `if` is executed inside the caller, and not as an extra call that just
488    // exits.
489    #[inline(always)]
490    pub fn resize(&mut self, new_len: usize, value: u8) {
491        self.try_resize(new_len, value)
492            .unwrap_or_else(|e| panic!("{e}"))
493    }
494
495    /// Fallible version of [`MutableBuffer::shrink_to_fit`].
496    pub fn try_shrink_to_fit(&mut self) -> Result<(), MutableBufferError> {
497        let new_capacity = self
498            .len
499            .checked_next_multiple_of(64)
500            .ok_or(MutableBufferError::LayoutError)?;
501        if new_capacity < self.layout.size() {
502            self.try_reallocate(new_capacity)?;
503        }
504        Ok(())
505    }
506    /// Shrinks the capacity of the buffer as much as possible.
507    /// The new capacity will aligned to the nearest 64 bit alignment.
508    ///
509    /// # Example
510    /// ```
511    /// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
512    /// // 2 cache lines
513    /// let mut buffer = MutableBuffer::new(128);
514    /// assert_eq!(buffer.capacity(), 128);
515    /// buffer.push(1);
516    /// buffer.push(2);
517    ///
518    /// buffer.shrink_to_fit();
519    /// assert!(buffer.capacity() >= 64 && buffer.capacity() < 128);
520    /// ```
521    ///
522    /// # Panics
523    ///
524    /// Panics if the current length is too large to round up to the next 64-byte boundary and
525    /// construct a valid allocation layout.
526    pub fn shrink_to_fit(&mut self) {
527        self.try_shrink_to_fit().unwrap_or_else(|e| panic!("{e}"))
528    }
529
530    /// Returns whether this buffer is empty or not.
531    #[inline]
532    pub const fn is_empty(&self) -> bool {
533        self.len == 0
534    }
535
536    /// Returns the length (the number of bytes written) in this buffer.
537    /// The invariant `buffer.len() <= buffer.capacity()` is always upheld.
538    #[inline]
539    pub const fn len(&self) -> usize {
540        self.len
541    }
542
543    /// Returns the total capacity in this buffer, in bytes.
544    ///
545    /// The invariant `buffer.len() <= buffer.capacity()` is always upheld.
546    #[inline]
547    pub const fn capacity(&self) -> usize {
548        self.layout.size()
549    }
550
551    /// Clear all existing data from this buffer.
552    pub fn clear(&mut self) {
553        self.len = 0;
554        #[cfg(feature = "pool")]
555        self.reservation.resize(self.len);
556    }
557
558    /// Returns the data stored in this buffer as a slice.
559    pub fn as_slice(&self) -> &[u8] {
560        self
561    }
562
563    /// Returns the data stored in this buffer as a mutable slice.
564    pub fn as_slice_mut(&mut self) -> &mut [u8] {
565        self
566    }
567
568    /// Returns a raw pointer to this buffer's internal memory
569    /// This pointer is guaranteed to be aligned along cache-lines.
570    #[inline]
571    pub const fn as_ptr(&self) -> *const u8 {
572        self.data.as_ptr()
573    }
574
575    /// Returns a mutable raw pointer to this buffer's internal memory
576    /// This pointer is guaranteed to be aligned along cache-lines.
577    #[inline]
578    pub fn as_mut_ptr(&mut self) -> *mut u8 {
579        self.data.as_ptr()
580    }
581
582    #[inline]
583    pub(super) fn into_buffer(self) -> Buffer {
584        let bytes = unsafe { Bytes::new(self.data, self.len, Deallocation::Standard(self.layout)) };
585        #[cfg(feature = "pool")]
586        bytes.reservation.replace(self.reservation.take());
587        std::mem::forget(self);
588        Buffer::from(bytes)
589    }
590
591    /// View this buffer as a mutable slice of a specific type.
592    ///
593    /// # Panics
594    ///
595    /// This function panics if the underlying buffer is not aligned correctly for type `T`, or
596    /// if its length is not a multiple of `size_of::<T>()`.
597    pub fn typed_data_mut<T: ArrowNativeType>(&mut self) -> &mut [T] {
598        // SAFETY
599        // ArrowNativeType is trivially transmutable, is sealed to prevent potentially incorrect
600        // implementation outside this crate, and this method checks alignment
601        let (prefix, offsets, suffix) = unsafe { self.as_slice_mut().align_to_mut::<T>() };
602        assert!(prefix.is_empty() && suffix.is_empty());
603        offsets
604    }
605
606    /// View buffer as a immutable slice of a specific type.
607    ///
608    /// # Panics
609    ///
610    /// This function panics if the underlying buffer is not aligned correctly for type `T`, or
611    /// if its length is not a multiple of `size_of::<T>()`.
612    pub fn typed_data<T: ArrowNativeType>(&self) -> &[T] {
613        // SAFETY
614        // ArrowNativeType is trivially transmutable, is sealed to prevent potentially incorrect
615        // implementation outside this crate, and this method checks alignment
616        let (prefix, offsets, suffix) = unsafe { self.as_slice().align_to::<T>() };
617        assert!(prefix.is_empty() && suffix.is_empty());
618        offsets
619    }
620
621    /// Fallible version of [`MutableBuffer::extend_from_slice`].
622    #[inline]
623    pub fn try_extend_from_slice<T: ArrowNativeType>(
624        &mut self,
625        items: &[T],
626    ) -> Result<(), MutableBufferError> {
627        let additional = mem::size_of_val(items);
628        self.try_reserve(additional)?;
629        unsafe {
630            // this assumes that `[ToByteSlice]` can be copied directly
631            // without calling `to_byte_slice` for each element,
632            // which is correct for all ArrowNativeType implementations.
633            let src = items.as_ptr().cast::<u8>();
634            let dst = self.data.as_ptr().add(self.len);
635            std::ptr::copy_nonoverlapping(src, dst, additional);
636        }
637        self.len += additional;
638        Ok(())
639    }
640    /// Extends this buffer from a slice of items that can be represented in bytes, increasing its capacity if needed.
641    /// # Example
642    /// ```
643    /// # use arrow_buffer::buffer::MutableBuffer;
644    /// let mut buffer = MutableBuffer::new(0);
645    /// buffer.extend_from_slice(&[2u32, 0]);
646    /// assert_eq!(buffer.len(), 8) // u32 has 4 bytes
647    /// ```
648    ///
649    /// # Panics
650    ///
651    /// Panics if extending the buffer requires reserving a capacity that fails for the same
652    /// reasons as [`MutableBuffer::reserve`].
653    #[inline]
654    pub fn extend_from_slice<T: ArrowNativeType>(&mut self, items: &[T]) {
655        self.try_extend_from_slice(items)
656            .unwrap_or_else(|e| panic!("{e}"))
657    }
658
659    /// Extends the buffer with a new item, increasing its capacity if needed.
660    /// # Example
661    /// ```
662    /// # use arrow_buffer::buffer::MutableBuffer;
663    /// let mut buffer = MutableBuffer::new(0);
664    /// buffer.push(256u32);
665    /// assert_eq!(buffer.len(), 4) // u32 has 4 bytes
666    /// ```
667    ///
668    /// # Panics
669    ///
670    /// Panics if extending the buffer requires reserving a capacity that fails for the same
671    /// reasons as [`MutableBuffer::reserve`].
672    #[inline]
673    pub fn push<T: ToByteSlice>(&mut self, item: T) {
674        let additional = std::mem::size_of::<T>();
675        self.reserve(additional);
676        unsafe {
677            let src = item.to_byte_slice().as_ptr();
678            let dst = self.data.as_ptr().add(self.len);
679            std::ptr::copy_nonoverlapping(src, dst, additional);
680        }
681        self.len += additional;
682    }
683
684    /// Fallible version of [`MutableBuffer::push`].
685    #[inline]
686    pub fn try_push<T: ToByteSlice>(&mut self, item: T) -> Result<(), MutableBufferError> {
687        let additional = std::mem::size_of::<T>();
688        self.try_reserve(additional)?;
689        unsafe {
690            let src = item.to_byte_slice().as_ptr();
691            let dst = self.data.as_ptr().add(self.len);
692            std::ptr::copy_nonoverlapping(src, dst, additional);
693        }
694        self.len += additional;
695        Ok(())
696    }
697
698    /// Extends the buffer with a new item, without checking for sufficient capacity
699    /// # Safety
700    /// Caller must ensure that the capacity()-len()>=`size_of<T>`()
701    #[inline]
702    pub unsafe fn push_unchecked<T: ToByteSlice>(&mut self, item: T) {
703        let additional = std::mem::size_of::<T>();
704        let src = item.to_byte_slice().as_ptr();
705        let dst = unsafe { self.data.as_ptr().add(self.len) };
706        unsafe { std::ptr::copy_nonoverlapping(src, dst, additional) };
707        self.len += additional;
708    }
709
710    /// Fallible version of [`MutableBuffer::extend_zeros`].
711    #[inline]
712    pub fn try_extend_zeros(&mut self, additional: usize) -> Result<(), MutableBufferError> {
713        let new_len = self
714            .len
715            .checked_add(additional)
716            .ok_or(MutableBufferError::LengthOverflow)?;
717        self.try_resize(new_len, 0)
718    }
719    /// Extends the buffer by `additional` bytes equal to `0u8`, incrementing its capacity if needed.
720    ///
721    /// # Panics
722    ///
723    /// Panics if `self.len + additional` overflows `usize`, or if growing the buffer requires
724    /// reserving a capacity that fails for the same reasons as [`MutableBuffer::reserve`].
725    #[inline]
726    pub fn extend_zeros(&mut self, additional: usize) {
727        self.try_extend_zeros(additional)
728            .unwrap_or_else(|e| panic!("{e}"))
729    }
730
731    /// # Safety
732    /// The caller must ensure that the buffer was properly initialized up to `len`.
733    ///
734    /// # Panics
735    ///
736    /// Panics if `len` exceeds the buffer capacity.
737    #[inline]
738    pub unsafe fn set_len(&mut self, len: usize) {
739        assert!(len <= self.capacity());
740        self.len = len;
741    }
742
743    /// Invokes `f` with values `0..len` collecting the boolean results into a new `MutableBuffer`
744    ///
745    /// This is similar to `from_trusted_len_iter_bool`, however, can be significantly faster
746    /// as it eliminates the conditional `Iterator::next`
747    ///
748    /// # Panics
749    ///
750    /// Panics if the backing storage for `len` bits cannot be allocated. Use
751    /// [`MutableBuffer::try_collect_bool`] for a fallible version.
752    #[inline]
753    pub fn collect_bool<F: FnMut(usize) -> bool>(len: usize, f: F) -> Self {
754        Self::try_collect_bool(len, f).unwrap_or_else(|e| panic!("{e}"))
755    }
756
757    /// Fallible version of [`MutableBuffer::collect_bool`].
758    ///
759    /// `len` is a bit count, so the reservation is `ceil(len / 64)` u64 slots. This function
760    /// returns an error if that much memory cannot be reserved up front.
761    #[inline]
762    pub fn try_collect_bool<F: FnMut(usize) -> bool>(
763        len: usize,
764        mut f: F,
765    ) -> Result<Self, MutableBufferError> {
766        let words = bit_util::ceil(len, 64);
767        let layout = Layout::array::<u64>(words).map_err(|_| MutableBufferError::LayoutError)?;
768        let mut buffer: Vec<u64> = Vec::new();
769        buffer
770            .try_reserve(words)
771            .map_err(|_| MutableBufferError::AllocationError(layout))?;
772
773        let chunks = len / 64;
774        let remainder = len % 64;
775        buffer.extend((0..chunks).map(|chunk| {
776            let mut packed = 0;
777            for bit_idx in 0..64 {
778                let i = bit_idx + chunk * 64;
779                packed |= (f(i) as u64) << bit_idx;
780            }
781
782            packed
783        }));
784
785        if remainder != 0 {
786            let mut packed = 0;
787            for bit_idx in 0..remainder {
788                let i = bit_idx + chunks * 64;
789                packed |= (f(i) as u64) << bit_idx;
790            }
791
792            buffer.push(packed)
793        }
794
795        let mut buffer: MutableBuffer = buffer.into();
796        buffer.truncate(bit_util::ceil(len, 8));
797        Ok(buffer)
798    }
799
800    /// Extends this buffer with boolean values.
801    ///
802    /// This requires `iter` to report an exact size via `size_hint`.
803    /// `offset` indicates the starting offset in bits in this buffer to begin writing to
804    /// and must be less than or equal to the current length of this buffer.
805    /// All bits not written to (but readable due to byte alignment) will be zeroed out.
806    ///
807    /// # Panics
808    ///
809    /// Panics if `iter` does not report an exact size via `size_hint`, or if it yields fewer
810    /// items than reported, or if extending the buffer requires reserving a capacity that fails
811    /// for the same reasons as [`MutableBuffer::reserve`].
812    ///
813    /// # Safety
814    /// Callers must ensure that `iter` reports an exact size via `size_hint`
815    /// and that `I::next()` does not panic, or `set_len` will leave the buffer
816    /// in an inconsistent state, exposing uninitialized/stale bytes as though
817    /// they were valid.
818    #[inline]
819    pub unsafe fn extend_bool_trusted_len<I: Iterator<Item = bool>>(
820        &mut self,
821        mut iter: I,
822        offset: usize,
823    ) {
824        let (lower, upper) = iter.size_hint();
825        let len = upper.expect("Iterator must have exact size_hint");
826        assert_eq!(lower, len, "Iterator must have exact size_hint");
827        debug_assert!(
828            offset <= self.len * 8,
829            "offset must be <= buffer length in bits"
830        );
831
832        if len == 0 {
833            return;
834        }
835
836        let start_len = offset;
837        let end_bit = start_len + len;
838
839        // SAFETY: we will initialize all newly exposed bytes before they are read
840        let new_len_bytes = bit_util::ceil(end_bit, 8);
841        if new_len_bytes > self.len {
842            self.reserve(new_len_bytes - self.len);
843            // SAFETY: caller will initialize all newly exposed bytes before they are read
844            unsafe { self.set_len(new_len_bytes) };
845        }
846
847        let slice = self.as_slice_mut();
848
849        let mut bit_idx = start_len;
850
851        // ---- Unaligned prefix: advance to the next 64-bit boundary ----
852        let misalignment = bit_idx & 63;
853        let prefix_bits = if misalignment == 0 {
854            0
855        } else {
856            (64 - misalignment).min(end_bit - bit_idx)
857        };
858
859        if prefix_bits != 0 {
860            let byte_start = bit_idx / 8;
861            let byte_end = bit_util::ceil(bit_idx + prefix_bits, 8);
862            let bit_offset = bit_idx % 8;
863
864            // Clear any newly-visible bits in the existing partial byte
865            if bit_offset != 0 {
866                let keep_mask = (1u8 << bit_offset).wrapping_sub(1);
867                slice[byte_start] &= keep_mask;
868            }
869
870            // Zero any new bytes we will partially fill in this prefix
871            let zero_from = if bit_offset == 0 {
872                byte_start
873            } else {
874                byte_start + 1
875            };
876            if byte_end > zero_from {
877                slice[zero_from..byte_end].fill(0);
878            }
879
880            for _ in 0..prefix_bits {
881                let v = iter.next().unwrap();
882                if v {
883                    let byte_idx = bit_idx / 8;
884                    let bit = bit_idx % 8;
885                    slice[byte_idx] |= 1 << bit;
886                }
887                bit_idx += 1;
888            }
889        }
890
891        if bit_idx < end_bit {
892            // ---- Aligned middle: write u64 chunks ----
893            debug_assert_eq!(bit_idx & 63, 0);
894            let remaining_bits = end_bit - bit_idx;
895            let chunks = remaining_bits / 64;
896
897            let words_start = bit_idx / 8;
898            let words_end = words_start + chunks * 8;
899            for dst in slice[words_start..words_end].as_chunks_mut::<8>().0 {
900                let mut packed: u64 = 0;
901                for i in 0..64 {
902                    packed |= (iter.next().unwrap() as u64) << i;
903                }
904                dst.copy_from_slice(&packed.to_le_bytes());
905                bit_idx += 64;
906            }
907
908            // ---- Unaligned suffix: remaining < 64 bits ----
909            let suffix_bits = end_bit - bit_idx;
910            if suffix_bits != 0 {
911                debug_assert_eq!(bit_idx % 8, 0);
912                let byte_start = bit_idx / 8;
913                let byte_end = bit_util::ceil(end_bit, 8);
914                slice[byte_start..byte_end].fill(0);
915
916                for _ in 0..suffix_bits {
917                    let v = iter.next().unwrap();
918                    if v {
919                        let byte_idx = bit_idx / 8;
920                        let bit = bit_idx % 8;
921                        slice[byte_idx] |= 1 << bit;
922                    }
923                    bit_idx += 1;
924                }
925            }
926        }
927
928        // Clear any unused bits in the last byte
929        let remainder = end_bit % 8;
930        if remainder != 0 {
931            let mask = (1u8 << remainder).wrapping_sub(1);
932            slice[bit_util::ceil(end_bit, 8) - 1] &= mask;
933        }
934
935        debug_assert_eq!(bit_idx, end_bit);
936    }
937
938    /// Register this [`MutableBuffer`] with the provided [`MemoryPool`]
939    ///
940    /// This claims the memory used by this buffer in the pool, allowing for
941    /// accurate accounting of memory usage. Any prior reservation will be
942    /// released so this works well when the buffer is being shared among
943    /// multiple arrays.
944    #[cfg(feature = "pool")]
945    pub fn claim(&self, pool: &dyn MemoryPool) {
946        self.reservation.claim(pool, self.capacity());
947    }
948}
949
950/// Creates a non-null pointer with alignment of [`ALIGNMENT`]
951///
952/// This is similar to [`NonNull::dangling`]
953#[inline]
954pub(crate) fn dangling_ptr() -> NonNull<u8> {
955    // SAFETY: ALIGNMENT is a non-zero usize which is then cast
956    // to a *mut u8. Therefore, `ptr` is not null and the conditions for
957    // calling new_unchecked() are respected.
958    #[cfg(miri)]
959    {
960        // Since miri implies a nightly rust version we can use the unstable strict_provenance feature
961        unsafe { NonNull::new_unchecked(std::ptr::without_provenance_mut(ALIGNMENT)) }
962    }
963    #[cfg(not(miri))]
964    {
965        unsafe { NonNull::new_unchecked(ALIGNMENT as *mut u8) }
966    }
967}
968
969impl<A: ArrowNativeType> Extend<A> for MutableBuffer {
970    #[inline]
971    fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
972        let iterator = iter.into_iter();
973        self.extend_from_iter(iterator)
974    }
975}
976
977impl<T: ArrowNativeType> From<Vec<T>> for MutableBuffer {
978    fn from(mut value: Vec<T>) -> Self {
979        // Safety
980        // Vec::as_mut_ptr guaranteed to not be null and ArrowNativeType are trivially transmutable
981        let data = unsafe { NonNull::new_unchecked(value.as_mut_ptr().cast()) };
982        let len = value.len() * mem::size_of::<T>();
983        // Safety
984        // Vec guaranteed to have a valid layout matching that of `Layout::array`
985        // This is based on `RawVec::current_memory`
986        let layout = unsafe { Layout::array::<T>(value.capacity()).unwrap_unchecked() };
987        mem::forget(value);
988        Self {
989            data,
990            len,
991            layout,
992            #[cfg(feature = "pool")]
993            reservation: TrackedReservation::default(),
994        }
995    }
996}
997
998impl MutableBuffer {
999    #[inline]
1000    pub(super) fn extend_from_iter<T: ArrowNativeType, I: Iterator<Item = T>>(
1001        &mut self,
1002        mut iterator: I,
1003    ) {
1004        let item_size = std::mem::size_of::<T>();
1005        let (lower, _) = iterator.size_hint();
1006        let additional = lower * item_size;
1007        self.reserve(additional);
1008
1009        // this is necessary because of https://github.com/rust-lang/rust/issues/32155
1010        let mut len = SetLenOnDrop::new(&mut self.len);
1011        let mut dst = unsafe { self.data.as_ptr().add(len.local_len) };
1012        let capacity = self.layout.size();
1013
1014        while len.local_len + item_size <= capacity {
1015            if let Some(item) = iterator.next() {
1016                unsafe {
1017                    let src = item.to_byte_slice().as_ptr();
1018                    std::ptr::copy_nonoverlapping(src, dst, item_size);
1019                    dst = dst.add(item_size);
1020                }
1021                len.local_len += item_size;
1022            } else {
1023                break;
1024            }
1025        }
1026        drop(len);
1027
1028        iterator.for_each(|item| self.push(item));
1029    }
1030
1031    /// Creates a [`MutableBuffer`] from an [`Iterator`] with a trusted (upper) length.
1032    /// Prefer this to `collect` whenever possible, as it is faster ~60% faster.
1033    /// # Example
1034    /// ```
1035    /// # use arrow_buffer::buffer::MutableBuffer;
1036    /// let v = vec![1u32];
1037    /// let iter = v.iter().map(|x| x * 2);
1038    /// let buffer = unsafe { MutableBuffer::from_trusted_len_iter(iter) };
1039    /// assert_eq!(buffer.len(), 4) // u32 has 4 bytes
1040    /// ```
1041    ///
1042    /// # Panics
1043    ///
1044    /// Panics if the iterator does not report an upper bound via `size_hint`, or if the
1045    /// reported length does not match the number of items produced, or if allocating the
1046    /// required buffer fails for the same reasons as [`MutableBuffer::new`].
1047    ///
1048    /// # Safety
1049    /// This method assumes that the iterator's size is correct and is undefined behavior
1050    /// to use it on an iterator that reports an incorrect length.
1051    // This implementation is required for two reasons:
1052    // 1. there is no trait `TrustedLen` in stable rust and therefore
1053    //    we can't specialize `extend` for `TrustedLen` like `Vec` does.
1054    // 2. `from_trusted_len_iter` is faster.
1055    #[inline]
1056    pub unsafe fn from_trusted_len_iter<T: ArrowNativeType, I: Iterator<Item = T>>(
1057        iterator: I,
1058    ) -> Self {
1059        let item_size = std::mem::size_of::<T>();
1060        let (_, upper) = iterator.size_hint();
1061        let upper = upper.expect("from_trusted_len_iter requires an upper limit");
1062        let len = upper * item_size;
1063
1064        let mut buffer = MutableBuffer::new(len);
1065
1066        let mut dst = buffer.data.as_ptr();
1067        for item in iterator {
1068            // note how there is no reserve here (compared with `extend_from_iter`)
1069            let src = item.to_byte_slice().as_ptr();
1070            unsafe { std::ptr::copy_nonoverlapping(src, dst, item_size) };
1071            dst = unsafe { dst.add(item_size) };
1072        }
1073        assert_eq!(
1074            unsafe { dst.offset_from(buffer.data.as_ptr()) } as usize,
1075            len,
1076            "Trusted iterator length was not accurately reported"
1077        );
1078        buffer.len = len;
1079        buffer
1080    }
1081
1082    /// Creates a [`MutableBuffer`] from a boolean [`Iterator`] with a trusted (upper) length.
1083    /// # use arrow_buffer::buffer::MutableBuffer;
1084    /// # Example
1085    /// ```
1086    /// # use arrow_buffer::buffer::MutableBuffer;
1087    /// let v = vec![false, true, false];
1088    /// let iter = v.iter().map(|x| *x || true);
1089    /// let buffer = unsafe { MutableBuffer::from_trusted_len_iter_bool(iter) };
1090    /// assert_eq!(buffer.len(), 1) // 3 booleans have 1 byte
1091    /// ```
1092    ///
1093    /// # Panics
1094    ///
1095    /// Panics if the iterator does not report an upper bound via `size_hint`, or if it yields
1096    /// fewer items than reported.
1097    ///
1098    /// # Safety
1099    /// This method assumes that the iterator's size is correct and is undefined behavior
1100    /// to use it on an iterator that reports an incorrect length.
1101    // This implementation is required for two reasons:
1102    // 1. there is no trait `TrustedLen` in stable rust and therefore
1103    //    we can't specialize `extend` for `TrustedLen` like `Vec` does.
1104    // 2. `from_trusted_len_iter_bool` is faster.
1105    #[inline]
1106    pub unsafe fn from_trusted_len_iter_bool<I: Iterator<Item = bool>>(mut iterator: I) -> Self {
1107        let (_, upper) = iterator.size_hint();
1108        let len = upper.expect("from_trusted_len_iter requires an upper limit");
1109
1110        Self::collect_bool(len, |_| iterator.next().unwrap())
1111    }
1112
1113    /// Creates a [`MutableBuffer`] from an [`Iterator`] with a trusted (upper) length or errors
1114    /// if any of the items of the iterator is an error.
1115    /// Prefer this to `collect` whenever possible, as it is faster ~60% faster.
1116    ///
1117    /// # Errors
1118    ///
1119    /// Returns the first error yielded by the iterator.
1120    ///
1121    /// # Panics
1122    ///
1123    /// Note that unlike the [`Err`] cases, these panics are violations of the safety contract
1124    /// below, and are only checks that happen to be cheap enough to keep:
1125    ///
1126    /// Panics if the iterator does not report an upper bound via `size_hint`, or if the
1127    /// reported length does not match the number of items produced before an error-free finish,
1128    /// or if allocating the required buffer fails for the same reasons as
1129    /// [`MutableBuffer::new`].
1130    ///
1131    /// # Safety
1132    /// This method assumes that the iterator's size is correct and is undefined behavior
1133    /// to use it on an iterator that reports an incorrect length.
1134    #[inline]
1135    pub unsafe fn try_from_trusted_len_iter<
1136        E,
1137        T: ArrowNativeType,
1138        I: Iterator<Item = Result<T, E>>,
1139    >(
1140        iterator: I,
1141    ) -> Result<Self, E> {
1142        let item_size = std::mem::size_of::<T>();
1143        let (_, upper) = iterator.size_hint();
1144        let upper = upper.expect("try_from_trusted_len_iter requires an upper limit");
1145        let len = upper * item_size;
1146
1147        let mut buffer = MutableBuffer::new(len);
1148
1149        let mut dst = buffer.data.as_ptr();
1150        for item in iterator {
1151            let item = item?;
1152            // note how there is no reserve here (compared with `extend_from_iter`)
1153            let src = item.to_byte_slice().as_ptr();
1154            unsafe { std::ptr::copy_nonoverlapping(src, dst, item_size) };
1155            dst = unsafe { dst.add(item_size) };
1156        }
1157        // try_from_trusted_len_iter is instantiated a lot, so we extract part of it into a less
1158        // generic method to reduce compile time
1159        unsafe fn finalize_buffer(dst: *mut u8, buffer: &mut MutableBuffer, len: usize) {
1160            unsafe {
1161                assert_eq!(
1162                    dst.offset_from(buffer.data.as_ptr()) as usize,
1163                    len,
1164                    "Trusted iterator length was not accurately reported"
1165                );
1166                buffer.len = len;
1167            }
1168        }
1169        unsafe { finalize_buffer(dst, &mut buffer, len) };
1170        Ok(buffer)
1171    }
1172}
1173
1174impl Default for MutableBuffer {
1175    fn default() -> Self {
1176        Self::with_capacity(0)
1177    }
1178}
1179
1180impl std::ops::Deref for MutableBuffer {
1181    type Target = [u8];
1182
1183    fn deref(&self) -> &[u8] {
1184        unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len) }
1185    }
1186}
1187
1188impl std::ops::DerefMut for MutableBuffer {
1189    fn deref_mut(&mut self) -> &mut [u8] {
1190        unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1191    }
1192}
1193
1194impl AsRef<[u8]> for &MutableBuffer {
1195    fn as_ref(&self) -> &[u8] {
1196        self.as_slice()
1197    }
1198}
1199
1200impl Drop for MutableBuffer {
1201    fn drop(&mut self) {
1202        if self.layout.size() != 0 {
1203            // Safety: data was allocated with standard allocator with given layout
1204            unsafe { std::alloc::dealloc(self.data.as_ptr().cast(), self.layout) };
1205        }
1206    }
1207}
1208
1209impl PartialEq for MutableBuffer {
1210    fn eq(&self, other: &MutableBuffer) -> bool {
1211        if self.len != other.len {
1212            return false;
1213        }
1214        if self.layout != other.layout {
1215            return false;
1216        }
1217        self.as_slice() == other.as_slice()
1218    }
1219}
1220
1221unsafe impl Sync for MutableBuffer {}
1222unsafe impl Send for MutableBuffer {}
1223
1224struct SetLenOnDrop<'a> {
1225    len: &'a mut usize,
1226    local_len: usize,
1227}
1228
1229impl<'a> SetLenOnDrop<'a> {
1230    #[inline]
1231    fn new(len: &'a mut usize) -> Self {
1232        SetLenOnDrop {
1233            local_len: *len,
1234            len,
1235        }
1236    }
1237}
1238
1239impl Drop for SetLenOnDrop<'_> {
1240    #[inline]
1241    fn drop(&mut self) {
1242        *self.len = self.local_len;
1243    }
1244}
1245
1246/// Creating a `MutableBuffer` instance by setting bits according to the boolean values
1247impl std::iter::FromIterator<bool> for MutableBuffer {
1248    fn from_iter<I>(iter: I) -> Self
1249    where
1250        I: IntoIterator<Item = bool>,
1251    {
1252        let mut iterator = iter.into_iter();
1253        let mut result = {
1254            let byte_capacity: usize = iterator.size_hint().0.saturating_add(7) / 8;
1255            MutableBuffer::new(byte_capacity)
1256        };
1257
1258        loop {
1259            let mut exhausted = false;
1260            let mut byte_accum: u8 = 0;
1261            let mut mask: u8 = 1;
1262
1263            //collect (up to) 8 bits into a byte
1264            while mask != 0 {
1265                if let Some(value) = iterator.next() {
1266                    byte_accum |= match value {
1267                        true => mask,
1268                        false => 0,
1269                    };
1270                    mask <<= 1;
1271                } else {
1272                    exhausted = true;
1273                    break;
1274                }
1275            }
1276
1277            // break if the iterator was exhausted before it provided a bool for this byte
1278            if exhausted && mask == 1 {
1279                break;
1280            }
1281
1282            //ensure we have capacity to write the byte
1283            if result.len() == result.capacity() {
1284                //no capacity for new byte, allocate 1 byte more (plus however many more the iterator advertises)
1285                let additional_byte_capacity = 1usize.saturating_add(
1286                    iterator.size_hint().0.saturating_add(7) / 8, //convert bit count to byte count, rounding up
1287                );
1288                result.reserve(additional_byte_capacity)
1289            }
1290
1291            // Soundness: capacity was allocated above
1292            unsafe { result.push_unchecked(byte_accum) };
1293            if exhausted {
1294                break;
1295            }
1296        }
1297        result
1298    }
1299}
1300
1301impl<T: ArrowNativeType> std::iter::FromIterator<T> for MutableBuffer {
1302    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1303        let mut buffer = Self::default();
1304        buffer.extend_from_iter(iter.into_iter());
1305        buffer
1306    }
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311    use super::*;
1312
1313    #[test]
1314    fn test_mutable_new() {
1315        let buf = MutableBuffer::new(63);
1316        assert_eq!(64, buf.capacity());
1317        assert_eq!(0, buf.len());
1318        assert!(buf.is_empty());
1319    }
1320
1321    #[test]
1322    fn test_mutable_default() {
1323        let buf = MutableBuffer::default();
1324        assert_eq!(0, buf.capacity());
1325        assert_eq!(0, buf.len());
1326        assert!(buf.is_empty());
1327
1328        let mut buf = MutableBuffer::default();
1329        buf.extend_from_slice(b"hello");
1330        assert_eq!(5, buf.len());
1331        assert_eq!(b"hello", buf.as_slice());
1332    }
1333
1334    #[test]
1335    fn test_mutable_extend_from_slice() {
1336        let mut buf = MutableBuffer::new(100);
1337        buf.extend_from_slice(b"hello");
1338        assert_eq!(5, buf.len());
1339        assert_eq!(b"hello", buf.as_slice());
1340
1341        buf.extend_from_slice(b" world");
1342        assert_eq!(11, buf.len());
1343        assert_eq!(b"hello world", buf.as_slice());
1344
1345        buf.clear();
1346        assert_eq!(0, buf.len());
1347        buf.extend_from_slice(b"hello arrow");
1348        assert_eq!(11, buf.len());
1349        assert_eq!(b"hello arrow", buf.as_slice());
1350    }
1351
1352    #[test]
1353    fn mutable_extend_from_iter() {
1354        let mut buf = MutableBuffer::new(0);
1355        buf.extend(vec![1u32, 2]);
1356        assert_eq!(8, buf.len());
1357        assert_eq!(&[1u8, 0, 0, 0, 2, 0, 0, 0], buf.as_slice());
1358
1359        buf.extend(vec![3u32, 4]);
1360        assert_eq!(16, buf.len());
1361        assert_eq!(
1362            &[1u8, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0],
1363            buf.as_slice()
1364        );
1365    }
1366
1367    #[test]
1368    fn mutable_extend_from_iter_unaligned_u64() {
1369        let mut buf = MutableBuffer::new(16);
1370        buf.push(1_u8);
1371        buf.extend([1_u64]);
1372        assert_eq!(9, buf.len());
1373        assert_eq!(&[1u8, 1u8, 0, 0, 0, 0, 0, 0, 0], buf.as_slice());
1374    }
1375
1376    #[test]
1377    fn mutable_extend_from_slice_unaligned_u64() {
1378        let mut buf = MutableBuffer::new(16);
1379        buf.extend_from_slice(&[1_u8]);
1380        buf.extend_from_slice(&[1_u64]);
1381        assert_eq!(9, buf.len());
1382        assert_eq!(&[1u8, 1u8, 0, 0, 0, 0, 0, 0, 0], buf.as_slice());
1383    }
1384
1385    #[test]
1386    fn mutable_push_unaligned_u64() {
1387        let mut buf = MutableBuffer::new(16);
1388        buf.push(1_u8);
1389        buf.push(1_u64);
1390        assert_eq!(9, buf.len());
1391        assert_eq!(&[1u8, 1u8, 0, 0, 0, 0, 0, 0, 0], buf.as_slice());
1392    }
1393
1394    #[test]
1395    fn mutable_try_push_matches_push() {
1396        let mut fallible = MutableBuffer::new(0);
1397        fallible.try_push(1_u8).unwrap();
1398        fallible.try_push(1_u64).unwrap();
1399
1400        let mut infallible = MutableBuffer::new(0);
1401        infallible.push(1_u8);
1402        infallible.push(1_u64);
1403
1404        assert_eq!(fallible.as_slice(), infallible.as_slice());
1405        assert_eq!(fallible.len(), infallible.len());
1406        assert_eq!(fallible.capacity(), infallible.capacity());
1407    }
1408
1409    #[test]
1410    fn mutable_try_new_null() {
1411        let buffer = MutableBuffer::try_new_null(9).unwrap();
1412        assert_eq!(buffer.len(), 2);
1413        assert_eq!(buffer.as_slice(), &[0, 0]);
1414    }
1415
1416    #[test]
1417    fn mutable_push_unchecked_unaligned_u64() {
1418        let mut buf = MutableBuffer::new(16);
1419        unsafe {
1420            buf.push_unchecked(1_u8);
1421            buf.push_unchecked(1_u64);
1422        }
1423        assert_eq!(9, buf.len());
1424        assert_eq!(&[1u8, 1u8, 0, 0, 0, 0, 0, 0, 0], buf.as_slice());
1425    }
1426
1427    #[test]
1428    fn test_from_trusted_len_iter() {
1429        let iter = vec![1u32, 2].into_iter();
1430        let buf = unsafe { MutableBuffer::from_trusted_len_iter(iter) };
1431        assert_eq!(8, buf.len());
1432        assert_eq!(&[1u8, 0, 0, 0, 2, 0, 0, 0], buf.as_slice());
1433    }
1434
1435    #[test]
1436    fn test_mutable_reserve() {
1437        let mut buf = MutableBuffer::new(1);
1438        assert_eq!(64, buf.capacity());
1439
1440        // Reserving a smaller capacity should have no effect.
1441        buf.reserve(10);
1442        assert_eq!(64, buf.capacity());
1443
1444        buf.reserve(80);
1445        assert_eq!(128, buf.capacity());
1446
1447        buf.reserve(129);
1448        assert_eq!(256, buf.capacity());
1449    }
1450
1451    #[test]
1452    fn test_mutable_resize() {
1453        let mut buf = MutableBuffer::new(1);
1454        assert_eq!(64, buf.capacity());
1455        assert_eq!(0, buf.len());
1456
1457        buf.resize(20, 0);
1458        assert_eq!(64, buf.capacity());
1459        assert_eq!(20, buf.len());
1460
1461        buf.resize(10, 0);
1462        assert_eq!(64, buf.capacity());
1463        assert_eq!(10, buf.len());
1464
1465        buf.resize(100, 0);
1466        assert_eq!(128, buf.capacity());
1467        assert_eq!(100, buf.len());
1468
1469        buf.resize(30, 0);
1470        assert_eq!(128, buf.capacity());
1471        assert_eq!(30, buf.len());
1472
1473        buf.resize(0, 0);
1474        assert_eq!(128, buf.capacity());
1475        assert_eq!(0, buf.len());
1476    }
1477
1478    #[test]
1479    fn test_mutable_into() {
1480        let mut buf = MutableBuffer::new(1);
1481        buf.extend_from_slice(b"aaaa bbbb cccc dddd");
1482        assert_eq!(19, buf.len());
1483        assert_eq!(64, buf.capacity());
1484        assert_eq!(b"aaaa bbbb cccc dddd", buf.as_slice());
1485
1486        let immutable_buf: Buffer = buf.into();
1487        assert_eq!(19, immutable_buf.len());
1488        assert_eq!(64, immutable_buf.capacity());
1489        assert_eq!(b"aaaa bbbb cccc dddd", immutable_buf.as_slice());
1490    }
1491
1492    #[test]
1493    fn test_mutable_equal() {
1494        let mut buf = MutableBuffer::new(1);
1495        let mut buf2 = MutableBuffer::new(1);
1496
1497        buf.extend_from_slice(&[0xaa]);
1498        buf2.extend_from_slice(&[0xaa, 0xbb]);
1499        assert_ne!(buf, buf2);
1500
1501        buf.extend_from_slice(&[0xbb]);
1502        assert_eq!(buf, buf2);
1503
1504        buf2.reserve(65);
1505        assert_ne!(buf, buf2);
1506    }
1507
1508    #[test]
1509    fn test_mutable_shrink_to_fit() {
1510        let mut buffer = MutableBuffer::new(128);
1511        assert_eq!(buffer.capacity(), 128);
1512        buffer.push(1);
1513        buffer.push(2);
1514
1515        buffer.shrink_to_fit();
1516        assert!(buffer.capacity() >= 64 && buffer.capacity() < 128);
1517    }
1518
1519    #[test]
1520    fn test_mutable_set_null_bits() {
1521        let mut buffer = MutableBuffer::new(8).with_bitset(8, true);
1522
1523        for i in 0..=buffer.capacity() {
1524            buffer.set_null_bits(i, 0);
1525            assert_eq!(buffer[..8], [255; 8][..]);
1526        }
1527
1528        buffer.set_null_bits(1, 4);
1529        assert_eq!(buffer[..8], [255, 0, 0, 0, 0, 255, 255, 255][..]);
1530    }
1531
1532    #[test]
1533    #[should_panic = "out of bounds for buffer of length"]
1534    fn test_mutable_set_null_bits_oob() {
1535        let mut buffer = MutableBuffer::new(64);
1536        buffer.set_null_bits(1, buffer.capacity());
1537    }
1538
1539    #[test]
1540    #[should_panic = "out of bounds for buffer of length"]
1541    fn test_mutable_set_null_bits_oob_by_overflow() {
1542        let mut buffer = MutableBuffer::new(0);
1543        buffer.set_null_bits(1, usize::MAX);
1544    }
1545
1546    #[test]
1547    fn from_iter() {
1548        let buffer = [1u16, 2, 3, 4].into_iter().collect::<MutableBuffer>();
1549        assert_eq!(buffer.len(), 4 * mem::size_of::<u16>());
1550        assert_eq!(buffer.as_slice(), &[1, 0, 2, 0, 3, 0, 4, 0]);
1551    }
1552
1553    #[test]
1554    #[should_panic(expected = "invalid allocation layout for requested capacity")]
1555    fn test_with_capacity_panics_above_max_capacity() {
1556        let max_capacity = isize::MAX as usize - (isize::MAX as usize % ALIGNMENT);
1557        let _ = MutableBuffer::with_capacity(max_capacity + 1);
1558    }
1559
1560    #[cfg(feature = "pool")]
1561    mod pool_tests {
1562        use super::*;
1563        use crate::pool::{MemoryPool, TrackingMemoryPool};
1564
1565        #[test]
1566        fn test_reallocate_with_pool() {
1567            let pool = TrackingMemoryPool::default();
1568            let mut buffer = MutableBuffer::with_capacity(100);
1569            buffer.claim(&pool);
1570
1571            // Initial capacity should be 128 (multiple of 64)
1572            assert_eq!(buffer.capacity(), 128);
1573            assert_eq!(pool.used(), 128);
1574
1575            // Reallocate to a larger size
1576            buffer.try_reallocate(200).unwrap();
1577
1578            // The capacity is exactly the requested size, not rounded up
1579            assert_eq!(buffer.capacity(), 200);
1580            assert_eq!(pool.used(), 200);
1581
1582            // Reallocate to a smaller size
1583            buffer.try_reallocate(50).unwrap();
1584
1585            // The capacity is exactly the requested size, not rounded up
1586            assert_eq!(buffer.capacity(), 50);
1587            assert_eq!(pool.used(), 50);
1588        }
1589
1590        #[test]
1591        fn test_truncate_with_pool() {
1592            let pool = TrackingMemoryPool::default();
1593            let mut buffer = MutableBuffer::with_capacity(100);
1594
1595            // Fill buffer with some data
1596            buffer.resize(80, 1);
1597            assert_eq!(buffer.len(), 80);
1598
1599            buffer.claim(&pool);
1600            assert_eq!(pool.used(), 128);
1601
1602            // Truncate buffer
1603            buffer.truncate(40);
1604            assert_eq!(buffer.len(), 40);
1605            assert_eq!(pool.used(), 40);
1606
1607            // Truncate to zero
1608            buffer.clear();
1609            assert_eq!(buffer.len(), 0);
1610            assert_eq!(pool.used(), 0);
1611        }
1612
1613        #[test]
1614        fn test_resize_with_pool() {
1615            let pool = TrackingMemoryPool::default();
1616            let mut buffer = MutableBuffer::with_capacity(100);
1617            buffer.claim(&pool);
1618
1619            // Initial state
1620            assert_eq!(buffer.len(), 0);
1621            assert_eq!(pool.used(), 128);
1622
1623            // Resize to increase length
1624            buffer.resize(50, 1);
1625            assert_eq!(buffer.len(), 50);
1626            assert_eq!(pool.used(), 50);
1627
1628            // Resize to increase length beyond capacity
1629            buffer.resize(150, 1);
1630            assert_eq!(buffer.len(), 150);
1631            assert_eq!(buffer.capacity(), 256);
1632            assert_eq!(pool.used(), 150);
1633
1634            // Resize to decrease length
1635            buffer.resize(30, 1);
1636            assert_eq!(buffer.len(), 30);
1637            assert_eq!(pool.used(), 30);
1638        }
1639
1640        #[test]
1641        fn test_buffer_lifecycle_with_pool() {
1642            let pool = TrackingMemoryPool::default();
1643
1644            // Create a buffer with memory reservation
1645            let mut mutable = MutableBuffer::with_capacity(100);
1646            mutable.resize(80, 1);
1647            mutable.claim(&pool);
1648
1649            // Memory reservation is based on capacity when using claim()
1650            assert_eq!(pool.used(), 128);
1651
1652            // Convert to immutable Buffer
1653            let buffer = mutable.into_buffer();
1654
1655            // Memory reservation should be preserved
1656            assert_eq!(pool.used(), 128);
1657
1658            // Drop the buffer and the reservation should be released
1659            drop(buffer);
1660            assert_eq!(pool.used(), 0);
1661        }
1662    }
1663
1664    fn create_expected_repeated_slice<T: ArrowNativeType>(
1665        slice_to_repeat: &[T],
1666        repeat_count: usize,
1667    ) -> Buffer {
1668        let mut expected = MutableBuffer::new(size_of_val(slice_to_repeat) * repeat_count);
1669        for _ in 0..repeat_count {
1670            // Not using push_slice_repeated as this is the function under test
1671            expected.extend_from_slice(slice_to_repeat);
1672        }
1673        expected.into()
1674    }
1675
1676    // Helper to test a specific repeat count with various slice sizes
1677    fn test_repeat_count<T: ArrowNativeType + PartialEq + std::fmt::Debug>(
1678        repeat_count: usize,
1679        test_data: &[T],
1680    ) {
1681        let mut buffer = MutableBuffer::new(0);
1682        buffer.repeat_slice_n_times(test_data, repeat_count);
1683
1684        let expected = create_expected_repeated_slice(test_data, repeat_count);
1685        let result: Buffer = buffer.into();
1686
1687        assert_eq!(
1688            result,
1689            expected,
1690            "Failed for repeat_count={}, slice_len={}",
1691            repeat_count,
1692            test_data.len()
1693        );
1694    }
1695
1696    #[test]
1697    fn test_repeat_slice_count_edge_cases() {
1698        // Empty slice
1699        test_repeat_count(100, &[] as &[i32]);
1700
1701        // Zero repeats
1702        test_repeat_count(0, &[1i32, 2, 3]);
1703    }
1704
1705    #[test]
1706    #[should_panic(expected = "buffer length overflow")]
1707    fn test_repeat_slice_count_multiply_overflow() {
1708        let mut buffer = MutableBuffer::new(0);
1709        buffer.repeat_slice_n_times(&[0_u64], usize::MAX / mem::size_of::<u64>() + 1);
1710    }
1711
1712    #[test]
1713    #[should_panic(expected = "buffer length overflow")]
1714    fn test_repeat_slice_count_len_overflow() {
1715        let mut buffer = MutableBuffer::new(0);
1716        buffer.push(0_u8);
1717        buffer.repeat_slice_n_times(&[0_u8], usize::MAX);
1718    }
1719
1720    #[test]
1721    fn test_small_repeats_counts() {
1722        // test any special implementation for small repeat counts
1723        let data = &[1u8, 2, 3, 4, 5];
1724
1725        for _ in 1..=10 {
1726            test_repeat_count(2, data);
1727        }
1728    }
1729
1730    #[test]
1731    fn test_different_size_of_i32_repeat_slice() {
1732        let data: &[i32] = &[1, 2, 3];
1733        let data_with_single_item: &[i32] = &[42];
1734
1735        for data in &[data, data_with_single_item] {
1736            for item in 1..=9 {
1737                let base_repeat_count = 2_usize.pow(item);
1738                test_repeat_count(base_repeat_count - 1, data);
1739                test_repeat_count(base_repeat_count, data);
1740                test_repeat_count(base_repeat_count + 1, data);
1741            }
1742        }
1743    }
1744
1745    #[test]
1746    fn test_different_size_of_u8_repeat_slice() {
1747        let data: &[u8] = &[1, 2, 3];
1748        let data_with_single_item: &[u8] = &[10];
1749
1750        for data in &[data, data_with_single_item] {
1751            for item in 1..=9 {
1752                let base_repeat_count = 2_usize.pow(item);
1753                test_repeat_count(base_repeat_count - 1, data);
1754                test_repeat_count(base_repeat_count, data);
1755                test_repeat_count(base_repeat_count + 1, data);
1756            }
1757        }
1758    }
1759
1760    #[test]
1761    fn test_different_size_of_u16_repeat_slice() {
1762        let data: &[u16] = &[1, 2, 3];
1763        let data_with_single_item: &[u16] = &[10];
1764
1765        for data in &[data, data_with_single_item] {
1766            for item in 1..=9 {
1767                let base_repeat_count = 2_usize.pow(item);
1768                test_repeat_count(base_repeat_count - 1, data);
1769                test_repeat_count(base_repeat_count, data);
1770                test_repeat_count(base_repeat_count + 1, data);
1771            }
1772        }
1773    }
1774
1775    #[test]
1776    fn test_various_slice_lengths() {
1777        // Test different slice lengths with same repeat pattern
1778        let repeat_count = 37; // Arbitrary non-power-of-2
1779
1780        // Single element
1781        test_repeat_count(repeat_count, &[42i32]);
1782
1783        // Small slices
1784        test_repeat_count(repeat_count, &[1i32, 2]);
1785        test_repeat_count(repeat_count, &[1i32, 2, 3]);
1786        test_repeat_count(repeat_count, &[1i32, 2, 3, 4]);
1787        test_repeat_count(repeat_count, &[1i32, 2, 3, 4, 5]);
1788
1789        // Larger slices
1790        let data_10: Vec<i32> = (0..10).collect();
1791        test_repeat_count(repeat_count, &data_10);
1792
1793        let data_100: Vec<i32> = (0..100).collect();
1794        test_repeat_count(repeat_count, &data_100);
1795
1796        let data_1000: Vec<i32> = (0..1000).collect();
1797        test_repeat_count(repeat_count, &data_1000);
1798    }
1799
1800    #[test]
1801    #[should_panic(expected = "invalid allocation layout for requested capacity")]
1802    fn test_mutable_new_capacity_overflow() {
1803        // Tests overflow during initial allocation
1804        let _ = MutableBuffer::new(usize::MAX - 10);
1805    }
1806
1807    #[test]
1808    #[should_panic(expected = "buffer length overflow")]
1809    fn test_mutable_reserve_overflow() {
1810        // Tests overflow during growth (checked_add)
1811        let mut buf = MutableBuffer::new(1);
1812        buf.push(1u8);
1813        buf.reserve(usize::MAX);
1814    }
1815}