Skip to main content

vortex_array/arrays/constant/vtable/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::hash::Hash;
6use std::hash::Hasher;
7
8use vortex_buffer::ByteBufferMut;
9use vortex_error::VortexExpect;
10use vortex_error::VortexResult;
11use vortex_error::vortex_ensure;
12use vortex_error::vortex_panic;
13use vortex_session::VortexSession;
14use vortex_session::registry::CachedId;
15
16use crate::ArrayEq;
17use crate::ArrayHash;
18use crate::ArrayRef;
19use crate::ExecutionCtx;
20use crate::ExecutionResult;
21use crate::IntoArray;
22use crate::Precision;
23use crate::array::Array;
24use crate::array::ArrayId;
25use crate::array::ArrayView;
26use crate::array::VTable;
27use crate::arrays::constant::ConstantData;
28use crate::arrays::constant::compute::rules::PARENT_RULES;
29use crate::arrays::constant::vtable::canonical::constant_canonicalize;
30use crate::buffer::BufferHandle;
31use crate::builders::ArrayBuilder;
32use crate::builders::BoolBuilder;
33use crate::builders::DecimalBuilder;
34use crate::builders::NullBuilder;
35use crate::builders::PrimitiveBuilder;
36use crate::builders::VarBinViewBuilder;
37use crate::canonical::Canonical;
38use crate::dtype::DType;
39use crate::match_each_decimal_value;
40use crate::match_each_native_ptype;
41use crate::scalar::DecimalValue;
42use crate::scalar::Scalar;
43use crate::scalar::ScalarValue;
44use crate::serde::ArrayChildren;
45pub(crate) mod canonical;
46mod operations;
47mod validity;
48
49/// A [`Constant`]-encoded Vortex array.
50pub type ConstantArray = Array<Constant>;
51
52#[derive(Clone, Debug)]
53pub struct Constant;
54
55impl ArrayHash for ConstantData {
56    fn array_hash<H: Hasher>(&self, state: &mut H, _precision: Precision) {
57        self.scalar.hash(state);
58    }
59}
60
61impl ArrayEq for ConstantData {
62    fn array_eq(&self, other: &Self, _precision: Precision) -> bool {
63        self.scalar == other.scalar
64    }
65}
66
67impl VTable for Constant {
68    type ArrayData = ConstantData;
69
70    type OperationsVTable = Self;
71    type ValidityVTable = Self;
72
73    fn id(&self) -> ArrayId {
74        static ID: CachedId = CachedId::new("vortex.constant");
75        *ID
76    }
77
78    fn validate(
79        &self,
80        data: &ConstantData,
81        dtype: &DType,
82        _len: usize,
83        _slots: &[Option<ArrayRef>],
84    ) -> VortexResult<()> {
85        vortex_ensure!(
86            data.scalar.dtype() == dtype,
87            "ConstantArray scalar dtype does not match outer dtype"
88        );
89        Ok(())
90    }
91
92    fn nbuffers(_array: ArrayView<'_, Self>) -> usize {
93        1
94    }
95
96    fn buffer(array: ArrayView<'_, Self>, idx: usize) -> BufferHandle {
97        match idx {
98            0 => BufferHandle::new_host(
99                ScalarValue::to_proto_bytes::<ByteBufferMut>(array.scalar.value()).freeze(),
100            ),
101            _ => vortex_panic!("ConstantArray buffer index {idx} out of bounds"),
102        }
103    }
104
105    fn buffer_name(_array: ArrayView<'_, Self>, idx: usize) -> Option<String> {
106        match idx {
107            0 => Some("scalar".to_string()),
108            _ => None,
109        }
110    }
111
112    fn slot_name(_array: ArrayView<'_, Self>, idx: usize) -> String {
113        vortex_panic!("ConstantArray slot_name index {idx} out of bounds")
114    }
115
116    fn serialize(
117        _array: ArrayView<'_, Self>,
118        _session: &VortexSession,
119    ) -> VortexResult<Option<Vec<u8>>> {
120        // HACK: Because the scalar is stored in the buffers, we do not need to serialize the
121        // metadata at all.
122        Ok(Some(vec![]))
123    }
124
125    fn deserialize(
126        &self,
127        dtype: &DType,
128        len: usize,
129        _metadata: &[u8],
130
131        buffers: &[BufferHandle],
132        _children: &dyn ArrayChildren,
133        session: &VortexSession,
134    ) -> VortexResult<crate::array::ArrayParts<Self>> {
135        vortex_ensure!(
136            buffers.len() == 1,
137            "Expected 1 buffer, got {}",
138            buffers.len()
139        );
140
141        let buffer = buffers[0].clone().try_to_host_sync()?;
142        let bytes: &[u8] = buffer.as_ref();
143
144        let scalar_value = ScalarValue::from_proto_bytes(bytes, dtype, session)?;
145        let scalar = Scalar::try_new(dtype.clone(), scalar_value)?;
146
147        Ok(crate::array::ArrayParts::new(
148            self.clone(),
149            dtype.clone(),
150            len,
151            ConstantData::new(scalar),
152        ))
153    }
154
155    fn reduce_parent(
156        array: ArrayView<'_, Self>,
157        parent: &ArrayRef,
158        child_idx: usize,
159    ) -> VortexResult<Option<ArrayRef>> {
160        PARENT_RULES.evaluate(array, parent, child_idx)
161    }
162
163    fn execute(array: Array<Self>, ctx: &mut ExecutionCtx) -> VortexResult<ExecutionResult> {
164        Ok(ExecutionResult::done(constant_canonicalize(
165            array.as_view(),
166            ctx,
167        )?))
168    }
169
170    fn append_to_builder(
171        array: ArrayView<'_, Self>,
172        builder: &mut dyn ArrayBuilder,
173        ctx: &mut ExecutionCtx,
174    ) -> VortexResult<()> {
175        let n = array.len();
176        let scalar = array.scalar();
177
178        match array.dtype() {
179            DType::Null => append_value_or_nulls::<NullBuilder>(builder, true, n, |_| {}),
180            DType::Bool(_) => {
181                append_value_or_nulls::<BoolBuilder>(builder, scalar.is_null(), n, |b| {
182                    b.append_values(
183                        scalar
184                            .as_bool()
185                            .value()
186                            .vortex_expect("non-null bool scalar must have a value"),
187                        n,
188                    );
189                })
190            }
191            DType::Primitive(ptype, _) => {
192                match_each_native_ptype!(ptype, |P| {
193                    append_value_or_nulls::<PrimitiveBuilder<P>>(
194                        builder,
195                        scalar.is_null(),
196                        n,
197                        |b| {
198                            let value = P::try_from(scalar)
199                                .vortex_expect("Couldn't unwrap constant scalar to primitive");
200                            b.append_n_values(value, n);
201                        },
202                    );
203                });
204            }
205            DType::Decimal(..) => {
206                append_value_or_nulls::<DecimalBuilder>(builder, scalar.is_null(), n, |b| {
207                    let value = scalar
208                        .as_decimal()
209                        .decimal_value()
210                        .vortex_expect("non-null decimal scalar must have a value");
211                    match_each_decimal_value!(value, |v| { b.append_n_values(v, n) });
212                });
213            }
214            DType::Utf8(_) => {
215                append_value_or_nulls::<VarBinViewBuilder>(builder, scalar.is_null(), n, |b| {
216                    let typed = scalar.as_utf8();
217                    let value = typed
218                        .value()
219                        .vortex_expect("non-null utf8 scalar must have a value");
220                    b.append_n_values(value.as_bytes(), n);
221                });
222            }
223            DType::Binary(_) => {
224                append_value_or_nulls::<VarBinViewBuilder>(builder, scalar.is_null(), n, |b| {
225                    let typed = scalar.as_binary();
226                    let value = typed
227                        .value()
228                        .vortex_expect("non-null binary scalar must have a value");
229                    b.append_n_values(value, n);
230                });
231            }
232            // TODO: add fast paths for DType::Struct, DType::List, DType::FixedSizeList, DType::Extension.
233            _ => {
234                let canonical = array
235                    .array()
236                    .clone()
237                    .execute::<Canonical>(ctx)?
238                    .into_array();
239                builder.extend_from_array(&canonical);
240            }
241        }
242
243        Ok(())
244    }
245}
246
247/// Downcasts `builder` to `B`, then either appends `n` nulls or calls `fill` with the typed
248/// builder depending on `is_null`.
249///
250/// `is_null` must only be `true` when the builder is nullable.
251fn append_value_or_nulls<B: ArrayBuilder + 'static>(
252    builder: &mut dyn ArrayBuilder,
253    is_null: bool,
254    n: usize,
255    fill: impl FnOnce(&mut B),
256) {
257    let b = builder
258        .as_any_mut()
259        .downcast_mut::<B>()
260        .vortex_expect("builder dtype must match array dtype");
261    if is_null {
262        // SAFETY: is_null=true only when the scalar (and thus the builder) is nullable.
263        unsafe { b.append_nulls_unchecked(n) };
264    } else {
265        fill(b);
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use rstest::rstest;
272    use vortex_error::VortexResult;
273    use vortex_session::VortexSession;
274
275    use crate::IntoArray;
276    use crate::VortexSessionExecute;
277    use crate::arrays::ConstantArray;
278    use crate::arrays::constant::vtable::canonical::constant_canonicalize;
279    use crate::assert_arrays_eq;
280    use crate::builders::builder_with_capacity;
281    use crate::dtype::DType;
282    use crate::dtype::Nullability;
283    use crate::dtype::PType;
284    use crate::dtype::StructFields;
285    use crate::scalar::Scalar;
286
287    /// Appends `array` into a fresh builder and asserts the result matches `constant_canonicalize`.
288    fn assert_append_matches_canonical(array: ConstantArray) -> VortexResult<()> {
289        let mut ctx = VortexSession::empty().create_execution_ctx();
290
291        let expected = constant_canonicalize(array.as_view(), &mut ctx)?.into_array();
292        let mut builder = builder_with_capacity(array.dtype(), array.len());
293        array
294            .into_array()
295            .append_to_builder(builder.as_mut(), &mut ctx)?;
296        let result = builder.finish();
297        assert_arrays_eq!(&result, &expected);
298        Ok(())
299    }
300
301    #[test]
302    fn test_null_constant_append() -> VortexResult<()> {
303        assert_append_matches_canonical(ConstantArray::new(Scalar::null(DType::Null), 5))
304    }
305
306    #[rstest]
307    #[case::bool_true(true, 5)]
308    #[case::bool_false(false, 3)]
309    fn test_bool_constant_append(#[case] value: bool, #[case] n: usize) -> VortexResult<()> {
310        assert_append_matches_canonical(ConstantArray::new(
311            Scalar::bool(value, Nullability::NonNullable),
312            n,
313        ))
314    }
315
316    #[test]
317    fn test_bool_null_constant_append() -> VortexResult<()> {
318        assert_append_matches_canonical(ConstantArray::new(
319            Scalar::null(DType::Bool(Nullability::Nullable)),
320            4,
321        ))
322    }
323
324    #[rstest]
325    #[case::i32(Scalar::primitive(42i32, Nullability::NonNullable), 5)]
326    #[case::u8(Scalar::primitive(7u8, Nullability::NonNullable), 3)]
327    #[case::f64(Scalar::primitive(1.5f64, Nullability::NonNullable), 4)]
328    #[case::i32_null(Scalar::null(DType::Primitive(PType::I32, Nullability::Nullable)), 3)]
329    fn test_primitive_constant_append(
330        #[case] scalar: Scalar,
331        #[case] n: usize,
332    ) -> VortexResult<()> {
333        assert_append_matches_canonical(ConstantArray::new(scalar, n))
334    }
335
336    #[rstest]
337    #[case::utf8_inline("hi", 5)] // ≤12 bytes: inlined in BinaryView
338    #[case::utf8_noninline("hello world!!", 5)] // >12 bytes: requires buffer block
339    #[case::utf8_empty("", 3)]
340    #[case::utf8_n_zero("hello world!!", 0)] // n=0 with non-inline: must not write orphaned bytes
341    fn test_utf8_constant_append(#[case] value: &str, #[case] n: usize) -> VortexResult<()> {
342        assert_append_matches_canonical(ConstantArray::new(
343            Scalar::utf8(value, Nullability::NonNullable),
344            n,
345        ))
346    }
347
348    #[test]
349    fn test_utf8_null_constant_append() -> VortexResult<()> {
350        assert_append_matches_canonical(ConstantArray::new(
351            Scalar::null(DType::Utf8(Nullability::Nullable)),
352            4,
353        ))
354    }
355
356    #[rstest]
357    #[case::binary_inline(vec![1u8, 2, 3], 5)] // ≤12 bytes: inlined
358    #[case::binary_noninline(vec![0u8; 13], 5)] // >12 bytes: buffer block
359    fn test_binary_constant_append(#[case] value: Vec<u8>, #[case] n: usize) -> VortexResult<()> {
360        assert_append_matches_canonical(ConstantArray::new(
361            Scalar::binary(value, Nullability::NonNullable),
362            n,
363        ))
364    }
365
366    #[test]
367    fn test_binary_null_constant_append() -> VortexResult<()> {
368        assert_append_matches_canonical(ConstantArray::new(
369            Scalar::null(DType::Binary(Nullability::Nullable)),
370            4,
371        ))
372    }
373
374    #[test]
375    fn test_struct_constant_append() -> VortexResult<()> {
376        let fields = StructFields::new(
377            ["x", "y"].into(),
378            vec![
379                DType::Primitive(PType::I32, Nullability::NonNullable),
380                DType::Utf8(Nullability::NonNullable),
381            ],
382        );
383        let scalar = Scalar::struct_(
384            DType::Struct(fields, Nullability::NonNullable),
385            [
386                Scalar::primitive(42i32, Nullability::NonNullable),
387                Scalar::utf8("hi", Nullability::NonNullable),
388            ],
389        );
390        assert_append_matches_canonical(ConstantArray::new(scalar, 3))
391    }
392
393    #[test]
394    fn test_null_struct_constant_append() -> VortexResult<()> {
395        let fields = StructFields::new(
396            ["x"].into(),
397            vec![DType::Primitive(PType::I32, Nullability::Nullable)],
398        );
399        let dtype = DType::Struct(fields, Nullability::Nullable);
400        assert_append_matches_canonical(ConstantArray::new(Scalar::null(dtype), 4))
401    }
402}