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::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, _accuracy: EqMode) {}
56}
57
58impl ArrayEq for ListData {
59    fn array_eq(&self, _other: &Self, _accuracy: EqMode) -> bool {
60        true
61    }
62}
63
64impl VTable for List {
65    type TypedArrayData = 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 with_buffers(
87        &self,
88        array: ArrayView<'_, Self>,
89        buffers: &[BufferHandle],
90    ) -> VortexResult<ArrayParts<Self>> {
91        with_empty_buffers(self, array, buffers)
92    }
93
94    fn reduce_parent(
95        array: ArrayView<'_, Self>,
96        parent: &ArrayRef,
97        child_idx: usize,
98    ) -> VortexResult<Option<ArrayRef>> {
99        PARENT_RULES.evaluate(array, parent, child_idx)
100    }
101
102    fn serialize(
103        array: ArrayView<'_, Self>,
104        _session: &VortexSession,
105    ) -> VortexResult<Option<Vec<u8>>> {
106        Ok(Some(
107            ListMetadata {
108                elements_len: array.elements().len() as u64,
109                offset_ptype: PType::try_from(array.offsets().dtype())? as i32,
110            }
111            .encode_to_vec(),
112        ))
113    }
114
115    fn validate(
116        &self,
117        _data: &ListData,
118        dtype: &DType,
119        len: usize,
120        slots: &[Option<ArrayRef>],
121    ) -> VortexResult<()> {
122        vortex_ensure!(
123            slots.len() == ListSlots::COUNT,
124            "ListArray expected {} slots, found {}",
125            ListSlots::COUNT,
126            slots.len()
127        );
128        let elements = slots[ListSlots::ELEMENTS]
129            .as_ref()
130            .vortex_expect("ListArray elements slot");
131        let offsets = slots[ListSlots::OFFSETS]
132            .as_ref()
133            .vortex_expect("ListArray offsets slot");
134        vortex_ensure!(
135            offsets.len().saturating_sub(1) == len,
136            "ListArray length {} does not match outer length {}",
137            offsets.len().saturating_sub(1),
138            len
139        );
140
141        let actual_dtype = DType::List(Arc::new(elements.dtype().clone()), dtype.nullability());
142        vortex_ensure!(
143            &actual_dtype == dtype,
144            "ListArray dtype {} does not match outer dtype {}",
145            actual_dtype,
146            dtype
147        );
148
149        Ok(())
150    }
151
152    fn deserialize(
153        &self,
154        dtype: &DType,
155        len: usize,
156        metadata: &[u8],
157
158        _buffers: &[BufferHandle],
159        children: &dyn ArrayChildren,
160        _session: &VortexSession,
161    ) -> VortexResult<ArrayParts<Self>> {
162        let metadata = ListMetadata::decode(metadata)?;
163        let validity = if children.len() == 2 {
164            Validity::from(dtype.nullability())
165        } else if children.len() == 3 {
166            let validity = children.get(2, &Validity::DTYPE, len)?;
167            Validity::Array(validity)
168        } else {
169            vortex_bail!("Expected 2 or 3 children, got {}", children.len());
170        };
171
172        let DType::List(element_dtype, _) = &dtype else {
173            vortex_bail!("Expected List dtype, got {:?}", dtype);
174        };
175        let elements = children.get(
176            0,
177            element_dtype.as_ref(),
178            usize::try_from(metadata.elements_len)?,
179        )?;
180
181        let offsets = children.get(
182            1,
183            &DType::Primitive(metadata.offset_ptype(), Nullability::NonNullable),
184            len + 1,
185        )?;
186
187        let data = ListData::try_build(elements.clone(), offsets.clone(), validity.clone())?;
188        let slots = ListData::make_slots(&elements, &offsets, &validity, len);
189        Ok(ArrayParts::new(self.clone(), dtype.clone(), len, data).with_slots(slots))
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    fn append_to_builder(
203        array: ArrayView<'_, Self>,
204        builder: &mut dyn ArrayBuilder,
205        ctx: &mut ExecutionCtx,
206    ) -> VortexResult<()> {
207        builder.append_list_array(array, ctx)
208    }
209}
210
211#[derive(Clone, Debug)]
212pub struct List;