Skip to main content

arrow_buffer/buffer/
immutable.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::alloc::Layout;
19use std::fmt::Debug;
20use std::ptr::NonNull;
21use std::sync::Arc;
22
23use crate::BufferBuilder;
24use crate::alloc::{Allocation, Deallocation};
25use crate::util::bit_chunk_iterator::{BitChunks, UnalignedBitChunk};
26use crate::{bit_util, bytes::Bytes, native::ArrowNativeType};
27
28#[cfg(feature = "pool")]
29use crate::pool::MemoryPool;
30
31use super::{MutableBuffer, ScalarBuffer};
32
33/// A contiguous memory region that can be shared with other buffers and across
34/// thread boundaries that stores Arrow data.
35///
36/// `Buffer`s can be sliced and cloned without copying the underlying data and can
37/// be created from memory allocated by non-Rust sources such as C/C++.
38///
39/// # Example: Create a `Buffer` from a `Vec` (without copying)
40/// ```
41/// # use arrow_buffer::Buffer;
42/// let vec: Vec<u32> = vec![1, 2, 3];
43/// let buffer = Buffer::from(vec);
44/// ```
45///
46/// # Example: Convert a `Buffer` to a `Vec` (without copying)
47///
48/// Use [`Self::into_vec`] to convert a `Buffer` back into a `Vec` if there are
49/// no other references and the types are aligned correctly.
50/// ```
51/// # use arrow_buffer::Buffer;
52/// # let vec: Vec<u32> = vec![1, 2, 3];
53/// # let buffer = Buffer::from(vec);
54/// // convert the buffer back into a Vec of u32
55/// // note this will fail if the buffer is shared or not aligned correctly
56/// let vec: Vec<u32> = buffer.into_vec().unwrap();
57/// ```
58///
59/// # Example: Create a `Buffer` from a [`bytes::Bytes`] (without copying)
60///
61/// [`bytes::Bytes`] is a common type in the Rust ecosystem for shared memory
62/// regions. You can create a buffer from a `Bytes` instance using the `From`
63/// implementation, also without copying.
64///
65/// ```
66/// # use arrow_buffer::Buffer;
67/// let bytes = bytes::Bytes::from("hello");
68/// let buffer = Buffer::from(bytes);
69///```
70#[derive(Clone, Debug)]
71pub struct Buffer {
72    /// the internal byte buffer.
73    data: Arc<Bytes>,
74
75    /// Pointer into `data` valid
76    ///
77    /// We store a pointer instead of an offset to avoid pointer arithmetic
78    /// which causes LLVM to fail to vectorise code correctly
79    ptr: *const u8,
80
81    /// Byte length of the buffer.
82    ///
83    /// Must be less than or equal to `data.len()`
84    length: usize,
85}
86
87impl Default for Buffer {
88    #[inline]
89    fn default() -> Self {
90        MutableBuffer::default().into()
91    }
92}
93
94impl PartialEq for Buffer {
95    fn eq(&self, other: &Self) -> bool {
96        self.as_slice().eq(other.as_slice())
97    }
98}
99
100impl Eq for Buffer {}
101
102unsafe impl Send for Buffer where Bytes: Send {}
103unsafe impl Sync for Buffer where Bytes: Sync {}
104
105impl Buffer {
106    /// Returns the offset, in bytes, of `Self::ptr` to `Self::data`
107    ///
108    /// self.ptr and self.data can be different after slicing or advancing the buffer.
109    pub fn ptr_offset(&self) -> usize {
110        // Safety: `ptr` is always in bounds of `data`.
111        unsafe { self.ptr.offset_from(self.data.ptr().as_ptr()) as usize }
112    }
113
114    /// Returns the pointer to the start of the buffer without the offset.
115    pub fn data_ptr(&self) -> NonNull<u8> {
116        self.data.ptr()
117    }
118
119    /// Returns the number of strong references to the buffer.
120    ///
121    /// This method is safe but if the buffer is shared across multiple threads
122    /// the underlying value could change between calling this method and using
123    /// the result.
124    pub fn strong_count(&self) -> usize {
125        Arc::strong_count(&self.data)
126    }
127
128    /// Create a [`Buffer`] from the provided [`Vec`] without copying
129    #[inline]
130    pub fn from_vec<T: ArrowNativeType>(vec: Vec<T>) -> Self {
131        MutableBuffer::from(vec).into()
132    }
133
134    /// Initializes a [Buffer] from a slice of items.
135    pub fn from_slice_ref<U: ArrowNativeType, T: AsRef<[U]>>(items: T) -> Self {
136        let slice = items.as_ref();
137        let capacity = std::mem::size_of_val(slice);
138        let mut buffer = MutableBuffer::with_capacity(capacity);
139        buffer.extend_from_slice(slice);
140        buffer.into()
141    }
142
143    /// Creates a buffer from an existing memory region.
144    ///
145    /// Ownership of the memory is tracked via reference counting
146    /// and the memory will be freed using the `drop` method of
147    /// [crate::alloc::Allocation] when the reference count reaches zero.
148    ///
149    /// # Arguments
150    ///
151    /// * `ptr` - Pointer to raw parts
152    /// * `len` - Length of raw parts in **bytes**
153    /// * `owner` - A [crate::alloc::Allocation] which is responsible for freeing that data
154    ///
155    /// # Safety
156    ///
157    /// This function is unsafe as there is no guarantee that the given pointer is valid for `len` bytes
158    pub unsafe fn from_custom_allocation(
159        ptr: NonNull<u8>,
160        len: usize,
161        owner: Arc<dyn Allocation>,
162    ) -> Self {
163        unsafe { Buffer::build_with_arguments(ptr, len, Deallocation::Custom(owner, len)) }
164    }
165
166    /// Auxiliary method to create a new Buffer
167    unsafe fn build_with_arguments(
168        ptr: NonNull<u8>,
169        len: usize,
170        deallocation: Deallocation,
171    ) -> Self {
172        let bytes = unsafe { Bytes::new(ptr, len, deallocation) };
173        let ptr = bytes.as_ptr();
174        Buffer {
175            ptr,
176            data: Arc::new(bytes),
177            length: len,
178        }
179    }
180
181    /// Returns the number of bytes in the buffer
182    #[inline]
183    pub fn len(&self) -> usize {
184        self.length
185    }
186
187    /// Returns the capacity of this buffer.
188    /// For externally owned buffers, this returns zero
189    #[inline]
190    pub fn capacity(&self) -> usize {
191        self.data.capacity()
192    }
193
194    /// Tries to shrink the capacity of the buffer as much as possible, freeing unused memory.
195    ///
196    /// If the buffer is shared, this is a no-op.
197    ///
198    /// If the memory was allocated with a custom allocator, this is a no-op.
199    ///
200    /// If the capacity is already less than or equal to the desired capacity, this is a no-op.
201    ///
202    /// The memory region will be reallocated using `std::alloc::realloc`.
203    pub fn shrink_to_fit(&mut self) {
204        let offset = self.ptr_offset();
205        let is_empty = self.is_empty();
206        let desired_capacity = if is_empty {
207            0
208        } else {
209            // For realloc to work, we cannot free the elements before the offset
210            offset + self.len()
211        };
212        if desired_capacity < self.capacity() {
213            if let Some(bytes) = Arc::get_mut(&mut self.data) {
214                if bytes.try_realloc(desired_capacity).is_ok() {
215                    // Realloc complete - update our pointer into `bytes`:
216                    self.ptr = if is_empty {
217                        bytes.as_ptr()
218                    } else {
219                        // SAFETY: we kept all elements leading up to the offset
220                        unsafe { bytes.as_ptr().add(offset) }
221                    }
222                } else {
223                    // Failure to reallocate is fine; we just failed to free up memory.
224                }
225            }
226        }
227    }
228
229    /// Returns true if the buffer is empty.
230    #[inline]
231    pub fn is_empty(&self) -> bool {
232        self.length == 0
233    }
234
235    /// Returns the byte slice stored in this buffer
236    pub fn as_slice(&self) -> &[u8] {
237        unsafe { std::slice::from_raw_parts(self.ptr, self.length) }
238    }
239
240    pub(crate) fn deallocation(&self) -> &Deallocation {
241        self.data.deallocation()
242    }
243
244    /// Returns a new [Buffer] that is a slice of this buffer starting at `offset`.
245    ///
246    /// This function is `O(1)` and does not copy any data, allowing the
247    /// same memory region to be shared between buffers.
248    ///
249    /// # Panics
250    ///
251    /// Panics iff `offset` is larger than `len`.
252    pub fn slice(&self, offset: usize) -> Self {
253        let mut s = self.clone();
254        s.advance(offset);
255        s
256    }
257
258    /// Increases the offset of this buffer by `offset`
259    ///
260    /// # Panics
261    ///
262    /// Panics iff `offset` is larger than `len`.
263    #[inline]
264    pub fn advance(&mut self, offset: usize) {
265        assert!(
266            offset <= self.length,
267            "the offset of the new Buffer cannot exceed the existing length: offset={} length={}",
268            offset,
269            self.length
270        );
271        self.length -= offset;
272        // Safety:
273        // This cannot overflow as
274        // `self.offset + self.length < self.data.len()`
275        // `offset < self.length`
276        self.ptr = unsafe { self.ptr.add(offset) };
277    }
278
279    /// Returns a new [Buffer] that is a slice of this buffer starting at `offset`,
280    /// with `length` bytes.
281    ///
282    /// This function is `O(1)` and does not copy any data, allowing the same
283    /// memory region to be shared between buffers.
284    ///
285    /// # Panics
286    /// Panics iff `(offset + length)` is larger than the existing length.
287    pub fn slice_with_length(&self, offset: usize, length: usize) -> Self {
288        assert!(
289            offset.saturating_add(length) <= self.length,
290            "the offset of the new Buffer cannot exceed the existing length: slice offset={offset} length={length} selflen={}",
291            self.length
292        );
293        // Safety:
294        // offset + length <= self.length
295        let ptr = unsafe { self.ptr.add(offset) };
296        Self {
297            data: self.data.clone(),
298            ptr,
299            length,
300        }
301    }
302
303    /// Returns a pointer to the start of this buffer.
304    ///
305    /// Note that this should be used cautiously, and the returned pointer should not be
306    /// stored anywhere, to avoid dangling pointers.
307    #[inline]
308    pub fn as_ptr(&self) -> *const u8 {
309        self.ptr
310    }
311
312    /// View buffer as a slice of a specific type.
313    ///
314    /// # Panics
315    ///
316    /// This function panics if the underlying buffer is not aligned
317    /// correctly for type `T`.
318    pub fn typed_data<T: ArrowNativeType>(&self) -> &[T] {
319        // SAFETY
320        // ArrowNativeType is trivially transmutable, is sealed to prevent potentially incorrect
321        // implementation outside this crate, and this method checks alignment
322        let (prefix, offsets, suffix) = unsafe { self.as_slice().align_to::<T>() };
323        assert!(prefix.is_empty() && suffix.is_empty());
324        offsets
325    }
326
327    /// Returns a slice of this buffer starting at a certain bit offset.
328    /// If the offset is byte-aligned the returned buffer is a shallow clone,
329    /// otherwise a new buffer is allocated and filled with a copy of the bits in the range.
330    pub fn bit_slice(&self, offset: usize, len: usize) -> Self {
331        if offset % 8 == 0 {
332            return self.slice_with_length(offset / 8, bit_util::ceil(len, 8));
333        }
334
335        let chunks = self.bit_chunks(offset, len);
336
337        let buffer: Vec<u64> = if chunks.remainder_len() > 0 {
338            chunks.iter().chain(Some(chunks.remainder_bits())).collect()
339        } else {
340            chunks.iter().collect()
341        };
342        let mut buffer = Buffer::from_vec(buffer);
343        // Update length to be byte-aligned
344        buffer.length = bit_util::ceil(len, 8);
345        buffer
346    }
347
348    /// Returns a `BitChunks` instance which can be used to iterate over this buffers bits
349    /// in larger chunks and starting at arbitrary bit offsets.
350    /// Note that both `offset` and `length` are measured in bits.
351    pub fn bit_chunks(&self, offset: usize, len: usize) -> BitChunks<'_> {
352        BitChunks::new(self.as_slice(), offset, len)
353    }
354
355    /// Returns the number of 1-bits in this buffer, starting from `offset` with `length` bits
356    /// inspected. Note that both `offset` and `length` are measured in bits.
357    pub fn count_set_bits_offset(&self, offset: usize, len: usize) -> usize {
358        UnalignedBitChunk::new(self.as_slice(), offset, len).count_ones()
359    }
360
361    /// Returns `MutableBuffer` for mutating the buffer if this buffer is not shared or sliced.
362    /// Returns `Err` if this is shared or the [`Self::ptr_offset`] is greater than 0 or its allocation is from an external source or
363    /// it is not allocated with alignment [`ALIGNMENT`]
364    ///
365    /// # Example: Creating a [`MutableBuffer`] from a [`Buffer`]
366    /// ```
367    /// # use arrow_buffer::buffer::{Buffer, MutableBuffer};
368    /// let buffer: Buffer = Buffer::from(&[1u8, 2, 3, 4][..]);
369    /// // Only possible to convert a Buffer into a MutableBuffer if uniquely owned
370    /// // (i.e., there are no other references to it).
371    /// let mut mutable_buffer = match buffer.into_mutable() {
372    ///    Ok(mutable) => mutable,
373    ///    Err(orig_buffer) => {
374    ///      panic!("buffer was not uniquely owned");
375    ///    }
376    /// };
377    /// mutable_buffer.push(5u8);
378    /// let buffer = Buffer::from(mutable_buffer);
379    /// assert_eq!(buffer.as_slice(), &[1u8, 2, 3, 4, 5])
380    /// ```
381    ///
382    /// [`ALIGNMENT`]: crate::alloc::ALIGNMENT
383    pub fn into_mutable(self) -> Result<MutableBuffer, Self> {
384        let ptr = self.ptr;
385        let length = self.length;
386
387        // Disallow converting when the offset is not 0 because we can't start a mutable from offset
388        let res = if self.ptr_offset() > 0 {
389            Err(self.data)
390        } else {
391            Arc::try_unwrap(self.data)
392        };
393
394        res.and_then(|bytes| {
395            // The pointer of underlying buffer should not be offset.
396            assert_eq!(ptr, bytes.ptr().as_ptr());
397            MutableBuffer::from_bytes(bytes).map_err(Arc::new)
398        })
399        .map_err(|bytes| Buffer {
400            data: bytes,
401            ptr,
402            length,
403        })
404        .map(|mut mutable| {
405            // We need to update the length since in case we are converting sliced buffer we need to return MutableBuffer with the same length
406            // SAFETY: this is safe as the length is coming from valid Buffer (this) and it is guaranteed to be less than the underlying data buffer
407            unsafe { mutable.set_len(length) };
408            mutable
409        })
410    }
411
412    /// Converts self into a `Vec`, if possible.
413    ///
414    /// This can be used to reuse / mutate the underlying data.
415    ///
416    /// # Errors
417    ///
418    /// Returns `Err(self)` if
419    /// 1. The buffer does not have the same [`Layout`] as the destination Vec
420    /// 2. The buffer contains a non-zero offset
421    /// 3. The buffer is shared
422    pub fn into_vec<T: ArrowNativeType>(self) -> Result<Vec<T>, Self> {
423        let layout = match self.data.deallocation() {
424            Deallocation::Standard(l) => l,
425            _ => return Err(self), // Custom allocation
426        };
427
428        if self.ptr != self.data.as_ptr() {
429            return Err(self); // Data is offset
430        }
431
432        let v_capacity = layout.size() / std::mem::size_of::<T>();
433        match Layout::array::<T>(v_capacity) {
434            Ok(expected) if layout == &expected => {}
435            _ => return Err(self), // Incorrect layout
436        }
437
438        let length = self.length;
439        let ptr = self.ptr;
440        let v_len = self.length / std::mem::size_of::<T>();
441
442        Arc::try_unwrap(self.data)
443            .map(|bytes| unsafe {
444                let ptr = bytes.ptr().as_ptr() as _;
445                std::mem::forget(bytes);
446                // Safety
447                // Verified that bytes layout matches that of Vec
448                Vec::from_raw_parts(ptr, v_len, v_capacity)
449            })
450            .map_err(|bytes| Buffer {
451                data: bytes,
452                ptr,
453                length,
454            })
455    }
456
457    /// Returns true if this [`Buffer`] is equal to `other`, using pointer comparisons
458    /// to determine buffer equality. This is cheaper than `PartialEq::eq` but may
459    /// return false when the arrays are logically equal
460    #[inline]
461    pub fn ptr_eq(&self, other: &Self) -> bool {
462        self.ptr == other.ptr && self.length == other.length
463    }
464
465    /// Register this [`Buffer`] with the provided [`MemoryPool`]
466    ///
467    /// This claims the memory used by this buffer in the pool, allowing for
468    /// accurate accounting of memory usage. Any prior reservation will be
469    /// released so this works well when the buffer is being shared among
470    /// multiple arrays.
471    #[cfg(feature = "pool")]
472    pub fn claim(&self, pool: &dyn MemoryPool) {
473        self.data.claim(pool)
474    }
475}
476
477/// Note that here we deliberately do not implement
478/// `impl<T: AsRef<[u8]>> From<T> for Buffer`
479/// As it would accept `Buffer::from(vec![...])` that would cause an unexpected copy.
480/// Instead, we ask user to be explicit when copying is occurring, e.g., `Buffer::from(vec![...].to_byte_slice())`.
481/// For zero-copy conversion, user should use `Buffer::from_vec(vec![...])`.
482///
483/// Since we removed impl for `AsRef<u8>`, we added the following three specific implementations to reduce API breakage.
484/// See <https://github.com/apache/arrow-rs/issues/6033> for more discussion on this.
485impl From<&[u8]> for Buffer {
486    fn from(p: &[u8]) -> Self {
487        Self::from_slice_ref(p)
488    }
489}
490
491impl<const N: usize> From<[u8; N]> for Buffer {
492    fn from(p: [u8; N]) -> Self {
493        Self::from_slice_ref(p)
494    }
495}
496
497impl<const N: usize> From<&[u8; N]> for Buffer {
498    fn from(p: &[u8; N]) -> Self {
499        Self::from_slice_ref(p)
500    }
501}
502
503impl<T: ArrowNativeType> From<Vec<T>> for Buffer {
504    fn from(value: Vec<T>) -> Self {
505        Self::from_vec(value)
506    }
507}
508
509impl<T: ArrowNativeType> From<ScalarBuffer<T>> for Buffer {
510    fn from(value: ScalarBuffer<T>) -> Self {
511        value.into_inner()
512    }
513}
514
515/// Convert from internal `Bytes` (not [`bytes::Bytes`]) to `Buffer`
516impl From<Bytes> for Buffer {
517    #[inline]
518    fn from(bytes: Bytes) -> Self {
519        let length = bytes.len();
520        let ptr = bytes.as_ptr();
521        Self {
522            data: Arc::new(bytes),
523            ptr,
524            length,
525        }
526    }
527}
528
529/// Convert from [`bytes::Bytes`], not internal `Bytes` to `Buffer`
530impl From<bytes::Bytes> for Buffer {
531    fn from(bytes: bytes::Bytes) -> Self {
532        let bytes: Bytes = bytes.into();
533        Self::from(bytes)
534    }
535}
536
537/// Create a `Buffer` instance by storing the boolean values into the buffer
538impl FromIterator<bool> for Buffer {
539    fn from_iter<I>(iter: I) -> Self
540    where
541        I: IntoIterator<Item = bool>,
542    {
543        MutableBuffer::from_iter(iter).into()
544    }
545}
546
547impl std::ops::Deref for Buffer {
548    type Target = [u8];
549
550    fn deref(&self) -> &[u8] {
551        unsafe { std::slice::from_raw_parts(self.as_ptr(), self.len()) }
552    }
553}
554
555impl AsRef<[u8]> for &Buffer {
556    fn as_ref(&self) -> &[u8] {
557        self.as_slice()
558    }
559}
560
561impl From<MutableBuffer> for Buffer {
562    #[inline]
563    fn from(buffer: MutableBuffer) -> Self {
564        buffer.into_buffer()
565    }
566}
567
568impl<T: ArrowNativeType> From<BufferBuilder<T>> for Buffer {
569    fn from(mut value: BufferBuilder<T>) -> Self {
570        value.finish()
571    }
572}
573
574impl Buffer {
575    /// Creates a [`Buffer`] from an [`Iterator`] with a trusted (upper) length.
576    ///
577    /// Prefer this to `collect` whenever possible, as it is ~60% faster.
578    ///
579    /// # Example
580    /// ```
581    /// # use arrow_buffer::buffer::Buffer;
582    /// let v = vec![1u32];
583    /// let iter = v.iter().map(|x| x * 2);
584    /// let buffer = unsafe { Buffer::from_trusted_len_iter(iter) };
585    /// assert_eq!(buffer.len(), 4) // u32 has 4 bytes
586    /// ```
587    /// # Safety
588    /// This method assumes that the iterator's size is correct and is undefined behavior
589    /// to use it on an iterator that reports an incorrect length.
590    // This implementation is required for two reasons:
591    // 1. there is no trait `TrustedLen` in stable rust and therefore
592    //    we can't specialize `extend` for `TrustedLen` like `Vec` does.
593    // 2. `from_trusted_len_iter` is faster.
594    #[inline]
595    pub unsafe fn from_trusted_len_iter<T: ArrowNativeType, I: Iterator<Item = T>>(
596        iterator: I,
597    ) -> Self {
598        unsafe { MutableBuffer::from_trusted_len_iter(iterator).into() }
599    }
600
601    /// Creates a [`Buffer`] from an [`Iterator`] with a trusted (upper) length or errors
602    /// if any of the items of the iterator is an error.
603    /// Prefer this to `collect` whenever possible, as it is ~60% faster.
604    /// # Safety
605    /// This method assumes that the iterator's size is correct and is undefined behavior
606    /// to use it on an iterator that reports an incorrect length.
607    #[inline]
608    pub unsafe fn try_from_trusted_len_iter<
609        E,
610        T: ArrowNativeType,
611        I: Iterator<Item = Result<T, E>>,
612    >(
613        iterator: I,
614    ) -> Result<Self, E> {
615        unsafe { Ok(MutableBuffer::try_from_trusted_len_iter(iterator)?.into()) }
616    }
617}
618
619impl<T: ArrowNativeType> FromIterator<T> for Buffer {
620    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
621        let vec = Vec::from_iter(iter);
622        Buffer::from_vec(vec)
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use crate::i256;
629    use std::panic::{RefUnwindSafe, UnwindSafe};
630    use std::thread;
631
632    use super::*;
633
634    #[test]
635    fn test_buffer_data_equality() {
636        let buf1 = Buffer::from(&[0, 1, 2, 3, 4]);
637        let buf2 = Buffer::from(&[0, 1, 2, 3, 4]);
638        assert_eq!(buf1, buf2);
639
640        // slice with same offset and same length should still preserve equality
641        let buf3 = buf1.slice(2);
642        assert_ne!(buf1, buf3);
643        let buf4 = buf2.slice_with_length(2, 3);
644        assert_eq!(buf3, buf4);
645
646        // Different capacities should still preserve equality
647        let mut buf2 = MutableBuffer::new(65);
648        buf2.extend_from_slice(&[0u8, 1, 2, 3, 4]);
649
650        let buf2 = buf2.into();
651        assert_eq!(buf1, buf2);
652
653        // unequal because of different elements
654        let buf2 = Buffer::from(&[0, 0, 2, 3, 4]);
655        assert_ne!(buf1, buf2);
656
657        // unequal because of different length
658        let buf2 = Buffer::from(&[0, 1, 2, 3]);
659        assert_ne!(buf1, buf2);
660    }
661
662    #[test]
663    fn test_from_raw_parts() {
664        let buf = Buffer::from(&[0, 1, 2, 3, 4]);
665        assert_eq!(5, buf.len());
666        assert!(!buf.as_ptr().is_null());
667        assert_eq!([0, 1, 2, 3, 4], buf.as_slice());
668    }
669
670    #[test]
671    fn test_from_vec() {
672        let buf = Buffer::from(&[0, 1, 2, 3, 4]);
673        assert_eq!(5, buf.len());
674        assert!(!buf.as_ptr().is_null());
675        assert_eq!([0, 1, 2, 3, 4], buf.as_slice());
676    }
677
678    #[test]
679    fn test_copy() {
680        let buf = Buffer::from(&[0, 1, 2, 3, 4]);
681        let buf2 = buf;
682        assert_eq!(5, buf2.len());
683        assert_eq!(64, buf2.capacity());
684        assert!(!buf2.as_ptr().is_null());
685        assert_eq!([0, 1, 2, 3, 4], buf2.as_slice());
686    }
687
688    #[test]
689    fn test_slice() {
690        let buf = Buffer::from(&[2, 4, 6, 8, 10]);
691        let buf2 = buf.slice(2);
692
693        assert_eq!([6, 8, 10], buf2.as_slice());
694        assert_eq!(3, buf2.len());
695        assert_eq!(unsafe { buf.as_ptr().offset(2) }, buf2.as_ptr());
696
697        let buf3 = buf2.slice_with_length(1, 2);
698        assert_eq!([8, 10], buf3.as_slice());
699        assert_eq!(2, buf3.len());
700        assert_eq!(unsafe { buf.as_ptr().offset(3) }, buf3.as_ptr());
701
702        let buf4 = buf.slice(5);
703        let empty_slice: [u8; 0] = [];
704        assert_eq!(empty_slice, buf4.as_slice());
705        assert_eq!(0, buf4.len());
706        assert!(buf4.is_empty());
707        assert_eq!(buf2.slice_with_length(2, 1).as_slice(), &[10]);
708    }
709
710    #[test]
711    fn test_shrink_to_fit() {
712        let original = Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7]);
713        assert_eq!(original.as_slice(), &[0, 1, 2, 3, 4, 5, 6, 7]);
714        assert_eq!(original.capacity(), 64);
715
716        let slice = original.slice_with_length(2, 3);
717        drop(original); // Make sure the buffer isn't shared (or shrink_to_fit won't work)
718        assert_eq!(slice.as_slice(), &[2, 3, 4]);
719        assert_eq!(slice.capacity(), 64);
720
721        let mut shrunk = slice;
722        shrunk.shrink_to_fit();
723        assert_eq!(shrunk.as_slice(), &[2, 3, 4]);
724        assert_eq!(shrunk.capacity(), 5); // shrink_to_fit is allowed to keep the elements before the offset
725
726        // Test that we can handle empty slices:
727        let empty_slice = shrunk.slice_with_length(1, 0);
728        drop(shrunk); // Make sure the buffer isn't shared (or shrink_to_fit won't work)
729        assert_eq!(empty_slice.as_slice(), &[]);
730        assert_eq!(empty_slice.capacity(), 5);
731
732        let mut shrunk_empty = empty_slice;
733        shrunk_empty.shrink_to_fit();
734        assert_eq!(shrunk_empty.as_slice(), &[]);
735        assert_eq!(shrunk_empty.capacity(), 0);
736    }
737
738    #[test]
739    #[should_panic(expected = "the offset of the new Buffer cannot exceed the existing length")]
740    fn test_slice_offset_out_of_bound() {
741        let buf = Buffer::from(&[2, 4, 6, 8, 10]);
742        buf.slice(6);
743    }
744
745    #[test]
746    fn test_access_concurrently() {
747        let buffer = Buffer::from([1, 2, 3, 4, 5]);
748        let buffer2 = buffer.clone();
749        assert_eq!([1, 2, 3, 4, 5], buffer.as_slice());
750
751        let buffer_copy = thread::spawn(move || {
752            // access buffer in another thread.
753            buffer
754        })
755        .join();
756
757        assert!(buffer_copy.is_ok());
758        assert_eq!(buffer2, buffer_copy.ok().unwrap());
759    }
760
761    macro_rules! check_as_typed_data {
762        ($input: expr, $native_t: ty) => {{
763            let buffer = Buffer::from_slice_ref($input);
764            let slice: &[$native_t] = buffer.typed_data::<$native_t>();
765            assert_eq!($input, slice);
766        }};
767    }
768
769    #[test]
770    #[allow(clippy::float_cmp)]
771    fn test_as_typed_data() {
772        check_as_typed_data!(&[1i8, 3i8, 6i8], i8);
773        check_as_typed_data!(&[1u8, 3u8, 6u8], u8);
774        check_as_typed_data!(&[1i16, 3i16, 6i16], i16);
775        check_as_typed_data!(&[1i32, 3i32, 6i32], i32);
776        check_as_typed_data!(&[1i64, 3i64, 6i64], i64);
777        check_as_typed_data!(&[1u16, 3u16, 6u16], u16);
778        check_as_typed_data!(&[1u32, 3u32, 6u32], u32);
779        check_as_typed_data!(&[1u64, 3u64, 6u64], u64);
780        check_as_typed_data!(&[1f32, 3f32, 6f32], f32);
781        check_as_typed_data!(&[1f64, 3f64, 6f64], f64);
782    }
783
784    #[test]
785    fn test_count_bits() {
786        assert_eq!(0, Buffer::from(&[0b00000000]).count_set_bits_offset(0, 8));
787        assert_eq!(8, Buffer::from(&[0b11111111]).count_set_bits_offset(0, 8));
788        assert_eq!(3, Buffer::from(&[0b00001101]).count_set_bits_offset(0, 8));
789        assert_eq!(
790            6,
791            Buffer::from(&[0b01001001, 0b01010010]).count_set_bits_offset(0, 16)
792        );
793        assert_eq!(
794            16,
795            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(0, 16)
796        );
797    }
798
799    #[test]
800    fn test_count_bits_slice() {
801        assert_eq!(
802            0,
803            Buffer::from(&[0b11111111, 0b00000000])
804                .slice(1)
805                .count_set_bits_offset(0, 8)
806        );
807        assert_eq!(
808            8,
809            Buffer::from(&[0b11111111, 0b11111111])
810                .slice_with_length(1, 1)
811                .count_set_bits_offset(0, 8)
812        );
813        assert_eq!(
814            3,
815            Buffer::from(&[0b11111111, 0b11111111, 0b00001101])
816                .slice(2)
817                .count_set_bits_offset(0, 8)
818        );
819        assert_eq!(
820            6,
821            Buffer::from(&[0b11111111, 0b01001001, 0b01010010])
822                .slice_with_length(1, 2)
823                .count_set_bits_offset(0, 16)
824        );
825        assert_eq!(
826            16,
827            Buffer::from(&[0b11111111, 0b11111111, 0b11111111, 0b11111111])
828                .slice(2)
829                .count_set_bits_offset(0, 16)
830        );
831    }
832
833    #[test]
834    fn test_count_bits_offset_slice() {
835        assert_eq!(8, Buffer::from(&[0b11111111]).count_set_bits_offset(0, 8));
836        assert_eq!(3, Buffer::from(&[0b11111111]).count_set_bits_offset(0, 3));
837        assert_eq!(5, Buffer::from(&[0b11111111]).count_set_bits_offset(3, 5));
838        assert_eq!(1, Buffer::from(&[0b11111111]).count_set_bits_offset(3, 1));
839        assert_eq!(0, Buffer::from(&[0b11111111]).count_set_bits_offset(8, 0));
840        assert_eq!(2, Buffer::from(&[0b01010101]).count_set_bits_offset(0, 3));
841        assert_eq!(
842            16,
843            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(0, 16)
844        );
845        assert_eq!(
846            10,
847            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(0, 10)
848        );
849        assert_eq!(
850            10,
851            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(3, 10)
852        );
853        assert_eq!(
854            8,
855            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(8, 8)
856        );
857        assert_eq!(
858            5,
859            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(11, 5)
860        );
861        assert_eq!(
862            0,
863            Buffer::from(&[0b11111111, 0b11111111]).count_set_bits_offset(16, 0)
864        );
865        assert_eq!(
866            2,
867            Buffer::from(&[0b01101101, 0b10101010]).count_set_bits_offset(7, 5)
868        );
869        assert_eq!(
870            4,
871            Buffer::from(&[0b01101101, 0b10101010]).count_set_bits_offset(7, 9)
872        );
873    }
874
875    #[test]
876    fn test_unwind_safe() {
877        fn assert_unwind_safe<T: RefUnwindSafe + UnwindSafe>() {}
878        assert_unwind_safe::<Buffer>()
879    }
880
881    #[test]
882    fn test_from_foreign_vec() {
883        let mut vector = vec![1_i32, 2, 3, 4, 5];
884        let buffer = unsafe {
885            Buffer::from_custom_allocation(
886                NonNull::new_unchecked(vector.as_mut_ptr() as *mut u8),
887                vector.len() * std::mem::size_of::<i32>(),
888                Arc::new(vector),
889            )
890        };
891
892        let slice = buffer.typed_data::<i32>();
893        assert_eq!(slice, &[1, 2, 3, 4, 5]);
894
895        let buffer = buffer.slice(std::mem::size_of::<i32>());
896
897        let slice = buffer.typed_data::<i32>();
898        assert_eq!(slice, &[2, 3, 4, 5]);
899    }
900
901    #[test]
902    #[should_panic(expected = "the offset of the new Buffer cannot exceed the existing length")]
903    fn slice_overflow() {
904        let buffer = Buffer::from(MutableBuffer::from_len_zeroed(12));
905        buffer.slice_with_length(2, usize::MAX);
906    }
907
908    #[test]
909    fn test_vec_interop() {
910        // Test empty vec
911        let a: Vec<i128> = Vec::new();
912        let b = Buffer::from_vec(a);
913        b.into_vec::<i128>().unwrap();
914
915        // Test vec with capacity
916        let a: Vec<i128> = Vec::with_capacity(20);
917        let b = Buffer::from_vec(a);
918        let back = b.into_vec::<i128>().unwrap();
919        assert_eq!(back.len(), 0);
920        assert_eq!(back.capacity(), 20);
921
922        // Test vec with values
923        let mut a: Vec<i128> = Vec::with_capacity(3);
924        a.extend_from_slice(&[1, 2, 3]);
925        let b = Buffer::from_vec(a);
926        let back = b.into_vec::<i128>().unwrap();
927        assert_eq!(back.len(), 3);
928        assert_eq!(back.capacity(), 3);
929
930        // Test vec with values and spare capacity
931        let mut a: Vec<i128> = Vec::with_capacity(20);
932        a.extend_from_slice(&[1, 4, 7, 8, 9, 3, 6]);
933        let b = Buffer::from_vec(a);
934        let back = b.into_vec::<i128>().unwrap();
935        assert_eq!(back.len(), 7);
936        assert_eq!(back.capacity(), 20);
937
938        // Test incorrect alignment
939        let a: Vec<i128> = Vec::new();
940        let b = Buffer::from_vec(a);
941        let b = b.into_vec::<i32>().unwrap_err();
942        b.into_vec::<i8>().unwrap_err();
943
944        // Test convert between types with same alignment
945        // This is an implementation quirk, but isn't harmful
946        // as ArrowNativeType are trivially transmutable
947        let a: Vec<i64> = vec![1, 2, 3, 4];
948        let b = Buffer::from_vec(a);
949        let back = b.into_vec::<u64>().unwrap();
950        assert_eq!(back.len(), 4);
951        assert_eq!(back.capacity(), 4);
952
953        // i256 has the same layout as i128 so this is valid
954        let mut b: Vec<i128> = Vec::with_capacity(4);
955        b.extend_from_slice(&[1, 2, 3, 4]);
956        let b = Buffer::from_vec(b);
957        let back = b.into_vec::<i256>().unwrap();
958        assert_eq!(back.len(), 2);
959        assert_eq!(back.capacity(), 2);
960
961        // Invalid layout
962        let b: Vec<i128> = vec![1, 2, 3];
963        let b = Buffer::from_vec(b);
964        b.into_vec::<i256>().unwrap_err();
965
966        // Invalid layout
967        let mut b: Vec<i128> = Vec::with_capacity(5);
968        b.extend_from_slice(&[1, 2, 3, 4]);
969        let b = Buffer::from_vec(b);
970        b.into_vec::<i256>().unwrap_err();
971
972        // Truncates length
973        // This is an implementation quirk, but isn't harmful
974        let mut b: Vec<i128> = Vec::with_capacity(4);
975        b.extend_from_slice(&[1, 2, 3]);
976        let b = Buffer::from_vec(b);
977        let back = b.into_vec::<i256>().unwrap();
978        assert_eq!(back.len(), 1);
979        assert_eq!(back.capacity(), 2);
980
981        // Cannot use aligned allocation
982        let b = Buffer::from(MutableBuffer::new(10));
983        let b = b.into_vec::<u8>().unwrap_err();
984        b.into_vec::<u64>().unwrap_err();
985
986        // Test slicing
987        let mut a: Vec<i128> = Vec::with_capacity(20);
988        a.extend_from_slice(&[1, 4, 7, 8, 9, 3, 6]);
989        let b = Buffer::from_vec(a);
990        let slice = b.slice_with_length(0, 64);
991
992        // Shared reference fails
993        let slice = slice.into_vec::<i128>().unwrap_err();
994        drop(b);
995
996        // Succeeds as no outstanding shared reference
997        let back = slice.into_vec::<i128>().unwrap();
998        assert_eq!(&back, &[1, 4, 7, 8]);
999        assert_eq!(back.capacity(), 20);
1000
1001        // Slicing by non-multiple length truncates
1002        let mut a: Vec<i128> = Vec::with_capacity(8);
1003        a.extend_from_slice(&[1, 4, 7, 3]);
1004
1005        let b = Buffer::from_vec(a);
1006        let slice = b.slice_with_length(0, 34);
1007        drop(b);
1008
1009        let back = slice.into_vec::<i128>().unwrap();
1010        assert_eq!(&back, &[1, 4]);
1011        assert_eq!(back.capacity(), 8);
1012
1013        // Offset prevents conversion
1014        let a: Vec<u32> = vec![1, 3, 4, 6];
1015        let b = Buffer::from_vec(a).slice(2);
1016        b.into_vec::<u32>().unwrap_err();
1017
1018        let b = MutableBuffer::new(16).into_buffer();
1019        let b = b.into_vec::<u8>().unwrap_err(); // Invalid layout
1020        let b = b.into_vec::<u32>().unwrap_err(); // Invalid layout
1021        b.into_mutable().unwrap();
1022
1023        let b = Buffer::from_vec(vec![1_u32, 3, 5]);
1024        let b = b.into_mutable().unwrap();
1025        let b = Buffer::from(b);
1026        let b = b.into_vec::<u32>().unwrap();
1027        assert_eq!(b, &[1, 3, 5]);
1028    }
1029
1030    #[test]
1031    #[should_panic(expected = "capacity overflow")]
1032    fn test_from_iter_overflow() {
1033        let iter_len = usize::MAX / std::mem::size_of::<u64>() + 1;
1034        let _ = Buffer::from_iter(std::iter::repeat_n(0_u64, iter_len));
1035    }
1036
1037    #[test]
1038    fn bit_slice_length_preserved() {
1039        // Create a boring buffer
1040        let buf = Buffer::from_iter(std::iter::repeat_n(true, 64));
1041
1042        let assert_preserved = |offset: usize, len: usize| {
1043            let new_buf = buf.bit_slice(offset, len);
1044            assert_eq!(new_buf.len(), bit_util::ceil(len, 8));
1045
1046            // if the offset is not byte-aligned, we have to create a deep copy to a new buffer
1047            // (since the `offset` value inside a Buffer is byte-granular, not bit-granular), so
1048            // checking the offset should always return 0 if so. If the offset IS byte-aligned, we
1049            // want to make sure it doesn't unnecessarily create a deep copy.
1050            if offset % 8 == 0 {
1051                assert_eq!(new_buf.ptr_offset(), offset / 8);
1052            } else {
1053                assert_eq!(new_buf.ptr_offset(), 0);
1054            }
1055        };
1056
1057        // go through every available value for offset
1058        for o in 0..=64 {
1059            // and go through every length that could accompany that offset - we can't have a
1060            // situation where offset + len > 64, because that would go past the end of the buffer,
1061            // so we use the map to ensure it's in range.
1062            for l in (o..=64).map(|l| l - o) {
1063                // and we just want to make sure every one of these keeps its offset and length
1064                // when neeeded
1065                assert_preserved(o, l);
1066            }
1067        }
1068    }
1069
1070    #[test]
1071    fn test_strong_count() {
1072        let buffer = Buffer::from_iter(std::iter::repeat_n(0_u8, 100));
1073        assert_eq!(buffer.strong_count(), 1);
1074
1075        let buffer2 = buffer.clone();
1076        assert_eq!(buffer.strong_count(), 2);
1077
1078        let buffer3 = buffer2.clone();
1079        assert_eq!(buffer.strong_count(), 3);
1080
1081        drop(buffer);
1082        assert_eq!(buffer2.strong_count(), 2);
1083        assert_eq!(buffer3.strong_count(), 2);
1084
1085        // Strong count does not increase on move
1086        let capture = move || {
1087            assert_eq!(buffer3.strong_count(), 2);
1088        };
1089
1090        capture();
1091        assert_eq!(buffer2.strong_count(), 2);
1092
1093        drop(capture);
1094        assert_eq!(buffer2.strong_count(), 1);
1095    }
1096
1097    #[test]
1098    fn into_mutable_should_return_error_for_sliced_owned_buffer_when_ptr_offset_is_not_0() {
1099        let original_buffer_data = [1_u8, 2, 3, 4, 5, 6, 7, 8];
1100        for (slice_from, slice_length) in [
1101            (original_buffer_data.len(), 0),
1102            (2, 4),
1103            (2, original_buffer_data.len() - 2),
1104        ] {
1105            let buffer = Buffer::from(original_buffer_data);
1106            let sliced = buffer.slice_with_length(slice_from, slice_length);
1107            drop(buffer); // Keep only 1 owner
1108            assert_ne!(sliced.ptr_offset(), 0);
1109
1110            sliced
1111                .into_mutable()
1112                .expect_err("should not convert sliced buffer when ptr_offset is not 0");
1113        }
1114    }
1115
1116    #[test]
1117    fn into_mutable_should_allow_converting_sliced_owned_buffer_when_ptr_offset_is_0() {
1118        let original_buffer_data = [1_u8, 2, 3, 4, 5, 6, 7, 8];
1119        for slice_length in [0, original_buffer_data.len() - 2] {
1120            let buffer = Buffer::from(original_buffer_data);
1121            let sliced = buffer.slice_with_length(0, slice_length);
1122            drop(buffer); // Keep only 1 owner
1123            assert_eq!(sliced.ptr_offset(), 0);
1124
1125            let original_ptr = sliced.data_ptr();
1126
1127            let mutable = sliced
1128                        .into_mutable()
1129                        .unwrap_or_else(|_| panic!("should allow converting to mutable when not sliced from end when slice_length is {slice_length}"));
1130
1131            let buffer_back: Buffer = mutable.into();
1132            assert_eq!(buffer_back.data_ptr(), original_ptr);
1133
1134            let expected = Buffer::from(original_buffer_data).slice_with_length(0, slice_length);
1135            assert_eq!(buffer_back.as_slice(), expected.as_slice());
1136        }
1137    }
1138}