Skip to main content

font_parse/tables/
head.rs

1//! `head` — font header: units per em, loca format, style flags.
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::{be_i16_at, be_u16_at};
5use font_types::{Fixed, Version16Dot16};
6
7pub(crate) const TAG: RawTag = *b"head";
8
9/// Minimum `head` table size (through `glyphDataFormat`).
10const MIN_LEN: usize = 54;
11
12/// Zero-copy view over the `head` table.
13///
14/// Field offsets (OpenType 1.9): version 0, fontRevision 4, checkSumAdjustment
15/// 8, magicNumber 12, flags 16, unitsPerEm 18, created 20, modified 28,
16/// xMin 36, yMin 38, xMax 40, yMax 42, macStyle 44, lowestRecPPEM 46,
17/// fontDirectionHint 48, indexToLocFormat 50, glyphDataFormat 52.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct HeadTable<'a> {
20    data: &'a [u8],
21}
22
23impl<'a> HeadTable<'a> {
24    /// Parse and validate the `head` table bytes.
25    ///
26    /// # Errors
27    /// [`ParseError::TruncatedTable`] when the table is shorter than 54
28    /// bytes; [`ParseError::InvalidUnitsPerEm`] when `unitsPerEm` is zero or
29    /// above 16384; [`ParseError::InvalidGlyphFormat`] when
30    /// `indexToLocFormat` is neither 0 (short) nor 1 (long).
31    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
32        if data.len() < MIN_LEN {
33            return Err(ParseError::TruncatedTable {
34                tag: TAG,
35                expected: MIN_LEN,
36                got: data.len(),
37            });
38        }
39        let upem = be_u16_at(data, 18, TAG)?;
40        if upem == 0 || upem > 16_384 {
41            return Err(ParseError::InvalidUnitsPerEm(upem));
42        }
43        match be_i16_at(data, 50, TAG)? {
44            0 | 1 => {}
45            _ => return Err(ParseError::InvalidGlyphFormat),
46        }
47        Ok(Self { data })
48    }
49
50    /// Raw table bytes.
51    #[must_use]
52    pub fn as_bytes(&self) -> &'a [u8] {
53        self.data
54    }
55
56    /// Table version (typically 1.0).
57    ///
58    /// # Errors
59    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
60    pub fn version(&self) -> Result<Version16Dot16, ParseError> {
61        Ok(Version16Dot16::new(
62            be_u16_at(self.data, 0, TAG)?,
63            be_u16_at(self.data, 2, TAG)?,
64        ))
65    }
66
67    /// Font revision set by the font manufacturer.
68    ///
69    /// # Errors
70    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
71    pub fn font_revision(&self) -> Result<Fixed, ParseError> {
72        Ok(Fixed::from_bits(self.i32_at(4)?))
73    }
74
75    /// Checksum adjustment; computed over the whole font with this field
76    /// zeroed (`0xB1B0AFBA - sum`).
77    ///
78    /// # Errors
79    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
80    pub fn check_sum_adjustment(&self) -> Result<u32, ParseError> {
81        crate::reader::be_u32_at(self.data, 8, TAG)
82    }
83
84    /// Magic number (`0x5F0F3CF5`).
85    ///
86    /// # Errors
87    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
88    pub fn magic_number(&self) -> Result<u32, ParseError> {
89        crate::reader::be_u32_at(self.data, 12, TAG)
90    }
91
92    /// `head.flags` — font-wide behavior bits (bit 11 signals a
93    /// losslessly-transformed font, e.g. after WOFF2 decoding).
94    ///
95    /// # Errors
96    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
97    pub fn flags(&self) -> Result<u16, ParseError> {
98        be_u16_at(self.data, 16, TAG)
99    }
100
101    /// Units per em: 16..=16384, validated nonzero.
102    ///
103    /// # Errors
104    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
105    pub fn units_per_em(&self) -> Result<u16, ParseError> {
106        be_u16_at(self.data, 18, TAG)
107    }
108
109    /// International date (seconds since 1904-01-01) the font was created.
110    ///
111    /// # Errors
112    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
113    pub fn created(&self) -> Result<i64, ParseError> {
114        self.i64_at(20)
115    }
116
117    /// International date (seconds since 1904-01-01) the font was modified.
118    ///
119    /// # Errors
120    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
121    pub fn modified(&self) -> Result<i64, ParseError> {
122        self.i64_at(28)
123    }
124
125    /// Glyph bounding box: `xMin`.
126    ///
127    /// # Errors
128    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
129    pub fn x_min(&self) -> Result<i16, ParseError> {
130        self.i16_at(36)
131    }
132
133    /// Glyph bounding box: `yMin`.
134    ///
135    /// # Errors
136    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
137    pub fn y_min(&self) -> Result<i16, ParseError> {
138        self.i16_at(38)
139    }
140
141    /// Glyph bounding box: `xMax`.
142    ///
143    /// # Errors
144    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
145    pub fn x_max(&self) -> Result<i16, ParseError> {
146        self.i16_at(40)
147    }
148
149    /// Glyph bounding box: `yMax`.
150    ///
151    /// # Errors
152    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
153    pub fn y_max(&self) -> Result<i16, ParseError> {
154        self.i16_at(42)
155    }
156
157    /// `macStyle` — bold (bit 0), italic (bit 1) style flags.
158    ///
159    /// # Errors
160    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
161    pub fn mac_style(&self) -> Result<u16, ParseError> {
162        self.u16_at(44)
163    }
164
165    /// Smallest readable size in pixels.
166    ///
167    /// # Errors
168    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
169    pub fn lowest_rec_ppem(&self) -> Result<u16, ParseError> {
170        self.u16_at(46)
171    }
172
173    /// Deprecated font direction hint.
174    ///
175    /// # Errors
176    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
177    pub fn font_direction_hint(&self) -> Result<i16, ParseError> {
178        self.i16_at(48)
179    }
180
181    /// 0 = short (`u16`, offsets/2), 1 = long (`u32`) `loca` entries.
182    /// Validated to be one of the two in [`parse`](Self::parse).
183    ///
184    /// # Errors
185    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
186    pub fn index_to_loc_format(&self) -> Result<i16, ParseError> {
187        self.i16_at(50)
188    }
189
190    /// Always 0; reserved for future glyph data formats.
191    ///
192    /// # Errors
193    /// Truncation (structurally impossible post-[`parse`](Self::parse)).
194    pub fn glyph_data_format(&self) -> Result<i16, ParseError> {
195        self.i16_at(52)
196    }
197
198    fn u16_at(&self, at: usize) -> Result<u16, ParseError> {
199        be_u16_at(self.data, at, TAG)
200    }
201
202    fn i16_at(&self, at: usize) -> Result<i16, ParseError> {
203        be_i16_at(self.data, at, TAG)
204    }
205
206    fn i32_at(&self, at: usize) -> Result<i32, ParseError> {
207        let raw = self
208            .data
209            .get(at..at + 4)
210            .ok_or(ParseError::TruncatedTable {
211                tag: TAG,
212                expected: at + 4,
213                got: self.data.len(),
214            })?;
215        font_types::BigEndian::<i32>::from_slice(raw)
216            .map(|b| b.get())
217            .ok_or(ParseError::TruncatedTable {
218                tag: TAG,
219                expected: at + 4,
220                got: self.data.len(),
221            })
222    }
223
224    fn i64_at(&self, at: usize) -> Result<i64, ParseError> {
225        let raw = self
226            .data
227            .get(at..at + 8)
228            .ok_or(ParseError::TruncatedTable {
229                tag: TAG,
230                expected: at + 8,
231                got: self.data.len(),
232            })?;
233        font_types::BigEndian::<i64>::from_slice(raw)
234            .map(|b| b.get())
235            .ok_or(ParseError::TruncatedTable {
236                tag: TAG,
237                expected: at + 8,
238                got: self.data.len(),
239            })
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
246    use super::HeadTable;
247    use crate::error::ParseError;
248
249    // Test harness: assertions legitimately panic; the lib target stays
250    // lint-clean.
251
252    fn sample() -> [u8; 54] {
253        let mut d = [0u8; 54];
254        d[0..4].copy_from_slice(&0x0001_0000u32.to_be_bytes());
255        d[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes()); // revision 1.0
256        d[12..16].copy_from_slice(&0x5F0F_3CF5u32.to_be_bytes());
257        d[16..18].copy_from_slice(&0x080Bu16.to_be_bytes()); // flags
258        d[18..20].copy_from_slice(&1000u16.to_be_bytes());
259        d[20..28].copy_from_slice(&3725107200i64.to_be_bytes()); // 2012-01-01ish
260        d[36..38].copy_from_slice(&(-10i16).to_be_bytes());
261        d[38..40].copy_from_slice(&(-20i16).to_be_bytes());
262        d[40..42].copy_from_slice(&800i16.to_be_bytes());
263        d[42..44].copy_from_slice(&900i16.to_be_bytes());
264        d[44..46].copy_from_slice(&1u16.to_be_bytes()); // italic
265        d[46..48].copy_from_slice(&8u16.to_be_bytes());
266        d[48..50].copy_from_slice(&2i16.to_be_bytes());
267        d[50..52].copy_from_slice(&1i16.to_be_bytes()); // long loca
268        d[52..54].copy_from_slice(&0i16.to_be_bytes());
269        d
270    }
271
272    #[test]
273    fn parses_fields() {
274        let d = sample();
275        let h = HeadTable::parse(&d).unwrap();
276        assert_eq!(h.units_per_em().unwrap(), 1000);
277        assert_eq!(h.magic_number().unwrap(), 0x5F0F_3CF5);
278        assert_eq!(h.index_to_loc_format().unwrap(), 1);
279        assert_eq!(h.mac_style().unwrap(), 1);
280        assert_eq!(h.x_min().unwrap(), -10);
281        assert_eq!(h.y_max().unwrap(), 900);
282        assert_eq!(h.version().unwrap(), font_types::Version16Dot16::new(1, 0));
283        assert!((h.font_revision().unwrap().to_f32() - 1.0).abs() < 1e-6);
284        assert_eq!(h.lowest_rec_ppem().unwrap(), 8);
285        assert_eq!(h.created().unwrap(), 3_725_107_200);
286    }
287
288    #[test]
289    fn validation_errors() {
290        // Too short.
291        let d = [0u8; 53];
292        assert_eq!(
293            HeadTable::parse(&d),
294            Err(ParseError::TruncatedTable {
295                tag: *b"head",
296                expected: 54,
297                got: 53
298            })
299        );
300        // Zero unitsPerEm.
301        let mut d = sample();
302        d[18..20].copy_from_slice(&0u16.to_be_bytes());
303        assert_eq!(HeadTable::parse(&d), Err(ParseError::InvalidUnitsPerEm(0)));
304        // Over 16384.
305        let mut d = sample();
306        d[18..20].copy_from_slice(&20000u16.to_be_bytes());
307        assert_eq!(
308            HeadTable::parse(&d),
309            Err(ParseError::InvalidUnitsPerEm(20000))
310        );
311        // Bad loca format.
312        let mut d = sample();
313        d[50..52].copy_from_slice(&7i16.to_be_bytes());
314        assert_eq!(HeadTable::parse(&d), Err(ParseError::InvalidGlyphFormat));
315    }
316
317    #[test]
318    fn as_bytes_round_trip() {
319        let d = sample();
320        let h = HeadTable::parse(&d).unwrap();
321        assert_eq!(h.as_bytes().len(), 54);
322    }
323}