vortex_array/arrays/list/
array.rs1use std::fmt::Display;
5use std::fmt::Formatter;
6use std::sync::Arc;
7
8use num_traits::AsPrimitive;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_ensure;
13use vortex_error::vortex_ensure_eq;
14
15use crate::ArrayRef;
16use crate::ArraySlots;
17use crate::Canonical;
18use crate::ExecutionCtx;
19use crate::IntoArray;
20use crate::array::Array;
21use crate::array::ArrayParts;
22use crate::array::TypedArrayRef;
23use crate::array::child_to_validity;
24use crate::array::validity_to_child;
25use crate::array_slots;
26use crate::arrays::ConstantArray;
27use crate::arrays::List;
28use crate::arrays::ListArray;
29use crate::arrays::Primitive;
30use crate::arrays::PrimitiveArray;
31use crate::builtins::ArrayBuiltins;
32use crate::dtype::DType;
33use crate::dtype::IntegerPType;
34use crate::match_each_integer_ptype;
35use crate::match_each_native_ptype;
36use crate::optimizer::ArrayOptimizer;
37use crate::scalar::NumericOperator;
38use crate::scalar::ScalarValue;
39use crate::stats::Precision;
40use crate::stats::Stat;
41use crate::validity::Validity;
42
43#[array_slots(List)]
44pub struct ListSlots {
45 #[slot(0)]
47 pub elements: ArrayRef,
48 #[slot(1)]
50 pub offsets: ArrayRef,
51 #[slot(2)]
53 pub validity_child: Option<ArrayRef>,
54}
55
56#[derive(Clone, Debug, Default)]
113pub struct ListData;
114
115impl Display for ListData {
116 fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
117 Ok(())
118 }
119}
120
121pub struct ListDataParts {
122 pub elements: ArrayRef,
123 pub offsets: ArrayRef,
124 pub validity: Validity,
125 pub dtype: DType,
126}
127
128impl ListData {
129 pub(crate) fn make_slots(
130 elements: &ArrayRef,
131 offsets: &ArrayRef,
132 validity: &Validity,
133 len: usize,
134 ) -> ArraySlots {
135 ListSlots {
136 elements: elements.clone(),
137 offsets: offsets.clone(),
138 validity_child: validity_to_child(validity, len),
139 }
140 .into_slots()
141 }
142
143 pub fn build(
150 elements: ArrayRef,
151 offsets: ArrayRef,
152 validity: Validity,
153 ctx: &mut ExecutionCtx,
154 ) -> Self {
155 Self::try_build(elements, offsets, validity, ctx).vortex_expect("ListArray new")
156 }
157
158 pub(crate) fn try_build(
167 elements: ArrayRef,
168 offsets: ArrayRef,
169 validity: Validity,
170 ctx: &mut ExecutionCtx,
171 ) -> VortexResult<Self> {
172 Self::validate(&elements, &offsets, &validity, ctx)?;
173
174 Ok(unsafe { Self::new_unchecked() })
176 }
177
178 pub unsafe fn new_unchecked() -> Self {
195 Self
196 }
197
198 pub fn validate(
202 elements: &ArrayRef,
203 offsets: &ArrayRef,
204 validity: &Validity,
205 ctx: &mut ExecutionCtx,
206 ) -> VortexResult<()> {
207 vortex_ensure!(
209 !offsets.is_empty(),
210 "Offsets must have at least one element, [0] for an empty list"
211 );
212
213 vortex_ensure!(
215 offsets.dtype().is_int() && !offsets.dtype().is_nullable(),
216 "offsets have invalid type {}",
217 offsets.dtype()
218 );
219
220 if offsets.is_host() {
223 let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
227 let elements_len = elements.len();
228
229 match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |P| {
230 Self::validate_offset_slice(
231 offsets,
232 primitive_offsets.as_slice::<P>(),
233 elements_len,
234 )
235 })?;
236 }
237
238 if let Some(validity_len) = validity.maybe_len() {
240 vortex_ensure_eq!(
241 validity_len,
242 offsets.len() - 1,
243 "validity length does not match array size",
244 );
245 }
246
247 Ok(())
248 }
249
250 fn validate_offset_slice<P>(
251 offsets: &ArrayRef,
252 offsets_slice: &[P],
253 elements_len: usize,
254 ) -> VortexResult<()>
255 where
256 P: IntegerPType + TryFrom<usize> + Into<ScalarValue>,
257 {
258 if let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1]) {
260 vortex_bail!(
261 "offsets must be sorted, but offset {} at index {idx} is greater than \
262 offset {} at index {}",
263 offsets_slice[idx],
264 offsets_slice[idx + 1],
265 idx + 1
266 );
267 }
268
269 if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
272 vortex_ensure!(
273 min >= P::zero(),
274 "offsets minimum {min} outside valid range [0, {max}]"
275 );
276
277 vortex_ensure!(
279 P::try_from(elements_len).ok().is_none_or(|len| max <= len),
280 "Max offset {max} is beyond the length of the elements array {elements_len}"
281 );
282
283 let stats = offsets.statistics();
286 stats.set(Stat::IsSorted, Precision::exact(true));
287 stats.set(Stat::Min, Precision::exact(min));
288 stats.set(Stat::Max, Precision::exact(max));
289 }
290
291 Ok(())
292 }
293 }
298
299pub trait ListArrayExt: TypedArrayRef<List> {
300 fn nullability(&self) -> crate::dtype::Nullability {
301 match self.dtype() {
302 DType::List(_, nullability) => *nullability,
303 _ => unreachable!("ListArrayExt requires a list dtype"),
304 }
305 }
306
307 fn list_validity(&self) -> Validity {
308 child_to_validity(self.validity_child(), self.nullability())
309 }
310
311 fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
312 vortex_ensure!(
313 index <= self.len(),
314 "Index {index} out of bounds 0..={}",
315 self.len()
316 );
317
318 if let Some(p) = self.offsets().as_opt::<Primitive>() {
319 Ok(match_each_native_ptype!(p.ptype(), |P| {
320 p.as_slice::<P>()[index].as_()
321 }))
322 } else {
323 self.offsets()
324 .execute_scalar(index, ctx)?
325 .as_primitive()
326 .as_::<usize>()
327 .ok_or_else(|| vortex_error::vortex_err!("offset value does not fit in usize"))
328 }
329 }
330
331 fn list_elements_at(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
332 let start = self.offset_at(index, ctx)?;
333 let end = self.offset_at(index + 1, ctx)?;
334 self.elements().slice(start..end)?.optimize_ctx(ctx)
335 }
336
337 fn sliced_elements(&self, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
338 let start = self.offset_at(0, ctx)?;
339 let end = self.offset_at(self.len(), ctx)?;
340 self.elements().slice(start..end)?.optimize_ctx(ctx)
341 }
342
343 fn element_dtype(&self) -> &DType {
344 self.elements().dtype()
345 }
346
347 fn reset_offsets(&self, recurse: bool, ctx: &mut ExecutionCtx) -> VortexResult<Array<List>> {
348 let mut elements = self.sliced_elements(ctx)?;
349 if recurse && elements.is_canonical() {
350 let compacted = elements
351 .execute::<Canonical>(ctx)?
352 .compact(ctx)?
353 .into_array();
354 elements = compacted;
355 } else if recurse && let Some(child_list_array) = elements.as_opt::<List>() {
356 elements = child_list_array
357 .into_owned()
358 .reset_offsets(recurse, ctx)?
359 .into_array();
360 }
361
362 let offsets = self.offsets();
363 let first_offset = offsets.execute_scalar(0, ctx)?;
364 let adjusted_offsets = if first_offset.is_zero() == Some(true) {
365 offsets.clone()
366 } else {
367 offsets.clone().numeric(
368 ConstantArray::new(first_offset, offsets.len()).into_array(),
369 NumericOperator::Sub,
370 )?
371 };
372
373 Ok(unsafe { ListArray::new_unchecked(elements, adjusted_offsets, self.list_validity()) })
375 }
376}
377impl<T: TypedArrayRef<List>> ListArrayExt for T {}
378
379impl Array<List> {
380 pub fn new(
382 elements: ArrayRef,
383 offsets: ArrayRef,
384 validity: Validity,
385 ctx: &mut ExecutionCtx,
386 ) -> Self {
387 let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
388 let len = offsets.len().saturating_sub(1);
389 let slots = ListData::make_slots(&elements, &offsets, &validity, len);
390 let data = ListData::build(elements, offsets, validity, ctx);
391 unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) }
392 }
393
394 pub fn try_new(
396 elements: ArrayRef,
397 offsets: ArrayRef,
398 validity: Validity,
399 ctx: &mut ExecutionCtx,
400 ) -> VortexResult<Self> {
401 let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
402 let len = offsets.len().saturating_sub(1);
403 let slots = ListData::make_slots(&elements, &offsets, &validity, len);
404 let data = ListData::try_build(elements, offsets, validity, ctx)?;
405 Ok(unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) })
406 }
407
408 pub unsafe fn new_unchecked(elements: ArrayRef, offsets: ArrayRef, validity: Validity) -> Self {
414 let dtype = DType::List(Arc::new(elements.dtype().clone()), validity.nullability());
415 let len = offsets.len().saturating_sub(1);
416 let slots = ListData::make_slots(&elements, &offsets, &validity, len);
417 let data = unsafe { ListData::new_unchecked() };
418 unsafe { Array::from_parts_unchecked(ArrayParts::new(List, dtype, len, data, slots)) }
419 }
420
421 pub fn into_data_parts(self) -> ListDataParts {
422 let dtype = self.dtype().clone();
423 let elements = self.elements().clone();
424 let offsets = self.offsets().clone();
425 let validity = self.list_validity();
426 ListDataParts {
427 elements,
428 offsets,
429 validity,
430 dtype,
431 }
432 }
433}