Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.2.3555.5 KB2026-10-160.2.2572.8 KB2026-10-150.2.1580.5 KB2026-10-150.2.0579.9 KB2026-09-150.1.1576.6 KB2026-09-12
Version
0.2.2
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
572.8 KB
Downloads
28
Checksum
ce26f898ba26eb49c71ebc68597f62f268b83e41bb265b1b5a01688966054588
Dependencies
None

opentype.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//! Extracts tables from an OpenType file
//!
//! Only what is needed to typeset math is read: the six tables head, hhea, maxp, hmtx, cmap,
//! and name; glyf or CFF, which hold the glyph outlines; and the MATH table. The glyph outlines
//! and MATH are read elsewhere.

use crate::error::Error;
use std::collections::HashMap;


/// What is taken from head
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Head {
    /// Coordinate units per em
    pub units_per_em: f64,
    /// Whether loca uses 4-byte offsets
    pub long_loca: bool,
}


fn short(at: usize) -> Error {
    Error::new("the font file ends too early", at)
}


pub fn read_u8(data: &[u8], at: usize) -> Result<u8, Error> {
    data.get(at).copied().ok_or_else(|| short(at))
}


pub fn read_u16(data: &[u8], at: usize) -> Result<u16, Error> {
    let slice = data.get(at..at + 2).ok_or_else(|| short(at))?;

    Ok(u16::from_be_bytes([slice[0], slice[1]]))
}


pub fn read_i16(data: &[u8], at: usize) -> Result<i16, Error> {
    Ok(read_u16(data, at)? as i16)
}


pub fn read_u32(data: &[u8], at: usize) -> Result<u32, Error> {
    let slice = data.get(at..at + 4).ok_or_else(|| short(at))?;

    Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}


/// The position of the table directory. For a font collection (ttcf), the first font is used
fn directory(data: &[u8]) -> Result<usize, Error> {
    if data.len() >= 4 && &data[0..4] == b"ttcf" {
        return Ok(read_u32(data, 12)? as usize);
    }

    Ok(0)
}


/// Looks up the position and length of a table
pub fn find(data: &[u8], tag: &str) -> Result<Option<(usize, usize)>, Error> {
    let base = directory(data)?;
    let count = read_u16(data, base + 4)? as usize;

    for index in 0..count {
        let at = base + 12 + index * 16;
        let name = data.get(at..at + 4).ok_or_else(|| short(at))?;

        if name == tag.as_bytes() {
            let start = read_u32(data, at + 8)? as usize;
            let length = read_u32(data, at + 12)? as usize;

            return Ok(Some((start, length)));
        }
    }

    Ok(None)
}


/// Looks up a required table. If it is missing, the error says which one
pub fn require(data: &[u8], tag: &str) -> Result<(usize, usize), Error> {
    match find(data, tag)? {
        Some(found) => Ok(found),
        None => Err(Error::new(format!("the {tag} table is missing"), 0)),
    }
}


pub fn head(data: &[u8], at: usize) -> Result<Head, Error> {
    let units_per_em = read_u16(data, at + 18)? as f64;

    if units_per_em <= 0.0 {
        return Err(Error::new("unitsPerEm is 0", at + 18));
    }

    Ok(Head {units_per_em, long_loca: read_i16(data, at + 50)? != 0})
}


/// The number of glyphs
pub fn glyph_count(data: &[u8], maxp_at: usize) -> Result<usize, Error> {
    Ok(read_u16(data, maxp_at + 4)? as usize)
}


/// The advance of each glyph, returned in font units
pub fn advances(
    data: &[u8],
    hmtx_at: usize,
    hhea_at: usize,
    count: usize,
) -> Result<Vec<f64>, Error> {
    let metric_count = read_u16(data, hhea_at + 34)? as usize;

    if metric_count == 0 {
        return Err(Error::new("numberOfHMetrics in hhea is 0", hhea_at + 34));
    }

    let mut found = Vec::with_capacity(count);

    for index in 0..count {
        let at = hmtx_at + index.min(metric_count - 1) * 4;
        found.push(read_u16(data, at)? as f64);
    }

    Ok(found)
}


/// Picks the readable subtable in cmap with the widest coverage
fn best_subtable(data: &[u8], at: usize) -> Result<usize, Error> {
    let count = read_u16(data, at + 2)? as usize;
    let mut best: Option<(u8, usize)> = None;

    for index in 0..count {
        let record = at + 4 + index * 8;
        let platform = read_u16(data, record)?;
        let encoding = read_u16(data, record + 2)?;
        let offset = at + read_u32(data, record + 4)? as usize;
        let format = read_u16(data, offset)?;
        let score = match (platform, encoding, format) {
            (3, 10, 12) => 5,
            (0, _, 12) => 4,
            (3, 1, 4) => 3,
            (0, _, 4) => 2,
            (_, _, 4) | (_, _, 12) => 1,
            _ => continue,
        };

        if best.is_none_or(|(current, _)| score > current) {
            best = Some((score, offset));
        }
    }

    match best {
        Some((_, offset)) => Ok(offset),
        None => Err(Error::new("no readable cmap subtable", at)),
    }
}


/// A limit that stops too many mappings from being added. There are at most 65536 glyphs, so a
/// table that goes past this is broken
const MAP_LIMIT: usize = 300_000;


/// The mapping from characters to glyph IDs
pub fn character_map(data: &[u8], at: usize) -> Result<HashMap<char, u16>, Error> {
    let offset = best_subtable(data, at)?;

    match read_u16(data, offset)? {
        4 => segment_map(data, offset),
        12 => group_map(data, offset),
        format => Err(Error::new(format!("cannot read cmap format {format}"), offset)),
    }
}


/// cmap format 4
fn segment_map(data: &[u8], at: usize) -> Result<HashMap<char, u16>, Error> {
    let segment_count = read_u16(data, at + 6)? as usize / 2;
    let end_at = at + 14;
    let start_at = end_at + segment_count * 2 + 2;
    let delta_at = start_at + segment_count * 2;
    let range_at = delta_at + segment_count * 2;
    let mut found = HashMap::new();

    for index in 0..segment_count {
        let end = read_u16(data, end_at + index * 2)? as u32;
        let start = read_u16(data, start_at + index * 2)? as u32;
        let delta = read_i16(data, delta_at + index * 2)? as i32;
        let range = read_u16(data, range_at + index * 2)? as usize;

        if start > end || start == 0xffff {
            continue;
        }

        for code in start..=end {
            if found.len() >= MAP_LIMIT {
                return Err(Error::new("cmap has too many mappings", at));
            }

            let glyph = if range == 0 {
                ((code as i32 + delta) & 0xffff) as u16
            } else {
                let entry = range_at + index * 2 + range + (code - start) as usize * 2;
                let raw = read_u16(data, entry)?;

                if raw == 0 {
                    continue;
                }

                ((raw as i32 + delta) & 0xffff) as u16
            };

            if glyph == 0 {
                continue;
            }

            if let Some(character) = char::from_u32(code) {
                found.insert(character, glyph);
            }
        }
    }

    Ok(found)
}


/// cmap format 12
fn group_map(data: &[u8], at: usize) -> Result<HashMap<char, u16>, Error> {
    let count = read_u32(data, at + 12)? as usize;
    let mut found = HashMap::new();

    for index in 0..count {
        let group = at + 16 + index * 12;
        let start = read_u32(data, group)?;
        let end = read_u32(data, group + 4)?;
        let glyph = read_u32(data, group + 8)?;

        if start > end {
            continue;
        }

        for step in 0..=(end - start) {
            if found.len() >= MAP_LIMIT {
                return Err(Error::new("cmap has too many mappings", at));
            }

            let number = glyph + step;

            if number == 0 || number > 0xffff {
                continue;
            }

            if let Some(character) = char::from_u32(start + step) {
                found.insert(character, number as u16);
            }
        }
    }

    Ok(found)
}


/// Takes the typeface name from the name table. It looks at typographic family (name ID 16)
/// first, and uses family (name ID 1) if there is none
pub fn family_name(data: &[u8], at: usize) -> Result<String, Error> {
    let count = read_u16(data, at + 2)? as usize;
    let storage = at + read_u16(data, at + 4)? as usize;
    let mut best: Option<(u8, String)> = None;

    for index in 0..count {
        let record = at + 6 + index * 12;
        let platform = read_u16(data, record)?;
        let encoding = read_u16(data, record + 2)?;
        let name_id = read_u16(data, record + 6)?;

        if name_id != 1 && name_id != 16 {
            continue;
        }

        let length = read_u16(data, record + 8)? as usize;
        let offset = storage + read_u16(data, record + 10)? as usize;
        let slice = match data.get(offset..offset + length) {
            Some(slice) => slice,
            None => continue,
        };
        let text = match (platform, encoding) {
            (3, _) | (0, _) => decode_utf16(slice),
            (1, 0) => slice.iter().map(|byte| *byte as char).collect(),
            _ => continue,
        };

        if text.is_empty() {
            continue;
        }

        let score = if name_id == 16 {2} else {1};

        if best.as_ref().is_none_or(|(current, _)| score > *current) {
            best = Some((score, text));
        }
    }

    match best {
        Some((_, text)) => Ok(text),
        None => Err(Error::new("the name table has no typeface name", at)),
    }
}


fn decode_utf16(slice: &[u8]) -> String {
    let units: Vec<u16> = slice
        .chunks_exact(2)
        .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
        .collect();

    String::from_utf16_lossy(&units)
}


#[cfg(test)]
mod tests {
    use super::*;

    fn sample() -> Vec<u8> {
        std::fs::read("font/latinmodern-math.otf").expect("cannot read the test font")
    }

    #[test]
    fn reads_numbers() {
        let data = [0x12u8, 0x34, 0xff, 0xfe];
        assert_eq!(read_u16(&data, 0).unwrap(), 0x1234);
        assert_eq!(read_i16(&data, 2).unwrap(), -2);
        assert_eq!(read_u32(&data, 0).unwrap(), 0x1234fffe);
        assert!(read_u16(&data, 3).is_err());
    }

    #[test]
    fn finds_the_tables_of_the_sample_font() {
        let data = sample();
        assert!(find(&data, "CFF ").unwrap().is_some());
        assert!(find(&data, "MATH").unwrap().is_some());
        assert!(find(&data, "glyf").unwrap().is_none());
        assert!(require(&data, "nope").is_err());
    }

    #[test]
    fn reads_head_and_the_glyph_count() {
        let data = sample();
        let (head_at, _) = require(&data, "head").unwrap();
        assert_eq!(head(&data, head_at).unwrap().units_per_em, 1000.0);
        let (maxp_at, _) = require(&data, "maxp").unwrap();
        assert!(glyph_count(&data, maxp_at).unwrap() > 1000);
    }

    #[test]
    fn maps_characters_to_glyphs() {
        let data = sample();
        let (cmap_at, _) = require(&data, "cmap").unwrap();
        let map = character_map(&data, cmap_at).unwrap();
        assert!(map.contains_key(&'x'));
        assert!(map.contains_key(&'\u{221a}'));
        assert!(map.contains_key(&'\u{2211}'));
        assert_ne!(map[&'x'], map[&'y']);
    }

    #[test]
    fn reads_the_advances() {
        let data = sample();
        let (hmtx_at, _) = require(&data, "hmtx").unwrap();
        let (hhea_at, _) = require(&data, "hhea").unwrap();
        let (maxp_at, _) = require(&data, "maxp").unwrap();
        let count = glyph_count(&data, maxp_at).unwrap();
        let width = advances(&data, hmtx_at, hhea_at, count).unwrap();
        assert_eq!(width.len(), count);
        assert!(width.iter().any(|value| *value > 0.0));
    }

    #[test]
    fn reads_the_family_name() {
        let data = sample();
        let (name_at, _) = require(&data, "name").unwrap();
        assert_eq!(family_name(&data, name_at).unwrap(), "Latin Modern Math");
    }
}