vortex_array/builders/
extension.rs

1use std::any::Any;
2use std::sync::Arc;
3
4use vortex_dtype::{DType, ExtDType};
5use vortex_error::{VortexResult, vortex_bail};
6use vortex_scalar::ExtScalar;
7
8use crate::arrays::ExtensionArray;
9use crate::builders::{ArrayBuilder, ArrayBuilderExt, builder_with_capacity};
10use crate::{Array, ArrayRef, Canonical};
11
12pub struct ExtensionBuilder {
13    storage: Box<dyn ArrayBuilder>,
14    dtype: DType,
15}
16
17impl ExtensionBuilder {
18    pub fn new(ext_dtype: Arc<ExtDType>) -> Self {
19        Self::with_capacity(ext_dtype, 1024)
20    }
21
22    pub fn with_capacity(ext_dtype: Arc<ExtDType>, capacity: usize) -> Self {
23        Self {
24            storage: builder_with_capacity(ext_dtype.storage_dtype(), capacity),
25            dtype: DType::Extension(ext_dtype),
26        }
27    }
28
29    pub fn append_value(&mut self, value: ExtScalar) -> VortexResult<()> {
30        self.storage.append_scalar(&value.storage())
31    }
32
33    pub fn append_option(&mut self, value: Option<ExtScalar>) -> VortexResult<()> {
34        match value {
35            Some(value) => self.append_value(value),
36            None => {
37                self.append_nulls(1);
38                Ok(())
39            }
40        }
41    }
42
43    fn ext_dtype(&self) -> Arc<ExtDType> {
44        if let DType::Extension(ext_dtype) = &self.dtype {
45            ext_dtype.clone()
46        } else {
47            unreachable!()
48        }
49    }
50}
51
52impl ArrayBuilder for ExtensionBuilder {
53    fn as_any(&self) -> &dyn Any {
54        self
55    }
56
57    fn as_any_mut(&mut self) -> &mut dyn Any {
58        self
59    }
60
61    fn dtype(&self) -> &DType {
62        &self.dtype
63    }
64
65    fn len(&self) -> usize {
66        self.storage.len()
67    }
68
69    fn append_zeros(&mut self, n: usize) {
70        self.storage.append_zeros(n)
71    }
72
73    fn append_nulls(&mut self, n: usize) {
74        self.storage.append_nulls(n)
75    }
76
77    fn extend_from_array(&mut self, array: &dyn Array) -> VortexResult<()> {
78        let array = array.to_canonical()?;
79        let Canonical::Extension(array) = array else {
80            vortex_bail!("Expected Extension array, got {:?}", array);
81        };
82        array.storage().append_to_builder(self.storage.as_mut())
83    }
84
85    fn finish(&mut self) -> ArrayRef {
86        let storage = self.storage.finish();
87        ExtensionArray::new(self.ext_dtype(), storage).into_array()
88    }
89}