pub(crate) const NO_GAP: u64 = i64::MAX.unsigned_abs();
fn same_subset(a: u64, b: u64, fp_bits: u32) -> bool {
let shift = 64 - fp_bits.clamp(1, 63);
a >> shift == b >> shift
}
pub(crate) fn closer(gap: u64, a: u64, b: u64, fp_bits: u32) -> u64 {
if b > a && same_subset(a, b, fp_bits) {
gap.min(b - a)
} else {
gap
}
}
#[cfg(test)]
pub(crate) fn tlc_min_gap(fps: impl IntoIterator<Item = u64>, fp_bits: u32) -> u64 {
let mut v: Vec<u64> = fps.into_iter().collect();
v.sort_unstable();
v.dedup();
v.windows(2)
.fold(NO_GAP, |gap, w| closer(gap, w[0], w[1], fp_bits))
}
#[cfg(test)]
#[allow(
clippy::expect_used,
reason = "test code: a failed expectation is a test failure"
)]
mod tests {
use super::{NO_GAP, tlc_min_gap};
fn read_fps(model: &str) -> Vec<u64> {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/tlc-fingerprints")
.join(format!("{model}.fp64"));
let bytes = std::fs::read(path).expect("fingerprint fixture");
let (words, rest) = bytes.as_chunks::<8>();
assert_eq!(rest, &[] as &[u8]);
words.iter().map(|w| u64::from_le_bytes(*w)).collect()
}
#[allow(clippy::cast_precision_loss, reason = "a printed two-digit estimate")]
fn figure(gap: u64) -> String {
format!("{:.1E}", 1.0 / gap as f64)
}
#[test]
fn sub_sets_split_by_top_bits() {
assert_eq!(tlc_min_gap([10, 3, 7], 1), 3);
assert_eq!(
tlc_min_gap([0x7fff_ffff_ffff_ffff, 0x8000_0000_0000_0000], 1),
NO_GAP
);
}
#[test]
fn gap_matches_tlc_on_tlc_fingerprints() {
let voteproof = read_fps("VoteProof");
assert_eq!(voteproof.len(), 6_962);
assert_eq!(figure(tlc_min_gap(voteproof, 1)), "8.6E-12");
let nbacg = read_fps("nbacg_guer01");
assert_eq!(nbacg.len(), 24_922);
assert_eq!(figure(tlc_min_gap(nbacg.iter().copied(), 1)), "1.5E-11");
let masked = tlc_min_gap(nbacg.iter().map(|fp| fp & !(1 << 63)), 1);
assert_eq!(figure(masked), "1.7E-10");
}
}