vortex_array/stats/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Traits and utilities to compute and access array statistics.
5
6use arrow_buffer::BooleanBufferBuilder;
7use arrow_buffer::MutableBuffer;
8use arrow_buffer::bit_iterator::BitIterator;
9use enum_iterator::last;
10pub use stats_set::*;
11
12mod array;
13pub mod flatbuffers;
14mod stats_set;
15
16pub use array::*;
17use vortex_error::VortexExpect;
18
19use crate::expr::stats::Stat;
20
21/// Statistics that are used for pruning files (i.e., we want to ensure they are computed when compressing/writing).
22/// Sum is included for boolean arrays.
23pub const PRUNING_STATS: &[Stat] = &[
24    Stat::Min,
25    Stat::Max,
26    Stat::Sum,
27    Stat::NullCount,
28    Stat::NaNCount,
29];
30
31pub fn as_stat_bitset_bytes(stats: &[Stat]) -> Vec<u8> {
32    let max_stat = u8::from(last::<Stat>().vortex_expect("last stat")) as usize + 1;
33    // TODO(ngates): use vortex-buffer::BitBuffer
34    let mut stat_bitset = BooleanBufferBuilder::new_from_buffer(
35        MutableBuffer::from_len_zeroed(max_stat.div_ceil(8)),
36        max_stat,
37    );
38    for stat in stats {
39        stat_bitset.set_bit(u8::from(*stat) as usize, true);
40    }
41
42    stat_bitset
43        .finish()
44        .into_inner()
45        .into_vec()
46        .unwrap_or_else(|b| b.to_vec())
47}
48
49pub fn stats_from_bitset_bytes(bytes: &[u8]) -> Vec<Stat> {
50    BitIterator::new(bytes, 0, bytes.len() * 8)
51        .enumerate()
52        .filter_map(|(i, b)| b.then_some(i))
53        // Filter out indices failing conversion, these are stats written by newer version of library
54        .filter_map(|i| {
55            let Ok(stat) = u8::try_from(i) else {
56                tracing::debug!("invalid stat encountered: {i}");
57                return None;
58            };
59            Stat::try_from(stat).ok()
60        })
61        .collect::<Vec<_>>()
62}