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::ListArrayExt;
30use crate::arrays::list::ListData;
31use crate::arrays::list::array::ELEMENTS_SLOT;
32use crate::arrays::list::array::NUM_SLOTS;
33use crate::arrays::list::array::OFFSETS_SLOT;
34use crate::arrays::list::array::SLOT_NAMES;
35use crate::arrays::list::compute::rules::PARENT_RULES;
36use crate::arrays::listview::list_view_from_list;
37use crate::buffer::BufferHandle;
38use crate::dtype::DType;
39use crate::dtype::Nullability;
40use crate::dtype::PType;
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!(
125            slots.len() == NUM_SLOTS,
126            "ListArray expected {NUM_SLOTS} slots, found {}",
127            slots.len()
128        );
129        let elements = slots[ELEMENTS_SLOT]
130            .as_ref()
131            .vortex_expect("ListArray elements slot");
132        let offsets = slots[OFFSETS_SLOT]
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        SLOT_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
204#[derive(Clone, Debug)]
205pub struct List;