use std::cell::RefCell;
const GOLDEN: u64 = 0x9E37_79B9_7F4A_7C15;
pub(crate) struct Counts {
pub distinct: Option<usize>,
pub top: u64,
pub top_count: usize,
}
#[derive(Default)]
struct Table {
slots: Vec<(u64, u32)>,
used: Vec<u32>,
}
thread_local! {
static TABLE: RefCell<Table> = RefCell::new(Table::default());
}
pub(crate) fn count(values: &[u64], cap: usize) -> Counts {
TABLE.with(|table| {
let mut table = table.borrow_mut();
let want = (cap.min(values.len()) * 2).next_power_of_two().max(64);
if table.slots.len() < want {
table.slots = vec![(0, 0); want];
table.used = Vec::with_capacity(want / 2);
}
let Table { slots, used } = &mut *table;
for &slot in used.iter() {
slots[slot as usize] = (0, 0);
}
used.clear();
let mask = table.slots.len() - 1;
let cap = cap.min(values.len());
let mut full = false;
let mut top = values.first().copied().unwrap_or(0);
let mut top_count = 0usize;
for &v in values {
let mut at = (v.wrapping_mul(GOLDEN) >> 32) as usize & mask;
loop {
let (key, n) = table.slots[at];
if n == 0 {
if table.used.len() == cap {
full = true;
break;
}
table.slots[at] = (v, 1);
table.used.push(at as u32);
if top_count == 0 {
top = v;
top_count = 1;
}
break;
}
if key == v {
let n = n + 1;
table.slots[at].1 = n;
if n as usize > top_count {
top = v;
top_count = n as usize;
}
break;
}
at = (at + 1) & mask;
}
}
Counts {
distinct: (!full).then_some(table.used.len()),
top,
top_count,
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counts_distinct_and_top() {
let values = [7u64, 3, 7, 9, 7, 3];
let counts = count(&values, 64);
assert_eq!(counts.distinct, Some(3));
assert_eq!((counts.top, counts.top_count), (7, 3));
}
#[test]
fn gives_up_past_the_cap_and_keeps_counting_what_it_holds() {
let mut values = vec![5u64; 100];
values.extend(1000..2000u64);
let counts = count(&values, 8);
assert_eq!(counts.distinct, None);
assert_eq!((counts.top, counts.top_count), (5, 100));
}
#[test]
fn the_table_comes_back_clean() {
assert_eq!(count(&[1, 1, 2], 64).distinct, Some(2));
let counts = count(&[9, 9, 9], 64);
assert_eq!(counts.distinct, Some(1));
assert_eq!((counts.top, counts.top_count), (9, 3));
}
#[test]
fn empty_input() {
let counts = count(&[], 64);
assert_eq!(counts.distinct, Some(0));
assert_eq!(counts.top_count, 0);
}
#[test]
fn a_wide_run_of_keys_probes_without_losing_one() {
let values: Vec<u64> = (0..2000u64).map(|i| i.wrapping_mul(GOLDEN)).collect();
let counts = count(&values, 4096);
assert_eq!(counts.distinct, Some(2000));
assert_eq!(counts.top_count, 1);
}
}