ttf_parser/tables/cmap/
format0.rs

1// https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-0-byte-encoding-table
2
3use crate::parser::{Stream, NumFrom};
4
5pub fn parse(data: &[u8], code_point: u32) -> Option<u16> {
6    let mut s = Stream::new(data);
7    s.skip::<u16>(); // format
8    s.skip::<u16>(); // length
9    s.skip::<u16>(); // language
10
11    s.advance(usize::num_from(code_point));
12    let glyph_id: u8 = s.read()?;
13
14    // Make sure that the glyph is not zero, the array always has length 256,
15    // but some codepoints may be mapped to zero.
16    if glyph_id != 0 {
17        Some(u16::from(glyph_id))
18    } else {
19        None
20    }
21}
22
23pub fn codepoints(data: &[u8], mut f: impl FnMut(u32)) -> Option<()> {
24    let mut s = Stream::new(data);
25    s.skip::<u16>(); // format
26    s.skip::<u16>(); // length
27    s.skip::<u16>(); // language
28
29    for code_point in 0..256 {
30        // In contrast to every other format, here we take a look at the glyph
31        // id and check whether it is zero because otherwise this method would
32        // always simply call `f` for `0..256` which would be kind of pointless
33        // (this array always has length 256 even when the face has only fewer
34        // glyphs).
35        let glyph_id: u8 = s.read()?;
36        if glyph_id != 0 {
37            f(code_point);
38        }
39    }
40
41    Some(())
42}
43
44#[cfg(test)]
45mod tests {
46    use super::{parse, codepoints};
47
48    #[test]
49    fn maps_not_all_256_codepoints() {
50        let mut data = vec![
51            0x00, 0x00, // format: 0
52            0x01, 0x06, // subtable size: 262
53            0x00, 0x00, // language ID: 0
54        ];
55
56        // Map (only) codepoint 0x40 to 100.
57        data.extend(std::iter::repeat(0).take(256));
58        data[6 + 0x40] = 100;
59
60        assert_eq!(parse(&data, 0), None);
61        assert_eq!(parse(&data, 0x40), Some(100));
62        assert_eq!(parse(&data, 100), None);
63
64        let mut vec = vec![];
65        codepoints(&data, |c| vec.push(c));
66        assert_eq!(vec, [0x40]);
67    }
68}