Skip to main content

arrow_array/builder/
fixed_size_binary_builder.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::array::Array;
6use crate::builder::ArrayBuilder;
7use crate::{ArrayRef, FixedSizeBinaryArray};
8use arrow_buffer::Buffer;
9use arrow_buffer::NullBufferBuilder;
10use arrow_schema::ArrowError;
11use std::any::Any;
12use std::sync::Arc;
13
14/// Builder for [`FixedSizeBinaryArray`]
15/// ```
16/// # use arrow_array::builder::FixedSizeBinaryBuilder;
17/// # use arrow_array::Array;
18/// #
19/// let mut builder = FixedSizeBinaryBuilder::with_capacity(3, 5);
20/// // [b"hello", null, b"arrow"]
21/// builder.append_value(b"hello").unwrap();
22/// builder.append_null();
23/// builder.append_value(b"arrow").unwrap();
24///
25/// let array = builder.finish();
26/// assert_eq!(array.value(0), b"hello");
27/// assert!(array.is_null(1));
28/// assert_eq!(array.value(2), b"arrow");
29/// ```
30#[derive(Debug)]
31pub struct FixedSizeBinaryBuilder {
32    values_builder: Vec<u8>,
33    null_buffer_builder: NullBufferBuilder,
34    value_length: i32,
35}
36
37impl FixedSizeBinaryBuilder {
38    /// Creates a new [`FixedSizeBinaryBuilder`]
39    pub fn new(byte_width: i32) -> Self {
40        Self::with_capacity(1024, byte_width)
41    }
42
43    /// Creates a new [`FixedSizeBinaryBuilder`], `capacity` is the number of byte slices
44    /// that can be appended without reallocating
45    ///
46    /// # Panics
47    ///
48    /// Panics if `byte_width < 0`
49    pub fn with_capacity(capacity: usize, byte_width: i32) -> Self {
50        assert!(
51            byte_width >= 0,
52            "value length ({byte_width}) of the array must >= 0"
53        );
54        Self {
55            values_builder: Vec::with_capacity(capacity * byte_width as usize),
56            null_buffer_builder: NullBufferBuilder::new(capacity),
57            value_length: byte_width,
58        }
59    }
60
61    /// Appends a byte slice into the builder.
62    ///
63    /// Automatically update the null buffer to delimit the slice appended in as a
64    /// distinct value element.
65    #[inline]
66    pub fn append_value(&mut self, value: impl AsRef<[u8]>) -> Result<(), ArrowError> {
67        let value = value.as_ref();
68        if value.len() != self.value_length as usize {
69            Err(ArrowError::InvalidArgumentError(
70                "Byte slice does not have the same length as FixedSizeBinaryBuilder value lengths"
71                    .to_string(),
72            ))
73        } else {
74            self.values_builder.extend_from_slice(value);
75            self.null_buffer_builder.append_non_null();
76            Ok(())
77        }
78    }
79
80    /// Append a null value to the array.
81    #[inline]
82    pub fn append_null(&mut self) {
83        self.values_builder
84            .extend(std::iter::repeat_n(0u8, self.value_length as usize));
85        self.null_buffer_builder.append_null();
86    }
87
88    /// Appends `n` `null`s into the builder.
89    #[inline]
90    pub fn append_nulls(&mut self, n: usize) {
91        self.values_builder
92            .extend(std::iter::repeat_n(0u8, self.value_length as usize * n));
93        self.null_buffer_builder.append_n_nulls(n);
94    }
95
96    /// Appends all elements in array into the builder.
97    pub fn append_array(&mut self, array: &FixedSizeBinaryArray) -> Result<(), ArrowError> {
98        if self.value_length != array.value_length() {
99            return Err(ArrowError::InvalidArgumentError(
100                "Cannot append FixedSizeBinaryArray with different value length".to_string(),
101            ));
102        }
103        let buffer = array.value_data();
104        self.values_builder.extend_from_slice(buffer);
105        if let Some(validity) = array.nulls() {
106            self.null_buffer_builder.append_buffer(validity);
107        } else {
108            self.null_buffer_builder.append_n_non_nulls(array.len());
109        }
110        Ok(())
111    }
112
113    /// Returns the current values buffer as a slice
114    pub fn values_slice(&self) -> &[u8] {
115        self.values_builder.as_slice()
116    }
117
118    /// Builds the [`FixedSizeBinaryArray`] and reset this builder.
119    pub fn finish(&mut self) -> FixedSizeBinaryArray {
120        let array_length = self.len();
121        let values = std::mem::take(&mut self.values_builder).into();
122        let nulls = self.null_buffer_builder.finish();
123
124        // SAFETY: value_length >= 0, values.len() == len * value_length,
125        // and nulls.len() == len are all guaranteed by the builder.
126        unsafe {
127            FixedSizeBinaryArray::new_unchecked(self.value_length, values, nulls, array_length)
128        }
129    }
130
131    /// Builds the [`FixedSizeBinaryArray`] without resetting the builder.
132    pub fn finish_cloned(&self) -> FixedSizeBinaryArray {
133        let array_length = self.len();
134        let values = Buffer::from_slice_ref(self.values_builder.as_slice());
135        let nulls = self.null_buffer_builder.finish_cloned();
136
137        // SAFETY: value_length >= 0, values.len() == len * value_length,
138        // and nulls.len() == len are all guaranteed by the builder.
139        unsafe {
140            FixedSizeBinaryArray::new_unchecked(self.value_length, values, nulls, array_length)
141        }
142    }
143
144    /// Returns the current null buffer as a slice
145    pub fn validity_slice(&self) -> Option<&[u8]> {
146        self.null_buffer_builder.as_slice()
147    }
148    ///  Returns the total memory capacity in bytes currently
149    pub fn capacity(&self) -> usize {
150        self.values_builder.capacity() + self.null_buffer_builder.allocated_size() + 4 // i32
151    }
152}
153
154impl ArrayBuilder for FixedSizeBinaryBuilder {
155    /// Returns the builder as a non-mutable `Any` reference.
156    fn as_any(&self) -> &dyn Any {
157        self
158    }
159
160    /// Returns the builder as a mutable `Any` reference.
161    fn as_any_mut(&mut self) -> &mut dyn Any {
162        self
163    }
164
165    /// Returns the boxed builder as a box of `Any`.
166    fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
167        self
168    }
169
170    /// Returns the number of array slots in the builder
171    fn len(&self) -> usize {
172        self.null_buffer_builder.len()
173    }
174
175    /// Builds the array and reset this builder.
176    fn finish(&mut self) -> ArrayRef {
177        Arc::new(self.finish())
178    }
179
180    /// Builds the array without resetting the builder.
181    fn finish_cloned(&self) -> ArrayRef {
182        Arc::new(self.finish_cloned())
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    use crate::Array;
191    use arrow_schema::DataType;
192
193    #[test]
194    fn test_finish_materialized_without_nulls() {
195        let mut builder = FixedSizeBinaryBuilder::new(1);
196        builder.append_nulls(0);
197        builder.append_value(b"a").unwrap();
198        assert!(builder.finish_cloned().nulls().is_none());
199        assert!(builder.finish().nulls().is_none());
200    }
201
202    #[test]
203    fn test_fixed_size_binary_builder() {
204        let mut builder = FixedSizeBinaryBuilder::with_capacity(3, 5);
205
206        //  [b"hello", null, "arrow", null, null, "world"]
207        builder.append_value(b"hello").unwrap();
208        builder.append_null();
209        builder.append_value(b"arrow").unwrap();
210        builder.append_nulls(2);
211        builder.append_value(b"world").unwrap();
212        let array = builder.finish();
213
214        assert_eq!(&DataType::FixedSizeBinary(5), array.data_type());
215        assert_eq!(6, array.len());
216        assert_eq!(3, array.null_count());
217        assert_eq!(5, array.value_length());
218        assert_eq!(b"arrow", array.value(2));
219        assert!(array.is_null(3));
220        assert!(array.is_null(4));
221        assert_eq!(b"world", array.value(5));
222    }
223
224    #[test]
225    fn test_fixed_size_binary_builder_finish_cloned() {
226        let mut builder = FixedSizeBinaryBuilder::with_capacity(3, 5);
227
228        //  [b"hello", null, "arrow"]
229        builder.append_value(b"hello").unwrap();
230        builder.append_null();
231        builder.append_value(b"arrow").unwrap();
232        let mut array = builder.finish_cloned();
233
234        assert_eq!(&DataType::FixedSizeBinary(5), array.data_type());
235        assert_eq!(3, array.len());
236        assert_eq!(1, array.null_count());
237        assert_eq!(5, array.value_length());
238        assert_eq!(b"arrow", array.value(2));
239
240        //  [b"finis", null, "clone"]
241        builder.append_value(b"finis").unwrap();
242        builder.append_null();
243        builder.append_value(b"clone").unwrap();
244
245        array = builder.finish();
246
247        assert_eq!(&DataType::FixedSizeBinary(5), array.data_type());
248        assert_eq!(6, array.len());
249        assert_eq!(2, array.null_count());
250        assert_eq!(5, array.value_length());
251        assert_eq!(b"clone", array.value(5));
252    }
253
254    #[test]
255    fn test_fixed_size_binary_builder_with_zero_value_length() {
256        let mut builder = FixedSizeBinaryBuilder::new(0);
257
258        builder.append_value(b"").unwrap();
259        builder.append_null();
260        builder.append_value(b"").unwrap();
261        assert!(!builder.is_empty());
262
263        let array = builder.finish();
264        assert_eq!(&DataType::FixedSizeBinary(0), array.data_type());
265        assert_eq!(3, array.len());
266        assert_eq!(1, array.null_count());
267        assert_eq!(0, array.value_length());
268        assert_eq!(b"", array.value(0));
269        assert_eq!(b"", array.value(2));
270    }
271
272    #[test]
273    #[should_panic(
274        expected = "Byte slice does not have the same length as FixedSizeBinaryBuilder value lengths"
275    )]
276    fn test_fixed_size_binary_builder_with_inconsistent_value_length() {
277        let mut builder = FixedSizeBinaryBuilder::with_capacity(1, 4);
278        builder.append_value(b"hello").unwrap();
279    }
280    #[test]
281    fn test_fixed_size_binary_builder_empty() {
282        let mut builder = FixedSizeBinaryBuilder::new(5);
283        assert!(builder.is_empty());
284
285        let fixed_size_binary_array = builder.finish();
286        assert_eq!(
287            &DataType::FixedSizeBinary(5),
288            fixed_size_binary_array.data_type()
289        );
290        assert_eq!(0, fixed_size_binary_array.len());
291    }
292
293    #[test]
294    #[should_panic(expected = "value length (-1) of the array must >= 0")]
295    fn test_fixed_size_binary_builder_invalid_value_length() {
296        let _ = FixedSizeBinaryBuilder::with_capacity(15, -1);
297    }
298
299    #[test]
300    fn test_fixed_size_binary_builder_append_array() {
301        let mut other_builder = FixedSizeBinaryBuilder::with_capacity(3, 5);
302        other_builder.append_value(b"hello").unwrap();
303        other_builder.append_null();
304        other_builder.append_value(b"arrow").unwrap();
305        let other_array = other_builder.finish();
306
307        let mut builder = FixedSizeBinaryBuilder::with_capacity(6, 5);
308        builder.append_array(&other_array).unwrap();
309        // Append again to test if breaks when appending multiple times
310        builder.append_array(&other_array).unwrap();
311        let array = builder.finish();
312
313        assert_eq!(array.value_length(), other_array.value_length());
314        assert_eq!(&DataType::FixedSizeBinary(5), array.data_type());
315        assert_eq!(6, array.len());
316        assert_eq!(2, array.null_count());
317        assert_eq!(b"hello", array.value(0));
318        assert!(array.is_null(1));
319        assert_eq!(b"arrow", array.value(2));
320
321        assert_eq!(b"hello", array.value(3));
322        assert!(array.is_null(4));
323        assert_eq!(b"arrow", array.value(5));
324    }
325
326    #[test]
327    #[should_panic(expected = "Cannot append FixedSizeBinaryArray with different value length")]
328    fn test_fixed_size_binary_builder_append_array_invalid_value_length() {
329        let mut other_builder = FixedSizeBinaryBuilder::with_capacity(3, 4);
330        other_builder.append_value(b"test").unwrap();
331        let other_array = other_builder.finish();
332        let mut builder = FixedSizeBinaryBuilder::with_capacity(3, 5);
333        builder.append_array(&other_array).unwrap();
334    }
335
336    #[test]
337    fn test_fixed_size_binary_builder_append_array_trailing_bytes() {
338        let trailing = FixedSizeBinaryArray::new(3, vec![1_u8, 2, 3, 4, 5, 6, 99].into(), None);
339        assert_eq!(trailing.len(), 2);
340
341        let mut builder = FixedSizeBinaryBuilder::with_capacity(3, 3);
342        builder.append_array(&trailing).unwrap();
343        builder.append_value([7, 8, 9]).unwrap();
344        let array = builder.finish();
345
346        assert_eq!(array.len(), 3);
347        assert_eq!(array.value(0), &[1, 2, 3]);
348        assert_eq!(array.value(1), &[4, 5, 6]);
349        assert_eq!(array.value(2), &[7, 8, 9]);
350        assert_eq!(array.value_data(), &[1, 2, 3, 4, 5, 6, 7, 8, 9]);
351    }
352}