Skip to main content

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 expr::all_nan;
11pub use expr::all_non_nan;
12pub use expr::all_non_null;
13pub use expr::all_null;
14pub use expr::min_max;
15pub use expr::nan_count;
16pub use expr::null_count;
17pub use expr::stat;
18pub use expr::sum;
19pub use stats_set::*;
20
21mod array;
22pub mod expr;
23pub mod flatbuffers;
24pub(crate) mod rewrite;
25pub mod session;
26mod stats_set;
27
28pub use array::*;
29pub use session::*;
30use vortex_error::VortexExpect;
31
32use crate::expr::stats::Stat;
33
34/// Statistics that are used for pruning files (i.e., we want to ensure they are computed when compressing/writing).
35/// Sum is included for boolean arrays.
36pub const PRUNING_STATS: &[Stat] = &[
37    Stat::Min,
38    Stat::Max,
39    Stat::Sum,
40    Stat::NullCount,
41    Stat::NaNCount,
42];
43
44pub fn as_stat_bitset_bytes(stats: &[Stat]) -> Vec<u8> {
45    let max_stat = u8::from(last::<Stat>().vortex_expect("last stat")) as usize + 1;
46    // TODO(ngates): use vortex-buffer::BitBuffer
47    let mut stat_bitset = BooleanBufferBuilder::new_from_buffer(
48        MutableBuffer::from_len_zeroed(max_stat.div_ceil(8)),
49        max_stat,
50    );
51    for stat in stats {
52        stat_bitset.set_bit(u8::from(*stat) as usize, true);
53    }
54
55    stat_bitset
56        .finish()
57        .into_inner()
58        .into_vec()
59        .unwrap_or_else(|b| b.to_vec())
60}
61
62pub fn stats_from_bitset_bytes(bytes: &[u8]) -> Vec<Stat> {
63    BitIterator::new(bytes, 0, bytes.len() * 8)
64        .enumerate()
65        .filter_map(|(i, b)| b.then_some(i))
66        // Filter out indices failing conversion, these are stats written by newer version of library
67        .filter_map(|i| {
68            let Ok(stat) = u8::try_from(i) else {
69                tracing::debug!("invalid stat encountered: {i}");
70                return None;
71            };
72            Stat::try_from(stat).ok()
73        })
74        .collect::<Vec<_>>()
75}