Skip to main content

vortex_array/arrays/struct_/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_error::VortexExpect;
6use vortex_error::VortexResult;
7use vortex_error::vortex_bail;
8use vortex_error::vortex_panic;
9use vortex_session::VortexSession;
10
11use crate::ArrayRef;
12use crate::ExecutionCtx;
13use crate::ExecutionResult;
14use crate::array::Array;
15use crate::array::ArrayParts;
16use crate::array::ArrayView;
17use crate::array::EmptyArrayData;
18use crate::array::VTable;
19use crate::array::child_to_validity;
20use crate::array::with_empty_buffers;
21use crate::arrays::struct_::array::FIELDS_OFFSET;
22use crate::arrays::struct_::array::VALIDITY_SLOT;
23use crate::arrays::struct_::array::make_struct_slots;
24use crate::arrays::struct_::compute::rules::PARENT_RULES;
25use crate::buffer::BufferHandle;
26use crate::dtype::DType;
27use crate::serde::ArrayChildren;
28use crate::validity::Validity;
29mod kernel;
30mod operations;
31mod validity;
32
33use vortex_session::registry::CachedId;
34
35use crate::array::ArrayId;
36
37/// A [`Struct`]-encoded Vortex array.
38pub type StructArray = Array<Struct>;
39
40pub(crate) fn initialize(session: &VortexSession) {
41    kernel::initialize(session);
42}
43
44impl VTable for Struct {
45    type TypedArrayData = EmptyArrayData;
46
47    type OperationsVTable = Self;
48    type ValidityVTable = Self;
49    fn id(&self) -> ArrayId {
50        static ID: CachedId = CachedId::new("vortex.struct");
51        *ID
52    }
53
54    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
55        0
56    }
57
58    fn validate(
59        &self,
60        _data: &EmptyArrayData,
61        dtype: &DType,
62        len: usize,
63        slots: &[Option<ArrayRef>],
64    ) -> VortexResult<()> {
65        let DType::Struct(struct_dtype, nullability) = dtype else {
66            vortex_bail!("Expected struct dtype, found {:?}", dtype)
67        };
68
69        let expected_slots = struct_dtype.nfields() + 1;
70        if slots.len() != expected_slots {
71            vortex_bail!(
72                InvalidArgument: "StructArray has {} slots but expected {}",
73                slots.len(),
74                expected_slots
75            );
76        }
77
78        let validity = child_to_validity(slots[VALIDITY_SLOT].as_ref(), *nullability);
79        if let Some(validity_len) = validity.maybe_len()
80            && validity_len != len
81        {
82            vortex_bail!(
83                InvalidArgument: "StructArray validity length {} does not match outer length {}",
84                validity_len,
85                len
86            );
87        }
88
89        let field_slots = &slots[FIELDS_OFFSET..];
90        if field_slots.is_empty() {
91            return Ok(());
92        }
93
94        for (idx, (slot, field_dtype)) in field_slots.iter().zip(struct_dtype.fields()).enumerate()
95        {
96            let field = slot
97                .as_ref()
98                .ok_or_else(|| vortex_error::vortex_err!("StructArray missing field slot {idx}"))?;
99            if field.len() != len {
100                vortex_bail!(
101                    InvalidArgument: "StructArray field {idx} has length {} but expected {}",
102                    field.len(),
103                    len
104                );
105            }
106            if field.dtype() != &field_dtype {
107                vortex_bail!(
108                    InvalidArgument: "StructArray field {idx} has dtype {} but expected {}",
109                    field.dtype(),
110                    field_dtype
111                );
112            }
113        }
114
115        Ok(())
116    }
117
118    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
119        vortex_panic!("StructArray buffer index {idx} out of bounds")
120    }
121
122    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
123        vortex_panic!("StructArray buffer_name index {idx} out of bounds")
124    }
125
126    fn with_buffers(
127        &self,
128        array: ArrayView<'_, Self>,
129        buffers: &[BufferHandle],
130    ) -> VortexResult<ArrayParts<Self>> {
131        with_empty_buffers(self, array, buffers)
132    }
133
134    fn serialize(
135        _array: ArrayView<'_, Self>,
136        _session: &VortexSession,
137    ) -> VortexResult<Option<Vec<u8>>> {
138        Ok(Some(vec![]))
139    }
140
141    fn deserialize(
142        &self,
143        dtype: &DType,
144        len: usize,
145        metadata: &[u8],
146
147        _buffers: &[BufferHandle],
148        children: &dyn ArrayChildren,
149        _session: &VortexSession,
150    ) -> VortexResult<ArrayParts<Self>> {
151        if !metadata.is_empty() {
152            vortex_bail!(
153                "StructArray expects empty metadata, got {} bytes",
154                metadata.len()
155            );
156        }
157        let DType::Struct(struct_dtype, nullability) = dtype else {
158            vortex_bail!("Expected struct dtype, found {:?}", dtype)
159        };
160
161        let (validity, non_data_children) = if children.len() == struct_dtype.nfields() {
162            (Validity::from(*nullability), 0_usize)
163        } else if children.len() == struct_dtype.nfields() + 1 {
164            let validity = children.get(0, &Validity::DTYPE, len)?;
165            (Validity::Array(validity), 1_usize)
166        } else {
167            vortex_bail!(
168                "Expected {} or {} children, found {}",
169                struct_dtype.nfields(),
170                struct_dtype.nfields() + 1,
171                children.len()
172            );
173        };
174
175        let field_children: Vec<_> = (0..struct_dtype.nfields())
176            .map(|i| {
177                let child_dtype = struct_dtype
178                    .field_by_index(i)
179                    .vortex_expect("no out of bounds");
180                children.get(non_data_children + i, &child_dtype, len)
181            })
182            .try_collect()?;
183
184        let slots = make_struct_slots(&field_children, &validity, len);
185        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, EmptyArrayData).with_slots(slots))
186    }
187
188    fn slot_name(array: ArrayView<'_, Self>, idx: usize) -> String {
189        if idx == VALIDITY_SLOT {
190            "validity".to_string()
191        } else {
192            array.dtype().as_struct_fields().names()[idx - FIELDS_OFFSET].to_string()
193        }
194    }
195
196    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
197        Ok(ExecutionResult::done(array))
198    }
199
200    fn reduce_parent(
201        array: ArrayView<'_, Self>,
202        parent: &ArrayRef,
203        child_idx: usize,
204    ) -> VortexResult<Option<ArrayRef>> {
205        PARENT_RULES.evaluate(array, parent, child_idx)
206    }
207}
208
209#[derive(Clone, Debug)]
210pub struct Struct;