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