Skip to main content

read_fonts/tables/
name.rs

1//! The [name (Naming)](https://docs.microsoft.com/en-us/typography/opentype/spec/name) table
2
3include!("../../generated/generated_name.rs");
4
5mod language;
6
7pub use language::language_id_to_bcp47;
8pub use types::NameId;
9
10impl<'a> Name<'a> {
11    /// The FontData containing the encoded name strings.
12    pub fn string_data(&self) -> FontData<'a> {
13        let base = self.offset_data();
14        let off = self.storage_offset();
15        base.split_off(off as usize).unwrap_or_default()
16    }
17}
18
19impl NameRecord {
20    /// Return a type that can decode the string data for this name entry.
21    ///
22    /// The `data` argument should be the name table's data section, which can
23    /// be retrieved via [`Name::string_data`].
24    pub fn string<'a>(&self, data: FontData<'a>) -> Result<NameString<'a>, ReadError> {
25        let start = self.string_offset().non_null().unwrap_or(0);
26        let end = start + self.length() as usize;
27
28        let data = data
29            .as_bytes()
30            .get(start..end)
31            .ok_or(ReadError::OutOfBounds)?;
32
33        let encoding = Encoding::new(self.platform_id(), self.encoding_id());
34        Ok(NameString { data, encoding })
35    }
36
37    // reference from fonttools:
38    // https://github.com/fonttools/fonttools/blob/c2119229cfb02cdb7c5a63374ef29d3d514259e8/Lib/fontTools/ttLib/tables/_n_a_m_e.py#L509
39    pub fn is_unicode(&self) -> bool {
40        self.platform_id() == 0
41            || (self.platform_id() == 3 && [0, 1, 10].contains(&self.encoding_id()))
42    }
43}
44
45impl LangTagRecord {
46    /// Return a type that can decode the string data for this name entry.
47    pub fn lang_tag<'a>(&self, data: FontData<'a>) -> Result<NameString<'a>, ReadError> {
48        let start = self.lang_tag_offset().non_null().unwrap_or(0);
49        let end = start + self.length() as usize;
50
51        let data = data
52            .as_bytes()
53            .get(start..end)
54            .ok_or(ReadError::OutOfBounds)?;
55
56        let encoding = Encoding::Utf16Be;
57        Ok(NameString { data, encoding })
58    }
59}
60
61//-- all this is from pinot https://github.com/dfrg/pinot/blob/eff5239018ca50290fb890a84da3dd51505da364/src/name.rs
62/// Entry for a name in the naming table.
63///
64/// This provides an iterator over characters.
65#[derive(Copy, Clone, PartialEq, Eq)]
66pub struct NameString<'a> {
67    data: &'a [u8],
68    encoding: Encoding,
69}
70
71impl<'a> NameString<'a> {
72    /// An iterator over the `char`s in this name.
73    pub fn chars(&self) -> CharIter<'a> {
74        CharIter {
75            data: self.data,
76            encoding: self.encoding,
77            pos: 0,
78        }
79    }
80}
81
82impl<'a> IntoIterator for NameString<'a> {
83    type Item = char;
84    type IntoIter = CharIter<'a>;
85    fn into_iter(self) -> Self::IntoIter {
86        self.chars()
87    }
88}
89
90impl std::fmt::Display for NameString<'_> {
91    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
92        for c in self.chars() {
93            c.fmt(f)?;
94        }
95        Ok(())
96    }
97}
98
99impl std::fmt::Debug for NameString<'_> {
100    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
101        write!(f, "\"{self}\"")
102    }
103}
104
105/// An iterator over the chars of a name record.
106#[derive(Clone)]
107pub struct CharIter<'a> {
108    data: &'a [u8],
109    encoding: Encoding,
110    pos: usize,
111}
112
113impl CharIter<'_> {
114    fn bump_u16(&mut self) -> Option<u16> {
115        let result = self
116            .data
117            .get(self.pos..self.pos + 2)
118            .map(|x| u16::from_be_bytes(x.try_into().unwrap()))?;
119        self.pos += 2;
120        Some(result)
121    }
122
123    fn bump_u8(&mut self) -> Option<u8> {
124        let result = self.data.get(self.pos)?;
125        self.pos += 1;
126        Some(*result)
127    }
128}
129
130impl Iterator for CharIter<'_> {
131    type Item = char;
132
133    fn next(&mut self) -> Option<Self::Item> {
134        if self.pos >= self.data.len() {
135            return None;
136        }
137        let rep = core::char::REPLACEMENT_CHARACTER;
138        let raw_c = match self.encoding {
139            Encoding::Utf16Be => {
140                let c1 = self.bump_u16()? as u32;
141                if (0xD800..0xDC00).contains(&c1) {
142                    let Some(c2) = self.bump_u16() else {
143                        return Some(rep);
144                    };
145                    if !(0xDC00..=0xDFFF).contains(&c2) {
146                        // c1 is an unpaired high surrogate; rewind so c2 is
147                        // decoded on its own rather than folded into a bogus
148                        // scalar.
149                        self.pos -= 2;
150                        return Some(rep);
151                    }
152                    ((c1 & 0x3FF) << 10) + (c2 as u32 & 0x3FF) + 0x10000
153                } else {
154                    c1
155                }
156            }
157            Encoding::MacRoman => {
158                let c = self.bump_u8()?;
159                MacRomanMapping.decode(c) as u32
160            }
161            _ => return None,
162        };
163        Some(std::char::from_u32(raw_c).unwrap_or(rep))
164    }
165}
166
167/// The encoding used by the name table.
168#[derive(Copy, Clone, PartialEq, Eq)]
169pub enum Encoding {
170    Utf16Be,
171    MacRoman,
172    Unknown,
173}
174
175impl Encoding {
176    /// Determine the coding from the platform and encoding id.
177    pub fn new(platform_id: u16, encoding_id: u16) -> Encoding {
178        match (platform_id, encoding_id) {
179            (0, _) => Encoding::Utf16Be,
180            (1, 0) => Encoding::MacRoman,
181            (3, 0) => Encoding::Utf16Be,
182            (3, 1) => Encoding::Utf16Be,
183            (3, 10) => Encoding::Utf16Be,
184            _ => Encoding::Unknown,
185        }
186    }
187}
188
189/// A helper for encoding and decoding Mac OS Roman encoded strings.
190pub struct MacRomanMapping;
191
192impl MacRomanMapping {
193    const START_REMAP: u8 = 128;
194    /// Convert from a mac-roman encoded byte to a `char`
195    pub fn decode(self, raw: u8) -> char {
196        if raw < Self::START_REMAP {
197            raw as char
198        } else {
199            let idx = raw - Self::START_REMAP;
200            char::from_u32(MAC_ROMAN_DECODE[idx as usize] as u32).unwrap()
201        }
202    }
203
204    /// convert from a char to a mac-roman encoded byte, if the char is in the mac-roman charset.
205    pub fn encode(self, c: char) -> Option<u8> {
206        let raw_c = c as u32;
207        let raw_c: u16 = raw_c.try_into().ok()?;
208        if raw_c < Self::START_REMAP as u16 {
209            Some(raw_c as u8)
210        } else {
211            match MAC_ROMAN_ENCODE.binary_search_by_key(&raw_c, |(unic, _)| *unic) {
212                Ok(idx) => Some(MAC_ROMAN_ENCODE[idx].1),
213                Err(_) => None,
214            }
215        }
216    }
217}
218
219/// A lookup table for the Mac Roman encoding. This matches the values `128..=255`
220/// to specific Unicode values.
221#[rustfmt::skip]
222static MAC_ROMAN_DECODE: [u16; 128] = [
223    196, 197, 199, 201, 209, 214, 220, 225, 224, 226, 228, 227, 229, 231, 233,
224    232, 234, 235, 237, 236, 238, 239, 241, 243, 242, 244, 246, 245, 250, 249,
225    251, 252, 8224, 176, 162, 163, 167, 8226, 182, 223, 174, 169, 8482, 180,
226    168, 8800, 198, 216, 8734, 177, 8804, 8805, 165, 181, 8706, 8721, 8719,
227    960, 8747, 170, 186, 937, 230, 248, 191, 161, 172, 8730, 402, 8776, 8710,
228    171, 187, 8230, 160, 192, 195, 213, 338, 339, 8211, 8212, 8220, 8221, 8216,
229    8217, 247, 9674, 255, 376, 8260, 8364, 8249, 8250, 64257, 64258, 8225, 183,
230    8218, 8222, 8240, 194, 202, 193, 203, 200, 205, 206, 207, 204, 211, 212,
231    63743, 210, 218, 219, 217, 305, 710, 732, 175, 728, 729, 730, 184, 733,
232    731, 711,
233];
234
235/// A lookup pairing (sorted) Unicode values to Mac Roman values
236#[rustfmt::skip]
237static MAC_ROMAN_ENCODE: [(u16, u8); 128] = [
238    (160, 202), (161, 193), (162, 162), (163, 163),
239    (165, 180), (167, 164), (168, 172), (169, 169),
240    (170, 187), (171, 199), (172, 194), (174, 168),
241    (175, 248), (176, 161), (177, 177), (180, 171),
242    (181, 181), (182, 166), (183, 225), (184, 252),
243    (186, 188), (187, 200), (191, 192), (192, 203),
244    (193, 231), (194, 229), (195, 204), (196, 128),
245    (197, 129), (198, 174), (199, 130), (200, 233),
246    (201, 131), (202, 230), (203, 232), (204, 237),
247    (205, 234), (206, 235), (207, 236), (209, 132),
248    (210, 241), (211, 238), (212, 239), (213, 205),
249    (214, 133), (216, 175), (217, 244), (218, 242),
250    (219, 243), (220, 134), (223, 167), (224, 136),
251    (225, 135), (226, 137), (227, 139), (228, 138),
252    (229, 140), (230, 190), (231, 141), (232, 143),
253    (233, 142), (234, 144), (235, 145), (236, 147),
254    (237, 146), (238, 148), (239, 149), (241, 150),
255    (242, 152), (243, 151), (244, 153), (245, 155),
256    (246, 154), (247, 214), (248, 191), (249, 157),
257    (250, 156), (251, 158), (252, 159), (255, 216),
258    (305, 245), (338, 206), (339, 207), (376, 217),
259    (402, 196), (710, 246), (711, 255), (728, 249),
260    (729, 250), (730, 251), (731, 254), (732, 247),
261    (733, 253), (937, 189), (960, 185), (8211, 208),
262    (8212, 209), (8216, 212), (8217, 213), (8218, 226),
263    (8220, 210), (8221, 211), (8222, 227), (8224, 160),
264    (8225, 224), (8226, 165), (8230, 201), (8240, 228),
265    (8249, 220), (8250, 221), (8260, 218), (8364, 219),
266    (8482, 170), (8706, 182), (8710, 198), (8719, 184),
267    (8721, 183), (8730, 195), (8734, 176), (8747, 186),
268    (8776, 197), (8800, 173), (8804, 178), (8805, 179),
269    (9674, 215), (63743, 240), (64257, 222), (64258, 223),
270];
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn mac_roman() {
278        static INPUT: &str = "Joachim Müller-Lancé";
279        for c in INPUT.chars() {
280            let enc = MacRomanMapping.encode(c).unwrap();
281            assert_eq!(MacRomanMapping.decode(enc), c);
282        }
283    }
284
285    #[test]
286    fn lone_surrogate_at_end() {
287        let chars = CharIter {
288            // DEVANAGARI LETTER SHORT A (U+0904), unpaired high surrogate (0xD800)
289            data: &[0x09, 0x04, 0xD8, 0x00],
290            encoding: Encoding::Utf16Be,
291            pos: 0,
292        };
293        assert!(chars.eq(['ऄ', std::char::REPLACEMENT_CHARACTER].into_iter()))
294    }
295
296    #[test]
297    fn high_surrogate_followed_by_non_low() {
298        let rep = std::char::REPLACEMENT_CHARACTER;
299        // High surrogate (0xD800) followed by a BMP scalar 'A' (U+0041): the
300        // high surrogate is unpaired and 'A' must still be decoded.
301        let chars = CharIter {
302            data: &[0xD8, 0x00, 0x00, 0x41],
303            encoding: Encoding::Utf16Be,
304            pos: 0,
305        };
306        assert!(chars.eq([rep, 'A'].into_iter()));
307
308        // High surrogate (0xD800) followed by a valid pair (U+1F600): the first
309        // unit is unpaired and the following pair must decode intact.
310        let chars = CharIter {
311            data: &[0xD8, 0x00, 0xD8, 0x3D, 0xDE, 0x00],
312            encoding: Encoding::Utf16Be,
313            pos: 0,
314        };
315        assert!(chars.eq([rep, '😀'].into_iter()));
316    }
317}