vortex_array/arrays/listview/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::sync::Arc;
5
6use vortex_dtype::DType;
7use vortex_dtype::Nullability;
8use vortex_dtype::PType;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_vector::Vector;
14use vortex_vector::listview::ListViewVector;
15
16use crate::ArrayRef;
17use crate::DeserializeMetadata;
18use crate::ProstMetadata;
19use crate::SerializeMetadata;
20use crate::VectorExecutor;
21use crate::arrays::ListViewArray;
22use crate::arrays::listview::vtable::rules::PARENT_RULES;
23use crate::buffer::BufferHandle;
24use crate::executor::ExecutionCtx;
25use crate::serde::ArrayChildren;
26use crate::validity::Validity;
27use crate::vtable;
28use crate::vtable::ArrayId;
29use crate::vtable::ArrayVTable;
30use crate::vtable::ArrayVTableExt;
31use crate::vtable::NotSupported;
32use crate::vtable::VTable;
33use crate::vtable::ValidityVTableFromValidityHelper;
34
35mod array;
36mod canonical;
37mod operations;
38mod rules;
39mod validity;
40mod visitor;
41
42vtable!(ListView);
43
44#[derive(Debug)]
45pub struct ListViewVTable;
46
47#[derive(Clone, prost::Message)]
48pub struct ListViewMetadata {
49    #[prost(uint64, tag = "1")]
50    elements_len: u64,
51    #[prost(enumeration = "PType", tag = "2")]
52    offset_ptype: i32,
53    #[prost(enumeration = "PType", tag = "3")]
54    size_ptype: i32,
55}
56
57impl VTable for ListViewVTable {
58    type Array = ListViewArray;
59
60    type Metadata = ProstMetadata<ListViewMetadata>;
61
62    type ArrayVTable = Self;
63    type CanonicalVTable = Self;
64    type OperationsVTable = Self;
65    type ValidityVTable = ValidityVTableFromValidityHelper;
66    type VisitorVTable = Self;
67    type ComputeVTable = NotSupported;
68    type EncodeVTable = NotSupported;
69
70    fn id(&self) -> ArrayId {
71        ArrayId::new_ref("vortex.listview")
72    }
73
74    fn encoding(_array: &Self::Array) -> ArrayVTable {
75        ListViewVTable.as_vtable()
76    }
77
78    fn metadata(array: &ListViewArray) -> VortexResult<Self::Metadata> {
79        Ok(ProstMetadata(ListViewMetadata {
80            elements_len: array.elements().len() as u64,
81            offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
82            size_ptype: PType::try_from(array.sizes().dtype())? as i32,
83        }))
84    }
85
86    fn serialize(metadata: Self::Metadata) -> VortexResult<Option<Vec<u8>>> {
87        Ok(Some(metadata.serialize()))
88    }
89
90    fn deserialize(bytes: &[u8]) -> VortexResult<Self::Metadata> {
91        let metadata = <Self::Metadata as DeserializeMetadata>::deserialize(bytes)?;
92        Ok(ProstMetadata(metadata))
93    }
94
95    fn build(
96        &self,
97        dtype: &DType,
98        len: usize,
99        metadata: &Self::Metadata,
100        buffers: &[BufferHandle],
101        children: &dyn ArrayChildren,
102    ) -> VortexResult<ListViewArray> {
103        vortex_ensure!(
104            buffers.is_empty(),
105            "`ListViewArray::build` expects no buffers"
106        );
107
108        let DType::List(element_dtype, _) = dtype else {
109            vortex_bail!("Expected List dtype, got {:?}", dtype);
110        };
111
112        let validity = if children.len() == 3 {
113            Validity::from(dtype.nullability())
114        } else if children.len() == 4 {
115            let validity = children.get(3, &Validity::DTYPE, len)?;
116            Validity::Array(validity)
117        } else {
118            vortex_bail!(
119                "`ListViewArray::build` expects 3 or 4 children, got {}",
120                children.len()
121            );
122        };
123
124        // Get elements with the correct length from metadata.
125        let elements = children.get(
126            0,
127            element_dtype.as_ref(),
128            usize::try_from(metadata.0.elements_len)?,
129        )?;
130
131        // Get offsets with proper type from metadata.
132        let offsets = children.get(
133            1,
134            &DType::Primitive(metadata.0.offset_ptype(), Nullability::NonNullable),
135            len,
136        )?;
137
138        // Get sizes with proper type from metadata.
139        let sizes = children.get(
140            2,
141            &DType::Primitive(metadata.0.size_ptype(), Nullability::NonNullable),
142            len,
143        )?;
144
145        ListViewArray::try_new(elements, offsets, sizes, validity)
146    }
147
148    fn with_children(array: &mut Self::Array, children: Vec<ArrayRef>) -> VortexResult<()> {
149        vortex_ensure!(
150            children.len() == 3 || children.len() == 4,
151            "ListViewArray expects 3 or 4 children, got {}",
152            children.len()
153        );
154
155        let mut iter = children.into_iter();
156        let elements = iter
157            .next()
158            .vortex_expect("children length already validated");
159        let offsets = iter
160            .next()
161            .vortex_expect("children length already validated");
162        let sizes = iter
163            .next()
164            .vortex_expect("children length already validated");
165        let validity = if let Some(validity_array) = iter.next() {
166            Validity::Array(validity_array)
167        } else {
168            Validity::from(array.dtype.nullability())
169        };
170
171        let new_array = ListViewArray::try_new(elements, offsets, sizes, validity)?;
172        *array = new_array;
173        Ok(())
174    }
175
176    fn execute(array: &Self::Array, ctx: &mut ExecutionCtx) -> VortexResult<Vector> {
177        let elements = array.elements().execute(ctx)?;
178        let offsets = array.offsets().execute(ctx)?;
179        let sizes = array.sizes().execute(ctx)?;
180        let validity_mask = array.validity_mask();
181
182        Ok(unsafe {
183            ListViewVector::new_unchecked(
184                Arc::new(elements),
185                offsets.into_primitive(),
186                sizes.into_primitive(),
187                validity_mask,
188            )
189        }
190        .into())
191    }
192
193    fn reduce_parent(
194        array: &Self::Array,
195        parent: &ArrayRef,
196        child_idx: usize,
197    ) -> VortexResult<Option<ArrayRef>> {
198        PARENT_RULES.evaluate(array, parent, child_idx)
199    }
200}