use vyre_primitives::bitset::popcount::{
cpu_ref as primitive_popcount, cpu_ref_into as primitive_popcount_into,
};
#[must_use]
pub fn per_word_popcount(input: &[u32]) -> Vec<u32> {
use crate::observability::{bump, dataflow_fixpoint_calls};
bump(&dataflow_fixpoint_calls);
primitive_popcount(input)
}
pub fn per_word_popcount_into(input: &[u32], out: &mut Vec<u32>) {
use crate::observability::{bump, dataflow_fixpoint_calls};
bump(&dataflow_fixpoint_calls);
primitive_popcount_into(input, out);
}
#[must_use]
pub fn total_set_bits(input: &[u32]) -> u64 {
let mut total: u64 = 0;
for word in input {
total = total.saturating_add(u64::from(word.count_ones()));
}
total
}
#[must_use]
pub fn saturation_ratio(input: &[u32]) -> f64 {
if input.is_empty() {
return 0.0;
}
let capacity_bits = (input.len() as u64) * 32;
if capacity_bits == 0 {
return 0.0;
}
let set = total_set_bits(input);
(set as f64) / (capacity_bits as f64)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_input_yields_empty_summary() {
let v = per_word_popcount(&[]);
assert!(v.is_empty());
assert_eq!(total_set_bits(&[]), 0);
assert_eq!(saturation_ratio(&[]), 0.0);
}
#[test]
fn full_word_is_thirty_two_bits() {
let v = per_word_popcount(&[0xFFFF_FFFFu32]);
assert_eq!(v, vec![32u32]);
assert_eq!(total_set_bits(&[0xFFFF_FFFF]), 32);
assert!((saturation_ratio(&[0xFFFF_FFFF]) - 1.0).abs() < 1e-9);
}
#[test]
fn mixed_words_count_correctly() {
let v = per_word_popcount(&[0b1111u32, 0b101]);
assert_eq!(v, vec![4, 2]);
assert_eq!(total_set_bits(&[0b1111, 0b101]), 6);
}
#[test]
fn popcount_into_reuses_capacity() {
let mut out = Vec::with_capacity(8);
per_word_popcount_into(&[0b1111u32, 0xFFFF_FFFF], &mut out);
let capacity = out.capacity();
assert_eq!(out, vec![4, 32]);
per_word_popcount_into(&[0b1010u32], &mut out);
assert_eq!(out.capacity(), capacity);
assert_eq!(out, vec![2]);
}
#[test]
fn matches_primitive_directly() {
let input = vec![0u32, 1, 0xFFFF_FFFF, 0xAAAA_AAAA, 0x12345678];
assert_eq!(per_word_popcount(&input), primitive_popcount(&input));
}
#[test]
fn half_saturation_ratio() {
let r = saturation_ratio(&[0xAAAA_AAAAu32]);
assert!((r - 0.5).abs() < 1e-9, "expected 0.5, got {r}");
}
#[test]
fn single_bit_in_large_bitset() {
let mut input = vec![0u32; 32];
input[5] = 1;
let r = saturation_ratio(&input);
let expected = 1.0 / 1024.0;
assert!((r - expected).abs() < 1e-9);
}
#[test]
fn deterministic_summary() {
let input = vec![0xCAFE_BABEu32, 0x1234_5678];
let a = per_word_popcount(&input);
let b = per_word_popcount(&input);
assert_eq!(a, b);
}
}