use fasthash::metro::crc::Hash64_1 as Hasher;
use std::hash::BuildHasher;
pub(crate) mod common;
pub mod hll;
pub(crate) mod sealed {
pub trait RawApproxSet: Default {
fn insert_hash(&mut self, hash: u64);
fn count(&self) -> u64;
fn union(&self, other: &Self) -> Self;
}
}
pub trait RawApproxSet: sealed::RawApproxSet + Default {}
impl<T: sealed::RawApproxSet + Default> RawApproxSet for T {}
pub struct ApproxSet<T, S> {
set: S,
_marker: std::marker::PhantomData<T>,
}
impl<T, S: RawApproxSet> ApproxSet<T, S> {
pub fn new() -> Self {
Self::default()
}
pub fn into_raw(self) -> S {
self.set
}
pub fn from_raw(raw: S) -> Self {
Self {
set: raw,
_marker: std::marker::PhantomData,
}
}
pub fn count(&self) -> u64 {
self.set.count()
}
pub fn union(&self, other: &Self) -> Self {
Self::from_raw(self.set.union(&other.set))
}
}
impl<T: std::hash::Hash, S: RawApproxSet> ApproxSet<T, S> {
pub fn insert<R: core::borrow::Borrow<T>>(&mut self, value: R) {
let hash = Hasher.hash_one(value.borrow());
self.set.insert_hash(hash);
}
}
impl<T, S: Default> Default for ApproxSet<T, S> {
fn default() -> Self {
Self {
set: S::default(),
_marker: std::marker::PhantomData,
}
}
}
impl<T, S: std::fmt::Debug> std::fmt::Debug for ApproxSet<T, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HLL").field("set", &self.set).finish()
}
}
impl<T, S: Clone> Clone for ApproxSet<T, S> {
fn clone(&self) -> Self {
Self {
set: self.set.clone(),
_marker: std::marker::PhantomData,
}
}
}
pub type HLL<T> = ApproxSet<T, hll::RawHLL>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn small_sets() {
let mut pair1 = HLL::<u64>::new();
for i in 0..1000 {
pair1.insert(i);
}
common::compare_result(pair1.count(), 1000, 0.05);
let mut pair2 = HLL::<u64>::new();
for i in 500..1500 {
pair2.insert(i);
}
common::compare_result(pair2.count(), 1000, 0.05);
let union = pair1.union(&pair2);
common::compare_result(union.count(), 1500, 0.05);
}
}