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 prost::Message;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_ensure_eq;
11use vortex_session::VortexSession;
12
13use crate::Array;
14use crate::ArrayDeserialization;
15use crate::ArrayId;
16use crate::ArrayPlugin;
17use crate::ArrayRef;
18use crate::ArraySerialization;
19use crate::IntoArray;
20use crate::VTable;
21use crate::arrays::Union;
22use crate::arrays::union::UnionSlots;
23use crate::arrays::union::array::make_union_parts;
24use crate::arrays::union::union_type_ids_dtype;
25use crate::dtype::DType;
26
27/// Serialized metadata for `vortex.union`, which has no fields yet and encodes to zero bytes.
28///
29/// Readers decode it as a protobuf message, so a later writer can add a field describing an
30/// appended child that old readers may safely ignore.
31#[derive(Clone, prost::Message)]
32struct UnionMetadata {}
33
34impl ArrayPlugin for Union {
35    fn id(&self) -> ArrayId {
36        VTable::id(self)
37    }
38
39    fn serialize(
40        &self,
41        array: &ArrayRef,
42        _session: &VortexSession,
43    ) -> VortexResult<Option<ArraySerialization>> {
44        vortex_ensure_eq!(
45            array.encoding_id(),
46            ArrayPlugin::id(self),
47            "Union plugin cannot serialize an array of another encoding",
48        );
49        Ok(Some(ArraySerialization::from_array(
50            ArrayPlugin::id(self),
51            array,
52            UnionMetadata {}.encode_to_vec(),
53        )))
54    }
55
56    fn deserialize(
57        &self,
58        parts: ArrayDeserialization<'_>,
59        _session: &VortexSession,
60    ) -> VortexResult<ArrayRef> {
61        vortex_ensure_eq!(
62            parts.serialized_id,
63            ArrayPlugin::id(self),
64            "Union plugin does not recognize the serialized ID",
65        );
66        let ArrayDeserialization {
67            dtype,
68            len,
69            metadata,
70            buffers,
71            children,
72            ..
73        } = parts;
74        UnionMetadata::decode(metadata)?;
75        vortex_ensure!(buffers.is_empty(), "UnionArray expects no buffers");
76        let DType::Union(variants, nullability) = dtype else {
77            vortex_bail!("Expected union dtype, found {dtype}")
78        };
79        let required_children = UnionSlots::CHILDREN_OFFSET + variants.len();
80        vortex_ensure!(
81            children.len() >= required_children,
82            "UnionArray expects at least {required_children} children, got {}",
83            children.len()
84        );
85
86        let type_ids = children.get(
87            UnionSlots::TYPE_IDS,
88            &union_type_ids_dtype(*nullability),
89            len,
90        )?;
91        let sparse_children = variants
92            .variants()
93            .enumerate()
94            .map(|(index, dtype)| children.get(UnionSlots::CHILDREN_OFFSET + index, &dtype, len))
95            .collect::<VortexResult<Vec<_>>>()?;
96
97        Ok(Array::try_from_parts(make_union_parts(
98            type_ids,
99            variants.clone(),
100            sparse_children,
101        ))?
102        .into_array())
103    }
104}