Skip to main content

vortex_array/arrays/list/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::hash::Hasher;
5use std::sync::Arc;
6
7use prost::Message;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_panic;
13use vortex_session::VortexSession;
14use vortex_session::registry::CachedId;
15
16use crate::ArrayEq;
17use crate::ArrayHash;
18use crate::ArrayRef;
19use crate::ExecutionCtx;
20use crate::ExecutionResult;
21use crate::IntoArray;
22use crate::Precision;
23use crate::array::Array;
24use crate::array::ArrayId;
25use crate::array::ArrayParts;
26use crate::array::ArrayView;
27use crate::array::VTable;
28use crate::arrays::list::ListArrayExt;
29use crate::arrays::list::ListData;
30use crate::arrays::list::array::NUM_SLOTS;
31use crate::arrays::list::array::SLOT_NAMES;
32use crate::arrays::list::compute::PARENT_KERNELS;
33use crate::arrays::list::compute::rules::PARENT_RULES;
34use crate::arrays::listview::list_view_from_list;
35use crate::buffer::BufferHandle;
36use crate::dtype::DType;
37use crate::dtype::Nullability;
38use crate::dtype::PType;
39use crate::serde::ArrayChildren;
40use crate::validity::Validity;
41mod operations;
42mod validity;
43/// A [`List`]-encoded Vortex array.
44pub type ListArray = Array<List>;
45
46#[derive(Clone, prost::Message)]
47pub struct ListMetadata {
48    #[prost(uint64, tag = "1")]
49    elements_len: u64,
50    #[prost(enumeration = "PType", tag = "2")]
51    offset_ptype: i32,
52}
53
54impl ArrayHash for ListData {
55    fn array_hash<H: Hasher>(&self, _state: &mut H, _precision: Precision) {}
56}
57
58impl ArrayEq for ListData {
59    fn array_eq(&self, _other: &Self, _precision: Precision) -> bool {
60        true
61    }
62}
63
64impl VTable for List {
65    type ArrayData = ListData;
66
67    type OperationsVTable = Self;
68    type ValidityVTable = Self;
69    fn id(&self) -> ArrayId {
70        static ID: CachedId = CachedId::new("vortex.list");
71        *ID
72    }
73
74    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
75        0
76    }
77
78    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
79        vortex_panic!("ListArray buffer index {idx} out of bounds")
80    }
81
82    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
83        vortex_panic!("ListArray buffer_name index {idx} out of bounds")
84    }
85
86    fn reduce_parent(
87        array: ArrayView<'_, Self>,
88        parent: &ArrayRef,
89        child_idx: usize,
90    ) -> VortexResult<Option<ArrayRef>> {
91        PARENT_RULES.evaluate(array, parent, child_idx)
92    }
93
94    fn serialize(
95        array: ArrayView<'_, Self>,
96        _session: &VortexSession,
97    ) -> VortexResult<Option<Vec<u8>>> {
98        Ok(Some(
99            ListMetadata {
100                elements_len: array.elements().len() as u64,
101                offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
102            }
103            .encode_to_vec(),
104        ))
105    }
106
107    fn validate(
108        &self,
109        _data: &ListData,
110        dtype: &DType,
111        len: usize,
112        slots: &[Option<ArrayRef>],
113    ) -> VortexResult<()> {
114        vortex_ensure!(
115            slots.len() == NUM_SLOTS,
116            "ListArray expected {NUM_SLOTS} slots, found {}",
117            slots.len()
118        );
119        let elements = slots[crate::arrays::list::array::ELEMENTS_SLOT]
120            .as_ref()
121            .vortex_expect("ListArray elements slot");
122        let offsets = slots[crate::arrays::list::array::OFFSETS_SLOT]
123            .as_ref()
124            .vortex_expect("ListArray offsets slot");
125        vortex_ensure!(
126            offsets.len().saturating_sub(1) == len,
127            "ListArray length {} does not match outer length {}",
128            offsets.len().saturating_sub(1),
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            "ListArray 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<ArrayParts<Self>> {
153        let metadata = ListMetadata::decode(metadata)?;
154        let validity = if children.len() == 2 {
155            Validity::from(dtype.nullability())
156        } else if children.len() == 3 {
157            let validity = children.get(2, &Validity::DTYPE, len)?;
158            Validity::Array(validity)
159        } else {
160            vortex_bail!("Expected 2 or 3 children, got {}", children.len());
161        };
162
163        let DType::List(element_dtype, _) = &dtype else {
164            vortex_bail!("Expected List dtype, got {:?}", dtype);
165        };
166        let elements = children.get(
167            0,
168            element_dtype.as_ref(),
169            usize::try_from(metadata.elements_len)?,
170        )?;
171
172        let offsets = children.get(
173            1,
174            &DType::Primitive(metadata.offset_ptype(), Nullability::NonNullable),
175            len + 1,
176        )?;
177
178        let data = ListData::try_build(elements.clone(), offsets.clone(), validity.clone())?;
179        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
180        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
181    }
182
183    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
184        SLOT_NAMES[idx].to_string()
185    }
186
187    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
188        Ok(ExecutionResult::done(
189            list_view_from_list(array, ctx)?.into_array(),
190        ))
191    }
192
193    fn execute_parent(
194        array: ArrayView<'_, Self>,
195        parent: &ArrayRef,
196        child_idx: usize,
197        ctx: &mut ExecutionCtx,
198    ) -> VortexResult<Option<ArrayRef>> {
199        PARENT_KERNELS.execute(array, parent, child_idx, ctx)
200    }
201}
202
203#[derive(Clone, Debug)]
204pub struct List;