Skip to main content

vortex_array/builders/
extension.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use vortex_buffer::BufferAllocatorRef;
7use vortex_error::VortexResult;
8use vortex_error::vortex_ensure_eq;
9
10use crate::ArrayRef;
11use crate::ExecutionCtx;
12use crate::IntoArray;
13use crate::array::ArrayView;
14use crate::arrays::Extension;
15use crate::arrays::ExtensionArray;
16use crate::arrays::extension::ExtensionArrayExt;
17use crate::builders::ArrayBuilder;
18use crate::builders::ChildBuilder;
19use crate::builders::DEFAULT_BUILDER_CAPACITY;
20use crate::canonical::Canonical;
21use crate::dtype::DType;
22use crate::dtype::extension::ExtDTypeRef;
23use crate::scalar::ExtScalar;
24use crate::scalar::Scalar;
25
26/// The builder for building a [`ExtensionArray`].
27pub struct ExtensionBuilder {
28    dtype: DType,
29    storage: ChildBuilder,
30}
31
32impl ExtensionBuilder {
33    /// Creates a new `ExtensionBuilder` with a capacity of [`DEFAULT_BUILDER_CAPACITY`].
34    #[deprecated(note = "use `new_in` with an explicit allocator")]
35    pub fn new(ext_dtype: ExtDTypeRef) -> Self {
36        Self::new_in(ext_dtype, BufferAllocatorRef::static_ref())
37    }
38
39    /// Creates a new `ExtensionBuilder` with the default capacity using `allocator`.
40    pub fn new_in(ext_dtype: ExtDTypeRef, allocator: &BufferAllocatorRef) -> Self {
41        Self::with_capacity_in(ext_dtype, DEFAULT_BUILDER_CAPACITY, allocator)
42    }
43
44    /// Creates a new `ExtensionBuilder` with the given `capacity`.
45    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
46    pub fn with_capacity(ext_dtype: ExtDTypeRef, capacity: usize) -> Self {
47        Self::with_capacity_in(ext_dtype, capacity, BufferAllocatorRef::static_ref())
48    }
49
50    /// Creates a new `ExtensionBuilder` with `capacity` using `allocator`.
51    pub fn with_capacity_in(
52        ext_dtype: ExtDTypeRef,
53        capacity: usize,
54        allocator: &BufferAllocatorRef,
55    ) -> Self {
56        Self {
57            storage: ChildBuilder::with_capacity(ext_dtype.storage_dtype(), capacity, allocator),
58            dtype: DType::Extension(ext_dtype),
59        }
60    }
61
62    /// Appends an extension `value` to the builder.
63    pub fn append_value(&mut self, value: ExtScalar) -> VortexResult<()> {
64        self.storage.append_scalar(&value.to_storage_scalar())
65    }
66
67    /// Appends the values of a canonical [`ExtensionArray`] to the builder by appending its
68    /// storage array to the underlying storage builder.
69    pub(crate) fn append_extension_array(
70        &mut self,
71        array: ArrayView<'_, Extension>,
72        ctx: &mut ExecutionCtx,
73    ) -> VortexResult<()> {
74        self.storage.append_array(array.storage_array(), ctx)
75    }
76
77    /// Finishes the builder directly into a [`ExtensionArray`].
78    pub fn finish_into_extension(&mut self) -> ExtensionArray {
79        let storage = self.storage.finish();
80        // SAFETY: the storage child builder was created with this extension dtype's storage dtype
81        // and rejects an appended array of any other dtype.
82        unsafe { ExtensionArray::new_unchecked(self.ext_dtype(), storage) }
83    }
84
85    /// The [`ExtDType`] of this builder.
86    ///
87    /// [`ExtDType`]: crate::dtype::extension::ExtDType
88    fn ext_dtype(&self) -> ExtDTypeRef {
89        if let DType::Extension(ext_dtype) = &self.dtype {
90            ext_dtype.clone()
91        } else {
92            unreachable!()
93        }
94    }
95}
96
97impl ArrayBuilder for ExtensionBuilder {
98    fn as_any(&self) -> &dyn Any {
99        self
100    }
101
102    fn as_any_mut(&mut self) -> &mut dyn Any {
103        self
104    }
105
106    fn dtype(&self) -> &DType {
107        &self.dtype
108    }
109
110    fn len(&self) -> usize {
111        self.storage.len()
112    }
113
114    fn append_zeros(&mut self, n: usize) {
115        self.storage.append_zeros(n)
116    }
117
118    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
119        self.storage.append_nulls(n)
120    }
121
122    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
123        vortex_ensure_eq!(
124            scalar.dtype(),
125            self.dtype(),
126            "ExtensionBuilder received a scalar with the wrong dtype"
127        );
128
129        self.append_value(scalar.as_extension())
130    }
131
132    fn reserve_chunks(&mut self, additional: usize) {
133        self.storage.reserve_chunks(additional)
134    }
135
136    fn reserve_exact(&mut self, capacity: usize) {
137        self.storage.reserve_exact(capacity)
138    }
139
140    fn finish(&mut self) -> ArrayRef {
141        self.finish_into_extension().into_array()
142    }
143
144    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
145        Canonical::Extension(self.finish_into_extension())
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use std::sync::LazyLock;
152
153    use vortex_session::VortexSession;
154
155    use super::*;
156    use crate::VortexSessionExecute;
157    use crate::arrays::PrimitiveArray;
158    use crate::assert_arrays_eq;
159    use crate::builders::ArrayBuilder;
160    use crate::dtype::Nullability;
161    use crate::extension::datetime::Date;
162    use crate::extension::datetime::TimeUnit;
163    use crate::scalar::Scalar;
164
165    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
166
167    #[test]
168    fn test_append_scalar() {
169        let mut ctx = SESSION.create_execution_ctx();
170        let ext_dtype = Date::new(TimeUnit::Days, Nullability::Nullable).erased();
171
172        let mut builder =
173            ExtensionBuilder::new_in(ext_dtype.clone(), BufferAllocatorRef::static_ref());
174
175        // Test appending a valid extension value.
176        let storage1 = Scalar::from(Some(42i32));
177        let ext_scalar1 = Scalar::extension::<Date>(TimeUnit::Days, storage1);
178        builder.append_scalar(&ext_scalar1).unwrap();
179
180        // Test appending another value.
181        let storage2 = Scalar::from(Some(84i32));
182        let ext_scalar2 = Scalar::extension::<Date>(TimeUnit::Days, storage2);
183        builder.append_scalar(&ext_scalar2).unwrap();
184
185        // Test appending null value.
186        let null_storage = Scalar::null(DType::Primitive(
187            crate::dtype::PType::I32,
188            Nullability::Nullable,
189        ));
190        let null_scalar = Scalar::extension::<Date>(TimeUnit::Days, null_storage);
191        builder.append_scalar(&null_scalar).unwrap();
192
193        let array = builder.finish_into_extension();
194        let expected = ExtensionArray::new(
195            ext_dtype.clone(),
196            PrimitiveArray::from_option_iter([Some(42i32), Some(84), None]).into_array(),
197        );
198
199        assert_arrays_eq!(&array, &expected, &mut ctx);
200        assert_eq!(array.len(), 3);
201
202        // Test wrong dtype error.
203        let mut builder = ExtensionBuilder::new_in(ext_dtype, BufferAllocatorRef::static_ref());
204        let wrong_scalar = Scalar::from(true);
205        assert!(builder.append_scalar(&wrong_scalar).is_err());
206    }
207}