Skip to main content

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