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