1use std::any::type_name;
5use std::fmt::Debug;
6use std::fmt::Formatter;
7use std::hash::Hash;
8use std::hash::Hasher;
9use std::ops::Range;
10use std::ptr;
11use std::sync::Arc;
12
13use vortex_buffer::ByteBuffer;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_ensure;
17use vortex_error::vortex_ensure_eq;
18use vortex_error::vortex_err;
19use vortex_error::vortex_panic;
20use vortex_mask::Mask;
21
22use crate::AnyCanonical;
23use crate::Array;
24use crate::ArrayEq;
25use crate::ArrayHash;
26use crate::ArrayView;
27use crate::Canonical;
28use crate::ExecutionCtx;
29use crate::ExecutionResult;
30use crate::ExecutionStep;
31use crate::IntoArray;
32use crate::VTable;
33use crate::aggregate_fn::fns::sum::sum;
34use crate::array::ArrayData;
35use crate::array::ArrayId;
36use crate::array::ArrayInner;
37use crate::array::ArraySlots;
38use crate::array::DynArrayData;
39use crate::array::probe::ArrayProbe;
40use crate::array::probe::RepeatedArrayProbe;
41use crate::arrays::Constant;
42use crate::arrays::DictArray;
43use crate::arrays::FilterArray;
44use crate::arrays::SliceArray;
45use crate::buffer::BufferHandle;
46use crate::builders::ArrayBuilder;
47use crate::dtype::DType;
48use crate::matcher::Matcher;
49use crate::optimizer::ArrayOptimizer;
50use crate::optimizer::OptimizedState;
51use crate::scalar::Scalar;
52use crate::scalar::ScalarValue;
53use crate::stats::Precision;
54use crate::stats::Stat;
55use crate::stats::StatsProviderExt;
56use crate::stats::StatsSetRef;
57use crate::validity::Validity;
58
59pub struct DepthFirstArrayIterator {
61 stack: Vec<ArrayRef>,
62}
63
64impl Iterator for DepthFirstArrayIterator {
65 type Item = ArrayRef;
66
67 fn next(&mut self) -> Option<Self::Item> {
68 let next = self.stack.pop()?;
69 for child in next.children().into_iter().rev() {
70 self.stack.push(child);
71 }
72 Some(next)
73 }
74}
75
76#[derive(Clone)]
82pub struct ArrayRef(Arc<ArrayInner<dyn DynArrayData>>);
83
84impl ArrayRef {
85 pub(crate) fn from_inner<D: DynArrayData>(inner: Arc<ArrayInner<D>>) -> Self {
87 Self(inner)
88 }
89
90 #[allow(clippy::inline_always)]
92 #[inline(always)]
93 pub(crate) fn dyn_array(&self) -> &dyn DynArrayData {
94 &self.0.data
95 }
96
97 #[allow(clippy::inline_always)]
101 #[inline(always)]
102 pub(crate) fn inner_mut(&mut self) -> Option<&mut ArrayInner<dyn DynArrayData>> {
103 let inner = Arc::get_mut(&mut self.0)?;
104 *inner.optimized.0.get_mut() = false;
105 Some(inner)
106 }
107
108 pub(crate) fn optimized_state(&self) -> &OptimizedState {
112 &self.0.optimized
113 }
114
115 pub(crate) fn is_shared(&self) -> bool {
117 Arc::strong_count(&self.0) > 1
118 }
119
120 #[doc(hidden)]
123 pub fn addr(&self) -> usize {
124 Arc::as_ptr(&self.0).addr()
125 }
126
127 #[allow(dead_code)]
131 pub(crate) fn downcast_inner<V: VTable>(self) -> Result<Arc<ArrayInner<ArrayData<V>>>, Self> {
132 if self.0.data.as_any().is::<ArrayData<V>>() {
134 Ok(unsafe { self.downcast_inner_unchecked() })
135 } else {
136 Err(self)
137 }
138 }
139
140 #[allow(clippy::inline_always)]
145 #[inline(always)]
146 pub(crate) unsafe fn downcast_inner_unchecked<V: VTable>(
147 self,
148 ) -> Arc<ArrayInner<ArrayData<V>>> {
149 debug_assert!(self.0.data.as_any().is::<ArrayData<V>>());
150 let raw = Arc::into_raw(self.0);
154 unsafe { Arc::from_raw(raw.cast::<ArrayInner<ArrayData<V>>>()) }
156 }
157
158 pub fn ptr_eq(this: &ArrayRef, other: &ArrayRef) -> bool {
160 Arc::ptr_eq(&this.0, &other.0)
161 }
162}
163
164impl Debug for ArrayRef {
165 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
166 f.debug_struct("Array")
167 .field("encoding", &self.0.encoding_id)
168 .field("dtype", &self.0.dtype)
169 .field("len", &self.0.len)
170 .field("data", &self.0.data)
171 .finish()
172 }
173}
174
175impl ArrayHash for ArrayRef {
176 fn array_hash<H: Hasher>(&self, state: &mut H, accuracy: crate::EqMode) {
177 self.0.len.hash(state);
178 self.0.dtype.hash(state);
179 self.0.encoding_id.hash(state);
180 self.0.slots.len().hash(state);
181 for slot in &self.0.slots {
182 slot.array_hash(state, accuracy);
183 }
184 self.0
185 .data
186 .dyn_array_hash(state as &mut dyn Hasher, accuracy);
187 }
188}
189
190impl ArrayEq for ArrayRef {
191 fn array_eq(&self, other: &Self, accuracy: crate::EqMode) -> bool {
192 self.0.len == other.0.len
193 && self.0.dtype == other.0.dtype
194 && self.0.encoding_id == other.0.encoding_id
195 && self.0.slots.len() == other.0.slots.len()
196 && self
197 .0
198 .slots
199 .iter()
200 .zip(other.0.slots.iter())
201 .all(|(slot, other_slot)| slot.array_eq(other_slot, accuracy))
202 && self.0.data.dyn_array_eq(other, accuracy)
203 }
204}
205impl ArrayRef {
206 #[inline]
208 pub fn len(&self) -> usize {
209 self.0.len
210 }
211
212 #[inline]
214 pub fn is_empty(&self) -> bool {
215 self.0.len == 0
216 }
217
218 #[inline]
220 pub fn dtype(&self) -> &DType {
221 &self.0.dtype
222 }
223
224 #[inline]
226 pub fn encoding_id(&self) -> ArrayId {
227 self.0.encoding_id
228 }
229
230 pub fn slice(&self, range: Range<usize>) -> VortexResult<ArrayRef> {
232 let len = self.len();
233 let start = range.start;
234 let stop = range.end;
235
236 if start == 0 && stop == len {
237 return Ok(self.clone());
238 }
239
240 vortex_ensure!(start <= len, "OutOfBounds: start {start} > length {}", len);
241 vortex_ensure!(stop <= len, "OutOfBounds: stop {stop} > length {}", len);
242
243 vortex_ensure!(start <= stop, "start ({start}) must be <= stop ({stop})");
244
245 if start == stop {
246 return Ok(Canonical::empty(self.dtype()).into_array());
247 }
248
249 let sliced = SliceArray::try_new(self.clone(), range)?.into_array();
250
251 self.statistics().with_iter(|iter| {
253 sliced.statistics().inherit(iter.filter(|(stat, value)| {
254 matches!(
255 stat,
256 Stat::IsConstant | Stat::IsSorted | Stat::IsStrictSorted
257 ) && value
258 .as_ref()
259 .as_exact()
260 .is_some_and(|v| matches!(v, ScalarValue::Bool(true)))
261 }));
262 });
263
264 Ok(sliced)
265 }
266
267 pub fn filter(&self, mask: Mask) -> VortexResult<ArrayRef> {
269 Ok(FilterArray::try_new(self.clone(), mask)?.into_array())
270 }
271
272 pub fn take(&self, indices: ArrayRef) -> VortexResult<ArrayRef> {
274 Ok(DictArray::try_new(indices, self.clone())?.into_array())
275 }
276
277 #[inline]
282 pub fn execute_scalar(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<Scalar> {
283 self.probe().execute_scalar(index, ctx)
284 }
285
286 #[inline]
300 pub fn probe(&self) -> ArrayProbe<'_> {
301 ArrayProbe::Once(self)
302 }
303
304 pub fn repeated_probe(&self) -> RepeatedArrayProbe {
320 RepeatedArrayProbe::new(self.clone())
321 }
322
323 #[inline]
328 pub fn is_valid(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
329 self.probe().execute_is_valid(index, ctx)
330 }
331
332 #[inline]
335 pub fn is_invalid(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
336 Ok(!self.is_valid(index, ctx)?)
337 }
338
339 pub fn all_valid(&self, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
341 if self.is_empty() {
342 return Ok(true);
343 }
344
345 match self.validity()? {
346 Validity::NonNullable | Validity::AllValid => Ok(true),
347 Validity::AllInvalid => Ok(false),
348 Validity::Array(a) => Ok(a.statistics().compute_min::<bool>(ctx).unwrap_or(false)),
349 }
350 }
351
352 pub fn all_invalid(&self, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
354 if self.is_empty() {
355 return Ok(true);
356 }
357
358 match self.validity()? {
359 Validity::NonNullable | Validity::AllValid => Ok(false),
360 Validity::AllInvalid => Ok(true),
361 Validity::Array(a) => Ok(!a.statistics().compute_max::<bool>(ctx).unwrap_or(true)),
362 }
363 }
364
365 pub fn valid_count(&self, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
367 let len = self.len();
368 if let Precision::Exact(invalid_count) = self.statistics().get_as::<usize>(Stat::NullCount)
369 {
370 return Ok(len - invalid_count);
371 }
372
373 let count = match self.validity()? {
374 Validity::NonNullable | Validity::AllValid => len,
375 Validity::AllInvalid => 0,
376 Validity::Array(a) => {
377 let array_sum = sum(&a, ctx)?;
378 array_sum
379 .as_primitive()
380 .as_::<usize>()
381 .ok_or_else(|| vortex_err!("sum of validity array is null"))?
382 }
383 };
384 vortex_ensure!(count <= len, "Valid count exceeds array length");
385
386 self.statistics()
387 .set(Stat::NullCount, Precision::exact(len - count));
388
389 Ok(count)
390 }
391
392 pub fn invalid_count(&self, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
394 Ok(self.len() - self.valid_count(ctx)?)
395 }
396
397 pub fn validity(&self) -> VortexResult<Validity> {
399 self.0.data.validity(self)
400 }
401
402 pub fn append_to_builder(
404 &self,
405 builder: &mut dyn ArrayBuilder,
406 ctx: &mut ExecutionCtx,
407 ) -> VortexResult<()> {
408 let array = self.optimize_ctx(ctx)?;
409
410 array.0.data.append_to_builder(&array, builder, ctx)
411 }
412
413 pub fn statistics(&self) -> StatsSetRef<'_> {
415 self.0.stats.to_ref(self)
416 }
417
418 #[inline]
420 pub fn is<M: Matcher>(&self) -> bool {
421 M::matches(self)
422 }
423
424 #[inline]
426 pub fn as_<M: Matcher>(&self) -> M::Match<'_> {
427 self.as_opt::<M>().vortex_expect("Failed to downcast")
428 }
429
430 #[inline]
432 pub fn as_opt<M: Matcher>(&self) -> Option<M::Match<'_>> {
433 M::try_match(self)
434 }
435
436 pub fn try_downcast<V: VTable>(self) -> Result<Array<V>, ArrayRef> {
438 Array::<V>::try_from_array_ref(self)
439 }
440
441 pub fn downcast<V: VTable>(self) -> Array<V> {
447 Self::try_downcast(self)
448 .unwrap_or_else(|_| vortex_panic!("Failed to downcast to {}", type_name::<V>()))
449 }
450
451 pub fn as_typed<V: VTable>(&self) -> Option<ArrayView<'_, V>> {
453 let inner = self.0.data.as_any().downcast_ref::<ArrayData<V>>()?;
454 Some(unsafe { ArrayView::new_unchecked(self, &inner.data) })
455 }
456
457 #[inline]
462 pub(crate) unsafe fn as_typed_unchecked<V: VTable>(&self) -> ArrayView<'_, V> {
463 debug_assert!(self.is::<V>());
464 let inner = unsafe { &*ptr::from_ref(self.dyn_array()).cast::<ArrayData<V>>() };
467 unsafe { ArrayView::new_unchecked(self, &inner.data) }
469 }
470
471 pub fn as_constant(&self) -> Option<&Scalar> {
473 self.as_opt::<Constant>().map(|a| a.data().scalar())
474 }
475
476 pub fn nbytes(&self) -> u64 {
478 let mut nbytes = 0;
479 for array in self.depth_first_traversal() {
480 for buffer in array.buffers() {
481 nbytes += buffer.len() as u64;
482 }
483 }
484 nbytes
485 }
486
487 pub fn is_canonical(&self) -> bool {
489 self.is::<AnyCanonical>()
490 }
491
492 pub unsafe fn with_slot(
505 self,
506 slot_idx: usize,
507 replacement: ArrayRef,
508 ) -> VortexResult<ArrayRef> {
509 let mut slots: ArraySlots = self.slots().iter().cloned().collect();
510 let nslots = slots.len();
511 vortex_ensure!(
512 slot_idx < nslots,
513 "slot index {} out of bounds for array with {} slots",
514 slot_idx,
515 nslots
516 );
517 let existing = slots[slot_idx]
518 .as_ref()
519 .vortex_expect("with_slot cannot replace an absent slot");
520 vortex_ensure_eq!(
521 existing.dtype(),
522 replacement.dtype(),
523 "slot {} dtype changed during physical rewrite",
524 slot_idx
525 );
526 vortex_ensure_eq!(
527 existing.len(),
528 replacement.len(),
529 "slot {} len changed during physical rewrite",
530 slot_idx
531 );
532 slots[slot_idx] = Some(replacement);
533 unsafe { self.with_slots(slots) }
535 }
536
537 pub unsafe fn take_slot_unchecked(
549 mut self,
550 slot_idx: usize,
551 ) -> VortexResult<(ArrayRef, ArrayRef)> {
552 if let Some(inner) = self.inner_mut() {
553 let child = inner.slots[slot_idx]
554 .take()
555 .vortex_expect("take_slot_unchecked cannot take an absent slot");
556 return Ok((self, child));
557 }
558
559 let child = self.slots()[slot_idx]
562 .as_ref()
563 .vortex_expect("take_slot_unchecked cannot take an absent slot")
564 .clone();
565
566 let mut new_slots: ArraySlots = self.slots().iter().cloned().collect();
567 new_slots[slot_idx] = None;
568
569 let new_parent = unsafe { self.0.data.with_slots_unchecked(&self, new_slots) };
572 Ok((new_parent, child))
573 }
574
575 pub unsafe fn put_slot_unchecked(
583 mut self,
584 slot_idx: usize,
585 replacement: ArrayRef,
586 ) -> VortexResult<ArrayRef> {
587 if let Some(inner) = self.inner_mut() {
588 inner.slots[slot_idx] = Some(replacement);
589 return Ok(self);
590 }
591
592 let mut slots: ArraySlots = self.slots().iter().cloned().collect();
593 slots[slot_idx] = Some(replacement);
594 self.0.data.with_slots(&self, slots)
595 }
596
597 pub unsafe fn with_slots(self, slots: ArraySlots) -> VortexResult<ArrayRef> {
608 let old_slots = self.slots();
609 vortex_ensure_eq!(
610 old_slots.len(),
611 slots.len(),
612 "slot count changed during physical rewrite"
613 );
614 for (idx, (old_slot, new_slot)) in old_slots.iter().zip(slots.iter()).enumerate() {
615 vortex_ensure_eq!(
616 old_slot.is_some(),
617 new_slot.is_some(),
618 "slot {} presence changed during physical rewrite",
619 idx
620 );
621 if let (Some(old_slot), Some(new_slot)) = (old_slot.as_ref(), new_slot.as_ref()) {
622 vortex_ensure_eq!(
623 old_slot.dtype(),
624 new_slot.dtype(),
625 "slot {} dtype changed during physical rewrite",
626 idx
627 );
628 vortex_ensure_eq!(
629 old_slot.len(),
630 new_slot.len(),
631 "slot {} len changed during physical rewrite",
632 idx
633 );
634 }
635 }
636 self.0.data.with_slots(&self, slots)
637 }
638
639 pub unsafe fn with_buffers(
652 self,
653 buffers: impl IntoIterator<Item = BufferHandle>,
654 ) -> VortexResult<ArrayRef> {
655 let buffers = buffers.into_iter().collect::<Vec<_>>();
656 let nbuffers = self.nbuffers();
657 vortex_ensure_eq!(
658 nbuffers,
659 buffers.len(),
660 "buffer count changed during physical rewrite"
661 );
662 for (idx, (old_buffer, new_buffer)) in self
663 .buffer_handles()
664 .into_iter()
665 .zip(buffers.iter())
666 .enumerate()
667 {
668 vortex_ensure_eq!(
669 old_buffer.len(),
670 new_buffer.len(),
671 "buffer {} length changed during physical rewrite",
672 idx
673 );
674 }
675 self.0.data.with_buffers(&self, buffers)
676 }
677
678 pub fn reduce(&self) -> VortexResult<Option<ArrayRef>> {
679 self.0.data.reduce(self)
680 }
681
682 pub(crate) fn execute_encoding(self, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
683 let len = self.len();
684 let dtype = self.dtype().clone();
685 let stats = self.statistics().share_existing();
686 let encoding_id = self.encoding_id();
687 let result = self.execute_encoding_unchecked(ctx)?;
688
689 if matches!(result.step(), ExecutionStep::Done) {
690 if cfg!(debug_assertions) {
691 vortex_ensure_eq!(
692 result.array().len(),
693 len,
694 "Result length mismatch for {encoding_id}"
695 );
696 vortex_ensure_eq!(
697 result.array().dtype(),
698 &dtype,
699 "Executed canonical dtype mismatch for {encoding_id}"
700 );
701 }
702 result.array().statistics().transfer_from(&stats);
703 }
704 Ok(result)
705 }
706
707 pub(crate) fn execute_encoding_unchecked(
713 self,
714 ctx: &mut ExecutionCtx,
715 ) -> VortexResult<ExecutionResult> {
716 let execute = self.0.data.execute_fn();
721 execute(self, ctx)
722 }
723
724 pub fn children_iter(&self) -> impl Iterator<Item = &ArrayRef> {
728 self.0.slots.iter().filter_map(|s| s.as_ref())
729 }
730
731 pub fn children(&self) -> Vec<ArrayRef> {
733 self.children_iter().cloned().collect()
734 }
735
736 pub fn nchildren(&self) -> usize {
738 self.children_iter().count()
739 }
740
741 pub fn nth_child(&self, idx: usize) -> Option<&ArrayRef> {
745 self.children_iter().nth(idx)
746 }
747
748 pub fn children_names(&self) -> Vec<String> {
751 self.0
752 .slots
753 .iter()
754 .enumerate()
755 .filter(|(_, s)| s.is_some())
756 .map(|(slot_idx, _)| self.slot_name(slot_idx))
757 .collect()
758 }
759
760 pub fn named_children(&self) -> Vec<(String, ArrayRef)> {
762 self.children_names()
763 .into_iter()
764 .zip(self.children_iter().cloned())
765 .collect()
766 }
767
768 pub fn buffers(&self) -> Vec<ByteBuffer> {
770 self.0.data.buffers(self)
771 }
772
773 pub fn buffer_handles(&self) -> Vec<BufferHandle> {
775 self.0.data.buffer_handles(self)
776 }
777
778 pub fn buffer_names(&self) -> Vec<String> {
780 self.0.data.buffer_names(self)
781 }
782
783 pub fn named_buffers(&self) -> Vec<(String, BufferHandle)> {
785 self.0.data.named_buffers(self)
786 }
787
788 pub fn nbuffers(&self) -> usize {
790 self.0.data.nbuffers(self)
791 }
792
793 pub fn slots(&self) -> &[Option<ArrayRef>] {
795 &self.0.slots
796 }
797
798 pub fn slot_name(&self, idx: usize) -> String {
800 self.0.data.slot_name(self, idx)
801 }
802
803 pub fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
805 self.0.data.metadata_fmt(f)
806 }
807
808 pub fn is_host(&self) -> bool {
810 for array in self.depth_first_traversal() {
811 if !array.buffer_handles().iter().all(BufferHandle::is_on_host) {
812 return false;
813 }
814 }
815 true
816 }
817
818 pub fn nbuffers_recursive(&self) -> usize {
822 self.children()
823 .iter()
824 .map(|c| c.nbuffers_recursive())
825 .sum::<usize>()
826 + self.nbuffers()
827 }
828
829 pub fn depth_first_traversal(&self) -> DepthFirstArrayIterator {
831 DepthFirstArrayIterator {
832 stack: vec![self.clone()],
833 }
834 }
835}
836
837impl IntoArray for ArrayRef {
838 #[allow(clippy::inline_always)]
839 #[inline(always)]
840 fn into_array(self) -> ArrayRef {
841 self
842 }
843}
844
845impl<V: VTable> Matcher for V {
846 type Match<'a> = ArrayView<'a, V>;
847
848 #[inline]
849 fn matches(array: &ArrayRef) -> bool {
850 array.0.data.as_any().is::<ArrayData<V>>()
851 }
852
853 #[inline]
854 fn try_match(array: &'_ ArrayRef) -> Option<ArrayView<'_, V>> {
855 let inner = array.0.data.as_any().downcast_ref::<ArrayData<V>>()?;
856 Some(unsafe { ArrayView::new_unchecked(array, &inner.data) })
858 }
859}