Skip to main content

bloom_bitset/hll/
impl.rs

1use super::*;
2
3/// Default construction for [`HyperLogLog`].
4impl Default for HyperLogLog {
5    /// Creates a [`HyperLogLog`] with [`HLL_DEFAULT_PRECISION`] (`p = 14`).
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Empty HyperLogLog estimator.
10    fn default() -> Self {
11        Self::new(HLL_DEFAULT_PRECISION)
12    }
13}
14
15/// Core cardinality estimation and merge operations for [`HyperLogLog`].
16impl HyperLogLog {
17    /// Creates a new [`HyperLogLog`] with precision `p` clamped to `4..=16`.
18    ///
19    /// # Arguments
20    ///
21    /// - `u8` - Precision parameter `p` (`m = 2^p` registers).
22    ///
23    /// # Returns
24    ///
25    /// - `Self` - Empty HyperLogLog estimator.
26    pub fn new(precision: u8) -> Self {
27        let p: u8 = precision.clamp(HLL_MIN_PRECISION, HLL_MAX_PRECISION);
28        let m: usize = 1usize << p;
29        Self {
30            precision: p,
31            registers: vec![0u8; m],
32        }
33    }
34
35    /// Returns the configured precision `p`.
36    ///
37    /// # Returns
38    ///
39    /// - `u8` - Precision in `4..=16`.
40    #[inline(always)]
41    pub fn precision(&self) -> u8 {
42        let Self { precision, .. } = self;
43        *precision
44    }
45
46    /// Returns the number of registers (`2^p`).
47    ///
48    /// # Returns
49    ///
50    /// - `usize` - Register count.
51    #[inline(always)]
52    pub fn register_len(&self) -> usize {
53        let Self { registers, .. } = self;
54        registers.len()
55    }
56
57    /// Inserts `item` into the cardinality estimator.
58    ///
59    /// # Arguments
60    ///
61    /// - `&[u8]` - Element bytes to observe.
62    #[inline]
63    pub fn insert(&mut self, item: &[u8]) {
64        let (h, _): (u64, u64) = hash_pair(item);
65        let Self {
66            precision,
67            registers,
68        } = self;
69        let p: u32 = u32::from(*precision);
70        let idx: usize = (h >> (64 - p)) as usize;
71        let shifted: u64 = h << p;
72        let max_bits: u32 = 64 - p;
73        let zeros: u32 = if shifted == 0 {
74            max_bits
75        } else {
76            shifted.leading_zeros().min(max_bits)
77        };
78        let rank: u8 = (zeros + 1) as u8;
79        if rank > registers[idx] {
80            registers[idx] = rank;
81        }
82    }
83
84    /// Merges another [`HyperLogLog`] of identical precision into `self` (register-wise max).
85    ///
86    /// # Arguments
87    ///
88    /// - `&Self` - Other HyperLogLog estimator.
89    ///
90    /// # Returns
91    ///
92    /// - `bool` - `true` if merged, `false` if precisions differed.
93    pub fn merge(&mut self, other: &Self) -> bool {
94        let Self {
95            precision,
96            registers,
97        } = self;
98        let Self {
99            precision: other_p,
100            registers: other_regs,
101        } = other;
102        if *precision != *other_p || registers.len() != other_regs.len() {
103            return false;
104        }
105        for (dst, &src) in registers.iter_mut().zip(other_regs.iter()) {
106            if src > *dst {
107                *dst = src;
108            }
109        }
110        true
111    }
112
113    /// Resets all registers to zero.
114    pub fn clear(&mut self) {
115        let Self { registers, .. } = self;
116        registers.fill(0);
117    }
118
119    /// Estimates the number of distinct elements inserted so far using Flajolet et al. bias correction.
120    ///
121    /// # Returns
122    ///
123    /// - `f64` - Estimated distinct cardinality.
124    pub fn estimate(&self) -> f64 {
125        let Self { registers, .. } = self;
126        let m: usize = registers.len();
127        let mf: f64 = m as f64;
128        let alpha: f64 = match m {
129            16 => 0.673,
130            32 => 0.697,
131            64 => 0.709,
132            _ => 0.7213 / (1.0 + 1.079 / mf),
133        };
134        let mut sum: f64 = 0.0;
135        let mut zeros: usize = 0;
136        for &reg in registers {
137            if reg == 0 {
138                zeros += 1;
139            }
140            sum += 2.0f64.powi(-i32::from(reg));
141        }
142        let raw: f64 = alpha * mf * mf / sum;
143        if raw <= 2.5 * mf && zeros > 0 {
144            mf * (mf / (zeros as f64)).ln()
145        } else {
146            raw
147        }
148    }
149}