Skip to main content

vortex_array/arrays/extension/vtable/
plugin.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! [`ArrayPlugin`] implementation for [`Extension`].
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_bail;
8use vortex_error::vortex_ensure_eq;
9use vortex_session::VortexSession;
10
11use crate::Array;
12use crate::ArrayDeserialization;
13use crate::ArrayId;
14use crate::ArrayParts;
15use crate::ArrayPlugin;
16use crate::ArrayRef;
17use crate::ArraySerialization;
18use crate::IntoArray;
19use crate::VTable;
20use crate::array::EmptyArrayData;
21use crate::arrays::Extension;
22use crate::arrays::extension::array::ExtensionSlots;
23use crate::dtype::DType;
24
25impl ArrayPlugin for Extension {
26    fn id(&self) -> ArrayId {
27        VTable::id(self)
28    }
29
30    fn serialize(
31        &self,
32        array: &ArrayRef,
33        _session: &VortexSession,
34    ) -> VortexResult<Option<ArraySerialization>> {
35        vortex_ensure_eq!(
36            array.encoding_id(),
37            ArrayPlugin::id(self),
38            "Extension plugin cannot serialize an array of another encoding",
39        );
40        Ok(Some(ArraySerialization::from_array(
41            ArrayPlugin::id(self),
42            array,
43            vec![],
44        )))
45    }
46
47    fn deserialize(
48        &self,
49        parts: ArrayDeserialization<'_>,
50        _session: &VortexSession,
51    ) -> VortexResult<ArrayRef> {
52        vortex_ensure_eq!(
53            parts.serialized_id,
54            ArrayPlugin::id(self),
55            "Extension plugin does not recognize the serialized ID",
56        );
57        let ArrayDeserialization {
58            dtype,
59            len,
60            metadata,
61            children,
62            ..
63        } = parts;
64        if !metadata.is_empty() {
65            vortex_bail!(
66                "ExtensionArray expects empty metadata, got {} bytes",
67                metadata.len()
68            );
69        }
70        let DType::Extension(ext_dtype) = dtype else {
71            vortex_bail!("Not an extension DType");
72        };
73        if children.len() != 1 {
74            vortex_bail!("Expected 1 child, got {}", children.len());
75        }
76        let storage = children.get(0, ext_dtype.storage_dtype(), len)?;
77        Ok(Array::try_from_parts(ArrayParts::new(
78            self.clone(),
79            dtype.clone(),
80            len,
81            EmptyArrayData,
82            ExtensionSlots { storage }.into_slots(),
83        ))?
84        .into_array())
85    }
86}