vortex_array/arrays/listview/vtable/
mod.rs1use std::hash::Hash;
5use std::hash::Hasher;
6use std::sync::Arc;
7
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_ensure_eq;
13use vortex_error::vortex_err;
14use vortex_error::vortex_panic;
15use vortex_session::VortexSession;
16use vortex_session::registry::CachedId;
17
18use crate::ArrayEq;
19use crate::ArrayHash;
20use crate::ArrayParts;
21use crate::ArrayRef;
22use crate::EqMode;
23use crate::ExecutionCtx;
24use crate::ExecutionResult;
25use crate::array::Array;
26use crate::array::ArrayId;
27use crate::array::ArrayView;
28use crate::array::VTable;
29use crate::array::with_empty_buffers;
30use crate::arrays::listview::ListViewData;
31use crate::arrays::listview::ListViewSlots;
32use crate::buffer::BufferHandle;
33use crate::builders::ArrayBuilder;
34use crate::dtype::DType;
35use crate::dtype::PType;
36use crate::match_each_list_builder;
37mod kernel;
38mod operations;
39mod plugin;
40mod validity;
41pub type ListViewArray = Array<ListView>;
43
44pub(crate) fn initialize(session: &VortexSession) {
45 kernel::initialize(session);
46}
47
48#[derive(Clone, Debug)]
49pub struct ListView;
50
51#[derive(Clone, prost::Message)]
52pub struct ListViewMetadata {
53 #[prost(uint64, tag = "1")]
54 elements_len: u64,
55 #[prost(int32, tag = "2")]
56 offset_ptype: i32,
57 #[prost(int32, tag = "3")]
58 size_ptype: i32,
59}
60
61impl ListViewMetadata {
62 fn get_offset_ptype(&self) -> VortexResult<PType> {
63 PType::try_from(self.offset_ptype).map_err(|_| {
64 vortex_err!(
65 "ListViewMetadata offset_ptype must be a known PType, got {}",
66 self.offset_ptype
67 )
68 })
69 }
70
71 fn get_size_ptype(&self) -> VortexResult<PType> {
72 PType::try_from(self.size_ptype).map_err(|_| {
73 vortex_err!(
74 "ListViewMetadata size_ptype must be a known PType, got {}",
75 self.size_ptype
76 )
77 })
78 }
79}
80
81impl ArrayHash for ListViewData {
82 fn array_hash<H: Hasher>(&self, state: &mut H, _accuracy: EqMode) {
83 self.is_zero_copy_to_list().hash(state);
84 }
85}
86
87impl ArrayEq for ListViewData {
88 fn array_eq(&self, other: &Self, _accuracy: EqMode) -> bool {
89 self.is_zero_copy_to_list() == other.is_zero_copy_to_list()
90 }
91}
92
93impl VTable for ListView {
94 type TypedArrayData = ListViewData;
95
96 type OperationsVTable = Self;
97 type ValidityVTable = Self;
98 fn id(&self) -> ArrayId {
99 static ID: CachedId = CachedId::new("vortex.listview");
100 *ID
101 }
102
103 fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
104 0
105 }
106
107 fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
108 vortex_panic!("ListViewArray buffer index {idx} out of bounds")
109 }
110
111 fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
112 vortex_panic!("ListViewArray buffer_name index {idx} out of bounds")
113 }
114
115 fn with_buffers(
116 &self,
117 array: ArrayView<'_, Self>,
118 buffers: &[BufferHandle],
119 ) -> VortexResult<ArrayParts<Self>> {
120 with_empty_buffers(self, array, buffers)
121 }
122
123 fn validate(
124 &self,
125 _data: &ListViewData,
126 dtype: &DType,
127 len: usize,
128 slots: &[Option<ArrayRef>],
129 ) -> VortexResult<()> {
130 vortex_ensure_eq!(slots.len(), ListViewSlots::COUNT);
131 let elements = slots[ListViewSlots::ELEMENTS]
132 .as_ref()
133 .vortex_expect("ListViewArray elements slot");
134 let offsets = slots[ListViewSlots::OFFSETS]
135 .as_ref()
136 .vortex_expect("ListViewArray offsets slot");
137 let sizes = slots[ListViewSlots::SIZES]
138 .as_ref()
139 .vortex_expect("ListViewArray sizes slot");
140 vortex_ensure!(
141 offsets.len() == len && sizes.len() == len,
142 "ListViewArray length {} does not match outer length {}",
143 offsets.len(),
144 len
145 );
146
147 let actual_dtype = DType::List(Arc::new(elements.dtype().clone()), dtype.nullability());
148 vortex_ensure_eq!(
149 &actual_dtype,
150 dtype,
151 "ListViewArray dtype does not match outer dtype",
152 );
153
154 Ok(())
155 }
156
157 fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
158 ListViewSlots::NAMES[idx].to_string()
159 }
160
161 fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
162 Ok(ExecutionResult::done(array))
163 }
164
165 #[expect(clippy::cognitive_complexity)]
167 fn append_to_builder(
168 array: ArrayView<'_, Self>,
169 builder: &mut dyn ArrayBuilder,
170 ctx: &mut ExecutionCtx,
171 ) -> VortexResult<()> {
172 match match_each_list_builder!(&mut *builder, |b| b.append_listview_array(array, ctx)) {
173 Some(result) => result,
174 None => vortex_bail!(
175 "cannot append a ListView array of dtype {} to a {} builder",
176 array.dtype(),
177 builder.dtype()
178 ),
179 }
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use std::sync::Arc;
186 use std::sync::LazyLock;
187
188 use prost::Message;
189 use rstest::rstest;
190 use vortex_error::VortexResult;
191 use vortex_session::VortexSession;
192
193 use super::ListView;
194 use super::ListViewMetadata;
195 use crate::ArrayDeserialization;
196 use crate::ArrayPlugin;
197 use crate::ArrayRef;
198 use crate::array::VTable;
199 use crate::dtype::DType;
200 use crate::dtype::Nullability;
201 use crate::dtype::PType;
202
203 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
204
205 #[rstest]
206 #[case::offset_ptype(
207 |raw| ListViewMetadata { offset_ptype: raw, ..Default::default() },
208 ListViewMetadata::get_offset_ptype,
209 "ListViewMetadata offset_ptype must be a known PType, got 11",
210 )]
211 #[case::size_ptype(
212 |raw| ListViewMetadata { size_ptype: raw, ..Default::default() },
213 ListViewMetadata::get_size_ptype,
214 "ListViewMetadata size_ptype must be a known PType, got 11",
215 )]
216 fn test_deserialize_rejects_unknown_ptype(
217 #[case] with_ptype: fn(i32) -> ListViewMetadata,
218 #[case] get_ptype: fn(&ListViewMetadata) -> VortexResult<PType>,
219 #[case] expected: &str,
220 ) -> VortexResult<()> {
221 let dtype = DType::List(
222 Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
223 Nullability::NonNullable,
224 );
225 let metadata = with_ptype(11).encode_to_vec();
226 let children: Vec<ArrayRef> = Vec::new();
227 let result = ListView.deserialize(
228 ArrayDeserialization::new(VTable::id(&ListView), &dtype, 0, &metadata, &[], &children),
229 &SESSION,
230 );
231 assert!(result.is_err_and(|err| err.to_string().contains(expected)));
232
233 assert_eq!(get_ptype(&with_ptype(PType::U32 as i32))?, PType::U32);
234
235 Ok(())
236 }
237}