vortex_array/arrays/decimal/
utils.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::{Itertools, MinMaxResult};
5use vortex_error::VortexExpect;
6use vortex_scalar::{DecimalType, i256};
7
8use crate::arrays::DecimalArray;
9use crate::vtable::ValidityHelper;
10
11macro_rules! try_downcast {
12    ($array:expr, from: $src:ty, to: $($dst:ty),*) => {{
13        use vortex_dtype::BigCast;
14
15        // Collect the min/max of the values
16        let minmax = $array.buffer::<$src>().iter().copied().minmax();
17        match minmax {
18            MinMaxResult::NoElements => return $array,
19            MinMaxResult::OneElement(_) => return $array,
20            MinMaxResult::MinMax(min, max) => {
21                $(
22                    if <$dst as BigCast>::from(min).is_some() && <$dst as BigCast>::from(max).is_some() {
23                        return DecimalArray::new::<$dst>(
24                            $array
25                                .buffer::<$src>()
26                                .into_iter()
27                                .map(|v| <$dst as BigCast>::from(v).vortex_expect("decimal conversion failure"))
28                                .collect(),
29                            $array.decimal_dtype(),
30                            $array.validity().clone(),
31                        );
32                    }
33                )*
34
35                return $array;
36            }
37        }
38    }};
39}
40
41/// Attempt to narrow the decimal array to any smaller supported type.
42pub fn narrowed_decimal(decimal_array: DecimalArray) -> DecimalArray {
43    match decimal_array.values_type() {
44        // Cannot narrow any more
45        DecimalType::I8 => decimal_array,
46        DecimalType::I16 => {
47            try_downcast!(decimal_array, from: i16, to: i8)
48        }
49        DecimalType::I32 => {
50            try_downcast!(decimal_array, from: i32, to: i8, i16)
51        }
52        DecimalType::I64 => {
53            try_downcast!(decimal_array, from: i64, to: i8, i16, i32)
54        }
55        DecimalType::I128 => {
56            try_downcast!(decimal_array, from: i128, to: i8, i16, i32, i64)
57        }
58        DecimalType::I256 => {
59            try_downcast!(decimal_array, from: i256, to: i8, i16, i32, i64, i128)
60        }
61    }
62}