Skip to main content

vortex_array/builders/
primitive.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::mem::MaybeUninit;
6
7use vortex_buffer::BufferAllocatorRef;
8use vortex_buffer::BufferMut;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure_eq;
12use vortex_mask::Mask;
13
14use crate::ArrayRef;
15use crate::ExecutionCtx;
16use crate::IntoArray;
17use crate::array::ArrayView;
18use crate::arrays::Primitive;
19use crate::arrays::PrimitiveArray;
20use crate::builders::ArrayBuilder;
21use crate::builders::DEFAULT_BUILDER_CAPACITY;
22use crate::builders::LazyBitBufferBuilder;
23use crate::canonical::Canonical;
24use crate::dtype::DType;
25use crate::dtype::NativePType;
26use crate::dtype::Nullability;
27use crate::scalar::Scalar;
28
29/// The builder for building a [`PrimitiveArray`], parametrized by the `PType`.
30pub struct PrimitiveBuilder<T> {
31    dtype: DType,
32    values: BufferMut<T>,
33    nulls: LazyBitBufferBuilder,
34}
35
36impl<T: NativePType> PrimitiveBuilder<T> {
37    /// Creates a new `PrimitiveBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
38    #[deprecated(note = "use `new_in` with an explicit allocator")]
39    pub fn new(nullability: Nullability) -> Self {
40        Self::new_in(nullability, BufferAllocatorRef::static_ref())
41    }
42
43    /// Creates a new `PrimitiveBuilder` with the default capacity using `allocator`.
44    pub fn new_in(nullability: Nullability, allocator: &BufferAllocatorRef) -> Self {
45        Self::with_capacity_in(nullability, DEFAULT_BUILDER_CAPACITY, allocator)
46    }
47
48    /// Creates a new `PrimitiveBuilder` with the given `capacity`.
49    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
50    pub fn with_capacity(nullability: Nullability, capacity: usize) -> Self {
51        Self::with_capacity_in(nullability, capacity, BufferAllocatorRef::static_ref())
52    }
53
54    /// Creates a new `PrimitiveBuilder` with `capacity` using `allocator`.
55    pub fn with_capacity_in(
56        nullability: Nullability,
57        capacity: usize,
58        allocator: &BufferAllocatorRef,
59    ) -> Self {
60        Self {
61            values: BufferMut::with_capacity_in(capacity, allocator.clone()),
62            nulls: LazyBitBufferBuilder::new(capacity, allocator.clone()),
63            dtype: DType::Primitive(T::PTYPE, nullability),
64        }
65    }
66
67    /// Appends a primitive `value` to the builder.
68    pub fn append_value(&mut self, value: T) {
69        self.values.push(value);
70        self.nulls.append_non_null();
71    }
72
73    /// Appends `n` copies of `value` as non-null entries, directly writing into the buffer.
74    pub fn append_n_values(&mut self, value: T, n: usize) {
75        self.values.push_n(value, n);
76        self.nulls.append_n_non_nulls(n);
77    }
78
79    /// Returns the raw primitive values in this builder as a slice.
80    pub fn values(&self) -> &[T] {
81        self.values.as_ref()
82    }
83
84    /// Returns the raw primitive values in this builder as a mutable slice.
85    pub fn values_mut(&mut self) -> &mut [T] {
86        self.values.as_mut()
87    }
88
89    /// Create a new handle to the next `len` uninitialized values in the builder.
90    ///
91    /// All reads/writes through the handle to the values buffer or the validity buffer will operate
92    /// on indices relative to the start of the range.
93    ///
94    /// # Panics
95    ///
96    /// Panics if `len` is 0 or if the current length of the builder plus `len` would exceed the
97    /// capacity of the builder's memory.
98    ///
99    /// ## Example
100    ///
101    /// ```
102    /// use std::mem::MaybeUninit;
103    /// use vortex_array::builders::{ArrayBuilder, PrimitiveBuilder};
104    /// use vortex_array::dtype::Nullability;
105    /// use vortex_array::memory::BufferAllocatorRef;
106    ///
107    /// // Create a new builder.
108    /// let mut builder: PrimitiveBuilder<i32> =
109    ///     PrimitiveBuilder::with_capacity_in(Nullability::NonNullable, 5, BufferAllocatorRef::static_ref());
110    ///
111    /// // Populate the values.
112    /// let mut uninit_range = builder.uninit_range(5);
113    /// uninit_range.copy_from_slice(0, &[0, 1, 2, 3, 4]);
114    ///
115    /// // SAFETY: We have initialized all 5 values in the range, and since the array builder is
116    /// // non-nullable, we don't need to set any null bits.
117    /// unsafe { uninit_range.finish(); }
118    ///
119    /// let built = builder.finish_into_primitive();
120    ///
121    /// assert_eq!(built.as_slice::<i32>(), &[0i32, 1, 2, 3, 4]);
122    /// ```
123    pub fn uninit_range(&mut self, len: usize) -> UninitRange<'_, T> {
124        assert_ne!(0, len, "cannot create an uninit range of length 0");
125
126        let current_len = self.values.len();
127        assert!(
128            current_len + len <= self.values.capacity(),
129            "uninit_range of len {len} exceeds builder with length {} and capacity {}",
130            current_len,
131            self.values.capacity()
132        );
133
134        UninitRange { len, builder: self }
135    }
136
137    /// Finishes the builder directly into a [`PrimitiveArray`].
138    pub fn finish_into_primitive(&mut self) -> PrimitiveArray {
139        let values = self.values.take().freeze();
140        let validity = self
141            .nulls
142            .finish_with_nullability(self.dtype().nullability());
143
144        assert!(
145            validity.maybe_len().is_none_or(|len| len == values.len()),
146            "validity of length {:?} does not cover the {} values appended",
147            validity.maybe_len(),
148            values.len()
149        );
150
151        // SAFETY: the assert above establishes the only invariant, that an array-backed validity
152        // covers exactly the values appended. The other validities carry no length at all.
153        unsafe { PrimitiveArray::new_unchecked(values, validity) }
154    }
155
156    /// Extends the primitive array with an iterator.
157    pub fn extend_with_iterator(&mut self, iter: impl IntoIterator<Item = T>, mask: &Mask) {
158        self.values.extend(iter);
159        self.nulls.append_validity_mask(mask);
160    }
161
162    pub(crate) fn append_primitive_array(
163        &mut self,
164        array: ArrayView<'_, Primitive>,
165        ctx: &mut ExecutionCtx,
166    ) -> VortexResult<()> {
167        debug_assert_eq!(
168            array.ptype(),
169            T::PTYPE,
170            "Cannot append primitive array with different ptype"
171        );
172
173        self.values.extend_from_slice(array.as_slice::<T>());
174        self.nulls.append_validity_mask(
175            &array
176                .as_ref()
177                .validity()
178                .vortex_expect("validity_mask")
179                .execute_mask(array.as_ref().len(), ctx)?,
180        );
181        Ok(())
182    }
183}
184
185impl<T: NativePType> ArrayBuilder for PrimitiveBuilder<T> {
186    fn as_any(&self) -> &dyn Any {
187        self
188    }
189
190    fn as_any_mut(&mut self) -> &mut dyn Any {
191        self
192    }
193
194    fn dtype(&self) -> &DType {
195        &self.dtype
196    }
197
198    fn len(&self) -> usize {
199        self.values.len()
200    }
201
202    fn append_zeros(&mut self, n: usize) {
203        self.values.push_n(T::default(), n);
204        self.nulls.append_n_non_nulls(n);
205    }
206
207    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
208        self.values.push_n(T::default(), n);
209        self.nulls.append_n_nulls(n);
210    }
211
212    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
213        vortex_ensure_eq!(
214            scalar.dtype(),
215            self.dtype(),
216            "PrimitiveBuilder received a scalar with the wrong dtype"
217        );
218
219        if let Some(pv) = scalar.as_primitive().pvalue() {
220            self.append_value(pv.cast::<T>()?)
221        } else {
222            self.append_null()
223        }
224
225        Ok(())
226    }
227
228    fn reserve_exact(&mut self, additional: usize) {
229        self.values.reserve(additional);
230        self.nulls.reserve_exact(additional);
231    }
232
233    fn finish(&mut self) -> ArrayRef {
234        self.finish_into_primitive().into_array()
235    }
236
237    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
238        Canonical::Primitive(self.finish_into_primitive())
239    }
240}
241
242/// A range of uninitialized values in the primitive builder that can be filled.
243pub struct UninitRange<'a, T> {
244    /// The length of the uninitialized range.
245    ///
246    /// This is guaranteed to be within the memory capacity of the builder.
247    len: usize,
248
249    /// A mutable reference to the builder.
250    ///
251    /// Since this is a mutable reference, we can guarantee that nothing else can modify the builder
252    /// while this `UninitRange` exists.
253    builder: &'a mut PrimitiveBuilder<T>,
254}
255
256impl<T> UninitRange<'_, T> {
257    /// Returns the length of this uninitialized range.
258    #[inline]
259    pub fn len(&self) -> usize {
260        self.len
261    }
262
263    /// Returns true if this range has zero length.
264    #[inline]
265    pub fn is_empty(&self) -> bool {
266        self.len == 0
267    }
268
269    /// Set a value at the given index within this range.
270    ///
271    /// # Panics
272    ///
273    /// Panics if the index is out of bounds.
274    #[inline]
275    pub fn set_value(&mut self, index: usize, value: T) {
276        assert!(index < self.len, "index out of bounds");
277        let spare = self.builder.values.spare_capacity_mut();
278        spare[index] = MaybeUninit::new(value);
279    }
280
281    /// Append a [`Mask`] to this builder's null buffer.
282    ///
283    /// # Panics
284    ///
285    /// Panics if the mask length is not equal to the the length of the current `UninitRange`.
286    ///
287    /// # Safety
288    ///
289    /// - The caller must ensure that they safely initialize `mask.len()` primitive values via
290    ///   [`UninitRange::copy_from_slice`].
291    /// - The caller must also ensure that they only call this method once.
292    pub unsafe fn append_mask(&mut self, mask: &Mask) {
293        assert_eq!(
294            mask.len(),
295            self.len,
296            "Tried to append a mask to an `UninitRange` that was beyond the allowed range"
297        );
298
299        // TODO(connor): Ideally, we would call this function `set_mask` and directly set all of the
300        // bits (so that we can call this multiple times), but the underlying `BooleanBuffer` does
301        // not have an easy way to do this correctly.
302
303        self.builder.nulls.append_validity_mask(mask);
304    }
305
306    /// Set a validity bit at the given index.
307    ///
308    /// The index is relative to the start of this range (not relative to the values already in the
309    /// builder).
310    ///
311    /// Note that this will have no effect if the builder is non-nullable.
312    pub fn set_validity_bit(&mut self, index: usize, v: bool) {
313        assert!(index < self.len, "set_bit index out of bounds");
314        // Note that this won't panic because we can only create an `UninitRange` within the
315        // capacity of the builder (it will not automatically resize).
316        let absolute_index = self.builder.values.len() + index;
317        self.builder.nulls.set_bit(absolute_index, v);
318    }
319
320    /// Set values from an initialized range.
321    ///
322    /// Note that the input `offset` should be an offset relative to the local `UninitRange`, not
323    /// the entire `PrimitiveBuilder`.
324    pub fn copy_from_slice(&mut self, local_offset: usize, src: &[T])
325    where
326        T: Copy,
327    {
328        debug_assert!(
329            local_offset + src.len() <= self.len,
330            "tried to copy a slice into a `UninitRange` past its boundary"
331        );
332
333        // Note: spare_capacity_mut() returns the spare capacity starting from the current length,
334        // so we just use local_offset directly.
335        let dst =
336            &mut self.builder.values.spare_capacity_mut()[local_offset..local_offset + src.len()];
337        dst.write_copy_of_slice(src);
338    }
339
340    /// Get a mutable slice of uninitialized memory at the specified offset within this range.
341    ///
342    /// Note that the offsets are relative to this local range, not to the values already in the
343    /// builder.
344    ///
345    /// # Safety
346    ///
347    /// The caller must ensure that they properly initialize the returned memory before calling
348    /// `finish()` on this range.
349    ///
350    /// # Panics
351    ///
352    /// Panics if `offset + len` exceeds the range bounds.
353    pub unsafe fn slice_uninit_mut(&mut self, offset: usize, len: usize) -> &mut [MaybeUninit<T>] {
354        assert!(
355            offset + len <= self.len,
356            "slice_uninit_mut: offset {} + len {} exceeds range length {}",
357            offset,
358            len,
359            self.len
360        );
361        &mut self.builder.values.spare_capacity_mut()[offset..offset + len]
362    }
363
364    /// Finish building this range, marking it as initialized and advancing the length of the
365    /// underlying values buffer.
366    ///
367    /// # Safety
368    ///
369    /// The caller must ensure that they have safely initialized all `len` values via
370    /// [`copy_from_slice()`] or [`set_value()`], as well as correctly set all of the null bits via
371    /// [`set_validity_bit()`] or [`append_mask()`] if the builder is nullable.
372    ///
373    /// [`copy_from_slice()`]: UninitRange::copy_from_slice
374    /// [`set_value()`]: UninitRange::set_value
375    /// [`set_validity_bit()`]: UninitRange::set_validity_bit
376    /// [`append_mask()`]: UninitRange::append_mask
377    pub unsafe fn finish(self) {
378        // SAFETY: constructor enforces that current length + len does not exceed the capacity of the array.
379        let new_len = self.builder.values.len() + self.len;
380        unsafe { self.builder.values.set_len(new_len) };
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use std::sync::LazyLock;
387
388    use vortex_error::VortexExpect;
389    use vortex_session::VortexSession;
390
391    use super::*;
392    use crate::VortexSessionExecute;
393    use crate::assert_arrays_eq;
394
395    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
396
397    /// REGRESSION TEST: This test verifies that multiple sequential ranges have correct offsets.
398    ///
399    /// This would have caught the `Deref` bug where it always returned from the start of the
400    /// buffer.
401    #[test]
402    fn test_multiple_uninit_ranges_correct_offsets() {
403        let mut ctx = SESSION.create_execution_ctx();
404        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
405            Nullability::NonNullable,
406            10,
407            BufferAllocatorRef::static_ref(),
408        );
409
410        // First range.
411        let mut range1 = builder.uninit_range(3);
412        range1.copy_from_slice(0, &[1, 2, 3]);
413
414        // SAFETY: We initialized all 3 values.
415        unsafe {
416            range1.finish();
417        }
418
419        // Verify the builder now has these values.
420        assert_eq!(builder.values(), &[1, 2, 3]);
421
422        // Second range - this would fail with the old Deref implementation.
423        let mut range2 = builder.uninit_range(2);
424
425        // Set values using copy_from_slice.
426        range2.copy_from_slice(0, &[4, 5]);
427
428        // SAFETY: We initialized both values.
429        unsafe {
430            range2.finish();
431        }
432
433        // Verify the builder now has all 5 values.
434        assert_eq!(builder.values(), &[1, 2, 3, 4, 5]);
435
436        let array = builder.finish_into_primitive();
437        assert_arrays_eq!(
438            array,
439            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5]),
440            &mut ctx
441        );
442    }
443
444    /// REGRESSION TEST: This test verifies that `append_mask` was correctly moved from
445    /// `PrimitiveBuilder` to `UninitRange`.
446    ///
447    /// The old API had `append_mask` on the builder, which was confusing when used with ranges.
448    /// This test ensures the new API works correctly.
449    #[test]
450    fn test_append_mask_on_uninit_range() {
451        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
452            Nullability::Nullable,
453            5,
454            BufferAllocatorRef::static_ref(),
455        );
456        let mut range = builder.uninit_range(3);
457
458        // Create a mask for 3 values.
459        let mask = Mask::from_iter([true, false, true]);
460
461        // SAFETY: We're about to initialize the values.
462        unsafe {
463            range.append_mask(&mask);
464        }
465
466        // Initialize the values.
467        range.copy_from_slice(0, &[10, 20, 30]);
468
469        // SAFETY: We've initialized all values and set the mask.
470        unsafe {
471            range.finish();
472        }
473
474        let array = builder.finish_into_primitive();
475        assert_eq!(array.len(), 3);
476        // Check validity using scalar_at - nulls will return is_null() = true.
477        assert!(
478            !array
479                .execute_scalar(0, &mut SESSION.create_execution_ctx())
480                .unwrap()
481                .is_null()
482        );
483        assert!(
484            array
485                .execute_scalar(1, &mut SESSION.create_execution_ctx())
486                .unwrap()
487                .is_null()
488        );
489        assert!(
490            !array
491                .execute_scalar(2, &mut SESSION.create_execution_ctx())
492                .unwrap()
493                .is_null()
494        );
495        assert_arrays_eq!(
496            array,
497            PrimitiveArray::from_option_iter([Some(10i32), None, Some(30)]),
498            &mut SESSION.create_execution_ctx()
499        );
500    }
501
502    /// REGRESSION TEST: This test verifies that `append_mask` validates the mask length.
503    ///
504    /// This ensures that masks can only be appended if they match the range length.
505    #[test]
506    #[should_panic(
507        expected = "Tried to append a mask to an `UninitRange` that was beyond the allowed range"
508    )]
509    fn test_append_mask_wrong_length_panics() {
510        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
511            Nullability::Nullable,
512            10,
513            BufferAllocatorRef::static_ref(),
514        );
515        let mut range = builder.uninit_range(5);
516
517        // Try to append a mask with wrong length (3 instead of 5).
518        let wrong_mask = Mask::from_iter([true, false, true]);
519
520        // SAFETY: This is expected to panic due to length mismatch.
521        unsafe {
522            range.append_mask(&wrong_mask);
523        }
524    }
525
526    /// Test that `copy_from_slice` works correctly with different offsets.
527    ///
528    /// This verifies the new simplified API without the redundant `len` parameter.
529    #[test]
530    fn test_copy_from_slice_with_offsets() {
531        let mut ctx = SESSION.create_execution_ctx();
532        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
533            Nullability::NonNullable,
534            10,
535            BufferAllocatorRef::static_ref(),
536        );
537        let mut range = builder.uninit_range(6);
538
539        // Copy to different offsets.
540        range.copy_from_slice(0, &[1, 2]);
541        range.copy_from_slice(2, &[3, 4]);
542        range.copy_from_slice(4, &[5, 6]);
543
544        // SAFETY: We've initialized all 6 values.
545        unsafe {
546            range.finish();
547        }
548
549        let array = builder.finish_into_primitive();
550        assert_arrays_eq!(
551            array,
552            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6]),
553            &mut ctx
554        );
555    }
556
557    /// Test that `set_bit` uses relative indexing within the range.
558    ///
559    /// Note: `set_bit` requires the null buffer to already be initialized, so we first
560    /// use `append_mask` to set up the buffer, then demonstrate that `set_bit` can
561    /// modify individual bits with relative indexing.
562    #[test]
563    fn test_set_bit_relative_indexing() {
564        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
565            Nullability::Nullable,
566            10,
567            BufferAllocatorRef::static_ref(),
568        );
569
570        // First add some values to the builder.
571        builder.append_value(100);
572        builder.append_value(200);
573
574        // Create a range for new values.
575        let mut range = builder.uninit_range(3);
576
577        // Use append_mask to initialize the validity buffer for this range.
578        let initial_mask = Mask::from_iter([false, false, false]);
579        // SAFETY: We're about to initialize the values.
580        unsafe {
581            range.append_mask(&initial_mask);
582        }
583
584        // Now we can use set_bit to modify individual bits with relative indexing.
585        range.set_validity_bit(0, true); // Change first bit to valid
586        range.set_validity_bit(2, true); // Change third bit to valid
587        // Leave middle bit as false (null)
588
589        // Initialize the values.
590        range.copy_from_slice(0, &[10, 20, 30]);
591
592        // SAFETY: We've initialized all 3 values and set their validity.
593        unsafe {
594            range.finish();
595        }
596
597        let array = builder.finish_into_primitive();
598
599        // Verify the total length and values.
600        assert_eq!(array.len(), 5);
601        assert_eq!(array.as_slice::<i32>(), &[100, 200, 10, 20, 30]);
602
603        // Check validity - the first two should be valid (from append_value).
604        assert!(
605            !array
606                .execute_scalar(0, &mut SESSION.create_execution_ctx())
607                .unwrap()
608                .is_null()
609        ); // initial value 100
610        assert!(
611            !array
612                .execute_scalar(1, &mut SESSION.create_execution_ctx())
613                .unwrap()
614                .is_null()
615        ); // initial value 200
616
617        // Check the range items with modified validity.
618        assert!(
619            !array
620                .execute_scalar(2, &mut SESSION.create_execution_ctx())
621                .unwrap()
622                .is_null()
623        ); // range index 0 - set to valid
624        assert!(
625            array
626                .execute_scalar(3, &mut SESSION.create_execution_ctx())
627                .unwrap()
628                .is_null()
629        ); // range index 1 - left as null
630        assert!(
631            !array
632                .execute_scalar(4, &mut SESSION.create_execution_ctx())
633                .unwrap()
634                .is_null()
635        ); // range index 2 - set to valid
636    }
637
638    /// Test that creating a zero-length uninit range panics.
639    #[test]
640    #[should_panic(expected = "cannot create an uninit range of length 0")]
641    fn test_zero_length_uninit_range_panics() {
642        let mut builder = PrimitiveBuilder::<i32>::new_in(
643            Nullability::NonNullable,
644            BufferAllocatorRef::static_ref(),
645        );
646        let _range = builder.uninit_range(0);
647    }
648
649    /// Test that creating an uninit range exceeding capacity panics.
650    #[test]
651    #[should_panic(expected = "uninit_range of len 261 exceeds builder with length 0 and capacity")]
652    fn test_uninit_range_exceeds_capacity_panics() {
653        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
654            Nullability::NonNullable,
655            5,
656            BufferAllocatorRef::static_ref(),
657        );
658        let _range = builder.uninit_range(261);
659    }
660
661    /// Test that `copy_from_slice` debug asserts on out-of-bounds access.
662    ///
663    /// Note: This only panics in debug mode due to `debug_assert!`.
664    #[test]
665    #[cfg(debug_assertions)]
666    #[should_panic(expected = "tried to copy a slice into a `UninitRange` past its boundary")]
667    fn test_copy_from_slice_out_of_bounds() {
668        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
669            Nullability::NonNullable,
670            10,
671            BufferAllocatorRef::static_ref(),
672        );
673        let mut range = builder.uninit_range(3);
674
675        // Try to copy 3 elements starting at offset 1 (would need 4 slots total).
676        range.copy_from_slice(1, &[1, 2, 3]);
677    }
678
679    /// Test that the unsafe contract of `finish` is documented and works correctly.
680    ///
681    /// This test demonstrates proper usage of the unsafe `finish` method.
682    #[test]
683    fn test_finish_unsafe_contract() {
684        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
685            Nullability::Nullable,
686            5,
687            BufferAllocatorRef::static_ref(),
688        );
689        let mut range = builder.uninit_range(3);
690
691        // Set validity mask.
692        let mask = Mask::from_iter([true, true, false]);
693        // SAFETY: We're about to initialize the matching number of values.
694        unsafe {
695            range.append_mask(&mask);
696        }
697
698        // Initialize all values.
699        range.copy_from_slice(0, &[10, 20, 30]);
700
701        // SAFETY: We have initialized all 3 values and set their validity.
702        unsafe {
703            range.finish();
704        }
705
706        let array = builder.finish_into_primitive();
707        assert_eq!(array.len(), 3);
708        assert_eq!(array.as_slice::<i32>(), &[10, 20, 30]);
709        assert_arrays_eq!(
710            array,
711            PrimitiveArray::from_option_iter([Some(10i32), Some(20), None]),
712            &mut SESSION.create_execution_ctx()
713        );
714    }
715
716    #[test]
717    fn test_append_scalar() {
718        use crate::dtype::DType;
719        use crate::scalar::Scalar;
720
721        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
722            Nullability::Nullable,
723            10,
724            BufferAllocatorRef::static_ref(),
725        );
726
727        // Test appending a valid primitive value.
728        let scalar1 = Scalar::primitive(42i32, Nullability::Nullable);
729        builder.append_scalar(&scalar1).unwrap();
730
731        // Test appending another value.
732        let scalar2 = Scalar::primitive(84i32, Nullability::Nullable);
733        builder.append_scalar(&scalar2).unwrap();
734
735        // Test appending null value.
736        let null_scalar = Scalar::null(DType::Primitive(
737            crate::dtype::PType::I32,
738            Nullability::Nullable,
739        ));
740        builder.append_scalar(&null_scalar).unwrap();
741
742        let array = builder.finish_into_primitive();
743        assert_eq!(array.len(), 3);
744
745        // Check actual values.
746        let values = array.as_slice::<i32>();
747        assert_eq!(values[0], 42);
748        assert_eq!(values[1], 84);
749        // values[2] might be any value since it's null.
750
751        // Check validity - first two should be valid, third should be null.
752        let mut ctx = SESSION.create_execution_ctx();
753        assert!(
754            array
755                .validity()
756                .vortex_expect("primitive validity should be derivable")
757                .execute_is_valid(0, &mut ctx)
758                .unwrap()
759        );
760        assert!(
761            array
762                .validity()
763                .vortex_expect("primitive validity should be derivable")
764                .execute_is_valid(1, &mut ctx)
765                .unwrap()
766        );
767        assert!(
768            !array
769                .validity()
770                .vortex_expect("primitive validity should be derivable")
771                .execute_is_valid(2, &mut ctx)
772                .unwrap()
773        );
774
775        // Test wrong dtype error.
776        let mut builder = PrimitiveBuilder::<i32>::with_capacity_in(
777            Nullability::NonNullable,
778            10,
779            BufferAllocatorRef::static_ref(),
780        );
781        let wrong_scalar = Scalar::from(true);
782        assert!(builder.append_scalar(&wrong_scalar).is_err());
783    }
784}