Skip to main content

read_fonts/tables/
post.rs

1//! the [post (PostScript)](https://docs.microsoft.com/en-us/typography/opentype/spec/post#header) table
2
3include!("../../generated/generated_post.rs");
4
5impl<'a> Post<'a> {
6    /// The number of glyph names covered by this table
7    pub fn num_names(&self) -> usize {
8        match self.version() {
9            Version16Dot16::VERSION_1_0 => DEFAULT_GLYPH_NAMES.len(),
10            Version16Dot16::VERSION_2_0 => self.num_glyphs().unwrap_or_default() as usize,
11            _ => 0,
12        }
13    }
14
15    /// Returns the name for the given glyph.
16    ///
17    /// Note that this is a relatively expensive operation, as it may require
18    /// a linear scan through the string data to find the target name. If you
19    /// need to iterate over all glyph names or collect them into a map for
20    /// faster access, use [`Self::glyph_names`] instead.
21    pub fn glyph_name(&self, glyph_id: GlyphId16) -> Option<&'a str> {
22        let glyph_id = glyph_id.to_u16() as usize;
23        match self.version() {
24            Version16Dot16::VERSION_1_0 => DEFAULT_GLYPH_NAMES.get(glyph_id).copied(),
25            Version16Dot16::VERSION_2_0 => {
26                let idx = self.glyph_name_index()?.get(glyph_id)?.get() as usize;
27                if idx < DEFAULT_GLYPH_NAMES.len() {
28                    return DEFAULT_GLYPH_NAMES.get(idx).copied();
29                }
30                let idx = idx - DEFAULT_GLYPH_NAMES.len();
31                self.string_data()?.get(idx)?.ok().map(|s| s.0)
32            }
33            _ => None,
34        }
35    }
36
37    /// Return an iterator over the glyph names in this table.
38    pub fn glyph_names(&self) -> GlyphNames<'a> {
39        let num_names = self.num_names() as u32;
40        let kind = match self.version() {
41            Version16Dot16::VERSION_1_0 => GlyphNameIterKind::V1(self.clone(), 0),
42            Version16Dot16::VERSION_2_0 => GlyphNameIterKind::V2 {
43                post: self.clone(),
44                idx: 0,
45                checkpoint_stride: (num_names as usize).div_ceil(NUM_CHECKPOINTS + 1).max(1),
46                checkpoints: [UNSET_CHECKPOINT; NUM_CHECKPOINTS],
47                last_actual_idx: None,
48                last_offset: 0,
49                strings_end: usize::MAX,
50            },
51            _ => GlyphNameIterKind::None,
52        };
53        GlyphNames { num_names, kind }
54    }
55
56    //FIXME: how do we want to traverse this? I want to stop needing to
57    // add special cases for things...
58}
59
60/// A string in the post table.
61///
62/// This is basically just a newtype that knows how to parse from a Pascal-style
63/// string.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct PString<'a>(&'a str);
66
67impl<'a> PString<'a> {
68    pub fn as_str(&self) -> &'a str {
69        self.0
70    }
71}
72
73impl std::ops::Deref for PString<'_> {
74    type Target = str;
75    fn deref(&self) -> &Self::Target {
76        self.0
77    }
78}
79
80impl PartialEq<&str> for PString<'_> {
81    fn eq(&self, other: &&str) -> bool {
82        self.0 == *other
83    }
84}
85
86impl ReadArgs for PString<'_> {
87    type Args = ();
88}
89
90impl<'a> FontRead<'a> for PString<'a> {
91    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
92        let len: u8 = data.read_at(0)?;
93        let pstring = data
94            .as_bytes()
95            .get(1..len as usize + 1)
96            .ok_or(ReadError::OutOfBounds)?;
97
98        if pstring.is_ascii() {
99            Ok(PString(std::str::from_utf8(pstring).unwrap()))
100        } else {
101            //FIXME not really sure how we want to handle this?
102            Err(ReadError::MalformedData("Must be valid ascii"))
103        }
104    }
105}
106
107impl VarSize for PString<'_> {
108    type Size = u8;
109}
110
111const NUM_CHECKPOINTS: usize = 16;
112const UNSET_CHECKPOINT: u32 = u32::MAX;
113
114/// Returns the array slot that holds the offset of `index`, if `index` is one
115/// of the checkpoints we keep.
116///
117/// Slot `n` is read back as the start of index `(n + 1) * stride`, so an index
118/// past the last checkpoint has to be dropped rather than clamped into it.
119fn checkpoint_slot(index: usize, stride: usize) -> Option<usize> {
120    (index % stride == 0)
121        .then(|| index / stride)
122        .filter(|slot| (1..=NUM_CHECKPOINTS).contains(slot))
123        .map(|slot| slot - 1)
124}
125
126/// Iterator over the glyph names in a post table.
127#[derive(Clone)]
128pub struct GlyphNames<'a> {
129    num_names: u32,
130    kind: GlyphNameIterKind<'a>,
131}
132
133#[derive(Clone)]
134enum GlyphNameIterKind<'a> {
135    None,
136    V1(Post<'a>, u32),
137    V2 {
138        post: Post<'a>,
139        idx: u32,
140        // The number of indices between checkpoints
141        checkpoint_stride: usize,
142        // The offset of each checkpoint; checkpoint 0 is implicit
143        checkpoints: [u32; NUM_CHECKPOINTS],
144        // The last actual index and that was scanned, for monotonic fast path
145        last_actual_idx: Option<usize>,
146        // The offset associated with the last scanned index
147        last_offset: usize,
148        // The first string index the data cannot reach. Strings are read in
149        // order, so no later one can be read either.
150        strings_end: usize,
151    },
152}
153
154impl<'a> Iterator for GlyphNames<'a> {
155    type Item = (GlyphId, &'a str);
156
157    /// Returns the next glyph that has a readable name.
158    ///
159    /// Glyphs whose names cannot be read are skipped, so the glyph ids can
160    /// have gaps.
161    fn next(&mut self) -> Option<Self::Item> {
162        loop {
163            let (gid, name) = self.next_entry()?;
164            if let Some(name) = name {
165                return Some((gid.into(), name));
166            }
167        }
168    }
169}
170
171impl<'a> GlyphNames<'a> {
172    /// Returns the next glyph and its name, or `None` if there are no more
173    /// glyphs.
174    fn next_entry(&mut self) -> Option<(GlyphId16, Option<&'a str>)> {
175        match &mut self.kind {
176            GlyphNameIterKind::None => None,
177            GlyphNameIterKind::V1(post, idx) => {
178                if *idx >= self.num_names {
179                    return None;
180                }
181                let gid = GlyphId16::new(*idx as u16);
182                *idx += 1;
183                Some((gid, post.glyph_name(gid)))
184            }
185            GlyphNameIterKind::V2 {
186                post,
187                idx,
188                checkpoint_stride,
189                checkpoints,
190                last_actual_idx,
191                last_offset,
192                strings_end,
193            } => {
194                if *idx >= self.num_names {
195                    return None;
196                }
197                let stride = *checkpoint_stride;
198                let gid = GlyphId16::new(*idx as u16);
199                let index = *idx as usize;
200                *idx += 1;
201                let mut name = || -> Option<&'a str> {
202                    let mut actual_idx = post.glyph_name_index()?.get(index)?.get() as usize;
203                    Some(if actual_idx < DEFAULT_GLYPH_NAMES.len() {
204                        DEFAULT_GLYPH_NAMES.get(actual_idx).copied()?
205                    } else {
206                        actual_idx -= DEFAULT_GLYPH_NAMES.len();
207                        if actual_idx >= *strings_end {
208                            return None;
209                        }
210                        let string_data =
211                            post.offset_data().slice(post.string_data_byte_range())?;
212                        // Checkpoint 0 is implicit and always at offset 0; the
213                        // array stores logical checkpoints 1..=NUM_CHECKPOINTS.
214                        let target_slot = (actual_idx / stride).min(NUM_CHECKPOINTS);
215                        // Find the the starting location for our scan
216                        let (mut scan_idx, mut offset) = {
217                            // Search backward from the target slot to find the
218                            // nearest checkpoint that has been set
219                            let mut slot = target_slot;
220                            while slot > 0 && checkpoints[slot - 1] == UNSET_CHECKPOINT {
221                                slot -= 1;
222                            }
223                            if slot == 0 {
224                                // Fallback to implicit checkpoint 0
225                                (0, 0)
226                            } else {
227                                // Otherwise, start scanning from the nearest
228                                // checkpoint
229                                (slot * stride, checkpoints[slot - 1] as usize)
230                            }
231                        };
232                        // See if we can use the monotonic fast path.
233                        if let Some(last_idx) = *last_actual_idx {
234                            // Start scanning from the last index if that provides
235                            // a smaller search space than the nearest checkpoint
236                            if last_idx <= actual_idx && last_idx > scan_idx {
237                                scan_idx = last_idx;
238                                offset = *last_offset;
239                            }
240                        }
241                        // Now do the linear scan over the string data
242                        while scan_idx < actual_idx {
243                            let Some(next) = PString::read_len_at(string_data, offset)
244                                .and_then(|len| offset.checked_add(len))
245                            else {
246                                *strings_end = scan_idx;
247                                return None;
248                            };
249                            offset = next;
250                            scan_idx += 1;
251                            // If this index is a checkpoint, record the offset
252                            // for future scans
253                            if let Some(slot) = checkpoint_slot(scan_idx, stride) {
254                                checkpoints[slot] = u32::try_from(offset).ok()?;
255                            }
256                        }
257                        if let Some(slot) = checkpoint_slot(actual_idx, stride) {
258                            checkpoints[slot] = u32::try_from(offset).ok()?;
259                        }
260                        // Record the last index and offset for future scans
261                        *last_actual_idx = Some(actual_idx);
262                        *last_offset = offset;
263                        PString::read(string_data.split_off(offset)?).ok()?.0
264                    })
265                };
266                Some((gid, name()))
267            }
268        }
269    }
270}
271
272/// The 258 glyph names defined for Macintosh TrueType fonts
273#[rustfmt::skip]
274pub static DEFAULT_GLYPH_NAMES: [&str; 258] = [
275    ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar",
276    "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma",
277    "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven",
278    "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B",
279    "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
280    "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum",
281    "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",
282    "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright",
283    "asciitilde", "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis",
284    "aacute", "agrave", "acircumflex", "adieresis", "atilde", "aring", "ccedilla", "eacute",
285    "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", "ntilde",
286    "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex",
287    "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph",
288    "germandbls", "registered", "copyright", "trademark", "acute", "dieresis", "notequal", "AE",
289    "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", "mu", "partialdiff",
290    "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", "ae",
291    "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal",
292    "Delta", "guillemotleft", "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde",
293    "Otilde", "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright", "quoteleft",
294    "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency",
295    "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase",
296    "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave",
297    "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", "apple", "Ograve",
298    "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve",
299    "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash",
300    "Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn",
301    "thorn", "minus", "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf",
302    "onequarter", "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent", "Scedilla",
303    "scedilla", "Cacute", "cacute", "Ccaron", "ccaron", "dcroat",
304];
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309    use font_test_data::{bebuffer::BeBuffer, post as test_data};
310
311    #[test]
312    fn test_post() {
313        let table = Post::read(test_data::SIMPLE.into()).unwrap();
314        assert_eq!(table.version(), Version16Dot16::VERSION_2_0);
315        assert_eq!(table.underline_position(), FWord::new(-75));
316        assert_eq!(table.glyph_name(GlyphId16::new(1)), Some(".notdef"));
317        assert_eq!(table.glyph_name(GlyphId16::new(2)), Some("space"));
318        assert_eq!(table.glyph_name(GlyphId16::new(7)), Some("hello"));
319        assert_eq!(table.glyph_name(GlyphId16::new(8)), Some("hi"));
320        assert_eq!(table.glyph_name(GlyphId16::new(9)), Some("hola"));
321    }
322
323    fn make_basic_post(version: Version16Dot16, include_num_glyphs: bool) -> BeBuffer {
324        let buf = BeBuffer::new()
325            .push(version)
326            .push(Fixed::from_i32(5))
327            .extend([FWord::new(6), FWord::new(7)]) //underline pos/thickness
328            .push(0u32) // isFixedPitch
329            .extend([7u32, 8, 9, 10]); // min/max mem x
330        if include_num_glyphs {
331            buf.push(0u16)
332        } else {
333            buf
334        }
335    }
336
337    #[test]
338    fn parse_versioned_fields_v1() {
339        // v1, even if it has the extra field will not read it:
340
341        let buf = make_basic_post(Version16Dot16::VERSION_1_0, true);
342        let postv1 = Post::read(buf.data().into()).unwrap();
343        assert!(postv1.num_glyphs().is_none());
344    }
345
346    #[test]
347    fn parse_versioned_fields_v2() {
348        let buf = make_basic_post(Version16Dot16::VERSION_2_0, false);
349        let postv2 = Post::read(buf.data().into()).unwrap();
350        // v2 will fail to read if data is missing
351        assert!(postv2.num_glyphs().is_none());
352
353        // but read if data is present
354        let buf = make_basic_post(Version16Dot16::VERSION_2_0, true);
355        let postv2 = Post::read(buf.data().into()).unwrap();
356        // v2 will fail to read if data is missing
357        assert_eq!(postv2.num_glyphs(), Some(0));
358    }
359
360    #[test]
361    fn parse_versioned_fields_v3() {
362        // v3 will again not read since this field is not compatible
363        let buf = make_basic_post(Version16Dot16::VERSION_3_0, true);
364        let postv3 = Post::read(buf.data().into()).unwrap();
365        assert!(postv3.num_glyphs().is_none());
366    }
367
368    #[test]
369    fn num_names_defaults_to_zero_without_num_glyphs() {
370        let buf = make_basic_post(Version16Dot16::VERSION_2_0, false);
371        let post = Post::read(buf.data().into()).unwrap();
372        // Just don't panic
373        assert_eq!(post.num_names(), 0);
374    }
375
376    #[test]
377    fn glyph_name_missing_string_data_returns_none() {
378        let buf = BeBuffer::new()
379            .push(Version16Dot16::VERSION_2_0)
380            .push(Fixed::from_i32(5))
381            .extend([FWord::new(6), FWord::new(7)])
382            .push(0u32)
383            .extend([7u32, 8, 9, 10])
384            .push(1u16)
385            .push(258u16);
386        let post = Post::read(buf.data().into()).unwrap();
387        // Just don't panic
388        assert_eq!(post.glyph_name(GlyphId16::new(0)), None);
389    }
390
391    #[test]
392    fn glyph_names_matches_naive_on_varied_synthetic_v2_data() {
393        let num_glyphs = 2_000u16;
394        let orders = [
395            test_data::GlyphNameOrder::Monotonic,
396            test_data::GlyphNameOrder::MostlyMonotonicWithBackrefs,
397            test_data::GlyphNameOrder::AllPointToLast,
398        ];
399        for order in orders {
400            let (bytes, expected_custom_names) =
401                test_data::v2_with_varied_glyph_names(num_glyphs, 63, order);
402            let post = Post::read(bytes.as_slice().into()).unwrap();
403            let from_naive: Vec<_> = (0..num_glyphs)
404                .map(|gid| post.glyph_name(GlyphId16::new(gid)).unwrap())
405                .collect();
406            let from_iter: Vec<_> = post.glyph_names().map(|(_, name)| name).collect();
407            assert_eq!(from_iter, from_naive);
408            for (name, expected) in from_iter.iter().zip(expected_custom_names.iter()) {
409                assert_eq!(*name, expected.as_str());
410            }
411        }
412    }
413
414    #[test]
415    fn glyph_names_skip_a_name_that_cannot_be_read() {
416        let mut buf = BeBuffer::new()
417            .push(Version16Dot16::VERSION_2_0)
418            .push(Fixed::from_i32(0))
419            .extend([FWord::new(0), FWord::new(0)])
420            .push(0u32)
421            .extend([0u32, 0, 0, 0])
422            .push(3u16);
423        // The second glyph names a string the table does not have.
424        for index in [258u16, 258 + 9, 3] {
425            buf = buf.push(index);
426        }
427        buf = buf.push(2u8).extend(*b"ok");
428        let post = Post::read(buf.data().into()).unwrap();
429        assert_eq!(post.glyph_name(GlyphId16::new(1)), None);
430        let names: Vec<_> = post.glyph_names().collect();
431        assert_eq!(names, [(GlyphId::new(0), "ok"), (GlyphId::new(2), "space")]);
432    }
433
434    // Glyphs whose names lie past the end of the string data fail at once,
435    // rather than each rescanning the strings that are there.
436    #[test]
437    fn glyph_names_past_the_string_data_stay_linear() {
438        let num_glyphs = u16::MAX;
439        let mut buf = BeBuffer::new()
440            .push(Version16Dot16::VERSION_2_0)
441            .push(Fixed::from_i32(0))
442            .extend([FWord::new(0), FWord::new(0)])
443            .push(0u32)
444            .extend([0u32, 0, 0, 0])
445            .push(num_glyphs);
446        // The first two glyphs have names; every other glyph names a string
447        // far past the end of the data.
448        for gid in 0..num_glyphs {
449            let index = if gid < 2 { 258 + gid } else { 258 + 60_000 };
450            buf = buf.push(index);
451        }
452        for _ in 0..3854 {
453            buf = buf.push(2u8).extend(*b"ab");
454        }
455        let post = Post::read(buf.data().into()).unwrap();
456        let start = std::time::Instant::now();
457        let names: Vec<_> = post.glyph_names().collect();
458        let elapsed = start.elapsed();
459        assert_eq!(names, [(GlyphId::new(0), "ab"), (GlyphId::new(1), "ab")]);
460        // Linear work is a few milliseconds even in a debug build.
461        assert!(elapsed.as_millis() < 2000, "{elapsed:?}");
462    }
463
464    /// A post table may hold more strings than it has glyphs, which puts a
465    /// name index past the last checkpoint the iterator keeps. Clamping such
466    /// an index into the final slot makes a later scan resume from the wrong
467    /// offset.
468    #[test]
469    fn glyph_names_matches_naive_past_the_last_checkpoint() {
470        // Two glyphs give a stride of one, so only the first NUM_CHECKPOINTS
471        // string indices get a checkpoint of their own. The higher index is
472        // read first, so the clamped slot is written before it is read back.
473        let indices = [258u16 + 50, 258 + 30];
474        let mut buf = BeBuffer::new()
475            .push(Version16Dot16::VERSION_2_0)
476            .push(Fixed::from_i32(0))
477            .extend([FWord::new(0), FWord::new(0)])
478            .push(0u32)
479            .extend([0u32, 0, 0, 0])
480            .push(indices.len() as u16);
481        for index in indices {
482            buf = buf.push(index);
483        }
484        for i in 0..70u8 {
485            buf = buf.push(2u8).extend([b'a' + i / 26, b'a' + i % 26]);
486        }
487        let post = Post::read(buf.data().into()).unwrap();
488        let from_naive: Vec<_> = (0..indices.len() as u16)
489            .map(|gid| post.glyph_name(GlyphId16::new(gid)).unwrap())
490            .collect();
491        assert_eq!(from_naive, ["by", "be"]);
492        let from_iter: Vec<_> = post.glyph_names().map(|(_, name)| name).collect();
493        assert_eq!(from_iter, from_naive);
494    }
495}