Skip to main content

vortex_array/arrays/union/vtable/
plugin.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! [`ArrayPlugin`] implementation for [`Union`].
5
6use vortex_error::VortexResult;
7use vortex_error::vortex_bail;
8use vortex_error::vortex_ensure;
9use vortex_error::vortex_ensure_eq;
10use vortex_session::VortexSession;
11
12use crate::Array;
13use crate::ArrayDeserialization;
14use crate::ArrayId;
15use crate::ArrayPlugin;
16use crate::ArrayRef;
17use crate::ArraySerialization;
18use crate::IntoArray;
19use crate::VTable;
20use crate::arrays::Union;
21use crate::arrays::union::UnionSlots;
22use crate::arrays::union::array::make_union_parts;
23use crate::arrays::union::union_type_ids_dtype;
24use crate::dtype::DType;
25
26impl ArrayPlugin for Union {
27    fn id(&self) -> ArrayId {
28        VTable::id(self)
29    }
30
31    fn serialize(
32        &self,
33        array: &ArrayRef,
34        _session: &VortexSession,
35    ) -> VortexResult<Option<ArraySerialization>> {
36        vortex_ensure_eq!(
37            array.encoding_id(),
38            ArrayPlugin::id(self),
39            "Union plugin cannot serialize an array of another encoding",
40        );
41        Ok(Some(ArraySerialization::from_array(
42            ArrayPlugin::id(self),
43            array,
44            vec![],
45        )))
46    }
47
48    fn deserialize(
49        &self,
50        parts: ArrayDeserialization<'_>,
51        _session: &VortexSession,
52    ) -> VortexResult<ArrayRef> {
53        vortex_ensure_eq!(
54            parts.serialized_id,
55            ArrayPlugin::id(self),
56            "Union plugin does not recognize the serialized ID",
57        );
58        let ArrayDeserialization {
59            dtype,
60            len,
61            metadata,
62            buffers,
63            children,
64            ..
65        } = parts;
66        vortex_ensure!(metadata.is_empty(), "UnionArray expects empty metadata");
67        vortex_ensure!(buffers.is_empty(), "UnionArray expects no buffers");
68        let DType::Union(variants, nullability) = dtype else {
69            vortex_bail!("Expected union dtype, found {dtype}")
70        };
71        vortex_ensure_eq!(children.len(), UnionSlots::CHILDREN_OFFSET + variants.len());
72
73        let type_ids = children.get(
74            UnionSlots::TYPE_IDS,
75            &union_type_ids_dtype(*nullability),
76            len,
77        )?;
78        let sparse_children = variants
79            .variants()
80            .enumerate()
81            .map(|(index, dtype)| children.get(UnionSlots::CHILDREN_OFFSET + index, &dtype, len))
82            .collect::<VortexResult<Vec<_>>>()?;
83
84        Ok(Array::try_from_parts(make_union_parts(
85            type_ids,
86            variants.clone(),
87            sparse_children,
88        ))?
89        .into_array())
90    }
91}