use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MeasureKey {
width_signature: u64,
font_generation: u64,
dpr_bits: u32,
revision: u64,
}
impl MeasureKey {
pub fn new(width_signature: u64, font_generation: u64, dpr: f32, revision: u64) -> Self {
Self { width_signature, font_generation, dpr_bits: normalize_dpr(dpr).to_bits(), revision }
}
pub fn width_signature(&self) -> u64 {
self.width_signature
}
pub fn font_generation(&self) -> u64 {
self.font_generation
}
pub fn dpr(&self) -> f32 {
f32::from_bits(self.dpr_bits)
}
pub fn revision(&self) -> u64 {
self.revision
}
}
pub fn width_signature(widths: impl IntoIterator<Item = f32>) -> u64 {
let mut h = DefaultHasher::new();
for w in widths {
let w = if w.is_finite() && w > 0.0 { w } else { 0.0 };
w.to_bits().hash(&mut h);
}
h.finish()
}
pub fn single_width_signature(width: f32) -> u64 {
width_signature([width])
}
fn normalize_dpr(dpr: f32) -> f32 {
if dpr.is_finite() && dpr > 0.0 {
dpr
} else {
1.0
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(width: f32, gen: u64, dpr: f32, rev: u64) -> MeasureKey {
MeasureKey::new(single_width_signature(width), gen, dpr, rev)
}
#[test]
fn identical_environment_produces_identical_key() {
assert_eq!(key(200.0, 7, 1.5, 3), key(200.0, 7, 1.5, 3));
}
#[test]
fn each_dimension_invalidates_the_key() {
let base = key(200.0, 7, 1.5, 3);
assert_ne!(base, key(240.0, 7, 1.5, 3), "宽度变化必须重测");
assert_ne!(base, key(200.0, 8, 1.5, 3), "字体 generation 变化必须重测");
assert_ne!(base, key(200.0, 7, 2.0, 3), "DPR 变化必须重测");
assert_ne!(base, key(200.0, 7, 1.5, 4), "内容 revision 变化必须重测");
}
#[test]
fn non_finite_widths_are_normalized() {
assert_eq!(single_width_signature(f32::NAN), single_width_signature(0.0));
assert_eq!(single_width_signature(f32::INFINITY), single_width_signature(0.0));
assert_eq!(key(f32::NAN, 1, 1.0, 0), key(0.0, 1, 1.0, 0));
}
#[test]
fn invalid_dpr_falls_back_to_one() {
assert_eq!(key(200.0, 1, f32::NAN, 0), key(200.0, 1, 1.0, 0));
}
#[test]
fn width_signature_is_order_sensitive() {
assert_ne!(
width_signature([100.0, 200.0]),
width_signature([200.0, 100.0]),
"列序交换后可用宽度归属变了,不能命中旧实测值"
);
}
}