Skip to main content

font_parse/tables/
stat.rs

1//! `stat` — style attributes: design axes and axis-value tables.
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::{be_i32_at, be_u16_at, be_u32_at};
5use alloc::vec::Vec;
6use font_types::{Fixed, Tag};
7
8pub(crate) const TAG: RawTag = *b"stat";
9
10/// One design axis record.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct StatAxis {
13    /// Axis tag.
14    pub tag: Tag,
15    /// `name` table id of the axis name.
16    pub name_id: u16,
17    /// Sorting order.
18    pub ordering: u16,
19}
20
21/// A decoded axis-value table (formats 1-4).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum AxisValue {
24    /// Format 1 — one value along one axis.
25    Value1 {
26        /// Axis this value belongs to.
27        axis_index: u16,
28        /// Flags (bit 0 = elidable).
29        flags: u16,
30        /// `name` id of the value name.
31        value_name_id: u16,
32        /// The value.
33        value: Fixed,
34    },
35    /// Format 2 — a value with an inclusive range.
36    Range {
37        /// Axis this value belongs to.
38        axis_index: u16,
39        /// Flags.
40        flags: u16,
41        /// `name` id of the value name.
42        value_name_id: u16,
43        /// Range minimum.
44        nominal_min: Fixed,
45        /// The nominal value.
46        nominal: Fixed,
47        /// Range maximum.
48        nominal_max: Fixed,
49    },
50    /// Format 3 — a value with a linked "style-on" partner.
51    Linked {
52        /// Axis this value belongs to.
53        axis_index: u16,
54        /// Flags.
55        flags: u16,
56        /// `name` id of the value name.
57        value_name_id: u16,
58        /// The value.
59        value: Fixed,
60        /// The linked (auto-generated style) value.
61        linked_value: Fixed,
62    },
63    /// Format 4 — a named style across multiple axes.
64    Style {
65        /// Flags.
66        flags: u16,
67        /// `name` id of the style name.
68        value_name_id: u16,
69        /// (axis index, value) pairs.
70        values: Vec<(u16, Fixed)>,
71    },
72}
73
74impl AxisValue {
75    /// The value's name id.
76    #[must_use]
77    pub const fn value_name_id(&self) -> u16 {
78        match self {
79            AxisValue::Value1 { value_name_id, .. }
80            | AxisValue::Range { value_name_id, .. }
81            | AxisValue::Linked { value_name_id, .. }
82            | AxisValue::Style { value_name_id, .. } => *value_name_id,
83        }
84    }
85}
86
87/// Zero-copy view over the `stat` table.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct StatTable<'a> {
90    data: &'a [u8],
91}
92
93impl<'a> StatTable<'a> {
94    /// Parse and validate the `stat` header.
95    ///
96    /// # Errors
97    /// [`ParseError::TruncatedTable`] for short headers;
98    /// [`ParseError::InvalidGlyphFormat`] for inconsistent sizes.
99    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
100        if data.len() < 20 {
101            return Err(ParseError::TruncatedTable {
102                tag: TAG,
103                expected: 20,
104                got: data.len(),
105            });
106        }
107        match be_u16_at(data, 0, TAG)? {
108            1 => {}
109            _ => return Err(ParseError::InvalidGlyphFormat),
110        }
111        let design_axis_size = be_u16_at(data, 4, TAG)?;
112        if design_axis_size < 8 {
113            return Err(ParseError::InvalidGlyphFormat);
114        }
115        Ok(Self { data })
116    }
117
118    /// Raw table bytes.
119    #[must_use]
120    pub fn as_bytes(&self) -> &'a [u8] {
121        self.data
122    }
123
124    /// Version (1.0 or 1.1 — the minor field distinguishes them).
125    ///
126    /// # Errors
127    /// Truncation (impossible post-[`parse`](Self::parse)).
128    pub fn version(&self) -> Result<(u16, u16), ParseError> {
129        Ok((be_u16_at(self.data, 0, TAG)?, be_u16_at(self.data, 2, TAG)?))
130    }
131
132    /// Design axis records.
133    ///
134    /// # Errors
135    /// [`ParseError::TruncatedTable`] when the array is short.
136    pub fn design_axes(&self) -> Result<Vec<StatAxis>, ParseError> {
137        let count = be_u16_at(self.data, 6, TAG)?;
138        let offset = be_u32_at(self.data, 8, TAG)?;
139        let size = usize::from(be_u16_at(self.data, 4, TAG)?);
140        let base = usize::try_from(offset).map_err(|_| ParseError::InvalidGlyphFormat)?;
141        let mut out = Vec::with_capacity(usize::from(count));
142        for i in 0..usize::from(count) {
143            let at = base + i * size;
144            let raw = be_u32_at(self.data, at, TAG)?;
145            out.push(StatAxis {
146                tag: Tag::new(&raw.to_be_bytes()),
147                name_id: be_u16_at(self.data, at + 4, TAG)?,
148                ordering: be_u16_at(self.data, at + 6, TAG)?,
149            });
150        }
151        Ok(out)
152    }
153
154    /// Axis-value tables.
155    ///
156    /// # Errors
157    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
158    /// for malformed value tables.
159    pub fn axis_values(&self) -> Result<Vec<AxisValue>, ParseError> {
160        let count = be_u16_at(self.data, 12, TAG)?;
161        let offset = be_u32_at(self.data, 14, TAG)?;
162        let base = usize::try_from(offset).map_err(|_| ParseError::InvalidGlyphFormat)?;
163        let mut out = Vec::with_capacity(usize::from(count));
164        for i in 0..usize::from(count) {
165            let at = base + i * 2;
166            let off = usize::from(be_u16_at(self.data, at, TAG)?);
167            out.push(self.axis_value_at(base + off)?);
168        }
169        Ok(out)
170    }
171
172    fn axis_value_at(&self, at: usize) -> Result<AxisValue, ParseError> {
173        // STAT values are 16.16 Fixed.
174        let fixed_at = |off: usize| -> Result<Fixed, ParseError> {
175            Ok(Fixed::from_bits(be_i32_at(self.data, off, TAG)?))
176        };
177        let format = be_u16_at(self.data, at, TAG)?;
178        match format {
179            1 => {
180                let axis_index = be_u16_at(self.data, at + 2, TAG)?;
181                let flags = be_u16_at(self.data, at + 4, TAG)?;
182                let name = be_u16_at(self.data, at + 6, TAG)?;
183                Ok(AxisValue::Value1 {
184                    axis_index,
185                    flags,
186                    value_name_id: name,
187                    value: fixed_at(at + 8)?,
188                })
189            }
190            2 => {
191                let axis_index = be_u16_at(self.data, at + 2, TAG)?;
192                let flags = be_u16_at(self.data, at + 4, TAG)?;
193                let name = be_u16_at(self.data, at + 6, TAG)?;
194                Ok(AxisValue::Range {
195                    axis_index,
196                    flags,
197                    value_name_id: name,
198                    // Spec order: nominalValue, rangeMin, rangeMax.
199                    nominal: fixed_at(at + 8)?,
200                    nominal_min: fixed_at(at + 12)?,
201                    nominal_max: fixed_at(at + 16)?,
202                })
203            }
204            3 => {
205                let axis_index = be_u16_at(self.data, at + 2, TAG)?;
206                let flags = be_u16_at(self.data, at + 4, TAG)?;
207                let name = be_u16_at(self.data, at + 6, TAG)?;
208                Ok(AxisValue::Linked {
209                    axis_index,
210                    flags,
211                    value_name_id: name,
212                    value: fixed_at(at + 8)?,
213                    linked_value: fixed_at(at + 12)?,
214                })
215            }
216            4 => {
217                let axis_count = be_u16_at(self.data, at + 2, TAG)?;
218                let flags = be_u16_at(self.data, at + 4, TAG)?;
219                let name = be_u16_at(self.data, at + 6, TAG)?;
220                let mut values = Vec::with_capacity(usize::from(axis_count));
221                for a in 0..usize::from(axis_count) {
222                    let rec_at = at + 8 + a * 6;
223                    values.push((be_u16_at(self.data, rec_at, TAG)?, fixed_at(rec_at + 2)?));
224                }
225                Ok(AxisValue::Style {
226                    flags,
227                    value_name_id: name,
228                    values,
229                })
230            }
231            _ => Err(ParseError::InvalidGlyphFormat),
232        }
233    }
234
235    /// The elided fallback name id.
236    ///
237    /// # Errors
238    /// Truncation (impossible post-[`parse`](Self::parse)).
239    pub fn elided_fallback_name_id(&self) -> Result<u16, ParseError> {
240        be_u16_at(self.data, 18, TAG)
241    }
242}
243
244#[cfg(test)]
245mod tests {
246    #![allow(
247        clippy::unwrap_used,
248        clippy::expect_used,
249        clippy::indexing_slicing,
250        clippy::panic
251    )]
252
253    use super::{AxisValue, StatTable};
254    use crate::error::ParseError;
255    use alloc::vec::Vec;
256    use font_types::Fixed;
257
258    fn sample() -> Vec<u8> {
259        let mut d = Vec::new();
260        // Header: version 1.0, designAxisSize 8, 2 axes, 4 axis values,
261        // elidedFallbackNameID 2.
262        let design_axis_offset = 20u32;
263        let axis_values_offset = 60u32;
264        d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // version 1.0
265        d.extend_from_slice(&8u16.to_be_bytes()); // designAxisSize
266        d.extend_from_slice(&2u16.to_be_bytes()); // designAxisCount
267        d.extend_from_slice(&design_axis_offset.to_be_bytes());
268        d.extend_from_slice(&4u16.to_be_bytes()); // axisValueCount
269        d.extend_from_slice(&axis_values_offset.to_be_bytes());
270        d.extend_from_slice(&2u16.to_be_bytes()); // elidedFallbackNameID
271                                                  // Design axes @20 (header is exactly 20 bytes): (tag, nameID, ordering).
272        d.extend_from_slice(b"wght");
273        d.extend_from_slice(&256u16.to_be_bytes());
274        d.extend_from_slice(&0u16.to_be_bytes());
275        d.extend_from_slice(b"wdth");
276        d.extend_from_slice(&257u16.to_be_bytes());
277        d.extend_from_slice(&1u16.to_be_bytes());
278        // Axis-value offsets @60 (before @60? values at 60): 4 u16 offsets.
279        // We're at 36; pad to 60.
280        d.extend_from_slice(&[0u8; 24]);
281        // Value offsets (4 entries) relative to the axis-values base (60),
282        // then the four value tables at exactly those offsets.
283        d.extend_from_slice(&8u16.to_be_bytes()); // -> 68
284        d.extend_from_slice(&28u16.to_be_bytes()); // -> 88
285        d.extend_from_slice(&52u16.to_be_bytes()); // -> 112
286        d.extend_from_slice(&72u16.to_be_bytes()); // -> 132
287                                                   // fmt1 (12 bytes) @68: format, axisIndex, flags, name, value(Fixed)
288        d.extend_from_slice(&1u16.to_be_bytes());
289        d.extend_from_slice(&0u16.to_be_bytes());
290        d.extend_from_slice(&2u16.to_be_bytes());
291        d.extend_from_slice(&262u16.to_be_bytes());
292        d.extend_from_slice(&700i32.to_be_bytes()); // Fixed 700.0
293                                                    // pad 80..88
294        d.extend_from_slice(&[0u8; 8]);
295        // fmt2 (20 bytes) @88: format, axisIndex, flags, name, nominal, min, max
296        d.extend_from_slice(&2u16.to_be_bytes());
297        d.extend_from_slice(&0u16.to_be_bytes());
298        d.extend_from_slice(&2u16.to_be_bytes());
299        d.extend_from_slice(&263u16.to_be_bytes());
300        d.extend_from_slice(&400i32.to_be_bytes());
301        d.extend_from_slice(&350i32.to_be_bytes());
302        d.extend_from_slice(&450i32.to_be_bytes());
303        // pad 108..112
304        d.extend_from_slice(&[0u8; 4]);
305        // fmt3 (16 bytes) @112: format, axisIndex, flags, name, value, linked
306        d.extend_from_slice(&3u16.to_be_bytes());
307        d.extend_from_slice(&0u16.to_be_bytes());
308        d.extend_from_slice(&2u16.to_be_bytes());
309        d.extend_from_slice(&264u16.to_be_bytes());
310        d.extend_from_slice(&300i32.to_be_bytes());
311        d.extend_from_slice(&400i32.to_be_bytes());
312        // pad 128..132
313        d.extend_from_slice(&[0u8; 4]);
314        // fmt4 (8 + 6*2 = 20 bytes) @132: format, axisCount, flags, name,
315        // then (axisIndex, value) records.
316        d.extend_from_slice(&4u16.to_be_bytes());
317        d.extend_from_slice(&2u16.to_be_bytes());
318        d.extend_from_slice(&2u16.to_be_bytes());
319        d.extend_from_slice(&265u16.to_be_bytes());
320        d.extend_from_slice(&0u16.to_be_bytes());
321        d.extend_from_slice(&500i32.to_be_bytes());
322        d.extend_from_slice(&1u16.to_be_bytes());
323        d.extend_from_slice(&75i32.to_be_bytes());
324        d
325    }
326
327    #[test]
328    fn header_and_axes() {
329        let d = sample();
330        let t = StatTable::parse(&d).unwrap();
331        assert_eq!(t.version().unwrap(), (1, 0));
332        assert_eq!(t.elided_fallback_name_id().unwrap(), 2);
333        let axes = t.design_axes().unwrap();
334        assert_eq!(axes.len(), 2);
335        assert_eq!(axes[0].tag.to_be_bytes(), *b"wght");
336        assert_eq!(axes[0].name_id, 256);
337        assert_eq!(axes[0].ordering, 0);
338        assert_eq!(axes[1].tag.to_be_bytes(), *b"wdth");
339        assert_eq!(axes[1].ordering, 1);
340    }
341
342    #[test]
343    fn axis_value_formats() {
344        let d = sample();
345        let t = StatTable::parse(&d).unwrap();
346        let values = t.axis_values().unwrap();
347        assert_eq!(values.len(), 4);
348        assert_eq!(
349            values[0],
350            AxisValue::Value1 {
351                axis_index: 0,
352                flags: 2,
353                value_name_id: 262,
354                value: Fixed::from_bits(700)
355            }
356        );
357        match &values[1] {
358            AxisValue::Range {
359                axis_index,
360                nominal_min,
361                nominal,
362                nominal_max,
363                ..
364            } => {
365                assert_eq!(*axis_index, 0);
366                assert_eq!(*nominal, Fixed::from_bits(400));
367                assert_eq!(*nominal_min, Fixed::from_bits(350));
368                assert_eq!(*nominal_max, Fixed::from_bits(450));
369            }
370            other => panic!("expected range, got {other:?}"),
371        }
372        match &values[2] {
373            AxisValue::Linked {
374                value,
375                linked_value,
376                ..
377            } => {
378                assert_eq!(*value, Fixed::from_bits(300));
379                assert_eq!(*linked_value, Fixed::from_bits(400));
380            }
381            other => panic!("expected linked, got {other:?}"),
382        }
383        match &values[3] {
384            AxisValue::Style {
385                value_name_id,
386                values: vals,
387                ..
388            } => {
389                assert_eq!(*value_name_id, 265);
390                assert_eq!(vals.len(), 2);
391                assert_eq!(vals[0].0, 0);
392                assert_eq!(vals[0].1, Fixed::from_bits(500));
393            }
394            other => panic!("expected style, got {other:?}"),
395        }
396        // Every value exposes its name id.
397        assert_eq!(values[0].value_name_id(), 262);
398    }
399
400    #[test]
401    fn errors() {
402        assert!(matches!(
403            StatTable::parse(&[0u8; 19]),
404            Err(ParseError::TruncatedTable { .. })
405        ));
406        let mut d = sample();
407        d[0..2].copy_from_slice(&2u16.to_be_bytes()); // bad version
408        assert_eq!(
409            StatTable::parse(&d).unwrap_err(),
410            ParseError::InvalidGlyphFormat
411        );
412        // designAxisSize below 8.
413        let mut d = sample();
414        d[4..6].copy_from_slice(&4u16.to_be_bytes());
415        assert_eq!(
416            StatTable::parse(&d).unwrap_err(),
417            ParseError::InvalidGlyphFormat
418        );
419        // Unknown axis-value format.
420        let mut d = sample();
421        let fmt4_at = 60 + 72;
422        d[fmt4_at..fmt4_at + 2].copy_from_slice(&9u16.to_be_bytes());
423        let t = StatTable::parse(&d).unwrap();
424        assert_eq!(t.axis_values().unwrap_err(), ParseError::InvalidGlyphFormat);
425    }
426}