1use 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
29pub struct PrimitiveBuilder<T> {
31 dtype: DType,
32 values: BufferMut<T>,
33 nulls: LazyBitBufferBuilder,
34}
35
36impl<T: NativePType> PrimitiveBuilder<T> {
37 #[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 pub fn new_in(nullability: Nullability, allocator: &BufferAllocatorRef) -> Self {
45 Self::with_capacity_in(nullability, DEFAULT_BUILDER_CAPACITY, allocator)
46 }
47
48 #[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 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 pub fn append_value(&mut self, value: T) {
69 self.values.push(value);
70 self.nulls.append_non_null();
71 }
72
73 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 pub fn values(&self) -> &[T] {
81 self.values.as_ref()
82 }
83
84 pub fn values_mut(&mut self) -> &mut [T] {
86 self.values.as_mut()
87 }
88
89 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 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 unsafe { PrimitiveArray::new_unchecked(values, validity) }
154 }
155
156 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
242pub struct UninitRange<'a, T> {
244 len: usize,
248
249 builder: &'a mut PrimitiveBuilder<T>,
254}
255
256impl<T> UninitRange<'_, T> {
257 #[inline]
259 pub fn len(&self) -> usize {
260 self.len
261 }
262
263 #[inline]
265 pub fn is_empty(&self) -> bool {
266 self.len == 0
267 }
268
269 #[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 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 self.builder.nulls.append_validity_mask(mask);
304 }
305
306 pub fn set_validity_bit(&mut self, index: usize, v: bool) {
313 assert!(index < self.len, "set_bit index out of bounds");
314 let absolute_index = self.builder.values.len() + index;
317 self.builder.nulls.set_bit(absolute_index, v);
318 }
319
320 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 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 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 pub unsafe fn finish(self) {
378 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 #[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 let mut range1 = builder.uninit_range(3);
412 range1.copy_from_slice(0, &[1, 2, 3]);
413
414 unsafe {
416 range1.finish();
417 }
418
419 assert_eq!(builder.values(), &[1, 2, 3]);
421
422 let mut range2 = builder.uninit_range(2);
424
425 range2.copy_from_slice(0, &[4, 5]);
427
428 unsafe {
430 range2.finish();
431 }
432
433 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 #[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 let mask = Mask::from_iter([true, false, true]);
460
461 unsafe {
463 range.append_mask(&mask);
464 }
465
466 range.copy_from_slice(0, &[10, 20, 30]);
468
469 unsafe {
471 range.finish();
472 }
473
474 let array = builder.finish_into_primitive();
475 assert_eq!(array.len(), 3);
476 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 #[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 let wrong_mask = Mask::from_iter([true, false, true]);
519
520 unsafe {
522 range.append_mask(&wrong_mask);
523 }
524 }
525
526 #[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 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 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]
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 builder.append_value(100);
572 builder.append_value(200);
573
574 let mut range = builder.uninit_range(3);
576
577 let initial_mask = Mask::from_iter([false, false, false]);
579 unsafe {
581 range.append_mask(&initial_mask);
582 }
583
584 range.set_validity_bit(0, true); range.set_validity_bit(2, true); range.copy_from_slice(0, &[10, 20, 30]);
591
592 unsafe {
594 range.finish();
595 }
596
597 let array = builder.finish_into_primitive();
598
599 assert_eq!(array.len(), 5);
601 assert_eq!(array.as_slice::<i32>(), &[100, 200, 10, 20, 30]);
602
603 assert!(
605 !array
606 .execute_scalar(0, &mut SESSION.create_execution_ctx())
607 .unwrap()
608 .is_null()
609 ); assert!(
611 !array
612 .execute_scalar(1, &mut SESSION.create_execution_ctx())
613 .unwrap()
614 .is_null()
615 ); assert!(
619 !array
620 .execute_scalar(2, &mut SESSION.create_execution_ctx())
621 .unwrap()
622 .is_null()
623 ); assert!(
625 array
626 .execute_scalar(3, &mut SESSION.create_execution_ctx())
627 .unwrap()
628 .is_null()
629 ); assert!(
631 !array
632 .execute_scalar(4, &mut SESSION.create_execution_ctx())
633 .unwrap()
634 .is_null()
635 ); }
637
638 #[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]
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]
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 range.copy_from_slice(1, &[1, 2, 3]);
677 }
678
679 #[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 let mask = Mask::from_iter([true, true, false]);
693 unsafe {
695 range.append_mask(&mask);
696 }
697
698 range.copy_from_slice(0, &[10, 20, 30]);
700
701 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 let scalar1 = Scalar::primitive(42i32, Nullability::Nullable);
729 builder.append_scalar(&scalar1).unwrap();
730
731 let scalar2 = Scalar::primitive(84i32, Nullability::Nullable);
733 builder.append_scalar(&scalar2).unwrap();
734
735 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 let values = array.as_slice::<i32>();
747 assert_eq!(values[0], 42);
748 assert_eq!(values[1], 84);
749 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 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}