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