Skip to main content

vortex_array/arrays/extension/
array.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_ensure_eq;
7
8use crate::ArrayRef;
9use crate::EmptyArrayData;
10use crate::array::Array;
11use crate::array::ArrayParts;
12use crate::array::TypedArrayRef;
13use crate::array_slots;
14use crate::arrays::Extension;
15use crate::dtype::DType;
16use crate::dtype::extension::ExtDType;
17use crate::dtype::extension::ExtDTypeRef;
18use crate::dtype::extension::ExtVTable;
19
20#[array_slots(Extension)]
21pub struct ExtensionSlots {
22    /// The backing storage array for this extension array.
23    #[slot(0)]
24    pub storage: ArrayRef,
25}
26
27pub trait ExtensionArrayExt: TypedArrayRef<Extension> {
28    fn ext_dtype(&self) -> &ExtDTypeRef {
29        self.dtype()
30            .as_extension_opt()
31            .vortex_expect("extension array somehow did not have an extension dtype")
32    }
33
34    /// Returns the backing storage array.
35    fn storage_array(&self) -> &ArrayRef {
36        self.storage()
37    }
38}
39impl<T: TypedArrayRef<Extension>> ExtensionArrayExt for T {}
40
41impl Array<Extension> {
42    /// Reconstructs an extension array from stored metadata and its storage array.
43    ///
44    /// See [`try_from_storage_with_vtable`](Self::try_from_storage_with_vtable) for the checks.
45    pub fn try_from_storage<V: ExtVTable + Default>(
46        stored_metadata: V::StoredMetadata,
47        storage: ArrayRef,
48    ) -> VortexResult<Self> {
49        Self::try_from_storage_with_vtable(V::default(), stored_metadata, storage)
50    }
51
52    /// Reconstructs metadata and checks its declaration against the storage array's dtype.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error if metadata reconstruction or validation fails, or storage differs from
57    /// the declaration, including nested nullability.
58    pub fn try_from_storage_with_vtable<V: ExtVTable>(
59        vtable: V,
60        stored_metadata: V::StoredMetadata,
61        storage: ArrayRef,
62    ) -> VortexResult<Self> {
63        let dtype = ExtDType::try_from_storage_with_vtable(
64            vtable,
65            stored_metadata,
66            storage.dtype().clone(),
67        )?;
68
69        Self::try_new(dtype.erased(), storage)
70    }
71
72    /// Constructs a new `ExtensionArray`.
73    ///
74    /// # Panics
75    ///
76    /// Panics if the storage array is not compatible with the extension dtype.
77    pub fn new(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> Self {
78        Self::try_new(ext_dtype, storage_array).vortex_expect("Unable to create `ExtensionArray`")
79    }
80
81    /// Constructs an extension array whose storage dtype exactly matches `ext_dtype`.
82    ///
83    /// # Errors
84    ///
85    /// Returns an error if the storage dtypes differ, including top-level or nested nullability.
86    pub fn try_new(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> VortexResult<Self> {
87        vortex_ensure_eq!(
88            ext_dtype.storage_dtype(),
89            storage_array.dtype(),
90            "{} storage must match its declaration",
91            ext_dtype.id()
92        );
93
94        // SAFETY: the storage array's dtype was just checked against the extension dtype.
95        Ok(unsafe { Self::new_unchecked(ext_dtype, storage_array) })
96    }
97
98    /// Creates a new `ExtensionArray` without validating its storage array.
99    ///
100    /// # Safety
101    ///
102    /// The caller must ensure that `storage_array` has the extension dtype's storage dtype.
103    pub unsafe fn new_unchecked(ext_dtype: ExtDTypeRef, storage_array: ArrayRef) -> Self {
104        let dtype = DType::Extension(ext_dtype);
105        let len = storage_array.len();
106
107        let parts = ArrayParts::new(
108            Extension,
109            dtype,
110            len,
111            EmptyArrayData,
112            ExtensionSlots {
113                storage: storage_array,
114            }
115            .into_slots(),
116        );
117
118        unsafe { Array::from_parts_unchecked(parts) }
119    }
120
121    /// Creates a new [`ExtensionArray`](crate::arrays::ExtensionArray) from a vtable, metadata, and
122    /// a storage array.
123    ///
124    /// Uses the storage array's top-level nullability when constructing the dtype. The complete
125    /// storage dtype must match the metadata's declaration.
126    ///
127    /// # Errors
128    ///
129    /// Returns an error if metadata validation fails or the storage dtype differs from the
130    /// declaration, including nested nullability.
131    pub fn try_new_from_vtable<V: ExtVTable>(
132        vtable: V,
133        metadata: V::Metadata,
134        storage_array: ArrayRef,
135    ) -> VortexResult<Self> {
136        let ext_dtype =
137            ExtDType::<V>::try_with_vtable(vtable, metadata, storage_array.dtype().nullability())?
138                .erased();
139
140        Self::try_new(ext_dtype, storage_array)
141    }
142}