vortex_layout/layouts/struct_/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod reader;
5pub mod writer;
6
7use std::sync::Arc;
8
9use reader::StructReader;
10use vortex_array::ArrayContext;
11use vortex_array::DeserializeMetadata;
12use vortex_array::EmptyMetadata;
13use vortex_dtype::DType;
14use vortex_dtype::Field;
15use vortex_dtype::FieldMask;
16use vortex_dtype::Nullability;
17use vortex_dtype::StructFields;
18use vortex_error::VortexExpect;
19use vortex_error::VortexResult;
20use vortex_error::vortex_bail;
21use vortex_error::vortex_ensure;
22use vortex_error::vortex_err;
23use vortex_session::SessionExt;
24use vortex_session::VortexSession;
25
26use crate::LayoutChildType;
27use crate::LayoutEncodingRef;
28use crate::LayoutId;
29use crate::LayoutReaderRef;
30use crate::LayoutRef;
31use crate::VTable;
32use crate::children::LayoutChildren;
33use crate::children::OwnedLayoutChildren;
34use crate::segments::SegmentId;
35use crate::segments::SegmentSource;
36use crate::vtable;
37
38vtable!(Struct);
39
40impl VTable for StructVTable {
41    type Layout = StructLayout;
42    type Encoding = StructLayoutEncoding;
43    type Metadata = EmptyMetadata;
44
45    fn id(_encoding: &Self::Encoding) -> LayoutId {
46        LayoutId::new_ref("vortex.struct")
47    }
48
49    fn encoding(_layout: &Self::Layout) -> LayoutEncodingRef {
50        LayoutEncodingRef::new_ref(StructLayoutEncoding.as_ref())
51    }
52
53    fn row_count(layout: &Self::Layout) -> u64 {
54        layout.row_count
55    }
56
57    fn dtype(layout: &Self::Layout) -> &DType {
58        &layout.dtype
59    }
60
61    fn metadata(_layout: &Self::Layout) -> Self::Metadata {
62        EmptyMetadata
63    }
64
65    fn segment_ids(_layout: &Self::Layout) -> Vec<SegmentId> {
66        vec![]
67    }
68
69    fn nchildren(layout: &Self::Layout) -> usize {
70        let validity_children = if layout.dtype.is_nullable() { 1 } else { 0 };
71        layout.struct_fields().nfields() + validity_children
72    }
73
74    fn child(layout: &Self::Layout, index: usize) -> VortexResult<LayoutRef> {
75        let schema_index = if layout.dtype.is_nullable() {
76            index.saturating_sub(1)
77        } else {
78            index
79        };
80
81        let child_dtype = if index == 0 && layout.dtype.is_nullable() {
82            DType::Bool(Nullability::NonNullable)
83        } else {
84            layout
85                .struct_fields()
86                .field_by_index(schema_index)
87                .ok_or_else(|| vortex_err!("Missing field {schema_index}"))?
88        };
89
90        layout.children.child(index, &child_dtype)
91    }
92
93    fn child_type(layout: &Self::Layout, idx: usize) -> LayoutChildType {
94        let schema_index = if layout.dtype.is_nullable() {
95            idx.saturating_sub(1)
96        } else {
97            idx
98        };
99
100        if idx == 0 && layout.dtype.is_nullable() {
101            LayoutChildType::Auxiliary("validity".into())
102        } else {
103            LayoutChildType::Field(
104                layout
105                    .struct_fields()
106                    .field_name(schema_index)
107                    .vortex_expect("Field index out of bounds")
108                    .clone(),
109            )
110        }
111    }
112
113    fn new_reader(
114        layout: &Self::Layout,
115        name: Arc<str>,
116        segment_source: Arc<dyn SegmentSource>,
117        session: &VortexSession,
118    ) -> VortexResult<LayoutReaderRef> {
119        Ok(Arc::new(StructReader::try_new(
120            layout.clone(),
121            name,
122            segment_source,
123            session.session(),
124        )?))
125    }
126
127    #[cfg(gpu_unstable)]
128    fn new_gpu_reader(
129        layout: &Self::Layout,
130        name: Arc<str>,
131        segment_source: Arc<dyn SegmentSource>,
132        ctx: Arc<cudarc::driver::CudaContext>,
133    ) -> VortexResult<crate::gpu::GpuLayoutReaderRef> {
134        Ok(Arc::new(
135            crate::gpu::layouts::struct_::GpuStructReader::try_new(
136                layout.clone(),
137                name,
138                segment_source,
139                ctx,
140            )?,
141        ))
142    }
143
144    fn build(
145        _encoding: &Self::Encoding,
146        dtype: &DType,
147        row_count: u64,
148        _metadata: &<Self::Metadata as DeserializeMetadata>::Output,
149        _segment_ids: Vec<SegmentId>,
150        children: &dyn LayoutChildren,
151        _ctx: ArrayContext,
152    ) -> VortexResult<Self::Layout> {
153        let struct_dt = dtype
154            .as_struct_fields_opt()
155            .ok_or_else(|| vortex_err!("Expected struct dtype"))?;
156
157        let expected_children = struct_dt.nfields() + (dtype.is_nullable() as usize);
158        vortex_ensure!(
159            children.nchildren() == expected_children,
160            "Struct layout has {} children, but dtype has {} fields",
161            children.nchildren(),
162            struct_dt.nfields()
163        );
164
165        Ok(StructLayout {
166            row_count,
167            dtype: dtype.clone(),
168            children: children.to_arc(),
169        })
170    }
171}
172
173#[derive(Debug)]
174pub struct StructLayoutEncoding;
175
176#[derive(Clone, Debug)]
177pub struct StructLayout {
178    row_count: u64,
179    dtype: DType,
180    children: Arc<dyn LayoutChildren>,
181}
182
183impl StructLayout {
184    pub fn new(row_count: u64, dtype: DType, children: Vec<LayoutRef>) -> Self {
185        Self {
186            row_count,
187            dtype,
188            children: OwnedLayoutChildren::layout_children(children),
189        }
190    }
191
192    pub fn struct_fields(&self) -> &StructFields {
193        self.dtype
194            .as_struct_fields_opt()
195            .vortex_expect("Struct layout dtype must be a struct")
196    }
197
198    #[inline]
199    pub fn row_count(&self) -> u64 {
200        self.row_count
201    }
202
203    #[inline]
204    pub fn children(&self) -> &Arc<dyn LayoutChildren> {
205        &self.children
206    }
207
208    pub fn matching_fields<F>(&self, field_mask: &[FieldMask], mut per_child: F) -> VortexResult<()>
209    where
210        F: FnMut(FieldMask, usize) -> VortexResult<()>,
211    {
212        // If the field mask contains an `All` fields, then enumerate all fields.
213        if field_mask.iter().any(|mask| mask.matches_all()) {
214            for idx in 0..self.struct_fields().nfields() {
215                per_child(FieldMask::All, idx)?;
216            }
217            return Ok(());
218        }
219
220        // Enumerate each field in the mask
221        for path in field_mask {
222            let Some(field) = path.starting_field()? else {
223                // skip fields not in mask
224                continue;
225            };
226            let Field::Name(field_name) = field else {
227                vortex_bail!("Expected field name, got {field:?}");
228            };
229            let idx = self
230                .struct_fields()
231                .find(field_name)
232                .ok_or_else(|| vortex_err!("Field not found: {field_name}"))?;
233
234            per_child(path.clone().step_into()?, idx)?;
235        }
236
237        Ok(())
238    }
239}