Skip to main content

vortex_array/array/
erased.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use 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
59/// A depth-first pre-order iterator over an Array.
60pub 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/// A reference-counted pointer to a type-erased array.
77///
78/// Wraps `Arc<ArrayInner<dyn DynArrayData>>` — a single 16-byte fat pointer.
79/// Metadata (`len`, `dtype`, `encoding_id`) lives in `ArrayInner::meta` and is
80/// accessed as a normal struct field read — no vtable dispatch, no extra allocation.
81#[derive(Clone)]
82pub struct ArrayRef(Arc<ArrayInner<dyn DynArrayData>>);
83
84impl ArrayRef {
85    /// Create from an `Arc<ArrayInner<dyn DynArrayData>>`.
86    pub(crate) fn from_inner<D: DynArrayData>(inner: Arc<ArrayInner<D>>) -> Self {
87        Self(inner)
88    }
89
90    /// Returns a reference to the `dyn DynArrayData` inside the inner.
91    #[allow(clippy::inline_always)]
92    #[inline(always)]
93    pub(crate) fn dyn_array(&self) -> &dyn DynArrayData {
94        &self.0.data
95    }
96
97    /// Returns a mutable reference to the inner if this is the sole owner.
98    ///
99    /// The caller may change the array, so it is no longer known to be optimized.
100    #[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    /// Returns the record of whether the optimizer has already taken this array to its fixpoint.
109    ///
110    /// Only the optimizer can read or set the record.
111    pub(crate) fn optimized_state(&self) -> &OptimizedState {
112        &self.0.optimized
113    }
114
115    /// Returns whether another owner holds this array too.
116    pub(crate) fn is_shared(&self) -> bool {
117        Arc::strong_count(&self.0) > 1
118    }
119
120    /// Returns the Arc::as_ptr().addr() of the underlying array.
121    /// This function is used in a couple of places, and we should migrate them to using array_eq.
122    #[doc(hidden)]
123    pub fn addr(&self) -> usize {
124        Arc::as_ptr(&self.0).addr()
125    }
126
127    /// Downcast the inner to a concrete `ArrayInner<ArrayData<V>>`.
128    ///
129    /// Uses the same raw-pointer technique as `Arc::downcast`.
130    #[allow(dead_code)]
131    pub(crate) fn downcast_inner<V: VTable>(self) -> Result<Arc<ArrayInner<ArrayData<V>>>, Self> {
132        // TODO(joe): can we use encoding id here?
133        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    /// Downcast without a runtime type check.
141    ///
142    /// # Safety
143    /// The caller must guarantee the concrete type behind `dyn DynArrayData` is `ArrayData<V>`.
144    #[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        // Recover the original concrete Arc. The fat pointer's data pointer is the
151        // same allocation that was originally `Arc<ArrayInner<ArrayData<V>>>` before
152        // unsized coercion to `Arc<ArrayInner<dyn DynArrayData>>`.
153        let raw = Arc::into_raw(self.0);
154        // # Safety all arrays are constructed in this way and type aliased.
155        unsafe { Arc::from_raw(raw.cast::<ArrayInner<ArrayData<V>>>()) }
156    }
157
158    /// Returns true if the two ArrayRefs point to the same allocation.
159    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    /// Returns the length of the array.
207    #[inline]
208    pub fn len(&self) -> usize {
209        self.0.len
210    }
211
212    /// Returns whether the array is empty (has zero rows).
213    #[inline]
214    pub fn is_empty(&self) -> bool {
215        self.0.len == 0
216    }
217
218    /// Returns the logical Vortex [`DType`] of the array.
219    #[inline]
220    pub fn dtype(&self) -> &DType {
221        &self.0.dtype
222    }
223
224    /// Returns the encoding ID of the array.
225    #[inline]
226    pub fn encoding_id(&self) -> ArrayId {
227        self.0.encoding_id
228    }
229
230    /// Performs a constant-time slice of the array.
231    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        // Propagate some stats from the original array to the sliced array.
252        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    /// Wraps the array in a [`FilterArray`] such that it is logically filtered by the given mask.
268    pub fn filter(&self, mask: Mask) -> VortexResult<ArrayRef> {
269        Ok(FilterArray::try_new(self.clone(), mask)?.into_array())
270    }
271
272    /// Wraps the array in a [`DictArray`] such that it is logically taken by the given indices.
273    pub fn take(&self, indices: ArrayRef) -> VortexResult<ArrayRef> {
274        Ok(DictArray::try_new(indices, self.clone())?.into_array())
275    }
276
277    /// Execute the array to extract a scalar at the given index.
278    ///
279    /// A one-off read; the same as `self.probe().execute_scalar(index, ctx)`.
280    // TODO(joe): deprecate this in favour of `probe()`.
281    #[inline]
282    pub fn execute_scalar(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<Scalar> {
283        self.probe().execute_scalar(index, ctx)
284    }
285
286    /// A one-off row accessor over this array. It borrows the handle and retains nothing; for
287    /// many reads of the same array use [`Self::repeated_probe`].
288    ///
289    /// ```
290    /// use vortex_session::VortexSession;
291    /// use vortex_array::{IntoArray, VortexSessionExecute};
292    /// use vortex_array::arrays::PrimitiveArray;
293    ///
294    /// let array = PrimitiveArray::from_iter([10i32, 20, 30]).into_array();
295    /// let mut ctx = VortexSession::empty().create_execution_ctx();
296    /// assert_eq!(array.probe().execute_scalar(2, &mut ctx)?, 30i32.into());
297    /// # Ok::<(), vortex_error::VortexError>(())
298    /// ```
299    #[inline]
300    pub fn probe(&self) -> ArrayProbe<'_> {
301        ArrayProbe::Once(self)
302    }
303
304    /// A row accessor that owns a handle to this array and keeps encoding state, its validity
305    /// probe and child probes between reads.
306    ///
307    /// ```
308    /// use vortex_session::VortexSession;
309    /// use vortex_array::{IntoArray, VortexSessionExecute};
310    /// use vortex_array::arrays::PrimitiveArray;
311    ///
312    /// let array = PrimitiveArray::from_iter([10i32, 20, 30]).into_array();
313    /// let mut ctx = VortexSession::empty().create_execution_ctx();
314    /// let mut probe = array.repeated_probe();
315    /// assert_eq!(probe.execute_scalar(2, &mut ctx)?, 30i32.into());
316    /// assert_eq!(probe.execute_scalar(0, &mut ctx)?, 10i32.into());
317    /// # Ok::<(), vortex_error::VortexError>(())
318    /// ```
319    pub fn repeated_probe(&self) -> RepeatedArrayProbe {
320        RepeatedArrayProbe::new(self.clone())
321    }
322
323    /// Returns whether the item at `index` is valid.
324    ///
325    /// A one-off read; the same as `self.probe().execute_is_valid(index, ctx)`.
326    // TODO(joe): deprecate this in favour of `probe/repeated_probe()`.
327    #[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    /// Returns whether the item at `index` is invalid.
333    // TODO(joe): deprecate this.
334    #[inline]
335    pub fn is_invalid(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
336        Ok(!self.is_valid(index, ctx)?)
337    }
338
339    /// Returns whether all items in the array are valid.
340    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    /// Returns whether the array is all invalid.
353    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    /// Returns the number of valid elements in the array.
366    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    /// Returns the number of invalid elements in the array.
393    pub fn invalid_count(&self, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
394        Ok(self.len() - self.valid_count(ctx)?)
395    }
396
397    /// Returns the [`Validity`] of the array.
398    pub fn validity(&self) -> VortexResult<Validity> {
399        self.0.data.validity(self)
400    }
401
402    /// Writes the array into the canonical builder.
403    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    /// Returns the statistics of the array.
414    pub fn statistics(&self) -> StatsSetRef<'_> {
415        self.0.stats.to_ref(self)
416    }
417
418    /// Does the array match the given matcher.
419    #[inline]
420    pub fn is<M: Matcher>(&self) -> bool {
421        M::matches(self)
422    }
423
424    /// Returns the array downcast by the given matcher.
425    #[inline]
426    pub fn as_<M: Matcher>(&self) -> M::Match<'_> {
427        self.as_opt::<M>().vortex_expect("Failed to downcast")
428    }
429
430    /// Returns the array downcast by the given matcher.
431    #[inline]
432    pub fn as_opt<M: Matcher>(&self) -> Option<M::Match<'_>> {
433        M::try_match(self)
434    }
435
436    /// Returns the array downcast to the given `Array<V>` as an owned typed handle.
437    pub fn try_downcast<V: VTable>(self) -> Result<Array<V>, ArrayRef> {
438        Array::<V>::try_from_array_ref(self)
439    }
440
441    /// Returns the array downcast to the given `Array<V>` as an owned typed handle.
442    ///
443    /// # Panics
444    ///
445    /// Panics if the array is not of the given type.
446    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    /// Returns a reference to the typed `ArrayData<V>` if this array matches the given vtable type.
452    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    /// Returns a typed view without a runtime type check.
458    ///
459    /// # Safety
460    /// The caller must guarantee the concrete type behind `dyn DynArrayData` is `ArrayData<V>`.
461    #[inline]
462    pub(crate) unsafe fn as_typed_unchecked<V: VTable>(&self) -> ArrayView<'_, V> {
463        debug_assert!(self.is::<V>());
464        // SAFETY: the caller guarantees the concrete type, so the thin data pointer of the
465        // `dyn DynArrayData` points at an `ArrayData<V>`.
466        let inner = unsafe { &*ptr::from_ref(self.dyn_array()).cast::<ArrayData<V>>() };
467        // SAFETY: `inner` is the typed data stored inside `self`.
468        unsafe { ArrayView::new_unchecked(self, &inner.data) }
469    }
470
471    /// Returns the constant scalar if this is a constant array.
472    pub fn as_constant(&self) -> Option<&Scalar> {
473        self.as_opt::<Constant>().map(|a| a.data().scalar())
474    }
475
476    /// Total size of the array in bytes, including all children and buffers.
477    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    /// Whether the array is of a canonical encoding.
488    pub fn is_canonical(&self) -> bool {
489        self.is::<AnyCanonical>()
490    }
491
492    /// Returns a new array with the slot at `slot_idx` replaced by `replacement`.
493    ///
494    /// This is only valid for physical rewrites: the replacement must have the same logical
495    /// `DType` and `len` as the existing slot.
496    ///
497    /// # Safety
498    ///
499    /// If this returns `Ok`, the caller must guarantee that the replacement slot represents the
500    /// same logical values as the original slot. Only the physical representation may change.
501    /// Existing parent statistics are preserved and must remain valid.
502    ///
503    /// Takes ownership to allow in-place mutation when the refcount is 1.
504    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        // SAFETY: upheld by the caller of this unsafe API.
534        unsafe { self.with_slots(slots) }
535    }
536
537    /// Take a slot for executor-owned physical rewrites.
538    ///
539    /// On return the produced parent has the taken slot set to `None`
540    /// callers must put the slot back (typically via [`Self::put_slot_unchecked`]) before the parent is
541    /// returned from the execution loop.
542    ///
543    /// When the `Arc` was shared this allocates a fresh parent.
544    ///
545    /// # Safety
546    /// The caller must put back a slot with the same logical dtype and length before exposing the
547    /// parent array, and must only use this for physical rewrites.
548    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        // Arc is shared: clone the child out and build a fresh parent with slot_idx = None,
560        // bypassing encoding-level validation so the absent slot does not panic `V::validate`.
561        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        // SAFETY: ensured by the caller — the None slot is either put back or driven to completion
570        // via the builder path before the parent escapes the executor.
571        let new_parent = unsafe { self.0.data.with_slots_unchecked(&self, new_slots) };
572        Ok((new_parent, child))
573    }
574
575    /// Puts an array into `slot_idx` by either, cloning the inner array if the Arc is not exclusive
576    /// or replacing the slot in this `ArrayRef`.
577    /// This is the mirror of [`Self::take_slot_unchecked`].
578    ///
579    /// # Safety
580    /// The replacement must have the same logical dtype and length as the taken slot, and this
581    /// must only be used for physical rewrites.
582    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    /// Returns a new array with the provided slots.
598    ///
599    /// This is only valid for physical rewrites: slot count, presence, logical `DType`, and
600    /// logical `len` must remain unchanged.
601    ///
602    /// # Safety
603    ///
604    /// If this returns `Ok`, the caller must guarantee that each replacement slot represents the
605    /// same logical values as the original slot. Only physical representation may change. Existing
606    /// parent statistics are preserved and must remain valid.
607    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    /// Returns a new array with the provided top-level buffer handles.
640    ///
641    /// This is only valid for physical rewrites: buffer count, logical `DType`, logical `len`, and
642    /// child slots must remain unchanged. Encoding-specific validation checks buffer shape,
643    /// alignment, and metadata consistency.
644    ///
645    /// # Safety
646    ///
647    /// If this returns `Ok`, the caller must guarantee that the replacement buffers represent the
648    /// same logical values as the original buffers. Only the buffer handle implementation,
649    /// placement, or backing storage may change. Existing statistics are preserved and must remain
650    /// valid.
651    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    /// Execute a single encoding step without applying `Done`-result postconditions.
708    ///
709    /// This is for the iterative executor only. It may operate on suspended executor-private
710    /// arrays whose slots temporarily contain `None`, so the executor itself must interpret
711    /// `Done`, enforce any `len`/`dtype` invariants, and transfer statistics.
712    pub(crate) fn execute_encoding_unchecked(
713        self,
714        ctx: &mut ExecutionCtx,
715    ) -> VortexResult<ExecutionResult> {
716        // Take the step as a function first, so no borrow of the array's data is live while the
717        // step runs and possibly drops the last reference. Moving `self` in without an extra
718        // `Arc` clone preserves uniqueness, so execute-time metadata cursors can use
719        // `Arc::get_mut`.
720        let execute = self.0.data.execute_fn();
721        execute(self, ctx)
722    }
723
724    // ArrayVisitor delegation methods
725
726    /// Returns an iterator over the children of the array: its non-None slots in order.
727    pub fn children_iter(&self) -> impl Iterator<Item = &ArrayRef> {
728        self.0.slots.iter().filter_map(|s| s.as_ref())
729    }
730
731    /// Returns the children of the array.
732    pub fn children(&self) -> Vec<ArrayRef> {
733        self.children_iter().cloned().collect()
734    }
735
736    /// Returns the number of children of the array.
737    pub fn nchildren(&self) -> usize {
738        self.children_iter().count()
739    }
740
741    /// Returns the nth child of the array without allocating a Vec.
742    ///
743    /// Returns `None` if the index is out of bounds.
744    pub fn nth_child(&self, idx: usize) -> Option<&ArrayRef> {
745        self.children_iter().nth(idx)
746    }
747
748    /// Returns the names of the children of the array: the slot names of the non-None slots
749    /// in order.
750    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    /// Returns the array's children with their names.
761    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    /// Returns the data buffers of the array.
769    pub fn buffers(&self) -> Vec<ByteBuffer> {
770        self.0.data.buffers(self)
771    }
772
773    /// Returns the buffer handles of the array.
774    pub fn buffer_handles(&self) -> Vec<BufferHandle> {
775        self.0.data.buffer_handles(self)
776    }
777
778    /// Returns the names of the buffers of the array.
779    pub fn buffer_names(&self) -> Vec<String> {
780        self.0.data.buffer_names(self)
781    }
782
783    /// Returns the array's buffers with their names.
784    pub fn named_buffers(&self) -> Vec<(String, BufferHandle)> {
785        self.0.data.named_buffers(self)
786    }
787
788    /// Returns the number of data buffers of the array.
789    pub fn nbuffers(&self) -> usize {
790        self.0.data.nbuffers(self)
791    }
792
793    /// Returns the slots of the array.
794    pub fn slots(&self) -> &[Option<ArrayRef>] {
795        &self.0.slots
796    }
797
798    /// Returns the name of the slot at the given index.
799    pub fn slot_name(&self, idx: usize) -> String {
800        self.0.data.slot_name(self, idx)
801    }
802
803    /// Formats a human-readable metadata description.
804    pub fn metadata_fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
805        self.0.data.metadata_fmt(f)
806    }
807
808    /// Returns whether all buffers are host-resident.
809    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    // ArrayVisitorExt delegation methods
819
820    /// Count the number of buffers encoded by self and all child arrays.
821    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    /// Depth-first traversal of the array and its children.
830    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        // # Safety checked by `downcast_ref`.
857        Some(unsafe { ArrayView::new_unchecked(array, &inner.data) })
858    }
859}