vortex_array/arrays/extension/
array.rs1use 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 #[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 fn storage_array(&self) -> &ArrayRef {
36 self.storage()
37 }
38}
39impl<T: TypedArrayRef<Extension>> ExtensionArrayExt for T {}
40
41impl Array<Extension> {
42 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 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 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 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 Ok(unsafe { Self::new_unchecked(ext_dtype, storage_array) })
96 }
97
98 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 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}