Skip to main content

vortex_compressor/builtins/constant/
integer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Constant encoding for integer arrays.
5
6use vortex_array::ArrayRef;
7use vortex_array::Canonical;
8use vortex_error::VortexResult;
9
10use super::is_integer_primitive;
11use crate::CascadingCompressor;
12use crate::builtins::IntConstantScheme;
13use crate::builtins::constant::compress_constant_array_with_validity;
14use crate::ctx::CompressorContext;
15use crate::estimate::CompressionEstimate;
16use crate::estimate::EstimateVerdict;
17use crate::scheme::Scheme;
18use crate::stats::ArrayAndStats;
19
20impl Scheme for IntConstantScheme {
21    fn scheme_name(&self) -> &'static str {
22        "vortex.int.constant"
23    }
24
25    fn matches(&self, canonical: &Canonical) -> bool {
26        is_integer_primitive(canonical)
27    }
28
29    fn expected_compression_ratio(
30        &self,
31        data: &mut ArrayAndStats,
32        ctx: CompressorContext,
33    ) -> CompressionEstimate {
34        // Constant detection on a sample is a false positive, since the sample being constant does
35        // not mean the full array is constant.
36        if ctx.is_sample() {
37            return CompressionEstimate::Verdict(EstimateVerdict::Skip);
38        }
39
40        let array_len = data.array().len();
41        let stats = data.integer_stats();
42
43        // Note that we only compute distinct counts if other schemes have requested it.
44        if let Some(distinct_count) = stats.distinct_count() {
45            if distinct_count > 1 {
46                return CompressionEstimate::Verdict(EstimateVerdict::Skip);
47            } else {
48                debug_assert_eq!(distinct_count, 1);
49                return CompressionEstimate::Verdict(EstimateVerdict::AlwaysUse);
50            }
51        }
52
53        // We want to use `Constant` if there are only nulls in the array.
54        if stats.value_count() == 0 {
55            debug_assert_eq!(stats.null_count() as usize, array_len);
56            return CompressionEstimate::Verdict(EstimateVerdict::AlwaysUse);
57        }
58
59        // Otherwise, use the max and min to determine if there is a single value.
60        match stats.erased().max_minus_min().checked_ilog2() {
61            Some(_) => CompressionEstimate::Verdict(EstimateVerdict::Skip),
62            // If max-min == 0, then we know that there is only 1 value.
63            None => CompressionEstimate::Verdict(EstimateVerdict::AlwaysUse),
64        }
65    }
66
67    fn compress(
68        &self,
69        _compressor: &CascadingCompressor,
70        data: &mut ArrayAndStats,
71        _ctx: CompressorContext,
72    ) -> VortexResult<ArrayRef> {
73        compress_constant_array_with_validity(data.array())
74    }
75}