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//! Array statistics: the statistics an array can carry ([`Stat`]), how exact a value is
5//! ([`Precision`]) and its bounds, the [`StatsProvider`] traits that read them, and the cache each
6//! array keeps ([`ArrayStats`], [`StatsSet`]).
7
8use arrow_buffer::BooleanBufferBuilder;
9use arrow_buffer::MutableBuffer;
10use arrow_buffer::bit_iterator::BitIterator;
11use enum_iterator::last;
12pub use stats_set::*;
13
14mod array;
15mod bound;
16pub mod flatbuffers;
17mod precision;
18mod provider;
19mod stat;
20mod stat_bound;
21mod stats_set;
22
23pub use array::*;
24pub use bound::*;
25pub use precision::*;
26pub use provider::*;
27pub use stat::*;
28pub use stat_bound::*;
29use vortex_error::VortexExpect;
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}