Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+463 -271
View File
@@ -1,31 +1,64 @@
//! 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).
//! Validated TFM data and TeX's integer font-loading arithmetic.
//! Slots and lig/kern bytecode are retained independently of glyph encodings.
use std::{fs, path::Path};
use std::fs;
use std::path::Path;
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum FontSize {
Design,
At(i64),
Scaled(i32),
}
impl FontSize {
/// Validate the syntax-level request before opening a font file. A scaled
/// request additionally needs its actual design size checked when loaded.
pub fn validate(self) -> Result<(), String> {
match self {
Self::At(n) if n <= 0 || n >= 1 << 27 => {
Err("font size must be positive and less than 2048pt".into())
}
Self::Scaled(n) if !(1..=32768).contains(&n) => {
Err("font scaled ratio must be in 1..32768".into())
}
_ => Ok(()),
}
}
}
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub struct CharInfo {
pub width_index: u8,
pub height_index: u8,
pub depth_index: u8,
pub italic_index: u8,
pub tag: u8,
/// Start offset into the lig/kern instruction table (tag 1).
pub remainder: u8,
pub lig_kern_start: usize,
}
#[derive(Clone, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct LigKernInstruction {
pub skip: u8,
pub next: u8,
pub operation: u8,
pub remainder: u8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LigKernCommand {
Kern(i64),
Ligature { operation: u8, replacement: u8 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct ExtensibleRecipe {
pub top: u8,
pub middle: u8,
pub bottom: u8,
pub repeat: u8,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct TfmMetrics {
design_size_pt: f64,
checksum: u32,
design_size: i64,
size: i64,
bc: u16,
ec: u16,
char_info: Vec<CharInfo>,
@@ -34,298 +67,424 @@ pub struct TfmMetrics {
depths: Vec<i32>,
italics: Vec<i32>,
params: Vec<i32>,
kerns: std::collections::HashMap<(char, char), i64>,
ligatures: std::collections::HashMap<(char, char), (char, char)>,
extensibles: Vec<ExtensibleRecipe>,
kern_values: Vec<i32>,
lig_kern: Vec<LigKernInstruction>,
boundary_char: Option<u8>,
boundary_label: Option<usize>,
}
impl TfmMetrics {
pub fn parse(bytes: &[u8]) -> Result<Self, String> {
let word = |offset: usize| -> Result<u16, String> {
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<i32, String> {
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<Vec<i32>, 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"));
Self::parse_at(bytes, FontSize::Design)
}
pub fn parse_at(bytes: &[u8], requested: FontSize) -> Result<Self, String> {
let mut fields = [0usize; 12];
for (i, n) in fields.iter_mut().enumerate() {
let b = bytes
.get(2 * i..2 * i + 2)
.ok_or("truncated TFM size fields")?;
*n = usize::from(u16::from_be_bytes([b[0], b[1]]));
if *n > 32767 {
return Err("TFM size field exceeds 32767".into());
}
(0..count).map(|index| fixed(offset + index * 4)).collect()
}
let [lf, lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np] = fields;
if lh < 2 || ec > 255 || bc > ec + 1 || nw == 0 || nh == 0 || nd == 0 || ni == 0 {
return Err("invalid TFM header or table size".into());
}
let nc = ec + 1 - bc;
if lf != 6 + lh + nc + nw + nh + nd + ni + nl + nk + ne + np {
return Err("inconsistent TFM length fields".into());
}
if bytes.len() < lf * 4 {
return Err("truncated TFM data".into());
}
let fixed = |i: usize| i32::from_be_bytes(bytes[i..i + 4].try_into().unwrap());
let design_fixed = fixed(28);
if design_fixed < 1 << 20 {
return Err("TFM design size must be at least 1pt".into());
}
let design_size = i64::from(design_fixed) / 16;
let size = Self::resolve_size(design_size, requested)?;
let mut at = (6 + lh) * 4;
let mut char_info = Vec::with_capacity(nc);
for _ in 0..nc {
let b = &bytes[at..at + 4];
at += 4;
let c = CharInfo {
width_index: b[0],
height_index: b[1] >> 4,
depth_index: b[1] & 15,
italic_index: b[2] >> 2,
tag: b[2] & 3,
remainder: b[3],
lig_kern_start: usize::from(b[3]),
};
if usize::from(c.width_index) >= nw
|| usize::from(c.height_index) >= nh
|| usize::from(c.depth_index) >= nd
|| usize::from(c.italic_index) >= ni
{
return Err("TFM character metric index outside its table".into());
}
if c.tag == 1 && usize::from(c.remainder) >= nl
|| c.tag == 3 && usize::from(c.remainder) >= ne
{
return Err("TFM character program/recipe index outside its table".into());
}
char_info.push(c);
}
let mut table = |n: usize| {
let v = (0..n).map(|j| fixed(at + 4 * j)).collect::<Vec<_>>();
at += n * 4;
v
};
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] >> 2,
tag: bytes[offset + 2] & 0x03,
lig_kern_start: usize::from(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")?;
let kern_table = table(kern_offset, nk, "kern")?;
let (kerns, ligatures) = parse_kerns(
bytes,
lig_kern_offset,
usize::from(nl),
&kern_table,
&char_info,
u32::from(bc),
design_size_pt,
);
Ok(Self {
design_size_pt,
bc,
ec,
let widths = table(nw);
let heights = table(nh);
let depths = table(nd);
let italics = table(ni);
// At this point all table offsets are guaranteed by lf and the sizes.
let lig_at = at;
at += 4 * nl;
let kern_values = (0..nk).map(|j| fixed(at + 4 * j)).collect();
at += 4 * nk;
let extensibles = (0..ne)
.map(|j| {
let b = &bytes[at + 4 * j..at + 4 * j + 4];
ExtensibleRecipe {
top: b[0],
middle: b[1],
bottom: b[2],
repeat: b[3],
}
})
.collect();
at += 4 * ne;
let params = (0..np).map(|j| fixed(at + 4 * j)).collect();
let lig_kern = (0..nl)
.map(|j| {
let b = &bytes[lig_at + 4 * j..lig_at + 4 * j + 4];
LigKernInstruction {
skip: b[0],
next: b[1],
operation: b[2],
remainder: b[3],
}
})
.collect::<Vec<_>>();
let boundary_char = lig_kern.first().filter(|i| i.skip == 255).map(|i| i.next);
let boundary_label = lig_kern
.last()
.filter(|i| i.skip == 255)
.map(|i| usize::from(i.operation) * 256 + usize::from(i.remainder))
.filter(|n| *n < nl);
let font = Self {
checksum: u32::from_be_bytes(bytes[24..28].try_into().unwrap()),
design_size,
size,
bc: bc as u16,
ec: ec as u16,
char_info,
widths,
heights,
depths,
italics,
params,
kerns,
ligatures,
kern_values,
extensibles,
lig_kern,
boundary_char,
boundary_label,
};
font.validate()?;
Ok(font)
}
fn resolve_size(design: i64, requested: FontSize) -> Result<i64, String> {
requested.validate()?;
let size = match requested {
FontSize::Design => design,
FontSize::At(n) => n,
FontSize::Scaled(n) => design * i64::from(n) / 1000,
};
if size <= 0 || size >= 1 << 27 {
return Err("font size must be positive and less than 2048pt".into());
}
Ok(size)
}
/// Resolve a load request against this font's original design size, without
/// revalidating its tables at another size. Used to look up loaded fonts:
/// TeX reuses their current state before attempting any new file read.
pub fn requested_size(&self, requested: FontSize) -> Result<i64, String> {
Self::resolve_size(self.design_size, requested)
}
fn validate(&self) -> Result<(), String> {
for table in [
&self.widths,
&self.heights,
&self.depths,
&self.italics,
&self.kern_values,
] {
for raw in table {
self.scaled(*raw)?;
}
}
for raw in self.params.iter().skip(1) {
self.scaled(*raw)?;
}
for table in [&self.widths, &self.heights, &self.depths, &self.italics] {
if self.scaled(table[0])? != 0 {
return Err("TFM metric zero entry must scale to zero".into());
}
}
for (i, c) in self.char_info.iter().enumerate() {
if c.tag != 2 {
continue;
}
let mut next = c.remainder;
// TeX rejects cycles, including links through zero-width records.
for _ in 0..=self.char_info.len() {
let Some(info) = self.char_info(char::from(next)) else {
return Err("TFM next-larger character outside range".into());
};
if usize::from(next) == usize::from(self.bc) + i {
return Err("TFM next-larger cycle".into());
}
if info.tag != 2 {
break;
}
next = info.remainder;
}
}
for (i, ins) in self.lig_kern.iter().enumerate() {
if ins.skip > 128 {
if usize::from(ins.operation) * 256 + usize::from(ins.remainder)
>= self.lig_kern.len()
{
return Err("TFM lig/kern restart outside program".into());
}
} else {
if Some(ins.next) != self.boundary_char && !self.has_slot(ins.next) {
return Err("TFM lig/kern next character does not exist".into());
}
if ins.operation < 128 {
if !self.has_slot(ins.remainder) {
return Err("TFM ligature replacement does not exist".into());
}
} else if usize::from(ins.operation - 128) * 256 + usize::from(ins.remainder)
>= self.kern_values.len()
{
return Err("TFM kern index outside table".into());
}
if ins.skip < 128 && i + usize::from(ins.skip) + 1 >= self.lig_kern.len() {
return Err("TFM lig/kern skip outside program".into());
}
}
}
for r in &self.extensibles {
for c in [r.top, r.middle, r.bottom]
.into_iter()
.filter(|c| *c != 0)
.chain([r.repeat])
{
if !self.has_slot(c) {
return Err("TFM extensible component does not exist".into());
}
}
}
Ok(())
}
/// TeX store_scaled: reduce z before multiplying, preserving its deliberate
/// quantization above 128pt instead of computing a floating-point ratio.
fn scaled(&self, raw: i32) -> Result<i64, String> {
Self::scale_fix_word(raw, self.size)
}
pub(crate) fn scale_fix_word(raw: i32, size: i64) -> Result<i64, String> {
let [a, b, c, d] = raw.to_be_bytes();
if a != 0 && a != 255 {
return Err("TFM metric must be between -16 and 16".into());
}
let (mut z, mut alpha) = (size, 16i64);
while z >= 1 << 23 {
z /= 2;
alpha *= 2;
}
let beta = 256 / alpha;
let alpha = alpha * z;
let n = ((i64::from(d) * z / 256 + i64::from(c) * z) / 256 + i64::from(b) * z) / beta;
Ok(if a == 0 { n } else { n - alpha })
}
pub fn at_size(&self, requested: FontSize) -> Result<Self, String> {
let mut font = self.clone();
font.size = Self::resolve_size(self.design_size, requested)?;
font.validate()?;
Ok(font)
}
pub fn parse_file(path: &Path) -> Result<Self, String> {
Self::parse(&fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?)
}
pub fn checksum(&self) -> u32 {
self.checksum
}
pub fn design_size_sp(&self) -> i64 {
self.design_size
}
pub fn size_sp(&self) -> i64 {
self.size
}
pub fn design_size_pt(&self) -> f64 {
self.design_size as f64 / 65536.0
}
pub fn char_info(&self, c: char) -> Option<CharInfo> {
let c = c as u32;
if c < u32::from(self.bc) || c > u32::from(self.ec) {
return None;
}
self.char_info
.get((c - u32::from(self.bc)) as usize)
.copied()
}
pub fn has_slot(&self, slot: u8) -> bool {
self.char_info(char::from(slot))
.is_some_and(|c| c.width_index != 0)
}
fn dimension(&self, c: char, table: &[i32], index: impl FnOnce(CharInfo) -> u8) -> i64 {
self.char_info(c).map_or(0, |info| {
self.scaled(table[usize::from(index(info))])
.expect("validated TFM metric")
})
}
pub fn parse_file(path: &Path) -> Result<Self, String> {
let bytes = fs::read(path).map_err(|error| format!("read {}: {error}", path.display()))?;
Self::parse(&bytes)
pub fn width(&self, c: char) -> i64 {
self.dimension(c, &self.widths, |i| i.width_index)
}
pub fn design_size_pt(&self) -> f64 {
self.design_size_pt
pub fn height(&self, c: char) -> i64 {
self.dimension(c, &self.heights, |i| i.height_index)
}
fn fixed_to_scaled(&self, raw: i32) -> i64 {
(f64::from(raw) * self.design_size_pt / 16.0).round() as i64
pub fn depth(&self, c: char) -> i64 {
self.dimension(c, &self.depths, |i| i.depth_index)
}
pub fn italic(&self, c: char) -> i64 {
self.dimension(c, &self.italics, |i| i.italic_index)
}
pub fn parameter_count(&self) -> usize {
self.params.len().max(7)
}
/// Zero-based fontdimen. Slant is 16.16 and independent of the font size.
pub fn param(&self, index: usize) -> i64 {
self.params.get(index).map_or(0, |raw| {
if index == 0 {
i64::from(*raw).div_euclid(16)
} else {
self.scaled(*raw).expect("validated TFM parameter")
}
})
}
pub fn lig_kern_program(&self) -> &[LigKernInstruction] {
&self.lig_kern
}
pub fn boundary_char(&self) -> Option<u8> {
self.boundary_char
}
pub fn false_boundary_char(&self) -> Option<u8> {
self.boundary_char.filter(|c| !self.has_slot(*c))
}
pub fn boundary_label(&self) -> Option<usize> {
self.boundary_label
}
pub fn lig_kern(&self, left: Option<u8>, right: u8) -> Option<LigKernCommand> {
let mut at = if let Some(c) = left {
let info = self.char_info(char::from(c))?;
if info.width_index == 0 || info.tag != 1 {
return None;
}
info.lig_kern_start
} else {
self.boundary_label?
};
let first = self.lig_kern.get(at)?;
// Character labels may start with a restart. The left-boundary
// label enters the program directly, as TeX's main_lig_loop+1 does.
if left.is_some() && first.skip > 128 {
at = usize::from(first.operation) * 256 + usize::from(first.remainder);
}
loop {
let ins = self.lig_kern.get(at)?;
if ins.skip <= 128 && ins.next == right {
return Some(if ins.operation < 128 {
LigKernCommand::Ligature {
operation: ins.operation,
replacement: ins.remainder,
}
} else {
LigKernCommand::Kern(
self.scaled(
self.kern_values[usize::from(ins.operation - 128) * 256
+ usize::from(ins.remainder)],
)
.expect("validated kern"),
)
});
}
if ins.skip >= 128 {
return None;
}
at += usize::from(ins.skip) + 1;
}
}
/// Kerning between two characters, in scaled points.
pub fn kern(&self, left: char, right: char) -> i64 {
self.kerns.get(&(left, right)).copied().unwrap_or(0)
let (Ok(l), Ok(r)) = (u8::try_from(left as u32), u8::try_from(right as u32)) else {
return 0;
};
match self.lig_kern(Some(l), r) {
Some(LigKernCommand::Kern(k)) => k,
_ => 0,
}
}
/// Ligature replacement for a pair, as (Unicode display char, TFM slot char).
pub fn ligature(&self, left: char, right: char) -> Option<(char, char)> {
self.ligatures.get(&(left, right)).copied()
/// A simple replace-both operation. Full consumers must use lig_kern,
/// whose operation byte retains keep/pass semantics and arbitrary slots.
pub fn ligature_slot(&self, left: char, right: char) -> Option<u8> {
let (Ok(l), Ok(r)) = (u8::try_from(left as u32), u8::try_from(right as u32)) else {
return None;
};
match self.lig_kern(Some(l), r) {
Some(LigKernCommand::Ligature {
operation: 0,
replacement,
}) => Some(replacement),
_ => None,
}
}
fn index_for(&self, character: char) -> Option<usize> {
let code = u32::from(character);
if code < u32::from(self.bc) || code > u32::from(self.ec) {
pub fn next_larger(&self, c: char) -> Option<u8> {
let info = self.char_info(c)?;
(info.tag == 2 && self.has_slot(info.remainder)).then_some(info.remainder)
}
pub fn extensible_recipe(&self, c: char) -> Option<ExtensibleRecipe> {
let info = self.char_info(c)?;
if info.tag != 3 {
return None;
}
Some((code - u32::from(self.bc)) as usize)
self.extensibles.get(usize::from(info.remainder)).copied()
}
pub fn char_info(&self, character: char) -> Option<CharInfo> {
self.index_for(character)
.and_then(|index| self.char_info.get(index).copied())
}
fn table_value(&self, table: &[i32], index: u8) -> Option<i32> {
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)
}
/// `\fontdimen7`: extra space inserted after punctuation with a space
/// factor of 2000 or more.
pub fn extra_space(&self) -> i64 {
self.param(6)
}
}
fn parse_kerns(
bytes: &[u8],
lig_kern_offset: usize,
instruction_count: usize,
kern_table: &[i32],
char_info: &[CharInfo],
bc: u32,
design_size_pt: f64,
) -> (
std::collections::HashMap<(char, char), i64>,
std::collections::HashMap<(char, char), (char, char)>,
) {
let mut kerns = std::collections::HashMap::new();
let mut ligatures = std::collections::HashMap::new();
for (index, info) in char_info.iter().enumerate() {
if info.tag != 1 {
continue;
}
let left = char::from_u32(bc + index as u32).unwrap_or('?');
let mut cursor = info.lig_kern_start;
while cursor < instruction_count {
let offset = lig_kern_offset + cursor * 4;
let Some(entry) = bytes.get(offset..offset + 4) else {
break;
};
let (skip, next, op, remainder) = (entry[0], entry[1], entry[2], entry[3]);
if op < 128 {
let slot_char = char::from_u32(bc + u32::from(remainder)).unwrap_or('?');
let unicode = match remainder {
11 => Some('\u{FB00}'),
12 => Some('\u{FB01}'),
13 => Some('\u{FB02}'),
14 => Some('\u{FB03}'),
15 => Some('\u{FB04}'),
_ => None,
};
if let Some(unicode) = unicode {
let right = char::from_u32(u32::from(next)).unwrap_or('?');
ligatures
.entry((left, right))
.or_insert((unicode, slot_char));
}
} else {
let kern_index = usize::from(op - 128) * 256 + usize::from(remainder);
if let Some(raw) = kern_table.get(kern_index) {
let right = char::from_u32(u32::from(next)).unwrap_or('?');
// Kern values are design-size-relative, like character
// widths; at the design size they are in 1/16 pt units.
let value = (f64::from(*raw) * design_size_pt / 16.0).round() as i64;
// TeX stops at the first instruction that matches the
// pair, so later instructions must not overwrite it.
kerns.entry((left, right)).or_insert(value);
}
}
if skip >= 128 {
break;
}
cursor += usize::from(skip) + 1;
}
}
(kerns, ligatures)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -363,9 +522,7 @@ mod tests {
#[test]
fn cmr10_has_an_fi_ligature() {
let font = cmr10();
let (unicode, slot) = font.ligature('f', 'i').expect("fi ligature");
assert_eq!(unicode, '\u{FB01}');
assert_eq!(slot, char::from_u32(u32::from(font.bc) + 12).unwrap());
assert_eq!(font.ligature_slot('f', 'i'), Some(12));
}
#[test]
@@ -379,4 +536,39 @@ mod tests {
fn rejects_truncated_files() {
assert!(TfmMetrics::parse(&[0_u8; 8]).is_err());
}
#[test]
fn fontdimens_use_tex_truncation_before_mu_conversion() {
let font = cmr10();
assert_eq!(font.param(5), 655_361);
assert_eq!(font.param(5) / 18, 36_408);
assert_eq!(font.param(100), 0);
let symbol = TfmMetrics::parse(include_bytes!("../assets/cmsy10.tfm")).unwrap();
assert_eq!(symbol.param(7), 443_356); // fontdimen8 = num1
assert_eq!(symbol.param(21), 163_840); // fontdimen22 = axis height
}
#[test]
fn cmex_retains_next_larger_and_extensible_recipes() {
let font = TfmMetrics::parse(include_bytes!("../assets/cmex10.tfm")).unwrap();
assert_eq!(font.next_larger(char::from(80)), Some(88)); // display sum
assert_eq!(font.next_larger(char::from(88)), None);
assert_eq!(font.char_info(char::from(80)).unwrap().remainder, 88);
assert_eq!(
font.extensible_recipe(char::from(48)),
Some(ExtensibleRecipe {
top: 48,
middle: 0,
bottom: 64,
repeat: 66,
})
);
assert_eq!(font.extensible_recipe(char::from(80)), None);
let mut slot = 0;
for expected in [16, 18, 32, 48] {
slot = font.next_larger(char::from(slot)).unwrap();
assert_eq!(slot, expected);
}
assert!(font.extensible_recipe(char::from(slot)).is_some());
}
}