//! Minimal TeX Font Metric (TFM) parser. //! //! The parser follows the TFM layout used by `cmr10.tfm`: //! - 24-byte fixed header followed by `lh` 4-byte header words //! - one 4-byte char-info record per character in `bc..=ec` //! - width/height/depth/italic arrays of 4-byte fixed values //! - lig/kern, kern, extensible and parameter sections //! //! Metric values are stored as fixed-point values relative to the design //! size. They are converted to TeX scaled points (1pt = 65536sp). use std::fs; use std::path::Path; #[derive(Clone, Copy, Debug, Default)] pub struct CharInfo { pub width_index: u8, pub height_index: u8, pub depth_index: u8, pub italic_index: u8, pub tag: u8, } #[derive(Clone, Debug)] pub struct TfmMetrics { design_size_pt: f64, bc: u16, ec: u16, char_info: Vec, widths: Vec, heights: Vec, depths: Vec, italics: Vec, params: Vec, } impl TfmMetrics { pub fn parse(bytes: &[u8]) -> Result { let word = |offset: usize| -> Result { let slice = bytes .get(offset..offset + 2) .ok_or_else(|| format!("TFM truncated at byte {offset}"))?; Ok(u16::from_be_bytes([slice[0], slice[1]])) }; let fixed = |offset: usize| -> Result { let slice = bytes .get(offset..offset + 4) .ok_or_else(|| format!("TFM truncated at byte {offset}"))?; Ok(i32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]])) }; let table = |offset: usize, count: u16, label: &str| -> Result, String> { let count = usize::from(count); let end = offset .checked_add(count * 4) .ok_or_else(|| format!("TFM {label} table overflow"))?; if end > bytes.len() { return Err(format!("TFM {label} table extends past end of file")); } (0..count).map(|index| fixed(offset + index * 4)).collect() }; let lh = usize::from(word(2)?); let bc = word(4)?; let ec = word(6)?; let nw = word(8)?; let nh = word(10)?; let nd = word(12)?; let ni = word(14)?; let nl = word(16)?; let nk = word(18)?; let ne = word(20)?; let np = word(22)?; if ec < bc { return Err("TFM has ec < bc".to_string()); } let design_fixed = fixed(28)?; if design_fixed <= 0 { return Err("TFM design size is not positive".to_string()); } // TFM design size is a 16.16 fixed value in units of 1/16pt: dividing // by 2^20 yields points. let design_size_pt = f64::from(design_fixed) / 1_048_576.0; let header_end = 24usize .checked_add(lh.checked_mul(4).ok_or("TFM header size overflow")?) .ok_or("TFM header overflow")?; let char_count = usize::from(ec - bc) + 1; let char_end = header_end .checked_add(char_count * 4) .ok_or("TFM char-info overflow")?; if char_end > bytes.len() { return Err("TFM char-info table extends past end of file".to_string()); } let mut char_info = Vec::with_capacity(char_count); for index in 0..char_count { let offset = header_end + index * 4; char_info.push(CharInfo { width_index: bytes[offset], height_index: bytes[offset + 1] >> 4, depth_index: bytes[offset + 1] & 0x0f, italic_index: bytes[offset + 2], tag: bytes[offset + 3], }); } let width_offset = char_end; let height_offset = width_offset .checked_add(usize::from(nw) * 4) .ok_or("TFM width table overflow")?; let depth_offset = height_offset .checked_add(usize::from(nh) * 4) .ok_or("TFM height table overflow")?; let italic_offset = depth_offset .checked_add(usize::from(nd) * 4) .ok_or("TFM depth table overflow")?; let lig_kern_offset = italic_offset .checked_add(usize::from(ni) * 4) .ok_or("TFM italic table overflow")?; let kern_offset = lig_kern_offset .checked_add(usize::from(nl) * 4) .ok_or("TFM lig/kern table overflow")?; let extensible_offset = kern_offset .checked_add(usize::from(nk) * 4) .ok_or("TFM kern table overflow")?; let params_offset = extensible_offset .checked_add(usize::from(ne) * 4) .ok_or("TFM extensible table overflow")?; let widths = table(width_offset, nw, "width")?; let heights = table(height_offset, nh, "height")?; let depths = table(depth_offset, nd, "depth")?; let italics = table(italic_offset, ni, "italic")?; let params = table(params_offset, np, "parameter")?; Ok(Self { design_size_pt, bc, ec, char_info, widths, heights, depths, italics, params, }) } pub fn parse_file(path: &Path) -> Result { let bytes = fs::read(path).map_err(|error| format!("read {}: {error}", path.display()))?; Self::parse(&bytes) } pub fn design_size_pt(&self) -> f64 { self.design_size_pt } fn fixed_to_scaled(&self, raw: i32) -> i64 { (f64::from(raw) * self.design_size_pt / 16.0).round() as i64 } fn index_for(&self, character: char) -> Option { let code = u32::from(character); if code < u32::from(self.bc) || code > u32::from(self.ec) { return None; } Some((code - u32::from(self.bc)) as usize) } pub fn char_info(&self, character: char) -> Option { self.index_for(character) .and_then(|index| self.char_info.get(index).copied()) } fn table_value(&self, table: &[i32], index: u8) -> Option { if index == 0 { return None; } table.get(usize::from(index)).copied() } pub fn width(&self, character: char) -> i64 { self.char_info(character) .and_then(|info| self.table_value(&self.widths, info.width_index)) .map_or(0, |raw| self.fixed_to_scaled(raw)) } pub fn height(&self, character: char) -> i64 { self.char_info(character) .and_then(|info| self.table_value(&self.heights, info.height_index)) .map_or(0, |raw| self.fixed_to_scaled(raw)) } pub fn depth(&self, character: char) -> i64 { self.char_info(character) .and_then(|info| self.table_value(&self.depths, info.depth_index)) .map_or(0, |raw| self.fixed_to_scaled(raw)) } pub fn italic(&self, character: char) -> i64 { self.char_info(character) .and_then(|info| self.table_value(&self.italics, info.italic_index)) .map_or(0, |raw| self.fixed_to_scaled(raw)) } fn param(&self, index: usize) -> i64 { self.params .get(index) .copied() .map_or(0, |raw| self.fixed_to_scaled(raw)) } pub fn space(&self) -> i64 { self.param(1) } pub fn stretch(&self) -> i64 { self.param(2) } pub fn shrink(&self) -> i64 { self.param(3) } pub fn x_height(&self) -> i64 { self.param(4) } pub fn quad(&self) -> i64 { self.param(5) } } #[cfg(test)] mod tests { use super::*; fn cmr10() -> TfmMetrics { TfmMetrics::parse(include_bytes!("../assets/cmr10.tfm")).expect("parse cmr10") } #[test] fn parses_cmr10_header_and_widths() { let font = cmr10(); assert!((font.design_size_pt() - 10.0).abs() < 0.001); assert!((font.width('A') - 491_521).abs() <= 2); assert!((font.width('a') - 327_681).abs() <= 2); assert!((font.space() - 218_454).abs() <= 2); assert!(font.height('A') > 0); assert!(font.depth('g') > 0); } #[test] fn missing_characters_have_zero_metrics() { let font = cmr10(); assert_eq!(font.width('\u{4e2d}'), 0); assert_eq!(font.height('\u{4e2d}'), 0); } #[test] fn rejects_truncated_files() { assert!(TfmMetrics::parse(&[0_u8; 8]).is_err()); } }