Skip to main content

vortex_array/arrays/widen/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Array operations for the `Widen` encoding.
5//!
6//! Execution produces values at the logical dtype's width. [`WidenPlugin`] handles storage at the
7//! child's width.
8
9mod operations;
10
11mod plugin;
12pub use plugin::WidenPlugin;
13
14mod validity;
15
16use vortex_buffer::Buffer;
17use vortex_error::VortexResult;
18use vortex_error::vortex_ensure_eq;
19use vortex_error::vortex_err;
20use vortex_error::vortex_panic;
21use vortex_session::registry::CachedId;
22
23use crate::ArrayRef;
24use crate::EmptyArrayData;
25use crate::ExecutionCtx;
26use crate::ExecutionResult;
27use crate::IntoArray;
28use crate::array::Array;
29use crate::array::ArrayId;
30use crate::array::ArrayParts;
31use crate::array::ArrayView;
32use crate::array::VTable;
33use crate::array::ValidityVTableFromChild;
34use crate::array::with_empty_buffers;
35use crate::arrays::Decimal;
36use crate::arrays::DecimalArray;
37use crate::arrays::decimal::widened_buffer;
38use crate::arrays::widen::WidenArraySlotsExt;
39use crate::arrays::widen::WidenSlots;
40use crate::arrays::widen::array::validate_dtypes;
41use crate::buffer::BufferHandle;
42use crate::builtins::ArrayBuiltins;
43use crate::dtype::DType;
44use crate::dtype::DecimalDType;
45use crate::dtype::NativeDecimalType;
46use crate::match_each_decimal_value_type;
47use crate::require_child;
48
49/// The encoding of a [`WidenArray`].
50#[derive(Clone, Debug)]
51pub struct Widen;
52
53/// A [`Widen`]-encoded integer or decimal array.
54pub type WidenArray = Array<Widen>;
55
56impl VTable for Widen {
57    type TypedArrayData = EmptyArrayData;
58
59    type OperationsVTable = Self;
60    type ValidityVTable = ValidityVTableFromChild;
61
62    fn id(&self) -> ArrayId {
63        static ID: CachedId = CachedId::new("vortex.widen");
64        *ID
65    }
66
67    fn validate(
68        &self,
69        _data: &EmptyArrayData,
70        dtype: &DType,
71        len: usize,
72        slots: &[Option<ArrayRef>],
73    ) -> VortexResult<()> {
74        vortex_ensure_eq!(slots.len(), WidenSlots::COUNT);
75        let values = slots[WidenSlots::VALUES]
76            .as_ref()
77            .ok_or_else(|| vortex_err!("Widen requires a values child"))?;
78        vortex_ensure_eq!(values.len(), len);
79
80        validate_dtypes(values.dtype(), dtype)
81    }
82
83    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
84        0
85    }
86
87    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
88        vortex_panic!("Widen buffer index {idx} out of bounds")
89    }
90
91    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
92        None
93    }
94
95    fn with_buffers(
96        &self,
97        array: ArrayView<'_, Self>,
98        buffers: &[BufferHandle],
99    ) -> VortexResult<ArrayParts<Self>> {
100        with_empty_buffers(self, array, buffers)
101    }
102
103    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
104        WidenSlots::NAMES[idx].to_string()
105    }
106
107    fn execute(array: Array<Self>, _ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
108        match array.dtype() {
109            DType::Decimal(decimal_dtype, _) => {
110                let decimal_dtype = *decimal_dtype;
111                let array = require_child!(array, array.values(), WidenSlots::VALUES => Decimal);
112                let values = array.values().as_::<Decimal>();
113                let target_type = decimal_dtype.canonical_values_type();
114                let widened = match_each_decimal_value_type!(target_type, |T| {
115                    copy_decimal_values::<T>(values, decimal_dtype)?
116                });
117
118                Ok(ExecutionResult::done(widened.into_array()))
119            }
120            DType::Primitive(..) => {
121                // Integer casts let the child's kernel decode and widen its values in one pass.
122                let widened = array.values().cast(array.dtype().clone())?;
123
124                Ok(ExecutionResult::done(widened))
125            }
126            dtype => {
127                vortex_panic!("Widen validation requires an integer or decimal dtype, got {dtype}")
128            }
129        }
130    }
131
132    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
133        // A physical rewrite keeps only the dtype of each child, so it can put a `Widen` here.
134        if !array.values().is::<Widen>() {
135            return Ok(None);
136        }
137
138        let flattened = WidenArray::try_new(array.values().clone(), array.dtype().clone())?;
139        Ok(Some(flattened.into_array()))
140    }
141}
142
143/// Copies the executed decimal `values` of a [`WidenArray`] into the canonical width of
144/// `decimal_dtype`, the logical dtype of the `Widen`.
145fn copy_decimal_values<T: NativeDecimalType>(
146    values: ArrayView<'_, Decimal>,
147    decimal_dtype: DecimalDType,
148) -> VortexResult<DecimalArray> {
149    let validity = values.validity()?;
150    let buffer = if values.is_empty() {
151        Buffer::<T>::from_iter(std::iter::empty())
152    } else {
153        widened_buffer::<T>(&values)
154    };
155
156    // The wider precision holds every value of the child's native type, at the same scale.
157    DecimalArray::try_new_handle_from_trusted_values(
158        BufferHandle::new_host(buffer.into_byte_buffer()),
159        T::DECIMAL_TYPE,
160        decimal_dtype,
161        validity,
162    )
163}