arrow_array/array/
fixed_size_binary_array.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 crate::array::print_long_array;
19use crate::iterator::FixedSizeBinaryIter;
20use crate::{Array, ArrayAccessor, ArrayRef, FixedSizeListArray, Scalar};
21use arrow_buffer::buffer::NullBuffer;
22use arrow_buffer::{ArrowNativeType, BooleanBuffer, Buffer, MutableBuffer, bit_util};
23use arrow_data::{ArrayData, ArrayDataBuilder};
24use arrow_schema::{ArrowError, DataType};
25use std::any::Any;
26use std::sync::Arc;
27
28/// An array of [fixed size binary arrays](https://arrow.apache.org/docs/format/Columnar.html#fixed-size-primitive-layout)
29///
30/// # Examples
31///
32/// Create an array from an iterable argument of byte slices.
33///
34/// ```
35///    use arrow_array::{Array, FixedSizeBinaryArray};
36///    let input_arg = vec![ vec![1, 2], vec![3, 4], vec![5, 6] ];
37///    let arr = FixedSizeBinaryArray::try_from_iter(input_arg.into_iter()).unwrap();
38///
39///    assert_eq!(3, arr.len());
40///
41/// ```
42/// Create an array from an iterable argument of sparse byte slices.
43/// Sparsity means that the input argument can contain `None` items.
44/// ```
45///    use arrow_array::{Array, FixedSizeBinaryArray};
46///    let input_arg = vec![ None, Some(vec![7, 8]), Some(vec![9, 10]), None, Some(vec![13, 14]) ];
47///    let arr = FixedSizeBinaryArray::try_from_sparse_iter_with_size(input_arg.into_iter(), 2).unwrap();
48///    assert_eq!(5, arr.len())
49///
50/// ```
51///
52#[derive(Clone)]
53pub struct FixedSizeBinaryArray {
54    data_type: DataType, // Must be DataType::FixedSizeBinary(value_length)
55    value_data: Buffer,
56    nulls: Option<NullBuffer>,
57    len: usize,
58    value_length: i32,
59}
60
61impl FixedSizeBinaryArray {
62    /// Create a new [`FixedSizeBinaryArray`] with `size` element size, panicking on failure
63    ///
64    /// # Panics
65    ///
66    /// Panics if [`Self::try_new`] returns an error
67    pub fn new(size: i32, values: Buffer, nulls: Option<NullBuffer>) -> Self {
68        Self::try_new(size, values, nulls).unwrap()
69    }
70
71    /// Create a new [`Scalar`] from `value`
72    pub fn new_scalar(value: impl AsRef<[u8]>) -> Scalar<Self> {
73        let v = value.as_ref();
74        Scalar::new(Self::new(v.len() as _, Buffer::from(v), None))
75    }
76
77    /// Create a new [`FixedSizeBinaryArray`] from the provided parts, returning an error on failure
78    ///
79    /// Creating an arrow with `size == 0` will try to get the length from the null buffer. If
80    /// no null buffer is provided, the resulting array will have length zero.
81    ///
82    /// # Errors
83    ///
84    /// * `size < 0`
85    /// * `values.len() / size != nulls.len()`
86    /// * `size == 0 && values.len() != 0`
87    pub fn try_new(
88        size: i32,
89        values: Buffer,
90        nulls: Option<NullBuffer>,
91    ) -> Result<Self, ArrowError> {
92        let data_type = DataType::FixedSizeBinary(size);
93        let s = size.to_usize().ok_or_else(|| {
94            ArrowError::InvalidArgumentError(format!("Size cannot be negative, got {size}"))
95        })?;
96
97        let len = if s == 0 {
98            if !values.is_empty() {
99                return Err(ArrowError::InvalidArgumentError(
100                    "Buffer cannot have non-zero length if the item size is zero".to_owned(),
101                ));
102            }
103
104            // If the item size is zero, try to determine the length from the null buffer
105            nulls.as_ref().map(|n| n.len()).unwrap_or(0)
106        } else {
107            values.len() / s
108        };
109        if let Some(n) = nulls.as_ref() {
110            if n.len() != len {
111                return Err(ArrowError::InvalidArgumentError(format!(
112                    "Incorrect length of null buffer for FixedSizeBinaryArray, expected {} got {}",
113                    len,
114                    n.len(),
115                )));
116            }
117        }
118
119        Ok(Self {
120            data_type,
121            value_data: values,
122            value_length: size,
123            nulls,
124            len,
125        })
126    }
127
128    /// Create a new [`FixedSizeBinaryArray`] of length `len` where all values are null
129    ///
130    /// # Panics
131    ///
132    /// Panics if
133    ///
134    /// * `size < 0`
135    /// * `size * len` would overflow `usize`
136    pub fn new_null(size: i32, len: usize) -> Self {
137        const BITS_IN_A_BYTE: usize = 8;
138        let capacity_in_bytes = size.to_usize().unwrap().checked_mul(len).unwrap();
139        Self {
140            data_type: DataType::FixedSizeBinary(size),
141            value_data: MutableBuffer::new_null(capacity_in_bytes * BITS_IN_A_BYTE).into(),
142            nulls: Some(NullBuffer::new_null(len)),
143            value_length: size,
144            len,
145        }
146    }
147
148    /// Deconstruct this array into its constituent parts
149    pub fn into_parts(self) -> (i32, Buffer, Option<NullBuffer>) {
150        (self.value_length, self.value_data, self.nulls)
151    }
152
153    /// Returns the element at index `i` as a byte slice.
154    ///
155    /// Note: This method does not check for nulls and the value is arbitrary
156    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
157    ///
158    /// # Panics
159    /// Panics if index `i` is out of bounds.
160    pub fn value(&self, i: usize) -> &[u8] {
161        assert!(
162            i < self.len(),
163            "Trying to access an element at index {} from a FixedSizeBinaryArray of length {}",
164            i,
165            self.len()
166        );
167        let offset = i + self.offset();
168        unsafe {
169            let pos = self.value_offset_at(offset);
170            std::slice::from_raw_parts(
171                self.value_data.as_ptr().offset(pos as isize),
172                (self.value_offset_at(offset + 1) - pos) as usize,
173            )
174        }
175    }
176
177    /// Returns the element at index `i` as a byte slice.
178    ///
179    /// Note: This method does not check for nulls and the value is arbitrary
180    /// if [`is_null`](Self::is_null) returns true for the index.
181    ///
182    /// # Safety
183    ///
184    /// Caller is responsible for ensuring that the index is within the bounds
185    /// of the array
186    pub unsafe fn value_unchecked(&self, i: usize) -> &[u8] {
187        let offset = i + self.offset();
188        let pos = self.value_offset_at(offset);
189        unsafe {
190            std::slice::from_raw_parts(
191                self.value_data.as_ptr().offset(pos as isize),
192                (self.value_offset_at(offset + 1) - pos) as usize,
193            )
194        }
195    }
196
197    /// Returns the offset for the element at index `i`.
198    ///
199    /// Note this doesn't do any bound checking, for performance reason.
200    #[inline]
201    pub fn value_offset(&self, i: usize) -> i32 {
202        self.value_offset_at(self.offset() + i)
203    }
204
205    /// Returns the length for an element.
206    ///
207    /// All elements have the same length as the array is a fixed size.
208    #[inline]
209    pub fn value_length(&self) -> i32 {
210        self.value_length
211    }
212
213    /// Returns the values of this array.
214    ///
215    /// Unlike [`Self::value_data`] this returns the [`Buffer`]
216    /// allowing for zero-copy cloning.
217    #[inline]
218    pub fn values(&self) -> &Buffer {
219        &self.value_data
220    }
221
222    /// Returns the raw value data.
223    pub fn value_data(&self) -> &[u8] {
224        self.value_data.as_slice()
225    }
226
227    /// Returns a zero-copy slice of this array with the indicated offset and length.
228    pub fn slice(&self, offset: usize, len: usize) -> Self {
229        assert!(
230            offset.saturating_add(len) <= self.len,
231            "the length + offset of the sliced FixedSizeBinaryArray cannot exceed the existing length"
232        );
233
234        let size = self.value_length as usize;
235
236        Self {
237            data_type: self.data_type.clone(),
238            nulls: self.nulls.as_ref().map(|n| n.slice(offset, len)),
239            value_length: self.value_length,
240            value_data: self.value_data.slice_with_length(offset * size, len * size),
241            len,
242        }
243    }
244
245    /// Create an array from an iterable argument of sparse byte slices.
246    /// Sparsity means that items returned by the iterator are optional, i.e input argument can
247    /// contain `None` items.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// use arrow_array::FixedSizeBinaryArray;
253    /// let input_arg = vec![
254    ///     None,
255    ///     Some(vec![7, 8]),
256    ///     Some(vec![9, 10]),
257    ///     None,
258    ///     Some(vec![13, 14]),
259    ///     None,
260    /// ];
261    /// let array = FixedSizeBinaryArray::try_from_sparse_iter(input_arg.into_iter()).unwrap();
262    /// ```
263    ///
264    /// # Errors
265    ///
266    /// Returns error if argument has length zero, or sizes of nested slices don't match.
267    #[deprecated(
268        since = "28.0.0",
269        note = "This function will fail if the iterator produces only None values; prefer `try_from_sparse_iter_with_size`"
270    )]
271    pub fn try_from_sparse_iter<T, U>(mut iter: T) -> Result<Self, ArrowError>
272    where
273        T: Iterator<Item = Option<U>>,
274        U: AsRef<[u8]>,
275    {
276        let mut len = 0;
277        let mut size = None;
278        let mut byte = 0;
279
280        let iter_size_hint = iter.size_hint().0;
281        let mut null_buf = MutableBuffer::new(bit_util::ceil(iter_size_hint, 8));
282        let mut buffer = MutableBuffer::new(0);
283
284        let mut prepend = 0;
285        iter.try_for_each(|item| -> Result<(), ArrowError> {
286            // extend null bitmask by one byte per each 8 items
287            if byte == 0 {
288                null_buf.push(0u8);
289                byte = 8;
290            }
291            byte -= 1;
292
293            if let Some(slice) = item {
294                let slice = slice.as_ref();
295                if let Some(size) = size {
296                    if size != slice.len() {
297                        return Err(ArrowError::InvalidArgumentError(format!(
298                            "Nested array size mismatch: one is {}, and the other is {}",
299                            size,
300                            slice.len()
301                        )));
302                    }
303                } else {
304                    let len = slice.len();
305                    size = Some(len);
306                    // Now that we know how large each element is we can reserve
307                    // sufficient capacity in the underlying mutable buffer for
308                    // the data.
309                    buffer.reserve(iter_size_hint * len);
310                    buffer.extend_zeros(slice.len() * prepend);
311                }
312                bit_util::set_bit(null_buf.as_slice_mut(), len);
313                buffer.extend_from_slice(slice);
314            } else if let Some(size) = size {
315                buffer.extend_zeros(size);
316            } else {
317                prepend += 1;
318            }
319
320            len += 1;
321
322            Ok(())
323        })?;
324
325        if len == 0 {
326            return Err(ArrowError::InvalidArgumentError(
327                "Input iterable argument has no data".to_owned(),
328            ));
329        }
330
331        let null_buf = BooleanBuffer::new(null_buf.into(), 0, len);
332        let nulls = Some(NullBuffer::new(null_buf)).filter(|n| n.null_count() > 0);
333
334        let size = size.unwrap_or(0) as i32;
335        Ok(Self {
336            data_type: DataType::FixedSizeBinary(size),
337            value_data: buffer.into(),
338            nulls,
339            value_length: size,
340            len,
341        })
342    }
343
344    /// Create an array from an iterable argument of sparse byte slices.
345    /// Sparsity means that items returned by the iterator are optional, i.e input argument can
346    /// contain `None` items. In cases where the iterator returns only `None` values, this
347    /// also takes a size parameter to ensure that the a valid FixedSizeBinaryArray is still
348    /// created.
349    ///
350    /// # Examples
351    ///
352    /// ```
353    /// use arrow_array::FixedSizeBinaryArray;
354    /// let input_arg = vec![
355    ///     None,
356    ///     Some(vec![7, 8]),
357    ///     Some(vec![9, 10]),
358    ///     None,
359    ///     Some(vec![13, 14]),
360    ///     None,
361    /// ];
362    /// let array = FixedSizeBinaryArray::try_from_sparse_iter_with_size(input_arg.into_iter(), 2).unwrap();
363    /// ```
364    ///
365    /// # Errors
366    ///
367    /// Returns error if argument has length zero, or sizes of nested slices don't match.
368    pub fn try_from_sparse_iter_with_size<T, U>(mut iter: T, size: i32) -> Result<Self, ArrowError>
369    where
370        T: Iterator<Item = Option<U>>,
371        U: AsRef<[u8]>,
372    {
373        let mut len = 0;
374        let mut byte = 0;
375
376        let iter_size_hint = iter.size_hint().0;
377        let mut null_buf = MutableBuffer::new(bit_util::ceil(iter_size_hint, 8));
378        let mut buffer = MutableBuffer::new(iter_size_hint * (size as usize));
379
380        iter.try_for_each(|item| -> Result<(), ArrowError> {
381            // extend null bitmask by one byte per each 8 items
382            if byte == 0 {
383                null_buf.push(0u8);
384                byte = 8;
385            }
386            byte -= 1;
387
388            if let Some(slice) = item {
389                let slice = slice.as_ref();
390                if size as usize != slice.len() {
391                    return Err(ArrowError::InvalidArgumentError(format!(
392                        "Nested array size mismatch: one is {}, and the other is {}",
393                        size,
394                        slice.len()
395                    )));
396                }
397
398                bit_util::set_bit(null_buf.as_slice_mut(), len);
399                buffer.extend_from_slice(slice);
400            } else {
401                buffer.extend_zeros(size as usize);
402            }
403
404            len += 1;
405
406            Ok(())
407        })?;
408
409        let null_buf = BooleanBuffer::new(null_buf.into(), 0, len);
410        let nulls = Some(NullBuffer::new(null_buf)).filter(|n| n.null_count() > 0);
411
412        Ok(Self {
413            data_type: DataType::FixedSizeBinary(size),
414            value_data: buffer.into(),
415            nulls,
416            len,
417            value_length: size,
418        })
419    }
420
421    /// Create an array from an iterable argument of byte slices.
422    ///
423    /// # Examples
424    ///
425    /// ```
426    /// use arrow_array::FixedSizeBinaryArray;
427    /// let input_arg = vec![
428    ///     vec![1, 2],
429    ///     vec![3, 4],
430    ///     vec![5, 6],
431    /// ];
432    /// let array = FixedSizeBinaryArray::try_from_iter(input_arg.into_iter()).unwrap();
433    /// ```
434    ///
435    /// # Errors
436    ///
437    /// Returns error if argument has length zero, or sizes of nested slices don't match.
438    pub fn try_from_iter<T, U>(mut iter: T) -> Result<Self, ArrowError>
439    where
440        T: Iterator<Item = U>,
441        U: AsRef<[u8]>,
442    {
443        let mut len = 0;
444        let mut size = None;
445        let iter_size_hint = iter.size_hint().0;
446        let mut buffer = MutableBuffer::new(0);
447
448        iter.try_for_each(|item| -> Result<(), ArrowError> {
449            let slice = item.as_ref();
450            if let Some(size) = size {
451                if size != slice.len() {
452                    return Err(ArrowError::InvalidArgumentError(format!(
453                        "Nested array size mismatch: one is {}, and the other is {}",
454                        size,
455                        slice.len()
456                    )));
457                }
458            } else {
459                let len = slice.len();
460                size = Some(len);
461                buffer.reserve(iter_size_hint * len);
462            }
463
464            buffer.extend_from_slice(slice);
465
466            len += 1;
467
468            Ok(())
469        })?;
470
471        if len == 0 {
472            return Err(ArrowError::InvalidArgumentError(
473                "Input iterable argument has no data".to_owned(),
474            ));
475        }
476
477        let size = size.unwrap_or(0).try_into().unwrap();
478        Ok(Self {
479            data_type: DataType::FixedSizeBinary(size),
480            value_data: buffer.into(),
481            nulls: None,
482            value_length: size,
483            len,
484        })
485    }
486
487    #[inline]
488    fn value_offset_at(&self, i: usize) -> i32 {
489        self.value_length * i as i32
490    }
491
492    /// constructs a new iterator
493    pub fn iter(&self) -> FixedSizeBinaryIter<'_> {
494        FixedSizeBinaryIter::new(self)
495    }
496}
497
498impl From<ArrayData> for FixedSizeBinaryArray {
499    fn from(data: ArrayData) -> Self {
500        assert_eq!(
501            data.buffers().len(),
502            1,
503            "FixedSizeBinaryArray data should contain 1 buffer only (values)"
504        );
505        let value_length = match data.data_type() {
506            DataType::FixedSizeBinary(len) => *len,
507            _ => panic!("Expected data type to be FixedSizeBinary"),
508        };
509
510        let size = value_length as usize;
511        let value_data =
512            data.buffers()[0].slice_with_length(data.offset() * size, data.len() * size);
513
514        Self {
515            data_type: data.data_type().clone(),
516            nulls: data.nulls().cloned(),
517            len: data.len(),
518            value_data,
519            value_length,
520        }
521    }
522}
523
524impl From<FixedSizeBinaryArray> for ArrayData {
525    fn from(array: FixedSizeBinaryArray) -> Self {
526        let builder = ArrayDataBuilder::new(array.data_type)
527            .len(array.len)
528            .buffers(vec![array.value_data])
529            .nulls(array.nulls);
530
531        unsafe { builder.build_unchecked() }
532    }
533}
534
535/// Creates a `FixedSizeBinaryArray` from `FixedSizeList<u8>` array
536impl From<FixedSizeListArray> for FixedSizeBinaryArray {
537    fn from(v: FixedSizeListArray) -> Self {
538        let value_len = v.value_length();
539        let v = v.into_data();
540        assert_eq!(
541            v.child_data().len(),
542            1,
543            "FixedSizeBinaryArray can only be created from list array of u8 values \
544             (i.e. FixedSizeList<PrimitiveArray<u8>>)."
545        );
546        let child_data = &v.child_data()[0];
547
548        assert_eq!(
549            child_data.child_data().len(),
550            0,
551            "FixedSizeBinaryArray can only be created from list array of u8 values \
552             (i.e. FixedSizeList<PrimitiveArray<u8>>)."
553        );
554        assert_eq!(
555            child_data.data_type(),
556            &DataType::UInt8,
557            "FixedSizeBinaryArray can only be created from FixedSizeList<u8> arrays, mismatched data types."
558        );
559        assert_eq!(
560            child_data.null_count(),
561            0,
562            "The child array cannot contain null values."
563        );
564
565        let builder = ArrayData::builder(DataType::FixedSizeBinary(value_len))
566            .len(v.len())
567            .offset(v.offset())
568            .add_buffer(child_data.buffers()[0].slice(child_data.offset()))
569            .nulls(v.nulls().cloned());
570
571        let data = unsafe { builder.build_unchecked() };
572        Self::from(data)
573    }
574}
575
576impl From<Vec<Option<&[u8]>>> for FixedSizeBinaryArray {
577    fn from(v: Vec<Option<&[u8]>>) -> Self {
578        #[allow(deprecated)]
579        Self::try_from_sparse_iter(v.into_iter()).unwrap()
580    }
581}
582
583impl From<Vec<&[u8]>> for FixedSizeBinaryArray {
584    fn from(v: Vec<&[u8]>) -> Self {
585        Self::try_from_iter(v.into_iter()).unwrap()
586    }
587}
588
589impl<const N: usize> From<Vec<&[u8; N]>> for FixedSizeBinaryArray {
590    fn from(v: Vec<&[u8; N]>) -> Self {
591        Self::try_from_iter(v.into_iter()).unwrap()
592    }
593}
594
595impl std::fmt::Debug for FixedSizeBinaryArray {
596    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
597        write!(f, "FixedSizeBinaryArray<{}>\n[\n", self.value_length())?;
598        print_long_array(self, f, |array, index, f| {
599            std::fmt::Debug::fmt(&array.value(index), f)
600        })?;
601        write!(f, "]")
602    }
603}
604
605impl Array for FixedSizeBinaryArray {
606    fn as_any(&self) -> &dyn Any {
607        self
608    }
609
610    fn to_data(&self) -> ArrayData {
611        self.clone().into()
612    }
613
614    fn into_data(self) -> ArrayData {
615        self.into()
616    }
617
618    fn data_type(&self) -> &DataType {
619        &self.data_type
620    }
621
622    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
623        Arc::new(self.slice(offset, length))
624    }
625
626    fn len(&self) -> usize {
627        self.len
628    }
629
630    fn is_empty(&self) -> bool {
631        self.len == 0
632    }
633
634    fn shrink_to_fit(&mut self) {
635        self.value_data.shrink_to_fit();
636        if let Some(nulls) = &mut self.nulls {
637            nulls.shrink_to_fit();
638        }
639    }
640
641    fn offset(&self) -> usize {
642        0
643    }
644
645    fn nulls(&self) -> Option<&NullBuffer> {
646        self.nulls.as_ref()
647    }
648
649    fn logical_null_count(&self) -> usize {
650        // More efficient that the default implementation
651        self.null_count()
652    }
653
654    fn get_buffer_memory_size(&self) -> usize {
655        let mut sum = self.value_data.capacity();
656        if let Some(n) = &self.nulls {
657            sum += n.buffer().capacity();
658        }
659        sum
660    }
661
662    fn get_array_memory_size(&self) -> usize {
663        std::mem::size_of::<Self>() + self.get_buffer_memory_size()
664    }
665}
666
667impl<'a> ArrayAccessor for &'a FixedSizeBinaryArray {
668    type Item = &'a [u8];
669
670    fn value(&self, index: usize) -> Self::Item {
671        FixedSizeBinaryArray::value(self, index)
672    }
673
674    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
675        unsafe { FixedSizeBinaryArray::value_unchecked(self, index) }
676    }
677}
678
679impl<'a> IntoIterator for &'a FixedSizeBinaryArray {
680    type Item = Option<&'a [u8]>;
681    type IntoIter = FixedSizeBinaryIter<'a>;
682
683    fn into_iter(self) -> Self::IntoIter {
684        FixedSizeBinaryIter::<'a>::new(self)
685    }
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691    use crate::RecordBatch;
692    use arrow_schema::{Field, Schema};
693
694    #[test]
695    fn test_fixed_size_binary_array() {
696        let values: [u8; 15] = *b"hellotherearrow";
697
698        let array_data = ArrayData::builder(DataType::FixedSizeBinary(5))
699            .len(3)
700            .add_buffer(Buffer::from(&values))
701            .build()
702            .unwrap();
703        let fixed_size_binary_array = FixedSizeBinaryArray::from(array_data);
704        assert_eq!(3, fixed_size_binary_array.len());
705        assert_eq!(0, fixed_size_binary_array.null_count());
706        assert_eq!(
707            [b'h', b'e', b'l', b'l', b'o'],
708            fixed_size_binary_array.value(0)
709        );
710        assert_eq!(
711            [b't', b'h', b'e', b'r', b'e'],
712            fixed_size_binary_array.value(1)
713        );
714        assert_eq!(
715            [b'a', b'r', b'r', b'o', b'w'],
716            fixed_size_binary_array.value(2)
717        );
718        assert_eq!(5, fixed_size_binary_array.value_length());
719        assert_eq!(10, fixed_size_binary_array.value_offset(2));
720        for i in 0..3 {
721            assert!(fixed_size_binary_array.is_valid(i));
722            assert!(!fixed_size_binary_array.is_null(i));
723        }
724
725        // Test binary array with offset
726        let array_data = ArrayData::builder(DataType::FixedSizeBinary(5))
727            .len(2)
728            .offset(1)
729            .add_buffer(Buffer::from(&values))
730            .build()
731            .unwrap();
732        let fixed_size_binary_array = FixedSizeBinaryArray::from(array_data);
733        assert_eq!(
734            [b't', b'h', b'e', b'r', b'e'],
735            fixed_size_binary_array.value(0)
736        );
737        assert_eq!(
738            [b'a', b'r', b'r', b'o', b'w'],
739            fixed_size_binary_array.value(1)
740        );
741        assert_eq!(2, fixed_size_binary_array.len());
742        assert_eq!(0, fixed_size_binary_array.value_offset(0));
743        assert_eq!(5, fixed_size_binary_array.value_length());
744        assert_eq!(5, fixed_size_binary_array.value_offset(1));
745    }
746
747    #[test]
748    fn test_fixed_size_binary_array_from_fixed_size_list_array() {
749        let values = [0_u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
750        let values_data = ArrayData::builder(DataType::UInt8)
751            .len(12)
752            .offset(2)
753            .add_buffer(Buffer::from_slice_ref(values))
754            .build()
755            .unwrap();
756        // [null, [10, 11, 12, 13]]
757        let array_data = unsafe {
758            ArrayData::builder(DataType::FixedSizeList(
759                Arc::new(Field::new_list_field(DataType::UInt8, false)),
760                4,
761            ))
762            .len(2)
763            .offset(1)
764            .add_child_data(values_data)
765            .null_bit_buffer(Some(Buffer::from_slice_ref([0b101])))
766            .build_unchecked()
767        };
768        let list_array = FixedSizeListArray::from(array_data);
769        let binary_array = FixedSizeBinaryArray::from(list_array);
770
771        assert_eq!(2, binary_array.len());
772        assert_eq!(1, binary_array.null_count());
773        assert!(binary_array.is_null(0));
774        assert!(binary_array.is_valid(1));
775        assert_eq!(&[10, 11, 12, 13], binary_array.value(1));
776    }
777
778    #[test]
779    #[should_panic(
780        expected = "FixedSizeBinaryArray can only be created from FixedSizeList<u8> arrays"
781    )]
782    // Different error messages, so skip for now
783    // https://github.com/apache/arrow-rs/issues/1545
784    #[cfg(not(feature = "force_validate"))]
785    fn test_fixed_size_binary_array_from_incorrect_fixed_size_list_array() {
786        let values: [u32; 12] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
787        let values_data = ArrayData::builder(DataType::UInt32)
788            .len(12)
789            .add_buffer(Buffer::from_slice_ref(values))
790            .build()
791            .unwrap();
792
793        let array_data = unsafe {
794            ArrayData::builder(DataType::FixedSizeList(
795                Arc::new(Field::new_list_field(DataType::Binary, false)),
796                4,
797            ))
798            .len(3)
799            .add_child_data(values_data)
800            .build_unchecked()
801        };
802        let list_array = FixedSizeListArray::from(array_data);
803        drop(FixedSizeBinaryArray::from(list_array));
804    }
805
806    #[test]
807    #[should_panic(expected = "The child array cannot contain null values.")]
808    fn test_fixed_size_binary_array_from_fixed_size_list_array_with_child_nulls_failed() {
809        let values = [0_u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
810        let values_data = ArrayData::builder(DataType::UInt8)
811            .len(12)
812            .add_buffer(Buffer::from_slice_ref(values))
813            .null_bit_buffer(Some(Buffer::from_slice_ref([0b101010101010])))
814            .build()
815            .unwrap();
816
817        let array_data = unsafe {
818            ArrayData::builder(DataType::FixedSizeList(
819                Arc::new(Field::new_list_field(DataType::UInt8, false)),
820                4,
821            ))
822            .len(3)
823            .add_child_data(values_data)
824            .build_unchecked()
825        };
826        let list_array = FixedSizeListArray::from(array_data);
827        drop(FixedSizeBinaryArray::from(list_array));
828    }
829
830    #[test]
831    fn test_fixed_size_binary_array_fmt_debug() {
832        let values: [u8; 15] = *b"hellotherearrow";
833
834        let array_data = ArrayData::builder(DataType::FixedSizeBinary(5))
835            .len(3)
836            .add_buffer(Buffer::from(&values))
837            .build()
838            .unwrap();
839        let arr = FixedSizeBinaryArray::from(array_data);
840        assert_eq!(
841            "FixedSizeBinaryArray<5>\n[\n  [104, 101, 108, 108, 111],\n  [116, 104, 101, 114, 101],\n  [97, 114, 114, 111, 119],\n]",
842            format!("{arr:?}")
843        );
844    }
845
846    #[test]
847    fn test_fixed_size_binary_array_from_iter() {
848        let input_arg = vec![vec![1, 2], vec![3, 4], vec![5, 6]];
849        let arr = FixedSizeBinaryArray::try_from_iter(input_arg.into_iter()).unwrap();
850
851        assert_eq!(2, arr.value_length());
852        assert_eq!(3, arr.len())
853    }
854
855    #[test]
856    fn test_all_none_fixed_size_binary_array_from_sparse_iter() {
857        let none_option: Option<[u8; 32]> = None;
858        let input_arg = vec![none_option, none_option, none_option];
859        #[allow(deprecated)]
860        let arr = FixedSizeBinaryArray::try_from_sparse_iter(input_arg.into_iter()).unwrap();
861        assert_eq!(0, arr.value_length());
862        assert_eq!(3, arr.len())
863    }
864
865    #[test]
866    fn test_fixed_size_binary_array_from_sparse_iter() {
867        let input_arg = vec![
868            None,
869            Some(vec![7, 8]),
870            Some(vec![9, 10]),
871            None,
872            Some(vec![13, 14]),
873        ];
874        #[allow(deprecated)]
875        let arr = FixedSizeBinaryArray::try_from_sparse_iter(input_arg.iter().cloned()).unwrap();
876        assert_eq!(2, arr.value_length());
877        assert_eq!(5, arr.len());
878
879        let arr =
880            FixedSizeBinaryArray::try_from_sparse_iter_with_size(input_arg.into_iter(), 2).unwrap();
881        assert_eq!(2, arr.value_length());
882        assert_eq!(5, arr.len());
883    }
884
885    #[test]
886    fn test_fixed_size_binary_array_from_sparse_iter_with_size_all_none() {
887        let input_arg = vec![None, None, None, None, None] as Vec<Option<Vec<u8>>>;
888
889        let arr = FixedSizeBinaryArray::try_from_sparse_iter_with_size(input_arg.into_iter(), 16)
890            .unwrap();
891        assert_eq!(16, arr.value_length());
892        assert_eq!(5, arr.len())
893    }
894
895    #[test]
896    fn test_fixed_size_binary_array_from_vec() {
897        let values = vec!["one".as_bytes(), b"two", b"six", b"ten"];
898        let array = FixedSizeBinaryArray::from(values);
899        assert_eq!(array.len(), 4);
900        assert_eq!(array.null_count(), 0);
901        assert_eq!(array.logical_null_count(), 0);
902        assert_eq!(array.value(0), b"one");
903        assert_eq!(array.value(1), b"two");
904        assert_eq!(array.value(2), b"six");
905        assert_eq!(array.value(3), b"ten");
906        assert!(!array.is_null(0));
907        assert!(!array.is_null(1));
908        assert!(!array.is_null(2));
909        assert!(!array.is_null(3));
910    }
911
912    #[test]
913    #[should_panic(expected = "Nested array size mismatch: one is 3, and the other is 5")]
914    fn test_fixed_size_binary_array_from_vec_incorrect_length() {
915        let values = vec!["one".as_bytes(), b"two", b"three", b"four"];
916        let _ = FixedSizeBinaryArray::from(values);
917    }
918
919    #[test]
920    fn test_fixed_size_binary_array_from_opt_vec() {
921        let values = vec![
922            Some("one".as_bytes()),
923            Some(b"two"),
924            None,
925            Some(b"six"),
926            Some(b"ten"),
927        ];
928        let array = FixedSizeBinaryArray::from(values);
929        assert_eq!(array.len(), 5);
930        assert_eq!(array.value(0), b"one");
931        assert_eq!(array.value(1), b"two");
932        assert_eq!(array.value(3), b"six");
933        assert_eq!(array.value(4), b"ten");
934        assert!(!array.is_null(0));
935        assert!(!array.is_null(1));
936        assert!(array.is_null(2));
937        assert!(!array.is_null(3));
938        assert!(!array.is_null(4));
939    }
940
941    #[test]
942    #[should_panic(expected = "Nested array size mismatch: one is 3, and the other is 5")]
943    fn test_fixed_size_binary_array_from_opt_vec_incorrect_length() {
944        let values = vec![
945            Some("one".as_bytes()),
946            Some(b"two"),
947            None,
948            Some(b"three"),
949            Some(b"four"),
950        ];
951        let _ = FixedSizeBinaryArray::from(values);
952    }
953
954    #[test]
955    fn fixed_size_binary_array_all_null() {
956        let data = vec![None] as Vec<Option<String>>;
957        let array =
958            FixedSizeBinaryArray::try_from_sparse_iter_with_size(data.into_iter(), 0).unwrap();
959        array
960            .into_data()
961            .validate_full()
962            .expect("All null array has valid array data");
963    }
964
965    #[test]
966    // Test for https://github.com/apache/arrow-rs/issues/1390
967    fn fixed_size_binary_array_all_null_in_batch_with_schema() {
968        let schema = Schema::new(vec![Field::new("a", DataType::FixedSizeBinary(2), true)]);
969
970        let none_option: Option<[u8; 2]> = None;
971        let item = FixedSizeBinaryArray::try_from_sparse_iter_with_size(
972            vec![none_option, none_option, none_option].into_iter(),
973            2,
974        )
975        .unwrap();
976
977        // Should not panic
978        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(item)]).unwrap();
979    }
980
981    #[test]
982    #[should_panic(
983        expected = "Trying to access an element at index 4 from a FixedSizeBinaryArray of length 3"
984    )]
985    fn test_fixed_size_binary_array_get_value_index_out_of_bound() {
986        let values = vec![Some("one".as_bytes()), Some(b"two"), None];
987        let array = FixedSizeBinaryArray::from(values);
988
989        array.value(4);
990    }
991
992    #[test]
993    fn test_constructors() {
994        let buffer = Buffer::from_vec(vec![0_u8; 10]);
995        let a = FixedSizeBinaryArray::new(2, buffer.clone(), None);
996        assert_eq!(a.len(), 5);
997
998        let nulls = NullBuffer::new_null(5);
999        FixedSizeBinaryArray::new(2, buffer.clone(), Some(nulls));
1000
1001        let null_array = FixedSizeBinaryArray::new_null(4, 3);
1002        assert_eq!(null_array.len(), 3);
1003        assert_eq!(null_array.values().len(), 12);
1004
1005        let a = FixedSizeBinaryArray::new(3, buffer.clone(), None);
1006        assert_eq!(a.len(), 3);
1007
1008        let nulls = NullBuffer::new_null(3);
1009        FixedSizeBinaryArray::new(3, buffer.clone(), Some(nulls));
1010
1011        let err = FixedSizeBinaryArray::try_new(-1, buffer.clone(), None).unwrap_err();
1012
1013        assert_eq!(
1014            err.to_string(),
1015            "Invalid argument error: Size cannot be negative, got -1"
1016        );
1017
1018        let nulls = NullBuffer::new_null(3);
1019        let err = FixedSizeBinaryArray::try_new(2, buffer.clone(), Some(nulls)).unwrap_err();
1020        assert_eq!(
1021            err.to_string(),
1022            "Invalid argument error: Incorrect length of null buffer for FixedSizeBinaryArray, expected 5 got 3"
1023        );
1024
1025        let zero_sized = FixedSizeBinaryArray::new(0, Buffer::default(), None);
1026        assert_eq!(zero_sized.len(), 0);
1027
1028        let nulls = NullBuffer::new_null(3);
1029        let zero_sized_with_nulls = FixedSizeBinaryArray::new(0, Buffer::default(), Some(nulls));
1030        assert_eq!(zero_sized_with_nulls.len(), 3);
1031
1032        let zero_sized_with_non_empty_buffer_err =
1033            FixedSizeBinaryArray::try_new(0, buffer, None).unwrap_err();
1034        assert_eq!(
1035            zero_sized_with_non_empty_buffer_err.to_string(),
1036            "Invalid argument error: Buffer cannot have non-zero length if the item size is zero"
1037        );
1038    }
1039}