Skip to main content

vortex_array/arrays/listview/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hash;
5use std::hash::Hasher;
6use std::sync::Arc;
7
8use prost::Message;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_panic;
14use vortex_session::VortexSession;
15use vortex_session::registry::CachedId;
16
17use crate::ArrayEq;
18use crate::ArrayHash;
19use crate::ArrayRef;
20use crate::ExecutionCtx;
21use crate::ExecutionResult;
22use crate::Precision;
23use crate::array::Array;
24use crate::array::ArrayId;
25use crate::array::ArrayView;
26use crate::array::VTable;
27use crate::arrays::listview::ListViewArrayExt;
28use crate::arrays::listview::ListViewData;
29use crate::arrays::listview::array::NUM_SLOTS;
30use crate::arrays::listview::array::SLOT_NAMES;
31use crate::arrays::listview::compute::rules::PARENT_RULES;
32use crate::arrays::listview::vtable::kernel::PARENT_KERNELS;
33use crate::buffer::BufferHandle;
34use crate::dtype::DType;
35use crate::dtype::Nullability;
36use crate::dtype::PType;
37use crate::serde::ArrayChildren;
38use crate::validity::Validity;
39mod kernel;
40mod operations;
41mod validity;
42/// A [`ListView`]-encoded Vortex array.
43pub type ListViewArray = Array<ListView>;
44
45#[derive(Clone, Debug)]
46pub struct ListView;
47
48#[derive(Clone, prost::Message)]
49pub struct ListViewMetadata {
50    #[prost(uint64, tag = "1")]
51    elements_len: u64,
52    #[prost(enumeration = "PType", tag = "2")]
53    offset_ptype: i32,
54    #[prost(enumeration = "PType", tag = "3")]
55    size_ptype: i32,
56}
57
58impl ArrayHash for ListViewData {
59    fn array_hash<H: Hasher>(&self, state: &mut H, _precision: Precision) {
60        self.is_zero_copy_to_list().hash(state);
61    }
62}
63
64impl ArrayEq for ListViewData {
65    fn array_eq(&self, other: &Self, _precision: Precision) -> bool {
66        self.is_zero_copy_to_list() == other.is_zero_copy_to_list()
67    }
68}
69
70impl VTable for ListView {
71    type ArrayData = ListViewData;
72
73    type OperationsVTable = Self;
74    type ValidityVTable = Self;
75    fn id(&self) -> ArrayId {
76        static ID: CachedId = CachedId::new("vortex.listview");
77        *ID
78    }
79
80    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
81        0
82    }
83
84    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
85        vortex_panic!("ListViewArray buffer index {idx} out of bounds")
86    }
87
88    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
89        vortex_panic!("ListViewArray buffer_name index {idx} out of bounds")
90    }
91
92    fn serialize(
93        array: ArrayView<'_, Self>,
94        _session: &VortexSession,
95    ) -> VortexResult<Option<Vec<u8>>> {
96        Ok(Some(
97            ListViewMetadata {
98                elements_len: array.elements().len() as u64,
99                offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
100                size_ptype: PType::try_from(array.sizes().dtype())? as i32,
101            }
102            .encode_to_vec(),
103        ))
104    }
105
106    fn validate(
107        &self,
108        _data: &ListViewData,
109        dtype: &DType,
110        len: usize,
111        slots: &[Option<ArrayRef>],
112    ) -> VortexResult<()> {
113        vortex_ensure!(
114            slots.len() == NUM_SLOTS,
115            "ListViewArray expected {NUM_SLOTS} slots, found {}",
116            slots.len()
117        );
118        let elements = slots[crate::arrays::listview::array::ELEMENTS_SLOT]
119            .as_ref()
120            .vortex_expect("ListViewArray elements slot");
121        let offsets = slots[crate::arrays::listview::array::OFFSETS_SLOT]
122            .as_ref()
123            .vortex_expect("ListViewArray offsets slot");
124        let sizes = slots[crate::arrays::listview::array::SIZES_SLOT]
125            .as_ref()
126            .vortex_expect("ListViewArray sizes slot");
127        vortex_ensure!(
128            offsets.len() == len && sizes.len() == len,
129            "ListViewArray length {} does not match outer length {}",
130            offsets.len(),
131            len
132        );
133
134        let actual_dtype = DType::List(Arc::new(elements.dtype().clone()), dtype.nullability());
135        vortex_ensure!(
136            &actual_dtype == dtype,
137            "ListViewArray dtype {} does not match outer dtype {}",
138            actual_dtype,
139            dtype
140        );
141
142        Ok(())
143    }
144
145    fn deserialize(
146        &self,
147        dtype: &DType,
148        len: usize,
149        metadata: &[u8],
150
151        buffers: &[BufferHandle],
152        children: &dyn ArrayChildren,
153        _session: &VortexSession,
154    ) -> VortexResult<crate::array::ArrayParts<Self>> {
155        let metadata = ListViewMetadata::decode(metadata)?;
156        vortex_ensure!(
157            buffers.is_empty(),
158            "`ListViewArray::build` expects no buffers"
159        );
160
161        let DType::List(element_dtype, _) = dtype else {
162            vortex_bail!("Expected List dtype, got {:?}", dtype);
163        };
164
165        let validity = if children.len() == 3 {
166            Validity::from(dtype.nullability())
167        } else if children.len() == 4 {
168            let validity = children.get(3, &Validity::DTYPE, len)?;
169            Validity::Array(validity)
170        } else {
171            vortex_bail!(
172                "`ListViewArray::build` expects 3 or 4 children, got {}",
173                children.len()
174            );
175        };
176
177        // Get elements with the correct length from metadata.
178        let elements = children.get(
179            0,
180            element_dtype.as_ref(),
181            usize::try_from(metadata.elements_len)?,
182        )?;
183
184        // Get offsets with proper type from metadata.
185        let offsets = children.get(
186            1,
187            &DType::Primitive(metadata.offset_ptype(), Nullability::NonNullable),
188            len,
189        )?;
190
191        // Get sizes with proper type from metadata.
192        let sizes = children.get(
193            2,
194            &DType::Primitive(metadata.size_ptype(), Nullability::NonNullable),
195            len,
196        )?;
197
198        ListViewData::validate(&elements, &offsets, &sizes, &validity)?;
199        let data = ListViewData::try_new()?;
200        let slots = ListViewData::make_slots(&elements, &offsets, &sizes, &validity, len);
201        Ok(crate::array::ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
202    }
203
204    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
205        SLOT_NAMES[idx].to_string()
206    }
207
208    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
209        Ok(ExecutionResult::done(array))
210    }
211
212    fn reduce_parent(
213        array: ArrayView<'_, Self>,
214        parent: &ArrayRef,
215        child_idx: usize,
216    ) -> VortexResult<Option<ArrayRef>> {
217        PARENT_RULES.evaluate(array, parent, child_idx)
218    }
219
220    fn execute_parent(
221        array: ArrayView<'_, Self>,
222        parent: &ArrayRef,
223        child_idx: usize,
224        ctx: &mut ExecutionCtx,
225    ) -> VortexResult<Option<ArrayRef>> {
226        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
227    }
228}