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//! Vtable and wire adapter for the in-memory `Widen` encoding.
5//!
6//! Execution restores the logical width. The writer plugin uses an existing wire form because
7//! `Widen` has no wire form of its own.
8
9mod operations;
10
11mod plugin;
12pub use plugin::WidenPlugin;
13
14mod validity;
15
16use vortex_error::VortexResult;
17use vortex_error::vortex_bail;
18use vortex_error::vortex_ensure_eq;
19use vortex_error::vortex_err;
20use vortex_error::vortex_panic;
21use vortex_session::VortexSession;
22use vortex_session::registry::CachedId;
23
24use crate::ArrayRef;
25use crate::EmptyArrayData;
26use crate::ExecutionCtx;
27use crate::ExecutionResult;
28use crate::IntoArray;
29use crate::array::Array;
30use crate::array::ArrayId;
31use crate::array::ArrayParts;
32use crate::array::ArrayView;
33use crate::array::VTable;
34use crate::array::ValidityVTableFromChild;
35use crate::array::with_empty_buffers;
36use crate::arrays::Decimal;
37use crate::arrays::DecimalArray;
38use crate::arrays::decimal::DecimalArrayExt;
39use crate::arrays::decimal::copy_to_canonical_width;
40use crate::arrays::widen::WidenArraySlotsExt;
41use crate::arrays::widen::WidenSlots;
42use crate::arrays::widen::array::validate_dtypes;
43use crate::arrays::widen::compute::rules::PARENT_RULES;
44use crate::buffer::BufferHandle;
45use crate::builtins::ArrayBuiltins;
46use crate::dtype::DType;
47use crate::dtype::DecimalDType;
48use crate::match_each_decimal_value_type;
49use crate::require_child;
50use crate::serde::ArrayChildren;
51
52/// The encoding of a [`WidenArray`].
53#[derive(Clone, Debug)]
54pub struct Widen;
55
56/// A [`Widen`]-encoded integer or decimal array.
57pub type WidenArray = Array<Widen>;
58
59impl VTable for Widen {
60    type TypedArrayData = EmptyArrayData;
61
62    type OperationsVTable = Self;
63    type ValidityVTable = ValidityVTableFromChild;
64
65    fn id(&self) -> ArrayId {
66        static ID: CachedId = CachedId::new("vortex.widen");
67        *ID
68    }
69
70    fn validate(
71        &self,
72        _data: &EmptyArrayData,
73        dtype: &DType,
74        len: usize,
75        slots: &[Option<ArrayRef>],
76    ) -> VortexResult<()> {
77        vortex_ensure_eq!(slots.len(), WidenSlots::COUNT);
78        let values = slots[WidenSlots::VALUES]
79            .as_ref()
80            .ok_or_else(|| vortex_err!("Widen requires a values child"))?;
81        vortex_ensure_eq!(values.len(), len);
82
83        validate_dtypes(values.dtype(), dtype)
84    }
85
86    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
87        0
88    }
89
90    fn buffer(_array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
91        vortex_panic!("Widen buffer index {idx} out of bounds")
92    }
93
94    fn buffer_name(_array: ArrayView<'_, Self>, _idx: usize) -> Option<String> {
95        None
96    }
97
98    fn with_buffers(
99        &self,
100        array: ArrayView<'_, Self>,
101        buffers: &[BufferHandle],
102    ) -> VortexResult<ArrayParts<Self>> {
103        with_empty_buffers(self, array, buffers)
104    }
105
106    fn serialize(
107        _array: ArrayView<'_, Self>,
108        _session: &VortexSession,
109    ) -> VortexResult<Option<Vec<u8>>> {
110        Ok(None)
111    }
112
113    fn deserialize(
114        &self,
115        _dtype: &DType,
116        _len: usize,
117        _metadata: &[u8],
118        _buffers: &[BufferHandle],
119        _children: &dyn ArrayChildren,
120        _session: &VortexSession,
121    ) -> VortexResult<ArrayParts<Self>> {
122        vortex_bail!("Widen deserialization is not supported")
123    }
124
125    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
126        WidenSlots::NAMES[idx].to_string()
127    }
128
129    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
130        match array.dtype() {
131            DType::Decimal(decimal_dtype, _) => {
132                // The result must use the logical decimal dtype's canonical buffer width,
133                // independently of the child's stored width.
134                let decimal_dtype = *decimal_dtype;
135                let array = require_child!(array, array.values(), WidenSlots::VALUES => Decimal);
136                let widened =
137                    copy_decimal_values(array.values().as_::<Decimal>(), decimal_dtype, ctx)?;
138
139                Ok(ExecutionResult::done(widened.into_array()))
140            }
141            DType::Primitive(..) => {
142                // Integer casts let the child's kernel decode and widen its values in one pass.
143                let widened = array.values().cast(array.dtype().clone())?;
144
145                Ok(ExecutionResult::done(widened))
146            }
147            dtype => {
148                vortex_panic!("Widen validation requires an integer or decimal dtype, got {dtype}")
149            }
150        }
151    }
152
153    fn reduce(array: ArrayView<'_, Self>) -> VortexResult<Option<ArrayRef>> {
154        // A physical rewrite keeps only the dtype of each child, so it can put a `Widen` here.
155        if !array.values().is::<Widen>() {
156            return Ok(None);
157        }
158
159        let flattened = WidenArray::try_new(array.values().clone(), array.dtype().clone())?;
160        Ok(Some(flattened.into_array()))
161    }
162
163    fn reduce_parent(
164        array: ArrayView<'_, Self>,
165        parent: &ArrayRef,
166        child_idx: usize,
167    ) -> VortexResult<Option<ArrayRef>> {
168        PARENT_RULES.evaluate(array, parent, child_idx)
169    }
170}
171
172/// Copies the executed decimal `values` of a [`WidenArray`] into the canonical width of
173/// `decimal_dtype`, the logical dtype of the `Widen`.
174fn copy_decimal_values(
175    values: ArrayView<'_, Decimal>,
176    decimal_dtype: DecimalDType,
177    ctx: &mut ExecutionCtx,
178) -> VortexResult<DecimalArray> {
179    let validity = values.validity()?;
180    let mask = validity.execute_mask(values.len(), ctx)?;
181    let buffer_handle = match_each_decimal_value_type!(values.values_type(), |T| {
182        copy_to_canonical_width(values.buffer::<T>().as_slice(), &mask, decimal_dtype)?
183    });
184
185    Ok(DecimalArray::new_handle(
186        buffer_handle,
187        decimal_dtype.canonical_values_type(),
188        decimal_dtype,
189        validity,
190    ))
191}