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