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