Skip to main content

vortex_array/arrays/extension/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexExpect;
5use vortex_error::VortexResult;
6use vortex_error::vortex_bail;
7use vortex_error::vortex_ensure_eq;
8use vortex_error::vortex_err;
9use vortex_error::vortex_panic;
10use vortex_session::VortexSession;
11use vortex_session::registry::CachedId;
12
13use crate::ArrayRef;
14use crate::EmptyArrayData;
15use crate::ExecutionCtx;
16use crate::ExecutionResult;
17use crate::array::Array;
18use crate::array::ArrayId;
19use crate::array::ArrayParts;
20use crate::array::ArrayView;
21use crate::array::VTable;
22use crate::array::ValidityVTableFromChild;
23use crate::array::with_empty_buffers;
24use crate::arrays::extension::array::ExtensionSlots;
25use crate::arrays::extension::compute::rules::RULES;
26use crate::buffer::BufferHandle;
27use crate::builders::ArrayBuilder;
28use crate::builders::ExtensionBuilder;
29use crate::dtype::DType;
30
31mod kernel;
32mod operations;
33mod plugin;
34mod validity;
35
36/// An extension array that wraps another array with additional type information.
37///
38/// **⚠️ Unstable API**: This is an experimental feature that may change significantly
39/// in future versions. The extension type system is still evolving.
40///
41/// Unlike Apache Arrow's extension arrays, Vortex extension arrays provide a more flexible
42/// mechanism for adding semantic meaning to existing array types without requiring
43/// changes to the core type system.
44///
45/// ## Design Philosophy
46///
47/// Extension arrays serve as a type-safe wrapper that:
48/// - Preserves the underlying storage format and operations
49/// - Adds semantic type information via `ExtDType`
50/// - Enables custom serialization and deserialization logic
51/// - Allows domain-specific interpretations of generic data
52///
53/// ## Storage and Type Relationship
54///
55/// The extension array maintains a strict contract:
56/// - **Storage array**: Contains the actual data in a standard Vortex encoding
57/// - **Extension type**: Defines how to interpret the storage data semantically
58/// - **Type safety**: The storage array's dtype must match the extension type's storage dtype
59///
60/// ## Use Cases
61///
62/// Extension arrays are ideal for:
63/// - **Custom numeric types**: Units of measurement, currencies
64/// - **Temporal types**: Custom date/time formats, time zones, calendars
65/// - **Domain-specific types**: UUIDs, IP addresses, geographic coordinates
66/// - **Encoded types**: Base64 strings, compressed data, encrypted values
67///
68/// ## Validity and Operations
69///
70/// Extension arrays delegate validity and most operations to their storage array:
71/// - Validity is inherited from the underlying storage
72/// - Slicing preserves the extension type
73/// - Scalar access wraps storage scalars with extension metadata
74#[derive(Clone, Debug)]
75pub struct Extension;
76
77/// A [`Extension`]-encoded Vortex array.
78pub type ExtensionArray = Array<Extension>;
79
80pub(crate) fn initialize(session: &VortexSession) {
81    kernel::initialize(session);
82}
83
84impl VTable for Extension {
85    type TypedArrayData = EmptyArrayData;
86
87    type OperationsVTable = Self;
88    type ValidityVTable = ValidityVTableFromChild;
89
90    fn id(&self) -> ArrayId {
91        static ID: CachedId = CachedId::new("vortex.ext");
92        *ID
93    }
94
95    fn validate(
96        &self,
97        _data: &EmptyArrayData,
98        dtype: &DType,
99        len: usize,
100        slots: &[Option<ArrayRef>],
101    ) -> VortexResult<()> {
102        let storage = slots[ExtensionSlots::STORAGE]
103            .as_ref()
104            .vortex_expect("ExtensionArray storage slot");
105        vortex_ensure_eq!(
106            storage.len(),
107            len,
108            "ExtensionArray length does not match outer length",
109        );
110
111        let ext_dtype = dtype
112            .as_extension_opt()
113            .ok_or_else(|| vortex_err!("not an extension dtype"))?;
114
115        vortex_ensure_eq!(storage.dtype(), ext_dtype.storage_dtype());
116
117        Ok(())
118    }
119
120    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
121        0
122    }
123
124    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
125        vortex_panic!("ExtensionArray buffer index {idx} out of bounds")
126    }
127
128    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
129        None
130    }
131
132    fn with_buffers(
133        &self,
134        array: ArrayView<'_, Self>,
135        buffers: &[BufferHandle],
136    ) -> VortexResult<ArrayParts<Self>> {
137        with_empty_buffers(self, array, buffers)
138    }
139
140    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
141        ExtensionSlots::NAMES[idx].to_string()
142    }
143
144    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
145        Ok(ExecutionResult::done(array))
146    }
147
148    fn append_to_builder(
149        array: ArrayView<'_, Self>,
150        builder: &mut dyn ArrayBuilder,
151        ctx: &mut ExecutionCtx,
152    ) -> VortexResult<()> {
153        let Some(builder) = builder.as_any_mut().downcast_mut::<ExtensionBuilder>() else {
154            vortex_bail!("append_to_builder for Extension requires an ExtensionBuilder");
155        };
156        builder.append_extension_array(array, ctx)
157    }
158
159    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
160        RULES.evaluate(array)
161    }
162}