Skip to main content

font_parse/tables/
post.rs

1//! `post` — PostScript table: italic angle, underline metrics, glyph names.
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::Reader;
5use font_types::Fixed;
6
7pub(crate) const TAG: RawTag = *b"post";
8
9/// Header size (all versions).
10const HEADER: usize = 32;
11/// Number of standard Macintosh glyph names.
12const STD_NAMES: usize = 258;
13
14/// The 258 standard Macintosh glyph names (TrueType spec appendix), indexed
15/// by their post v2 `glyphNameIndex` values 0..257.
16#[rustfmt::skip]
17pub(crate) const MAC_GLYPH_NAMES: [&str; STD_NAMES] = [
18    ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign",
19    "dollar", "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk",
20    "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four",
21    "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater",
22    "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
23    "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash",
24    "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g",
25    "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y",
26    "z", "braceleft", "bar", "braceright", "asciitilde", "Adieresis", "Aring", "Ccedilla",
27    "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex",
28    "adieresis", "atilde", "aring", "ccedilla", "eacute", "egrave", "ecircumflex",
29    "edieresis", "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute",
30    "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex",
31    "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph",
32    "germandbls", "registered", "copyright", "trademark", "acute", "dieresis", "notequal",
33    "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", "mu",
34    "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine",
35    "Omega", "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical",
36    "florin", "approxequal", "Delta", "guillemotleft", "guillemotright", "ellipsis",
37    "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash",
38    "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge",
39    "ydieresis", "Ydieresis", "fraction", "currency", "guilsinglleft", "guilsinglright",
40    "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase",
41    "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute",
42    "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", "apple", "Ograve",
43    "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron",
44    "breve", "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash",
45    "lslash", "Scaron", "scaron", "Zcaron", "zcaron", "brokenbar", "Eth", "eth", "Yacute",
46    "yacute", "Thorn", "thorn", "minus", "multiply", "onesuperior", "twosuperior",
47    "threesuperior", "onehalf", "onequarter", "threequarters", "franc", "Gbreve",
48    "gbreve", "Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron", "ccaron",
49    "dcroat",
50];
51
52/// Zero-copy view over the `post` table.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct PostTable<'a> {
55    data: &'a [u8],
56}
57
58impl<'a> PostTable<'a> {
59    /// Parse and validate the `post` table header.
60    ///
61    /// # Errors
62    /// [`ParseError::TruncatedTable`] when shorter than 32 bytes.
63    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
64        if data.len() < HEADER {
65            return Err(ParseError::TruncatedTable {
66                tag: TAG,
67                expected: HEADER,
68                got: data.len(),
69            });
70        }
71        Ok(Self { data })
72    }
73
74    /// Raw table bytes.
75    #[must_use]
76    pub fn as_bytes(&self) -> &'a [u8] {
77        self.data
78    }
79
80    /// Raw version (`0x00010000`, `0x00020000`, `0x00030000`).
81    ///
82    /// # Errors
83    /// Truncation (impossible post-[`parse`](Self::parse)).
84    pub fn version(&self) -> Result<u32, ParseError> {
85        crate::reader::be_u32_at(self.data, 0, TAG)
86    }
87
88    /// Italic angle in degrees counter-clockwise from vertical.
89    ///
90    /// # Errors
91    /// Truncation (impossible post-[`parse`](Self::parse)).
92    pub fn italic_angle(&self) -> Result<f32, ParseError> {
93        Ok(Fixed::from_bits(crate::reader::be_i32_at(self.data, 4, TAG)?).to_f32())
94    }
95
96    /// Underline position.
97    ///
98    /// # Errors
99    /// Truncation (impossible post-[`parse`](Self::parse)).
100    pub fn underline_position(&self) -> Result<i16, ParseError> {
101        crate::reader::be_i16_at(self.data, 8, TAG)
102    }
103
104    /// Underline thickness.
105    ///
106    /// # Errors
107    /// Truncation (impossible post-[`parse`](Self::parse)).
108    pub fn underline_thickness(&self) -> Result<i16, ParseError> {
109        crate::reader::be_i16_at(self.data, 10, TAG)
110    }
111
112    /// Non-zero for monospaced fonts.
113    ///
114    /// # Errors
115    /// Truncation (impossible post-[`parse`](Self::parse)).
116    pub fn is_fixed_pitch(&self) -> Result<u32, ParseError> {
117        crate::reader::be_u32_at(self.data, 12, TAG)
118    }
119
120    /// Glyph name for `gid` (version 2 tables).
121    ///
122    /// Returns `None` for glyphs with no name (index 0/`NULL` handling per
123    /// spec: unmapped indices yield no name) or non-v2 tables.
124    ///
125    /// # Errors
126    /// [`ParseError::TruncatedTable`] when the v2 arrays are truncated;
127    /// [`ParseError::InvalidGlyphFormat`] when `glyphNameIndex` values run
128    /// past the custom-name storage.
129    pub fn glyph_name(&self, gid: u16) -> Result<Option<&'a str>, ParseError> {
130        if self.version()? != 0x0002_0000 {
131            return Ok(None);
132        }
133        if self.data.len() < 34 {
134            return Err(ParseError::TruncatedTable {
135                tag: TAG,
136                expected: 34,
137                got: self.data.len(),
138            });
139        }
140        let n = usize::from(crate::reader::be_u16_at(self.data, 32, TAG)?);
141        if usize::from(gid) >= n {
142            return Ok(None);
143        }
144        let index = crate::reader::be_u16_at(self.data, 34 + usize::from(gid) * 2, TAG)?;
145        if let Some(name) = MAC_GLYPH_NAMES.get(usize::from(index)) {
146            return Ok(Some(*name));
147        }
148        // Custom name number `index - 258`: the Nth Pascal string after the
149        // glyphNameIndex array.
150        let custom = usize::from(index) - STD_NAMES;
151        let names_start = 34 + n * 2;
152        let mut r = Reader::within(self.data, names_start, self.data.len(), TAG);
153        for _ in 0..custom {
154            let len = usize::from(r.u8()?);
155            r.skip(len)?;
156        }
157        let len = usize::from(r.u8()?);
158        let bytes = r.bytes(len)?;
159        Ok(core::str::from_utf8(bytes).ok())
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
166
167    use super::PostTable;
168    use crate::error::ParseError;
169    use alloc::vec::Vec;
170
171    // Test harness: assertions legitimately panic; the lib target stays
172    // lint-clean.
173
174    fn v2() -> Vec<u8> {
175        // Header + numberOfGlyphs + 3 glyphNameIndex entries + 2 custom
176        // Pascal strings ("customglyph", "uni0041alt").
177        let mut d = Vec::new();
178        d.extend_from_slice(&0x0002_0000u32.to_be_bytes());
179        d.extend_from_slice(&(-1200i32).to_be_bytes()); // italic angle
180        d.extend_from_slice(&(-50i16).to_be_bytes()); // underline position
181        d.extend_from_slice(&10i16.to_be_bytes());
182        d.extend_from_slice(&1u32.to_be_bytes()); // fixed pitch
183        d.extend_from_slice(&0u32.to_be_bytes()); // 4 memory fields
184        d.extend_from_slice(&0u32.to_be_bytes());
185        d.extend_from_slice(&0u32.to_be_bytes());
186        d.extend_from_slice(&0u32.to_be_bytes());
187        d.extend_from_slice(&3u16.to_be_bytes()); // numberOfGlyphs
188                                                  // Indexes: 0 -> ".notdef", 3 -> "space", 258 -> custom[0].
189        d.extend_from_slice(&0u16.to_be_bytes());
190        d.extend_from_slice(&3u16.to_be_bytes());
191        d.extend_from_slice(&258u16.to_be_bytes());
192        d.extend_from_slice(&[11u8]);
193        d.extend_from_slice(b"customglyph");
194        d.extend_from_slice(&[10u8]);
195        d.extend_from_slice(b"uni0041alt");
196        d
197    }
198
199    #[test]
200    fn header_fields() {
201        let d = v2();
202        let p = PostTable::parse(&d).unwrap();
203        assert_eq!(p.version().unwrap(), 0x0002_0000);
204        assert!((p.italic_angle().unwrap() - -0.018_310_547).abs() < 1e-6);
205        assert_eq!(p.underline_position().unwrap(), -50);
206        assert_eq!(p.underline_thickness().unwrap(), 10);
207        assert_eq!(p.is_fixed_pitch().unwrap(), 1);
208    }
209
210    #[test]
211    fn glyph_names_std_and_custom() {
212        let d = v2();
213        let p = PostTable::parse(&d).unwrap();
214        assert_eq!(p.glyph_name(0).unwrap(), Some(".notdef"));
215        assert_eq!(p.glyph_name(1).unwrap(), Some("space"));
216        assert_eq!(p.glyph_name(2).unwrap(), Some("customglyph"));
217        assert_eq!(p.glyph_name(3).unwrap(), None); // beyond numberOfGlyphs
218    }
219
220    #[test]
221    fn v3_has_no_names() {
222        let mut d = [0u8; 32];
223        d[0..4].copy_from_slice(&0x0003_0000u32.to_be_bytes());
224        let p = PostTable::parse(&d).unwrap();
225        assert_eq!(p.glyph_name(0).unwrap(), None);
226        assert_eq!(p.italic_angle().unwrap(), 0.0);
227    }
228
229    #[test]
230    fn truncated_and_bad_custom_index() {
231        assert_eq!(
232            PostTable::parse(&[0u8; 31]),
233            Err(ParseError::TruncatedTable {
234                tag: *b"post",
235                expected: 32,
236                got: 31
237            })
238        );
239        // A 32-byte v2 table parses but has no room for the glyph arrays.
240        let d = v2();
241        let p = PostTable::parse(&d[..32]).unwrap();
242        assert!(p.glyph_name(0).is_err());
243        // Custom index beyond the string storage -> error, not panic.
244        let mut d = v2();
245        let at = 34 + 2 * 2;
246        d[at..at + 2].copy_from_slice(&9999u16.to_be_bytes());
247        let p = PostTable::parse(&d).unwrap();
248        assert!(p.glyph_name(2).is_err());
249    }
250}