use std::fmt;
use vortex_error::VortexExpect;
use crate::compressor::ROOT_SCHEME_ID;
use crate::scheme::SchemeId;
use crate::stats::GenerateStatsOptions;
pub const MAX_CASCADE: usize = 3;
#[derive(Debug, Clone)]
pub struct CompressorContext {
is_sample: bool,
allowed_cascading: usize,
merged_stats_options: GenerateStatsOptions,
cascade_history: Vec<(SchemeId, usize)>,
}
impl CompressorContext {
pub(super) fn new() -> Self {
Self {
is_sample: false,
allowed_cascading: MAX_CASCADE,
merged_stats_options: GenerateStatsOptions::default(),
cascade_history: Vec::new(),
}
}
}
#[cfg(test)]
impl Default for CompressorContext {
fn default() -> Self {
Self::new()
}
}
impl CompressorContext {
pub fn is_sample(&self) -> bool {
self.is_sample
}
pub fn merged_stats_options(&self) -> GenerateStatsOptions {
self.merged_stats_options
}
pub fn cascade_history(&self) -> &[(SchemeId, usize)] {
&self.cascade_history
}
pub(crate) fn cascade_path(&self) -> impl fmt::Display + '_ {
CascadePath(&self.cascade_history)
}
pub(crate) fn cascade_depth(&self) -> usize {
self.cascade_history.len()
}
pub fn finished_cascading(&self) -> bool {
self.allowed_cascading == 0
}
pub fn as_leaf(mut self) -> Self {
self.allowed_cascading = 0;
self
}
pub(super) fn with_merged_stats_options(mut self, opts: GenerateStatsOptions) -> Self {
self.merged_stats_options = opts;
self
}
pub(super) fn with_sampling(mut self) -> Self {
self.is_sample = true;
self
}
pub(super) fn descend_with_scheme(mut self, id: SchemeId, child_index: usize) -> Self {
self.allowed_cascading = self
.allowed_cascading
.checked_sub(1)
.vortex_expect("cannot descend: cascade depth exhausted");
self.cascade_history.push((id, child_index));
self
}
}
struct CascadePath<'a>(&'a [(SchemeId, usize)]);
impl fmt::Display for CascadePath<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.0.is_empty() {
return f.write_str("root");
}
for (index, (scheme_id, child_index)) in self.0.iter().enumerate() {
if index > 0 {
f.write_str(" > ")?;
}
if *scheme_id == ROOT_SCHEME_ID {
write!(f, "root[{child_index}]")?;
} else {
write!(f, "{scheme_id}[{child_index}]")?;
}
}
Ok(())
}
}