Skip to main content

vortex_array/builders/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Builders for Vortex arrays.
5//!
6//! Every logical type in Vortex has a canonical (uncompressed) in-memory encoding. This module
7//! provides pre-allocated builders to construct new canonical arrays.
8//!
9//! Canonical form is not recursive, and neither are these builders: appending an array to a nested
10//! builder keeps the child in the encoding it arrived in instead of decoding it. The fields of a
11//! [`StructArray`](crate::arrays::StructArray), the elements of a list, and the storage of an
12//! [`ExtensionArray`](crate::arrays::ExtensionArray) may therefore come back compressed, or as a
13//! [`ChunkedArray`](crate::arrays::ChunkedArray) when several arrays were appended in turn.
14//!
15//! ## Example:
16//!
17//! ```
18//! use vortex_array::builders::{ArrayBuilder, builder_with_capacity_in};
19//! use vortex_array::dtype::{DType, Nullability};
20//! use vortex_array::memory::BufferAllocatorRef;
21//! use vortex_array::{VortexSessionExecute};
22//! use vortex_session::VortexSession;
23//!
24//! // Create a new builder for string data.
25//! let mut builder = builder_with_capacity_in(&DType::Utf8(Nullability::NonNullable), 4, BufferAllocatorRef::static_ref());
26//!
27//! builder.append_scalar(&"a".into()).unwrap();
28//! builder.append_scalar(&"b".into()).unwrap();
29//! builder.append_scalar(&"c".into()).unwrap();
30//! builder.append_scalar(&"d".into()).unwrap();
31//!
32//! let strings = builder.finish();
33//! let mut ctx = VortexSession::empty().create_execution_ctx();
34//!
35//! assert_eq!(strings.execute_scalar(0, &mut ctx).unwrap(), "a".into());
36//! assert_eq!(strings.execute_scalar(1, &mut ctx).unwrap(), "b".into());
37//! assert_eq!(strings.execute_scalar(2, &mut ctx).unwrap(), "c".into());
38//! assert_eq!(strings.execute_scalar(3, &mut ctx).unwrap(), "d".into());
39//! ```
40
41use std::any::Any;
42use std::sync::Arc;
43
44use vortex_error::VortexResult;
45use vortex_error::vortex_panic;
46
47use crate::ArrayRef;
48use crate::ExecutionCtx;
49use crate::canonical::Canonical;
50use crate::dtype::DType;
51use crate::match_each_native_ptype;
52use crate::memory::BufferAllocatorRef;
53use crate::scalar::Scalar;
54
55mod lazy_null_builder;
56pub use lazy_null_builder::LazyBitBufferBuilder;
57
58mod bool;
59mod child;
60mod decimal;
61pub mod dict;
62mod extension;
63mod fixed_size_list;
64mod list;
65mod listview;
66mod map;
67mod null;
68mod primitive;
69mod struct_;
70mod validity;
71mod varbinview;
72mod variant;
73
74pub use bool::*;
75pub(crate) use child::ChildBuilder;
76pub use decimal::*;
77pub use extension::*;
78pub use fixed_size_list::*;
79pub use list::*;
80pub use listview::*;
81pub use map::*;
82pub use null::*;
83pub use primitive::*;
84pub use struct_::*;
85pub(crate) use validity::ValidityBuilder;
86pub use varbinview::*;
87pub use variant::*;
88
89pub use crate::arrays::varbin::builder::VarBinBuilder;
90
91#[cfg(test)]
92mod tests;
93
94/// The default capacity for builders.
95///
96/// This is equal to the default capacity for Arrow Arrays.
97pub const DEFAULT_BUILDER_CAPACITY: usize = 1024;
98
99pub trait ArrayBuilder: Send {
100    fn as_any(&self) -> &dyn Any;
101
102    fn as_any_mut(&mut self) -> &mut dyn Any;
103
104    fn dtype(&self) -> &DType;
105
106    fn len(&self) -> usize;
107
108    fn is_empty(&self) -> bool {
109        self.len() == 0
110    }
111
112    /// Append a "zero" value to the array.
113    ///
114    /// Zero values are generally determined by [`Scalar::default_value`].
115    fn append_zero(&mut self) {
116        self.append_zeros(1)
117    }
118
119    /// Appends n "zero" values to the array.
120    ///
121    /// Zero values are generally determined by [`Scalar::default_value`].
122    fn append_zeros(&mut self, n: usize);
123
124    /// Append a "null" value to the array.
125    ///
126    /// Implementors should panic if this method is called on a non-nullable [`ArrayBuilder`].
127    fn append_null(&mut self) {
128        self.append_nulls(1)
129    }
130
131    /// The inner part of `append_nulls`.
132    ///
133    /// # Safety
134    ///
135    /// The array builder must be nullable.
136    unsafe fn append_nulls_unchecked(&mut self, n: usize);
137
138    /// Appends n "null" values to the array.
139    ///
140    /// Implementors should panic if this method is called on a non-nullable [`ArrayBuilder`].
141    fn append_nulls(&mut self, n: usize) {
142        assert!(
143            self.dtype().is_nullable(),
144            "tried to append {n} nulls to a non-nullable array builder"
145        );
146
147        // SAFETY: We check above that the array builder is nullable.
148        unsafe {
149            self.append_nulls_unchecked(n);
150        }
151    }
152
153    /// Appends a default value to the array.
154    fn append_default(&mut self) {
155        self.append_defaults(1)
156    }
157
158    /// Appends n default values to the array.
159    ///
160    /// If the array builder is nullable, then this has the behavior of `self.append_nulls(n)`.
161    /// If the array builder is non-nullable, then it has the behavior of `self.append_zeros(n)`.
162    fn append_defaults(&mut self, n: usize) {
163        if self.dtype().is_nullable() {
164            self.append_nulls(n);
165        } else {
166            self.append_zeros(n);
167        }
168    }
169
170    /// A generic function to append a scalar to the builder.
171    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()>;
172
173    /// Allocate space for extra `additional` items
174    fn reserve_exact(&mut self, additional: usize);
175
176    /// Reserves room for `additional` more appended arrays.
177    ///
178    /// A nested builder keeps an appended array as a chunk of its child rather than copying its
179    /// values, so a caller that is about to append many arrays in a row - canonicalizing a
180    /// [`ChunkedArray`](crate::arrays::ChunkedArray), say - can say how many are coming and spare
181    /// the chunk lists their incremental growth. Builders without children have no chunk list and
182    /// ignore this.
183    fn reserve_chunks(&mut self, additional: usize) {
184        let _ = additional;
185    }
186
187    /// Constructs an Array from the builder components.
188    ///
189    /// The returned array is canonical at the top level only; its children keep whatever encoding
190    /// they were appended with.
191    ///
192    /// # Panics
193    ///
194    /// This function may panic if the builder's methods are called with invalid arguments. If only
195    /// the methods on this interface are used, the builder should not panic. However, specific
196    /// builders have interfaces that may be misused. For example, if the number of values in a
197    /// [PrimitiveBuilder]'s [vortex_buffer::BufferMut] does not match the number of validity bits,
198    /// the PrimitiveBuilder's [Self::finish] will panic.
199    fn finish(&mut self) -> ArrayRef;
200
201    /// Constructs a canonical array directly from the builder.
202    ///
203    /// This method provides a default implementation that creates an [`ArrayRef`] via `finish` and
204    /// then converts it to canonical form. Specific builders can override this with optimized
205    /// implementations that avoid the intermediate [`ArrayRef`] creation.
206    fn finish_into_canonical(&mut self, ctx: &mut ExecutionCtx) -> Canonical;
207}
208
209/// Matches a `&mut dyn ArrayBuilder` against every concrete list builder type, i.e. every
210/// [`ListBuilder`]`<O>` and [`ListViewBuilder`]`<O, S>` instantiation over the
211/// [`OffsetBuilderPType`](crate::dtype::OffsetBuilderPType) offset/size types (`u32`, `u64`, `i32`,
212/// `i64`).
213///
214/// Binds the downcast builder as `$builder` and evaluates `$body` with it, yielding
215/// `Some($body)`; yields `None` when the builder is not a list builder. List encodings dispatch
216/// through this matcher because the concrete list builders are generic over their offset/size
217/// integer types, which cannot be named through a `dyn ArrayBuilder`. The matcher is exhaustive
218/// because `OffsetBuilderPType` is sealed, so no other instantiations can be constructed.
219#[macro_export]
220macro_rules! match_each_list_builder {
221    ($dyn_builder:expr, | $builder:ident | $body:expr) => {{
222        let __dyn_builder: &mut dyn $crate::builders::ArrayBuilder = $dyn_builder;
223        match $crate::__match_each_list_builder!(
224            __dyn_builder,
225            $builder,
226            $body,
227            [u32, u64, i32, i64]
228        ) {
229            ::core::option::Option::Some(__result) => ::core::option::Option::Some(__result),
230            ::core::option::Option::None => $crate::__match_each_listview_builder!(
231                __dyn_builder,
232                $builder,
233                $body,
234                [u32, u64, i32, i64]
235            ),
236        }
237    }};
238}
239
240/// Matches a `&mut dyn ArrayBuilder` against every concrete [`ListViewBuilder`]`<O, S>`
241/// instantiation over the [`OffsetBuilderPType`](crate::dtype::OffsetBuilderPType) offset/size
242/// types (`u32`, `u64`, `i32`, `i64`), and only those.
243///
244/// Binds the downcast builder as `$builder` and evaluates `$body` with it, yielding
245/// `Some($body)`; yields `None` when the builder is not a list-view builder - including when it
246/// is a [`ListBuilder`]. Callers reach for this instead of
247/// [`match_each_list_builder!`](crate::match_each_list_builder) when the body needs methods only
248/// a list-view builder has, such as
249/// [`append_array_as_repeated_list`](ListViewBuilder::append_array_as_repeated_list).
250#[macro_export]
251macro_rules! match_each_listview_builder {
252    ($dyn_builder:expr, | $builder:ident | $body:expr) => {{
253        let __dyn_builder: &mut dyn $crate::builders::ArrayBuilder = $dyn_builder;
254        $crate::__match_each_listview_builder!(__dyn_builder, $builder, $body, [u32, u64, i32, i64])
255    }};
256}
257
258#[doc(hidden)]
259#[macro_export]
260macro_rules! __match_each_list_builder {
261    ($target:ident, $builder:ident, $body:expr, []) => {
262        ::core::option::Option::None
263    };
264    ($target:ident, $builder:ident, $body:expr, [$offset:ty $(, $rest:ty)*]) => {
265        if let ::core::option::Option::Some($builder) =
266            $crate::builders::ArrayBuilder::as_any_mut($target)
267                .downcast_mut::<$crate::builders::ListBuilder<$offset>>()
268        {
269            ::core::option::Option::Some($body)
270        } else {
271            $crate::__match_each_list_builder!($target, $builder, $body, [$($rest),*])
272        }
273    };
274}
275
276#[doc(hidden)]
277#[macro_export]
278macro_rules! __match_each_listview_builder {
279    ($target:ident, $builder:ident, $body:expr, []) => {
280        ::core::option::Option::None
281    };
282    ($target:ident, $builder:ident, $body:expr, [$offset:ty $(, $rest:ty)*]) => {
283        match $crate::__match_each_listview_builder_size!(
284            $target,
285            $builder,
286            $body,
287            $offset,
288            [u32, u64, i32, i64]
289        ) {
290            ::core::option::Option::Some(__result) => ::core::option::Option::Some(__result),
291            ::core::option::Option::None => $crate::__match_each_listview_builder!(
292                $target,
293                $builder,
294                $body,
295                [$($rest),*]
296            ),
297        }
298    };
299}
300
301#[doc(hidden)]
302#[macro_export]
303macro_rules! __match_each_listview_builder_size {
304    ($target:ident, $builder:ident, $body:expr, $offset:ty, []) => {
305        ::core::option::Option::None
306    };
307    ($target:ident, $builder:ident, $body:expr, $offset:ty, [$size:ty $(, $rest:ty)*]) => {
308        if let ::core::option::Option::Some($builder) =
309            $crate::builders::ArrayBuilder::as_any_mut($target)
310                .downcast_mut::<$crate::builders::ListViewBuilder<$offset, $size>>()
311        {
312            ::core::option::Option::Some($body)
313        } else {
314            $crate::__match_each_listview_builder_size!(
315                $target, $builder, $body, $offset, [$($rest),*]
316            )
317        }
318    };
319}
320
321/// Matches a `&mut dyn ArrayBuilder` against every concrete map builder type.
322///
323/// Binds the downcast builder as `$builder` and evaluates `$body` with it, yielding
324/// `Some($body)`; yields `None` when the builder is not a map builder.
325#[macro_export]
326macro_rules! match_each_map_builder {
327    ($dyn_builder:expr, | $builder:ident | $body:expr) => {{
328        let __dyn_builder: &mut dyn $crate::builders::ArrayBuilder = $dyn_builder;
329        $crate::__match_each_map_builder!(__dyn_builder, $builder, $body, [u32, u64, i32, i64])
330    }};
331}
332
333#[doc(hidden)]
334#[macro_export]
335macro_rules! __match_each_map_builder {
336    ($target:ident, $builder:ident, $body:expr, []) => {
337        ::core::option::Option::None
338    };
339    ($target:ident, $builder:ident, $body:expr, [$offset:ty $(, $rest:ty)*]) => {
340        match $crate::__match_each_map_builder_size!(
341            $target,
342            $builder,
343            $body,
344            $offset,
345            [u32, u64, i32, i64]
346        ) {
347            ::core::option::Option::Some(__result) => ::core::option::Option::Some(__result),
348            ::core::option::Option::None => $crate::__match_each_map_builder!(
349                $target,
350                $builder,
351                $body,
352                [$($rest),*]
353            ),
354        }
355    };
356}
357
358#[doc(hidden)]
359#[macro_export]
360macro_rules! __match_each_map_builder_size {
361    ($target:ident, $builder:ident, $body:expr, $offset:ty, []) => {
362        ::core::option::Option::None
363    };
364    ($target:ident, $builder:ident, $body:expr, $offset:ty, [$size:ty $(, $rest:ty)*]) => {
365        if let ::core::option::Option::Some($builder) =
366            $crate::builders::ArrayBuilder::as_any_mut($target)
367                .downcast_mut::<$crate::builders::MapBuilder<$offset, $size>>()
368        {
369            ::core::option::Option::Some($body)
370        } else {
371            $crate::__match_each_map_builder_size!(
372                $target, $builder, $body, $offset, [$($rest),*]
373            )
374        }
375    };
376}
377
378/// Construct a new canonical builder for the given [`DType`].
379#[deprecated(note = "use `builder_with_capacity_in` with an explicit allocator")]
380pub fn builder_with_capacity(dtype: &DType, capacity: usize) -> Box<dyn ArrayBuilder> {
381    builder_with_capacity_in(dtype, capacity, BufferAllocatorRef::static_ref())
382}
383
384/// Construct a new canonical builder using `allocator`.
385///
386/// # Example
387///
388/// ```
389/// use vortex_array::builders::{ArrayBuilder, builder_with_capacity_in};
390/// use vortex_array::dtype::{DType, Nullability};
391/// use vortex_array::memory::BufferAllocatorRef;
392/// use vortex_array::{VortexSessionExecute};
393/// use vortex_session::VortexSession;
394///
395/// // Create a new builder for string data.
396/// let mut builder = builder_with_capacity_in(&DType::Utf8(Nullability::NonNullable), 4, BufferAllocatorRef::static_ref());
397///
398/// builder.append_scalar(&"a".into()).unwrap();
399/// builder.append_scalar(&"b".into()).unwrap();
400/// builder.append_scalar(&"c".into()).unwrap();
401/// builder.append_scalar(&"d".into()).unwrap();
402///
403/// let strings = builder.finish();
404/// let mut ctx = VortexSession::empty().create_execution_ctx();
405///
406/// assert_eq!(strings.execute_scalar(0, &mut ctx).unwrap(), "a".into());
407/// assert_eq!(strings.execute_scalar(1, &mut ctx).unwrap(), "b".into());
408/// assert_eq!(strings.execute_scalar(2, &mut ctx).unwrap(), "c".into());
409/// assert_eq!(strings.execute_scalar(3, &mut ctx).unwrap(), "d".into());
410/// ```
411pub fn builder_with_capacity_in(
412    dtype: &DType,
413    capacity: usize,
414    allocator: &BufferAllocatorRef,
415) -> Box<dyn ArrayBuilder> {
416    match dtype {
417        DType::Null => Box::new(NullBuilder::new()),
418        DType::Bool(n) => Box::new(BoolBuilder::with_capacity_in(*n, capacity, allocator)),
419        DType::Primitive(ptype, n) => {
420            match_each_native_ptype!(ptype, |P| {
421                Box::new(PrimitiveBuilder::<P>::with_capacity_in(
422                    *n, capacity, allocator,
423                ))
424            })
425        }
426        DType::Decimal(decimal_type, n) => Box::new(DecimalBuilder::with_capacity_in(
427            capacity,
428            *decimal_type,
429            *n,
430            allocator,
431        )),
432        DType::Utf8(n) => Box::new(VarBinViewBuilder::with_capacity_in(
433            DType::Utf8(*n),
434            capacity,
435            allocator.clone(),
436        )),
437        DType::Binary(n) => Box::new(VarBinViewBuilder::with_capacity_in(
438            DType::Binary(*n),
439            capacity,
440            allocator.clone(),
441        )),
442        DType::List(dtype, n) => Box::new(ListViewBuilder::<u64, u64>::with_capacity_in(
443            Arc::clone(dtype),
444            *n,
445            capacity,
446            allocator,
447        )),
448        DType::Map(map_dtype, nullability) => Box::new(MapBuilder::<u64, u64>::with_capacity_in(
449            map_dtype.clone(),
450            *nullability,
451            capacity,
452            allocator,
453        )),
454        DType::FixedSizeList(elem_dtype, list_size, null) => {
455            Box::new(FixedSizeListBuilder::with_capacity_in(
456                Arc::clone(elem_dtype),
457                *list_size,
458                *null,
459                capacity,
460                allocator,
461            ))
462        }
463        DType::Struct(struct_dtype, n) => Box::new(StructBuilder::with_capacity_in(
464            struct_dtype.clone(),
465            *n,
466            capacity,
467            allocator,
468        )),
469        DType::Union(..) => vortex_panic!("TODO(connor)[Union]: unimplemented"),
470        DType::Variant(n) => Box::new(VariantBuilder::new(*n)),
471        DType::Extension(ext_dtype) => Box::new(ExtensionBuilder::with_capacity_in(
472            ext_dtype.clone(),
473            capacity,
474            allocator,
475        )),
476    }
477}