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 = hash_one(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) | (1u64 << (p - 1));
72 let rank: u8 = (shifted.leading_zeros() + 1) as u8;
73 let slot: &mut u8 = unsafe { registers.get_unchecked_mut(idx) };
74 if rank > *slot {
75 *slot = rank;
76 }
77 }
78
79 /// Merges another [`HyperLogLog`] of identical precision into `self` (register-wise max).
80 ///
81 /// # Arguments
82 ///
83 /// - `&Self` - Other HyperLogLog estimator.
84 ///
85 /// # Returns
86 ///
87 /// - `bool` - `true` if merged, `false` if precisions differed.
88 pub fn merge(&mut self, other: &Self) -> bool {
89 let Self {
90 precision,
91 registers,
92 } = self;
93 let Self {
94 precision: other_p,
95 registers: other_regs,
96 } = other;
97 if *precision != *other_p || registers.len() != other_regs.len() {
98 return false;
99 }
100 for (dst, &src) in registers.iter_mut().zip(other_regs.iter()) {
101 if src > *dst {
102 *dst = src;
103 }
104 }
105 true
106 }
107
108 /// Resets all registers to zero.
109 pub fn clear(&mut self) {
110 let Self { registers, .. } = self;
111 registers.fill(0);
112 }
113
114 /// Estimates the number of distinct elements inserted so far using Flajolet et al. bias correction.
115 ///
116 /// # Returns
117 ///
118 /// - `f64` - Estimated distinct cardinality.
119 pub fn estimate(&self) -> f64 {
120 let Self { registers, .. } = self;
121 let m: usize = registers.len();
122 let mf: f64 = m as f64;
123 let alpha: f64 = match m {
124 16 => 0.673,
125 32 => 0.697,
126 64 => 0.709,
127 _ => 0.7213 / (1.0 + 1.079 / mf),
128 };
129 let mut sum: f64 = 0.0;
130 let mut zeros: usize = 0;
131 for ® in registers {
132 zeros += usize::from(reg == 0);
133 sum += HLL_POW2_NEG[(reg as usize).min(64)];
134 }
135 let raw: f64 = alpha * mf * mf / sum;
136 if raw <= 2.5 * mf && zeros > 0 {
137 mf * (mf / (zeros as f64)).ln()
138 } else {
139 raw
140 }
141 }
142}