1use std::any::Any;
5use std::fmt::Debug;
6use std::fmt::Formatter;
7use std::hash::Hasher;
8use std::sync::Arc;
9
10use vortex_buffer::ByteBuffer;
11use vortex_error::VortexExpect;
12use vortex_error::VortexResult;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_ensure_eq;
15use vortex_error::vortex_err;
16use vortex_error::vortex_panic;
17use vortex_session::registry::Id;
18
19use crate::ExecutionCtx;
20use crate::buffer::BufferHandle;
21use crate::builders::ArrayBuilder;
22use crate::canonical::CanonicalKind;
23use crate::dtype::DType;
24use crate::dtype::Nullability;
25use crate::executor::ExecutionResult;
26use crate::scalar::Scalar;
27use crate::validity::Validity;
28
29mod erased;
30pub use erased::*;
31
32mod plugin;
33pub use plugin::*;
34mod probe;
35pub use probe::*;
36
37mod foreign;
38pub(crate) use foreign::*;
39
40mod typed;
41pub use typed::*;
42
43pub mod vtable;
44pub use vtable::*;
45
46mod view;
47use smallvec::SmallVec;
48pub use view::*;
49
50use crate::hash::ArrayEq;
51use crate::hash::ArrayHash;
52
53pub type ArraySlots = SmallVec<[Option<ArrayRef>; 4]>;
58
59#[derive(Clone, Copy, Debug)]
64pub struct SlotSlice<'a> {
65 slots: &'a [Option<ArrayRef>],
66 expect: &'static str,
67}
68
69impl<'a> SlotSlice<'a> {
70 pub fn new(slots: &'a [Option<ArrayRef>], expect: &'static str) -> Self {
74 Self { slots, expect }
75 }
76
77 pub fn len(&self) -> usize {
79 self.slots.len()
80 }
81
82 pub fn is_empty(&self) -> bool {
84 self.slots.is_empty()
85 }
86
87 pub fn get(&self, idx: usize) -> Option<&'a ArrayRef> {
89 self.slots
90 .get(idx)
91 .map(|slot| slot.as_ref().vortex_expect(self.expect))
92 }
93
94 pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a ArrayRef> + use<'a> {
96 let expect = self.expect;
97 self.slots
98 .iter()
99 .map(move |slot| slot.as_ref().vortex_expect(expect))
100 }
101
102 pub fn to_vec(&self) -> Vec<ArrayRef> {
104 self.iter().cloned().collect()
105 }
106}
107
108impl std::ops::Index<usize> for SlotSlice<'_> {
109 type Output = ArrayRef;
110
111 fn index(&self, idx: usize) -> &Self::Output {
112 self.slots[idx].as_ref().vortex_expect(self.expect)
113 }
114}
115
116#[doc(hidden)]
121pub(crate) trait DynArrayData: 'static + private::Sealed + Send + Sync + Debug {
122 fn as_any(&self) -> &dyn Any;
124
125 fn canonical_kind(&self) -> Option<CanonicalKind>;
127
128 fn validity(&self, this: &ArrayRef) -> VortexResult<Validity>;
130
131 fn append_to_builder(
135 &self,
136 this: &ArrayRef,
137 builder: &mut dyn ArrayBuilder,
138 ctx: &mut ExecutionCtx,
139 ) -> VortexResult<()>;
140
141 fn buffers(&self, this: &ArrayRef) -> Vec<ByteBuffer>;
145
146 fn buffer_handles(&self, this: &ArrayRef) -> Vec<BufferHandle>;
148
149 fn buffer_names(&self, this: &ArrayRef) -> Vec<String>;
151
152 fn named_buffers(&self, this: &ArrayRef) -> Vec<(String, BufferHandle)>;
154
155 fn nbuffers(&self, this: &ArrayRef) -> usize;
157
158 fn slot_name(&self, this: &ArrayRef, idx: usize) -> String;
160
161 fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result;
163
164 fn dyn_array_hash(&self, state: &mut dyn Hasher, accuracy: crate::EqMode);
166
167 fn dyn_array_eq(&self, other: &ArrayRef, accuracy: crate::EqMode) -> bool;
169
170 fn with_slots(&self, this: &ArrayRef, slots: ArraySlots) -> VortexResult<ArrayRef>;
172
173 fn with_buffers(&self, this: &ArrayRef, buffers: Vec<BufferHandle>) -> VortexResult<ArrayRef>;
175
176 unsafe fn with_slots_unchecked(&self, this: &ArrayRef, slots: ArraySlots) -> ArrayRef;
189
190 fn reduce(&self, this: &ArrayRef) -> VortexResult<Option<ArrayRef>>;
192
193 fn execute_fn(&self) -> ExecuteFn;
199
200 fn probe_scalar_once(
208 &self,
209 this: &ArrayRef,
210 index: usize,
211 ctx: &mut ExecutionCtx,
212 ) -> VortexResult<Scalar>;
213
214 fn probe_scalar_retained(
218 &self,
219 this: &ArrayRef,
220 index: usize,
221 state: &mut Option<Box<dyn Any>>,
222 ctx: &mut ExecutionCtx,
223 ) -> VortexResult<Scalar>;
224
225 fn probe_is_valid_retained(
229 &self,
230 this: &ArrayRef,
231 index: usize,
232 state: &mut Option<Box<dyn Any>>,
233 ctx: &mut ExecutionCtx,
234 ) -> VortexResult<bool>;
235}
236
237pub(crate) type ExecuteFn = fn(ArrayRef, &mut ExecutionCtx) -> VortexResult<ExecutionResult>;
239
240fn execute_encoding<V: VTable>(
242 this: ArrayRef,
243 ctx: &mut ExecutionCtx,
244) -> VortexResult<ExecutionResult> {
245 let typed = Array::<V>::try_from_array_ref(this)
246 .map_err(|_| vortex_err!("Failed to downcast array for execute"))
247 .vortex_expect("Failed to downcast array for execute");
248 V::execute(typed, ctx)
249}
250
251pub trait IntoArray {
253 fn into_array(self) -> ArrayRef;
255}
256
257mod private {
258 use super::*;
259
260 pub trait Sealed {}
261
262 impl<V: VTable> Sealed for ArrayData<V> {}
263}
264
265impl<V: VTable> DynArrayData for ArrayData<V> {
274 fn canonical_kind(&self) -> Option<CanonicalKind> {
275 CanonicalKind::of::<V>()
276 }
277
278 fn as_any(&self) -> &dyn Any {
279 self
280 }
281
282 fn validity(&self, this: &ArrayRef) -> VortexResult<Validity> {
283 if this.dtype().is_nullable() {
284 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
285 let validity = <V::ValidityVTable as ValidityVTable<V>>::validity(view)?;
286 if let Validity::Array(array) = &validity {
287 vortex_ensure_eq!(array.len(), this.len(), "Validity array length mismatch");
288 vortex_ensure!(
289 matches!(array.dtype(), DType::Bool(Nullability::NonNullable)),
290 "Validity array is not non-nullable boolean: {}",
291 this.encoding_id(),
292 );
293 }
294 Ok(validity)
295 } else {
296 Ok(Validity::NonNullable)
297 }
298 }
299
300 fn append_to_builder(
301 &self,
302 this: &ArrayRef,
303 builder: &mut dyn ArrayBuilder,
304 ctx: &mut ExecutionCtx,
305 ) -> VortexResult<()> {
306 if builder.dtype() != this.dtype() {
307 vortex_panic!(
308 "Builder dtype mismatch: expected {}, got {}",
309 this.dtype(),
310 builder.dtype(),
311 );
312 }
313 let len = builder.len();
314
315 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
316 V::append_to_builder(view, builder, ctx)?;
317
318 assert_eq!(
319 len + this.len(),
320 builder.len(),
321 "Builder length mismatch after writing array for encoding {}",
322 this.encoding_id(),
323 );
324 Ok(())
325 }
326
327 fn buffers(&self, this: &ArrayRef) -> Vec<ByteBuffer> {
328 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
329 (0..V::nbuffers(view))
330 .map(|i| V::buffer(view, i).to_host_sync())
331 .collect()
332 }
333
334 fn buffer_handles(&self, this: &ArrayRef) -> Vec<BufferHandle> {
335 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
336 (0..V::nbuffers(view)).map(|i| V::buffer(view, i)).collect()
337 }
338
339 fn buffer_names(&self, this: &ArrayRef) -> Vec<String> {
340 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
341 (0..V::nbuffers(view))
342 .filter_map(|i| V::buffer_name(view, i))
343 .collect()
344 }
345
346 fn named_buffers(&self, this: &ArrayRef) -> Vec<(String, BufferHandle)> {
347 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
348 (0..V::nbuffers(view))
349 .filter_map(|i| V::buffer_name(view, i).map(|name| (name, V::buffer(view, i))))
350 .collect()
351 }
352
353 fn nbuffers(&self, this: &ArrayRef) -> usize {
354 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
355 V::nbuffers(view)
356 }
357
358 fn slot_name(&self, this: &ArrayRef, idx: usize) -> String {
359 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
360 V::slot_name(view, idx)
361 }
362
363 fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
364 std::fmt::Display::fmt(&self.data, f)
365 }
366
367 fn dyn_array_hash(&self, state: &mut dyn Hasher, accuracy: crate::EqMode) {
368 let mut wrapper = HasherWrapper(state);
369 self.data.array_hash(&mut wrapper, accuracy);
371 }
372
373 fn dyn_array_eq(&self, other: &ArrayRef, accuracy: crate::EqMode) -> bool {
374 other
376 .dyn_array()
377 .as_any()
378 .downcast_ref::<Self>()
379 .is_some_and(|other_inner| self.data.array_eq(&other_inner.data, accuracy))
380 }
381
382 fn with_slots(&self, this: &ArrayRef, slots: ArraySlots) -> VortexResult<ArrayRef> {
383 let stats = this.statistics().to_owned();
384 Ok(Array::<V>::try_from_parts(ArrayParts::new(
385 self.vtable.clone(),
386 this.dtype().clone(),
387 this.len(),
388 self.data.clone(),
389 slots,
390 ))?
391 .with_stats_set(stats)
392 .into_array())
393 }
394
395 fn with_buffers(&self, this: &ArrayRef, buffers: Vec<BufferHandle>) -> VortexResult<ArrayRef> {
396 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
397 let stats = this.statistics().to_owned();
398 Ok(
399 Array::<V>::try_from_parts(V::with_buffers(&self.vtable, view, &buffers)?)?
400 .with_stats_set(stats)
401 .into_array(),
402 )
403 }
404
405 unsafe fn with_slots_unchecked(&self, this: &ArrayRef, slots: ArraySlots) -> ArrayRef {
406 let parts = ArrayParts::new(
409 self.vtable.clone(),
410 this.dtype().clone(),
411 this.len(),
412 self.data.clone(),
413 slots,
414 );
415 let encoding_id = self.vtable.id();
416 let stats = this.statistics().share_existing();
417 let uninit = Arc::new_uninit();
418
419 let store = unsafe { ArrayInner::init_arc(uninit, parts, encoding_id, stats) };
421
422 ArrayRef::from_inner(store)
423 }
424
425 fn reduce(&self, this: &ArrayRef) -> VortexResult<Option<ArrayRef>> {
426 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
427 let Some(reduced) = V::reduce(view)? else {
428 return Ok(None);
429 };
430 vortex_ensure_eq!(
431 reduced.len(),
432 this.len(),
433 "Reduced array length mismatch from {} to {}",
434 this.encoding_id(),
435 reduced.encoding_id()
436 );
437 vortex_ensure!(
439 reduced.dtype() == this.dtype()
440 || (reduced.dtype().eq_ignore_nullability(this.dtype())
441 && !reduced.dtype().is_nullable()),
442 "Reduced array dtype mismatch from {} ({}) to {} ({})",
443 this.encoding_id(),
444 this.dtype(),
445 reduced.encoding_id(),
446 reduced.dtype()
447 );
448 Ok(Some(reduced))
449 }
450
451 fn execute_fn(&self) -> ExecuteFn {
452 execute_encoding::<V>
453 }
454
455 fn probe_scalar_once(
456 &self,
457 this: &ArrayRef,
458 index: usize,
459 ctx: &mut ExecutionCtx,
460 ) -> VortexResult<Scalar> {
461 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
463 <V::OperationsVTable as OperationsVTable<V>>::probe_scalar(
464 &mut ProbeState::once(view),
465 index,
466 ctx,
467 )
468 }
469
470 fn probe_scalar_retained(
471 &self,
472 this: &ArrayRef,
473 index: usize,
474 state: &mut Option<Box<dyn Any>>,
475 ctx: &mut ExecutionCtx,
476 ) -> VortexResult<Scalar> {
477 let view = unsafe { ArrayView::new_unchecked(this, &self.data) };
479 let mut state = ProbeState::repeated(view, repeated_state(state)?);
480 <V::OperationsVTable as OperationsVTable<V>>::probe_scalar(&mut state, index, ctx)
481 }
482
483 fn probe_is_valid_retained(
484 &self,
485 this: &ArrayRef,
486 index: usize,
487 state: &mut Option<Box<dyn Any>>,
488 ctx: &mut ExecutionCtx,
489 ) -> VortexResult<bool> {
490 repeated_state::<EncodingProbeState<V>>(state)?.is_valid(this, index, ctx)
491 }
492}
493
494struct HasherWrapper<'a>(&'a mut dyn Hasher);
496
497impl Hasher for HasherWrapper<'_> {
498 fn finish(&self) -> u64 {
499 self.0.finish()
500 }
501
502 fn write(&mut self, bytes: &[u8]) {
503 self.0.write(bytes);
504 }
505}
506
507pub type ArrayId = Id;