vortex_array/arrays/struct_/vtable/
plugin.rs1use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure_eq;
10use vortex_session::VortexSession;
11
12use crate::Array;
13use crate::ArrayDeserialization;
14use crate::ArrayId;
15use crate::ArrayParts;
16use crate::ArrayPlugin;
17use crate::ArrayRef;
18use crate::ArraySerialization;
19use crate::IntoArray;
20use crate::VTable;
21use crate::array::EmptyArrayData;
22use crate::arrays::Struct;
23use crate::arrays::struct_::array::struct_slots_with_capacity;
24use crate::dtype::DType;
25use crate::validity::Validity;
26
27impl ArrayPlugin for Struct {
28 fn id(&self) -> ArrayId {
29 VTable::id(self)
30 }
31
32 fn serialize(
33 &self,
34 array: &ArrayRef,
35 _session: &VortexSession,
36 ) -> VortexResult<Option<ArraySerialization>> {
37 vortex_ensure_eq!(
38 array.encoding_id(),
39 ArrayPlugin::id(self),
40 "Struct plugin cannot serialize an array of another encoding",
41 );
42 Ok(Some(ArraySerialization::from_array(
43 ArrayPlugin::id(self),
44 array,
45 vec![],
46 )))
47 }
48
49 fn deserialize(
50 &self,
51 parts: ArrayDeserialization<'_>,
52 _session: &VortexSession,
53 ) -> VortexResult<ArrayRef> {
54 vortex_ensure_eq!(
55 parts.serialized_id,
56 ArrayPlugin::id(self),
57 "Struct plugin does not recognize the serialized ID",
58 );
59 let ArrayDeserialization {
60 dtype,
61 len,
62 metadata,
63 children,
64 ..
65 } = parts;
66 if !metadata.is_empty() {
67 vortex_bail!(
68 "StructArray expects empty metadata, got {} bytes",
69 metadata.len()
70 );
71 }
72 let DType::Struct(struct_dtype, nullability) = dtype else {
73 vortex_bail!("Expected struct dtype, found {:?}", dtype)
74 };
75
76 let (validity, non_data_children) = if children.len() == struct_dtype.nfields() {
77 (Validity::from(*nullability), 0_usize)
78 } else if children.len() == struct_dtype.nfields() + 1 {
79 let validity = children.get(0, &Validity::DTYPE, len)?;
80 (Validity::Array(validity), 1_usize)
81 } else {
82 vortex_bail!(
83 "Expected {} or {} children, found {}",
84 struct_dtype.nfields(),
85 struct_dtype.nfields() + 1,
86 children.len()
87 );
88 };
89
90 let mut slots = struct_slots_with_capacity(&validity, len, struct_dtype.nfields());
91 for i in 0..struct_dtype.nfields() {
92 let child_dtype = struct_dtype
93 .field_by_index(i)
94 .vortex_expect("no out of bounds");
95 slots.push(Some(children.get(
96 non_data_children + i,
97 &child_dtype,
98 len,
99 )?));
100 }
101
102 Ok(Array::try_from_parts(ArrayParts::new(
103 self.clone(),
104 dtype.clone(),
105 len,
106 EmptyArrayData,
107 slots,
108 ))?
109 .into_array())
110 }
111}