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