use crate::common::ResizeFactor;
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
use crate::theta::CompactThetaSketch;
use crate::theta::ThetaSketchView;
use crate::theta::hash_table::ThetaEntry;
use crate::thetacommon::constants::DEFAULT_LG_K;
use crate::thetacommon::union::UnionMergePolicy;
use crate::thetacommon::union::UnionState;
#[derive(Debug)]
pub struct ThetaUnion {
state: UnionState<ThetaEntry, NoopUnionPolicy>,
}
#[derive(Debug)]
struct NoopUnionPolicy;
impl UnionMergePolicy<ThetaEntry> for NoopUnionPolicy {
fn merge(&self, _existing: &mut ThetaEntry, _incoming: ThetaEntry) {}
}
impl ThetaUnion {
pub fn update<'a>(&mut self, sketch: impl Into<ThetaSketchView<'a>>) -> Result<(), Error> {
let sketch = sketch.into();
self.state.update(sketch)
}
pub fn to_sketch(&self, ordered: bool) -> CompactThetaSketch {
let compact_state = self
.state
.to_compact_sketch_state(ordered)
.map_retained_entries(|entry| entry.hash());
CompactThetaSketch::from_compact_state(compact_state)
}
pub fn reset(&mut self) {
self.state.reset();
}
pub fn estimated_size(&self) -> usize {
size_of::<Self>() + self.state.estimated_size()
}
}
#[derive(Debug, Clone)]
pub struct ThetaUnionBuilder {
lg_k: u8,
resize_factor: ResizeFactor,
sampling_probability: f32,
seed: u64,
}
impl Default for ThetaUnionBuilder {
fn default() -> Self {
Self {
lg_k: DEFAULT_LG_K,
resize_factor: ResizeFactor::X8,
sampling_probability: 1.0,
seed: DEFAULT_UPDATE_SEED,
}
}
}
impl ThetaUnionBuilder {
pub fn lg_k(mut self, lg_k: u8) -> Self {
self.lg_k = lg_k;
self
}
pub fn resize_factor(mut self, factor: ResizeFactor) -> Self {
self.resize_factor = factor;
self
}
pub fn sampling_probability(mut self, probability: f32) -> Self {
self.sampling_probability = probability;
self
}
pub fn seed(mut self, seed: u64) -> Self {
self.seed = seed;
self
}
pub fn build(self) -> Result<ThetaUnion, Error> {
Ok(ThetaUnion {
state: UnionState::new(
self.lg_k,
self.resize_factor,
self.sampling_probability,
self.seed,
NoopUnionPolicy,
)?,
})
}
}