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_eq;
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_eq!(slots.len(), ListSlots::COUNT);
124        let elements = slots[ListSlots::ELEMENTS]
125            .as_ref()
126            .vortex_expect("ListArray elements slot");
127        let offsets = slots[ListSlots::OFFSETS]
128            .as_ref()
129            .vortex_expect("ListArray offsets slot");
130        vortex_ensure_eq!(
131            offsets.len().saturating_sub(1),
132            len,
133            "ListArray length does not match outer length",
134        );
135
136        let actual_dtype = DType::List(Arc::new(elements.dtype().clone()), dtype.nullability());
137        vortex_ensure_eq!(
138            &actual_dtype,
139            dtype,
140            "ListArray dtype does not match outer 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<ArrayParts<Self>> {
156        let metadata = ListMetadata::decode(metadata)?;
157        let validity = if children.len() == 2 {
158            Validity::from(dtype.nullability())
159        } else if children.len() == 3 {
160            let validity = children.get(2, &Validity::DTYPE, len)?;
161            Validity::Array(validity)
162        } else {
163            vortex_bail!("Expected 2 or 3 children, got {}", children.len());
164        };
165
166        let DType::List(element_dtype, _) = &dtype else {
167            vortex_bail!("Expected List dtype, got {:?}", dtype);
168        };
169        let elements = children.get(
170            0,
171            element_dtype.as_ref(),
172            usize::try_from(metadata.elements_len)?,
173        )?;
174
175        let offsets = children.get(
176            1,
177            &DType::Primitive(metadata.offset_ptype(), Nullability::NonNullable),
178            len + 1,
179        )?;
180
181        let data = ListData::try_build(elements.clone(), offsets.clone(), validity.clone())?;
182        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
183        Ok(ArrayParts::new(
184            self.clone(),
185            dtype.clone(),
186            len,
187            data,
188            slots,
189        ))
190    }
191
192    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
193        ListSlots::NAMES[idx].to_string()
194    }
195
196    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
197        Ok(ExecutionResult::done(
198            list_view_from_list(array, ctx)?.into_array(),
199        ))
200    }
201
202    // The complexity comes from the expansion of `match_each_list_builder!`.
203    #[expect(clippy::cognitive_complexity)]
204    fn append_to_builder(
205        array: ArrayView<'_, Self>,
206        builder: &mut dyn ArrayBuilder,
207        ctx: &mut ExecutionCtx,
208    ) -> VortexResult<()> {
209        match match_each_list_builder!(&mut *builder, |b| b.append_list_array(array, ctx)) {
210            Some(result) => result,
211            None => vortex_bail!(
212                "cannot append a List array of dtype {} to a {} builder",
213                array.dtype(),
214                builder.dtype()
215            ),
216        }
217    }
218}
219
220#[derive(Clone, Debug)]
221pub struct List;