Skip to main content

arrow_array/builder/
primitive_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::builder::ArrayBuilder;
6use crate::types::*;
7use crate::{Array, ArrayRef, PrimitiveArray};
8use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, ScalarBuffer};
9use arrow_schema::{ArrowError, DataType};
10use std::any::Any;
11use std::sync::Arc;
12
13/// A signed 8-bit integer array builder.
14pub type Int8Builder = PrimitiveBuilder<Int8Type>;
15/// A signed 16-bit integer array builder.
16pub type Int16Builder = PrimitiveBuilder<Int16Type>;
17/// A signed 32-bit integer array builder.
18pub type Int32Builder = PrimitiveBuilder<Int32Type>;
19/// A signed 64-bit integer array builder.
20pub type Int64Builder = PrimitiveBuilder<Int64Type>;
21/// An unsigned 8-bit integer array builder.
22pub type UInt8Builder = PrimitiveBuilder<UInt8Type>;
23/// An unsigned 16-bit integer array builder.
24pub type UInt16Builder = PrimitiveBuilder<UInt16Type>;
25/// An unsigned 32-bit integer array builder.
26pub type UInt32Builder = PrimitiveBuilder<UInt32Type>;
27/// An unsigned 64-bit integer array builder.
28pub type UInt64Builder = PrimitiveBuilder<UInt64Type>;
29/// A 16-bit floating point array builder.
30pub type Float16Builder = PrimitiveBuilder<Float16Type>;
31/// A 32-bit floating point array builder.
32pub type Float32Builder = PrimitiveBuilder<Float32Type>;
33/// A 64-bit floating point array builder.
34pub type Float64Builder = PrimitiveBuilder<Float64Type>;
35
36/// A timestamp second array builder.
37pub type TimestampSecondBuilder = PrimitiveBuilder<TimestampSecondType>;
38/// A timestamp millisecond array builder.
39pub type TimestampMillisecondBuilder = PrimitiveBuilder<TimestampMillisecondType>;
40/// A timestamp microsecond array builder.
41pub type TimestampMicrosecondBuilder = PrimitiveBuilder<TimestampMicrosecondType>;
42/// A timestamp nanosecond array builder.
43pub type TimestampNanosecondBuilder = PrimitiveBuilder<TimestampNanosecondType>;
44
45/// A 32-bit date array builder.
46pub type Date32Builder = PrimitiveBuilder<Date32Type>;
47/// A 64-bit date array builder.
48pub type Date64Builder = PrimitiveBuilder<Date64Type>;
49
50/// A 32-bit elapsed time in seconds array builder.
51pub type Time32SecondBuilder = PrimitiveBuilder<Time32SecondType>;
52/// A 32-bit elapsed time in milliseconds array builder.
53pub type Time32MillisecondBuilder = PrimitiveBuilder<Time32MillisecondType>;
54/// A 64-bit elapsed time in microseconds array builder.
55pub type Time64MicrosecondBuilder = PrimitiveBuilder<Time64MicrosecondType>;
56/// A 64-bit elapsed time in nanoseconds array builder.
57pub type Time64NanosecondBuilder = PrimitiveBuilder<Time64NanosecondType>;
58
59/// A “calendar” interval in months array builder.
60pub type IntervalYearMonthBuilder = PrimitiveBuilder<IntervalYearMonthType>;
61/// A “calendar” interval in days and milliseconds array builder.
62pub type IntervalDayTimeBuilder = PrimitiveBuilder<IntervalDayTimeType>;
63/// A “calendar” interval in months, days, and nanoseconds array builder.
64pub type IntervalMonthDayNanoBuilder = PrimitiveBuilder<IntervalMonthDayNanoType>;
65
66/// An elapsed time in seconds array builder.
67pub type DurationSecondBuilder = PrimitiveBuilder<DurationSecondType>;
68/// An elapsed time in milliseconds array builder.
69pub type DurationMillisecondBuilder = PrimitiveBuilder<DurationMillisecondType>;
70/// An elapsed time in microseconds array builder.
71pub type DurationMicrosecondBuilder = PrimitiveBuilder<DurationMicrosecondType>;
72/// An elapsed time in nanoseconds array builder.
73pub type DurationNanosecondBuilder = PrimitiveBuilder<DurationNanosecondType>;
74
75/// A decimal 32 array builder
76pub type Decimal32Builder = PrimitiveBuilder<Decimal32Type>;
77/// A decimal 64 array builder
78pub type Decimal64Builder = PrimitiveBuilder<Decimal64Type>;
79/// A decimal 128 array builder
80pub type Decimal128Builder = PrimitiveBuilder<Decimal128Type>;
81/// A decimal 256 array builder
82pub type Decimal256Builder = PrimitiveBuilder<Decimal256Type>;
83
84/// Builder for [`PrimitiveArray`]
85///
86/// # Performance
87///
88/// Rust's `Vec` is highly optimized, and Arrow's conversion from `Vec` to
89/// [`PrimitiveArray`] is zero-copy — the array reuses the same underlying allocation
90/// without any data being copied. If your values are already in a `Vec`, or can be
91/// collected into one, prefer constructing a [`PrimitiveArray`] directly:
92///
93/// ```
94/// # use arrow_array::{Int32Array, Array};
95/// // Zero-copy: the array reuses the Vec's allocation
96/// let array = Int32Array::from(vec![1, 2, 3]);
97/// assert_eq!(array.len(), 3);
98/// ```
99///
100/// Internally, [`PrimitiveBuilder`] is itself backed by a `Vec<T::Native>` and a
101/// [`NullBufferBuilder`], so using one does not unlock any additional performance —
102/// it is simply a convenience wrapper for incremental construction.
103///
104/// # When to use [`PrimitiveBuilder`]
105///
106/// Prefer the builder when your array **may contain nulls but you don't know their
107/// positions upfront**. Managing a `Vec<T>` and a [`NullBufferBuilder`] in parallel
108/// by hand is error-prone; the builder keeps them in sync automatically as you call
109/// [`append_value`](PrimitiveBuilder::append_value) and
110/// [`append_null`](PrimitiveBuilder::append_null).
111///
112/// ```
113/// # use arrow_array::builder::Int32Builder;
114/// # use arrow_array::Array;
115/// let mut builder = Int32Builder::new();
116/// for (i, v) in [1, 2, 3].iter().enumerate() {
117///     if i == 1 {
118///         builder.append_null();
119///     } else {
120///         builder.append_value(*v);
121///     }
122/// }
123/// let array = builder.finish();
124/// assert_eq!(array.len(), 3);
125/// assert!(array.is_null(1));
126/// ```
127#[derive(Debug)]
128pub struct PrimitiveBuilder<T: ArrowPrimitiveType> {
129    values_builder: Vec<T::Native>,
130    null_buffer_builder: NullBufferBuilder,
131    data_type: DataType,
132}
133
134impl<T: ArrowPrimitiveType> ArrayBuilder for PrimitiveBuilder<T> {
135    /// Returns the builder as a non-mutable `Any` reference.
136    fn as_any(&self) -> &dyn Any {
137        self
138    }
139
140    /// Returns the builder as a mutable `Any` reference.
141    fn as_any_mut(&mut self) -> &mut dyn Any {
142        self
143    }
144
145    /// Returns the boxed builder as a box of `Any`.
146    fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
147        self
148    }
149
150    /// Returns the number of array slots in the builder
151    fn len(&self) -> usize {
152        self.values_builder.len()
153    }
154
155    /// Builds the array and reset this builder.
156    fn finish(&mut self) -> ArrayRef {
157        Arc::new(self.finish())
158    }
159
160    /// Builds the array without resetting the builder.
161    fn finish_cloned(&self) -> ArrayRef {
162        Arc::new(self.finish_cloned())
163    }
164}
165
166impl<T: ArrowPrimitiveType> Default for PrimitiveBuilder<T> {
167    fn default() -> Self {
168        Self::new()
169    }
170}
171
172impl<T: ArrowPrimitiveType> PrimitiveBuilder<T> {
173    /// Creates a new primitive array builder
174    pub fn new() -> Self {
175        Self::with_capacity(1024)
176    }
177
178    /// Creates a new primitive array builder with capacity no of items
179    pub fn with_capacity(capacity: usize) -> Self {
180        Self {
181            values_builder: Vec::with_capacity(capacity),
182            null_buffer_builder: NullBufferBuilder::new(capacity),
183            data_type: T::DATA_TYPE,
184        }
185    }
186
187    /// Creates a new primitive array builder from buffers
188    pub fn new_from_buffer(
189        values_buffer: MutableBuffer,
190        null_buffer: Option<MutableBuffer>,
191    ) -> Self {
192        let values_builder: Vec<T::Native> = ScalarBuffer::<T::Native>::from(values_buffer).into();
193
194        let null_buffer_builder = null_buffer
195            .map(|buffer| NullBufferBuilder::new_from_buffer(buffer, values_builder.len()))
196            .unwrap_or_else(|| NullBufferBuilder::new_with_len(values_builder.len()));
197
198        Self {
199            values_builder,
200            null_buffer_builder,
201            data_type: T::DATA_TYPE,
202        }
203    }
204
205    /// By default [`PrimitiveBuilder`] uses [`ArrowPrimitiveType::DATA_TYPE`] as the
206    /// data type of the generated array.
207    ///
208    /// This method allows overriding the data type, to allow specifying timezones
209    /// for [`DataType::Timestamp`] or precision and scale for [`DataType::Decimal32`],
210    /// [`DataType::Decimal64`], [`DataType::Decimal128`] and [`DataType::Decimal256`]
211    ///
212    /// # Panics
213    ///
214    /// This method panics if `data_type` is not [PrimitiveArray::is_compatible]
215    pub fn with_data_type(self, data_type: DataType) -> Self {
216        assert!(
217            PrimitiveArray::<T>::is_compatible(&data_type),
218            "incompatible data type for builder, expected {} got {}",
219            T::DATA_TYPE,
220            data_type
221        );
222        Self { data_type, ..self }
223    }
224
225    /// Returns the capacity of this builder measured in slots of type `T`
226    pub fn capacity(&self) -> usize {
227        self.values_builder.capacity()
228    }
229
230    /// Appends a value of type `T` into the builder
231    #[inline]
232    pub fn append_value(&mut self, v: T::Native) {
233        self.null_buffer_builder.append_non_null();
234        self.values_builder.push(v);
235    }
236
237    /// Appends a value of type `T` into the builder `n` times
238    #[inline]
239    pub fn append_value_n(&mut self, v: T::Native, n: usize) {
240        self.null_buffer_builder.append_n_non_nulls(n);
241        self.values_builder.extend(std::iter::repeat_n(v, n));
242    }
243
244    /// Appends a null slot into the builder
245    #[inline]
246    pub fn append_null(&mut self) {
247        self.null_buffer_builder.append_null();
248        self.values_builder.push(T::Native::default());
249    }
250
251    /// Appends `n` no. of null's into the builder
252    #[inline]
253    pub fn append_nulls(&mut self, n: usize) {
254        self.null_buffer_builder.append_n_nulls(n);
255        self.values_builder
256            .extend(std::iter::repeat_n(T::Native::default(), n));
257    }
258
259    /// Appends an `Option<T>` into the builder
260    #[inline]
261    pub fn append_option(&mut self, v: Option<T::Native>) {
262        match v {
263            None => self.append_null(),
264            Some(v) => self.append_value(v),
265        }
266    }
267
268    /// Appends a slice of type `T` into the builder
269    #[inline]
270    pub fn append_slice(&mut self, v: &[T::Native]) {
271        self.null_buffer_builder.append_n_non_nulls(v.len());
272        self.values_builder.extend_from_slice(v);
273    }
274
275    /// Appends values from a slice of type `T` and a validity boolean slice
276    ///
277    /// # Panics
278    ///
279    /// Panics if `values` and `is_valid` have different lengths
280    #[inline]
281    pub fn append_values(&mut self, values: &[T::Native], is_valid: &[bool]) {
282        assert_eq!(
283            values.len(),
284            is_valid.len(),
285            "Value and validity lengths must be equal"
286        );
287        self.null_buffer_builder.append_slice(is_valid);
288        self.values_builder.extend_from_slice(values);
289    }
290
291    /// Appends values from a iter of type `Option<T>`
292    ///
293    /// # Panics
294    ///
295    /// Panics if `values` and `is_valid` have different lengths
296    #[inline]
297    pub fn extend_from_iter_option<I: IntoIterator<Item = Option<T::Native>>>(&mut self, iter: I) {
298        let iter = iter.into_iter();
299        self.values_builder.extend(iter.map(|v| match v {
300            Some(v) => {
301                self.null_buffer_builder.append_non_null();
302                v
303            }
304            None => {
305                self.null_buffer_builder.append_null();
306                T::Native::default()
307            }
308        }));
309    }
310
311    /// Appends array values and null to this builder as is
312    /// (this means that underlying null values are copied as is).
313    ///
314    /// # Panics
315    ///
316    /// Panics if `array` and `self` data types are different
317    #[inline]
318    pub fn append_array(&mut self, array: &PrimitiveArray<T>) {
319        assert_eq!(
320            &self.data_type,
321            array.data_type(),
322            "array data type mismatch"
323        );
324
325        self.values_builder.extend_from_slice(array.values());
326        if let Some(null_buffer) = array.nulls() {
327            self.null_buffer_builder.append_buffer(null_buffer);
328        } else {
329            self.null_buffer_builder.append_n_non_nulls(array.len());
330        }
331    }
332
333    /// Appends values from a trusted length iterator.
334    ///
335    /// # Safety
336    /// This requires the iterator be a trusted length. This could instead require
337    /// the iterator implement `TrustedLen` once that is stabilized.
338    #[inline]
339    pub unsafe fn append_trusted_len_iter(&mut self, iter: impl IntoIterator<Item = T::Native>) {
340        let iter = iter.into_iter();
341        let len = iter
342            .size_hint()
343            .1
344            .expect("append_trusted_len_iter requires an upper bound");
345
346        self.null_buffer_builder.append_n_non_nulls(len);
347        self.values_builder.extend(iter);
348    }
349
350    /// Builds the [`PrimitiveArray`] and reset this builder.
351    pub fn finish(&mut self) -> PrimitiveArray<T> {
352        let nulls = self.null_buffer_builder.finish();
353        let values = std::mem::take(&mut self.values_builder).into();
354        PrimitiveArray::new(values, nulls).with_data_type(self.data_type.clone())
355    }
356
357    /// Builds the [`PrimitiveArray`] without resetting the builder.
358    pub fn finish_cloned(&self) -> PrimitiveArray<T> {
359        let nulls = self.null_buffer_builder.finish_cloned();
360        let values = Buffer::from_slice_ref(self.values_builder.as_slice()).into();
361        PrimitiveArray::new(values, nulls).with_data_type(self.data_type.clone())
362    }
363
364    /// Returns the current values buffer as a slice
365    pub fn values_slice(&self) -> &[T::Native] {
366        self.values_builder.as_slice()
367    }
368
369    /// Returns the current values buffer as a mutable slice
370    pub fn values_slice_mut(&mut self) -> &mut [T::Native] {
371        self.values_builder.as_mut_slice()
372    }
373
374    /// Returns the current null buffer as a slice
375    pub fn validity_slice(&self) -> Option<&[u8]> {
376        self.null_buffer_builder.as_slice()
377    }
378
379    /// Returns the current null buffer allocated capacity, in bytes.
380    pub fn validity_capacity(&self) -> usize {
381        self.null_buffer_builder.allocated_size()
382    }
383
384    /// Returns the current null buffer as a mutable slice
385    pub fn validity_slice_mut(&mut self) -> Option<&mut [u8]> {
386        self.null_buffer_builder.as_slice_mut()
387    }
388
389    /// Returns the current values buffer and null buffer as a slice
390    pub fn slices_mut(&mut self) -> (&mut [T::Native], Option<&mut [u8]>) {
391        (
392            self.values_builder.as_mut_slice(),
393            self.null_buffer_builder.as_slice_mut(),
394        )
395    }
396}
397
398impl<P: DecimalType> PrimitiveBuilder<P> {
399    /// Sets the precision and scale
400    pub fn with_precision_and_scale(self, precision: u8, scale: i8) -> Result<Self, ArrowError> {
401        validate_decimal_precision_and_scale::<P>(precision, scale)?;
402        Ok(Self {
403            data_type: P::TYPE_CONSTRUCTOR(precision, scale),
404            ..self
405        })
406    }
407}
408
409impl<P: ArrowTimestampType> PrimitiveBuilder<P> {
410    /// Sets the timezone
411    pub fn with_timezone(self, timezone: impl Into<Arc<str>>) -> Self {
412        self.with_timezone_opt(Some(timezone.into()))
413    }
414
415    /// Sets an optional timezone
416    pub fn with_timezone_opt<S: Into<Arc<str>>>(self, timezone: Option<S>) -> Self {
417        Self {
418            data_type: DataType::Timestamp(P::UNIT, timezone.map(Into::into)),
419            ..self
420        }
421    }
422}
423
424impl<P: ArrowPrimitiveType> Extend<Option<P::Native>> for PrimitiveBuilder<P> {
425    #[inline]
426    fn extend<T: IntoIterator<Item = Option<P::Native>>>(&mut self, iter: T) {
427        for v in iter {
428            self.append_option(v)
429        }
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use arrow_buffer::{NullBuffer, ScalarBuffer};
437    use arrow_schema::TimeUnit;
438
439    use crate::array::Array;
440    use crate::array::BooleanArray;
441    use crate::array::Date32Array;
442    use crate::array::Int32Array;
443    use crate::array::TimestampSecondArray;
444
445    #[test]
446    fn test_finish_materialized_without_nulls() {
447        let mut builder = Int32Builder::new();
448        builder.append_nulls(0);
449        builder.append_value(1);
450        assert!(builder.finish_cloned().nulls().is_none());
451        assert!(builder.finish().nulls().is_none());
452    }
453
454    #[test]
455    fn test_primitive_array_builder_i32() {
456        let mut builder = Int32Array::builder(5);
457        for i in 0..5 {
458            builder.append_value(i);
459        }
460        let arr = builder.finish();
461        assert_eq!(5, arr.len());
462        assert_eq!(0, arr.offset());
463        assert_eq!(0, arr.null_count());
464        for i in 0..5 {
465            assert!(!arr.is_null(i));
466            assert!(arr.is_valid(i));
467            assert_eq!(i as i32, arr.value(i));
468        }
469    }
470
471    #[test]
472    fn test_primitive_array_builder_i32_append_iter() {
473        let mut builder = Int32Array::builder(5);
474        unsafe { builder.append_trusted_len_iter(0..5) };
475        let arr = builder.finish();
476        assert_eq!(5, arr.len());
477        assert_eq!(0, arr.offset());
478        assert_eq!(0, arr.null_count());
479        for i in 0..5 {
480            assert!(!arr.is_null(i));
481            assert!(arr.is_valid(i));
482            assert_eq!(i as i32, arr.value(i));
483        }
484    }
485
486    #[test]
487    fn test_primitive_array_builder_i32_append_nulls() {
488        let mut builder = Int32Array::builder(5);
489        builder.append_nulls(5);
490        let arr = builder.finish();
491        assert_eq!(5, arr.len());
492        assert_eq!(0, arr.offset());
493        assert_eq!(5, arr.null_count());
494        for i in 0..5 {
495            assert!(arr.is_null(i));
496            assert!(!arr.is_valid(i));
497        }
498    }
499
500    #[test]
501    fn test_primitive_array_builder_date32() {
502        let mut builder = Date32Array::builder(5);
503        for i in 0..5 {
504            builder.append_value(i);
505        }
506        let arr = builder.finish();
507        assert_eq!(5, arr.len());
508        assert_eq!(0, arr.offset());
509        assert_eq!(0, arr.null_count());
510        for i in 0..5 {
511            assert!(!arr.is_null(i));
512            assert!(arr.is_valid(i));
513            assert_eq!(i as i32, arr.value(i));
514        }
515    }
516
517    #[test]
518    fn test_primitive_array_builder_timestamp_second() {
519        let mut builder = TimestampSecondArray::builder(5);
520        for i in 0..5 {
521            builder.append_value(i);
522        }
523        let arr = builder.finish();
524        assert_eq!(5, arr.len());
525        assert_eq!(0, arr.offset());
526        assert_eq!(0, arr.null_count());
527        for i in 0..5 {
528            assert!(!arr.is_null(i));
529            assert!(arr.is_valid(i));
530            assert_eq!(i as i64, arr.value(i));
531        }
532    }
533
534    #[test]
535    fn test_primitive_array_builder_bool() {
536        // 00000010 01001000
537        let buf = Buffer::from([72_u8, 2_u8]);
538        let mut builder = BooleanArray::builder(10);
539        for i in 0..10 {
540            if i == 3 || i == 6 || i == 9 {
541                builder.append_value(true);
542            } else {
543                builder.append_value(false);
544            }
545        }
546
547        let arr = builder.finish();
548        assert_eq!(&buf, arr.values().inner());
549        assert_eq!(10, arr.len());
550        assert_eq!(0, arr.offset());
551        assert_eq!(0, arr.null_count());
552        for i in 0..10 {
553            assert!(!arr.is_null(i));
554            assert!(arr.is_valid(i));
555            assert_eq!(i == 3 || i == 6 || i == 9, arr.value(i), "failed at {i}")
556        }
557    }
558
559    #[test]
560    fn test_primitive_array_builder_append_option() {
561        let arr1 = Int32Array::from(vec![Some(0), None, Some(2), None, Some(4)]);
562
563        let mut builder = Int32Array::builder(5);
564        builder.append_option(Some(0));
565        builder.append_option(None);
566        builder.append_option(Some(2));
567        builder.append_option(None);
568        builder.append_option(Some(4));
569        let arr2 = builder.finish();
570
571        assert_eq!(arr1.len(), arr2.len());
572        assert_eq!(arr1.offset(), arr2.offset());
573        assert_eq!(arr1.null_count(), arr2.null_count());
574        for i in 0..5 {
575            assert_eq!(arr1.is_null(i), arr2.is_null(i));
576            assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
577            if arr1.is_valid(i) {
578                assert_eq!(arr1.value(i), arr2.value(i));
579            }
580        }
581    }
582
583    #[test]
584    fn test_primitive_array_builder_append_null() {
585        let arr1 = Int32Array::from(vec![Some(0), Some(2), None, None, Some(4)]);
586
587        let mut builder = Int32Array::builder(5);
588        builder.append_value(0);
589        builder.append_value(2);
590        builder.append_null();
591        builder.append_null();
592        builder.append_value(4);
593        let arr2 = builder.finish();
594
595        assert_eq!(arr1.len(), arr2.len());
596        assert_eq!(arr1.offset(), arr2.offset());
597        assert_eq!(arr1.null_count(), arr2.null_count());
598        for i in 0..5 {
599            assert_eq!(arr1.is_null(i), arr2.is_null(i));
600            assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
601            if arr1.is_valid(i) {
602                assert_eq!(arr1.value(i), arr2.value(i));
603            }
604        }
605    }
606
607    #[test]
608    fn test_primitive_array_builder_append_slice() {
609        let arr1 = Int32Array::from(vec![Some(0), Some(2), None, None, Some(4)]);
610
611        let mut builder = Int32Array::builder(5);
612        builder.append_slice(&[0, 2]);
613        builder.append_null();
614        builder.append_null();
615        builder.append_value(4);
616        let arr2 = builder.finish();
617
618        assert_eq!(arr1.len(), arr2.len());
619        assert_eq!(arr1.offset(), arr2.offset());
620        assert_eq!(arr1.null_count(), arr2.null_count());
621        for i in 0..5 {
622            assert_eq!(arr1.is_null(i), arr2.is_null(i));
623            assert_eq!(arr1.is_valid(i), arr2.is_valid(i));
624            if arr1.is_valid(i) {
625                assert_eq!(arr1.value(i), arr2.value(i));
626            }
627        }
628    }
629
630    #[test]
631    fn test_primitive_array_builder_finish() {
632        let mut builder = Int32Builder::new();
633        builder.append_slice(&[2, 4, 6, 8]);
634        let mut arr = builder.finish();
635        assert_eq!(4, arr.len());
636        assert_eq!(0, builder.len());
637
638        builder.append_slice(&[1, 3, 5, 7, 9]);
639        arr = builder.finish();
640        assert_eq!(5, arr.len());
641        assert_eq!(0, builder.len());
642    }
643
644    #[test]
645    fn test_primitive_array_builder_finish_cloned() {
646        let mut builder = Int32Builder::new();
647        builder.append_value(23);
648        builder.append_value(45);
649        let result = builder.finish_cloned();
650        assert_eq!(result, Int32Array::from(vec![23, 45]));
651        builder.append_value(56);
652        assert_eq!(builder.finish_cloned(), Int32Array::from(vec![23, 45, 56]));
653
654        builder.append_slice(&[2, 4, 6, 8]);
655        let mut arr = builder.finish();
656        assert_eq!(7, arr.len());
657        assert_eq!(arr, Int32Array::from(vec![23, 45, 56, 2, 4, 6, 8]));
658        assert_eq!(0, builder.len());
659
660        builder.append_slice(&[1, 3, 5, 7, 9]);
661        arr = builder.finish();
662        assert_eq!(5, arr.len());
663        assert_eq!(0, builder.len());
664    }
665
666    #[test]
667    fn test_primitive_array_builder_with_data_type() {
668        let mut builder = Decimal128Builder::new().with_data_type(DataType::Decimal128(1, 2));
669        builder.append_value(1);
670        let array = builder.finish();
671        assert_eq!(array.precision(), 1);
672        assert_eq!(array.scale(), 2);
673
674        let data_type = DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into()));
675        let mut builder = TimestampNanosecondBuilder::new().with_data_type(data_type.clone());
676        builder.append_value(1);
677        let array = builder.finish();
678        assert_eq!(array.data_type(), &data_type);
679    }
680
681    #[test]
682    #[should_panic(expected = "incompatible data type for builder, expected Int32 got Int64")]
683    fn test_invalid_with_data_type() {
684        Int32Builder::new().with_data_type(DataType::Int64);
685    }
686
687    #[test]
688    fn test_extend() {
689        let mut builder = PrimitiveBuilder::<Int16Type>::new();
690        builder.extend([1, 2, 3, 5, 2, 4, 4].into_iter().map(Some));
691        builder.extend([2, 4, 6, 2].into_iter().map(Some));
692        let array = builder.finish();
693        assert_eq!(array.values(), &[1, 2, 3, 5, 2, 4, 4, 2, 4, 6, 2]);
694    }
695
696    #[test]
697    fn test_primitive_array_append_array() {
698        let input = vec![
699            Some(1),
700            None,
701            Some(3),
702            None,
703            Some(5),
704            None,
705            None,
706            None,
707            Some(7),
708            Some(9),
709            Some(8),
710            Some(6),
711            Some(4),
712        ];
713        let arr1 = Int32Array::from(input[..5].to_vec());
714        let arr2 = Int32Array::from(input[5..8].to_vec());
715        let arr3 = Int32Array::from(input[8..].to_vec());
716
717        let mut builder = Int32Array::builder(5);
718        builder.append_array(&arr1);
719        builder.append_array(&arr2);
720        builder.append_array(&arr3);
721        let actual = builder.finish();
722        let expected = Int32Array::from(input);
723
724        assert_eq!(actual, expected);
725    }
726
727    #[test]
728    fn test_append_array_add_underlying_null_values() {
729        let array = Int32Array::new(
730            ScalarBuffer::from(vec![2, 3, 4, 5]),
731            Some(NullBuffer::from(&[true, true, false, false])),
732        );
733
734        let mut builder = Int32Array::builder(5);
735        builder.append_array(&array);
736        let actual = builder.finish();
737
738        assert_eq!(actual, array);
739        assert_eq!(actual.values(), array.values())
740    }
741
742    #[test]
743    #[should_panic(expected = "array data type mismatch")]
744    fn test_invalid_with_data_type_in_append_array() {
745        let array = {
746            let mut builder = Decimal128Builder::new().with_data_type(DataType::Decimal128(1, 2));
747            builder.append_value(1);
748            builder.finish()
749        };
750
751        let mut builder = Decimal128Builder::new().with_data_type(DataType::Decimal128(2, 3));
752        builder.append_array(&array)
753    }
754}