Skip to main content

font_parse/tables/
maxp.rs

1//! `maxp` — maximum profile: glyph count and memory-usage hints.
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::be_u16_at;
5
6pub(crate) const TAG: RawTag = *b"maxp";
7
8/// Zero-copy view over the `maxp` table.
9///
10/// Version 0.5 (CFF fonts) carries only `numGlyphs` (6 bytes); version 1.0
11/// (TrueType) adds the memory-hint fields (32 bytes).
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct MaxpTable<'a> {
14    data: &'a [u8],
15    num_glyphs: u16,
16}
17
18impl<'a> MaxpTable<'a> {
19    /// Parse and validate the `maxp` table bytes.
20    ///
21    /// # Errors
22    /// [`ParseError::TruncatedTable`] when the table is shorter than its
23    /// version's size (6 for 0.5, 32 for 1.0).
24    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
25        if data.len() < 6 {
26            return Err(ParseError::TruncatedTable {
27                tag: TAG,
28                expected: 6,
29                got: data.len(),
30            });
31        }
32        let version = crate::reader::be_u32_at(data, 0, TAG)?;
33        let min_len = match version {
34            0x0000_5000 => 6,
35            0x0001_0000 => 32,
36            _ => {
37                return Err(ParseError::InvalidSfnt);
38            }
39        };
40        if data.len() < min_len {
41            return Err(ParseError::TruncatedTable {
42                tag: TAG,
43                expected: min_len,
44                got: data.len(),
45            });
46        }
47        Ok(Self {
48            data,
49            num_glyphs: be_u16_at(data, 4, TAG)?,
50        })
51    }
52
53    /// Raw table bytes.
54    #[must_use]
55    pub fn as_bytes(&self) -> &'a [u8] {
56        self.data
57    }
58
59    /// Raw version field (`0x00005000` = 0.5, `0x00010000` = 1.0).
60    ///
61    /// # Errors
62    /// Truncation (impossible post-[`parse`](Self::parse)).
63    pub fn version(&self) -> Result<u32, ParseError> {
64        crate::reader::be_u32_at(self.data, 0, TAG)
65    }
66
67    /// The glyph count.
68    #[must_use]
69    pub const fn num_glyphs(&self) -> u16 {
70        self.num_glyphs
71    }
72
73    /// `maxPoints` — version 1.0 only.
74    ///
75    /// # Errors
76    /// [`ParseError::TruncatedTable`] on a 0.5 table.
77    pub fn max_points(&self) -> Result<u16, ParseError> {
78        be_u16_at(self.data, 6, TAG)
79    }
80
81    /// `maxContours` — version 1.0 only.
82    ///
83    /// # Errors
84    /// [`ParseError::TruncatedTable`] on a 0.5 table.
85    pub fn max_contours(&self) -> Result<u16, ParseError> {
86        be_u16_at(self.data, 8, TAG)
87    }
88
89    /// `maxCompositePoints` — version 1.0 only.
90    ///
91    /// # Errors
92    /// [`ParseError::TruncatedTable`] on a 0.5 table.
93    pub fn max_composite_points(&self) -> Result<u16, ParseError> {
94        be_u16_at(self.data, 10, TAG)
95    }
96
97    /// `maxCompositeContours` — version 1.0 only.
98    ///
99    /// # Errors
100    /// [`ParseError::TruncatedTable`] on a 0.5 table.
101    pub fn max_composite_contours(&self) -> Result<u16, ParseError> {
102        be_u16_at(self.data, 12, TAG)
103    }
104
105    /// `maxComponentElements` — number of components in the most complex
106    /// glyph; version 1.0 only.
107    ///
108    /// # Errors
109    /// [`ParseError::TruncatedTable`] on a 0.5 table.
110    pub fn max_component_elements(&self) -> Result<u16, ParseError> {
111        be_u16_at(self.data, 28, TAG)
112    }
113
114    /// `maxComponentDepth` — nesting level of the most complex composite;
115    /// version 1.0 only.
116    ///
117    /// # Errors
118    /// [`ParseError::TruncatedTable`] on a 0.5 table.
119    pub fn max_component_depth(&self) -> Result<u16, ParseError> {
120        be_u16_at(self.data, 30, TAG)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
127    use super::MaxpTable;
128    use crate::error::ParseError;
129
130    // Test harness: assertions legitimately panic; the lib target stays
131    // lint-clean.
132
133    fn v1() -> [u8; 32] {
134        let mut d = [0u8; 32];
135        d[0..4].copy_from_slice(&0x0001_0000u32.to_be_bytes());
136        d[4..6].copy_from_slice(&42u16.to_be_bytes());
137        d[6..8].copy_from_slice(&100u16.to_be_bytes());
138        d[28..30].copy_from_slice(&4u16.to_be_bytes()); // maxComponentElements
139        d[30..32].copy_from_slice(&2u16.to_be_bytes()); // maxComponentDepth
140        d
141    }
142
143    #[test]
144    fn v1_fields() {
145        let d = v1();
146        let m = MaxpTable::parse(&d).unwrap();
147        assert_eq!(m.version().unwrap(), 0x0001_0000);
148        assert_eq!(m.num_glyphs(), 42);
149        assert_eq!(m.max_points().unwrap(), 100);
150        assert_eq!(m.max_contours().unwrap(), 0);
151        assert_eq!(m.max_composite_points().unwrap(), 0);
152        assert_eq!(m.max_composite_contours().unwrap(), 0);
153        assert_eq!(m.max_component_elements().unwrap(), 4);
154        assert_eq!(m.max_component_depth().unwrap(), 2);
155    }
156
157    #[test]
158    fn v0_5_table() {
159        let mut d = [0u8; 6];
160        d[0..4].copy_from_slice(&0x0000_5000u32.to_be_bytes());
161        d[4..6].copy_from_slice(&7u16.to_be_bytes());
162        let m = MaxpTable::parse(&d).unwrap();
163        assert_eq!(m.num_glyphs(), 7);
164        assert!(m.max_points().is_err()); // version 1.0 fields absent
165    }
166
167    #[test]
168    fn errors() {
169        // Truncated header.
170        assert_eq!(
171            MaxpTable::parse(&[0u8; 5]),
172            Err(ParseError::TruncatedTable {
173                tag: *b"maxp",
174                expected: 6,
175                got: 5
176            })
177        );
178        // Unknown version.
179        let mut d = [0u8; 32];
180        d[0..4].copy_from_slice(&0x0002_0000u32.to_be_bytes());
181        assert_eq!(MaxpTable::parse(&d), Err(ParseError::InvalidSfnt));
182        // v1.0 declared but truncated.
183        let mut d = v1();
184        d[0..4].copy_from_slice(&0x0001_0000u32.to_be_bytes());
185        assert_eq!(
186            MaxpTable::parse(&d[..20]),
187            Err(ParseError::TruncatedTable {
188                tag: *b"maxp",
189                expected: 32,
190                got: 20
191            })
192        );
193    }
194}