#[rustfmt::skip]
const WIDTHS: [u16; 224] = [
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 350,
556, 350, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 350, 611, 350,
350, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500,
];
pub fn width(text: &[u8], size: f32) -> f32 {
let thousandths: u32 = text
.iter()
.map(|&b| {
if b < 32 {
0
} else {
u32::from(WIDTHS[usize::from(b) - 32])
}
})
.sum();
thousandths as f32 * size / 1000.0
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_table_covers_every_code_from_space_up() {
assert_eq!(WIDTHS.len(), 256 - 32);
}
#[test]
fn a_known_string_measures_to_its_afm_width() {
assert!((width(b"Hello", 10.0) - 22.78).abs() < 0.001);
}
#[test]
fn control_characters_contribute_nothing() {
assert_eq!(width(b"\n\r\t", 12.0), 0.0);
}
#[test]
fn width_scales_with_the_font_size() {
let a = width(b"alice@example.com", 7.0);
let b = width(b"alice@example.com", 14.0);
assert!((b - a * 2.0).abs() < 0.001);
}
#[test]
fn high_codes_are_measured_rather_than_skipped() {
assert!(width(&[0xF8], 10.0) > 0.0);
}
}