Skip to main content

font_parse/tables/
fvar.rs

1//! `fvar`/`avar` — variable-font axis data and normalization maps.
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::{F2Dot14, Fixed, Tag};
7
8pub(crate) const FVAR: RawTag = *b"fvar";
9pub(crate) const AVAR: RawTag = *b"avar";
10
11/// One design axis of a variable font.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct VariationAxis {
14    /// Axis tag (`wght`, `wdth`, `opsz`, custom).
15    pub tag: Tag,
16    /// Minimum coordinate (16.16).
17    pub min: Fixed,
18    /// Default coordinate (16.16).
19    pub default: Fixed,
20    /// Maximum coordinate (16.16).
21    pub max: Fixed,
22    /// Raw axis flags (bit 0 = hidden axis).
23    pub flags: u16,
24    /// `name` table id of the axis name.
25    pub name_id: u16,
26}
27
28/// One named instance of a variable font.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct VarInstance {
31    /// `name` table id of the instance (style) name.
32    pub name_id: u16,
33    /// Raw instance flags.
34    pub flags: u16,
35    /// Coordinates per axis, in axis order (16.16).
36    pub coordinates: Vec<Fixed>,
37}
38
39/// Zero-copy view over the `fvar` table.
40#[derive(Debug, Clone, Copy)]
41pub struct FvarTable<'a> {
42    data: &'a [u8],
43    axis_count: u16,
44    axis_size: u16,
45    instance_count: u16,
46    instance_size: u16,
47    data_offset: u16,
48}
49
50impl<'a> FvarTable<'a> {
51    /// Parse and validate the `fvar` table.
52    ///
53    /// # Errors
54    /// [`ParseError::TruncatedTable`] when the header is short;
55    /// [`ParseError::InvalidGlyphFormat`] for inconsistent counts/sizes.
56    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
57        if data.len() < 16 {
58            return Err(ParseError::TruncatedTable {
59                tag: FVAR,
60                expected: 16,
61                got: data.len(),
62            });
63        }
64        let axis_count = be_u16_at(data, 8, FVAR)?;
65        let axis_size = be_u16_at(data, 10, FVAR)?;
66        let instance_count = be_u16_at(data, 12, FVAR)?;
67        let instance_size = be_u16_at(data, 14, FVAR)?;
68        let data_offset = be_u16_at(data, 4, FVAR)?;
69        if axis_count == 0 || axis_size < 20 {
70            return Err(ParseError::InvalidGlyphFormat);
71        }
72        if instance_count > 0 {
73            let needed = usize::from(axis_count)
74                .checked_mul(4)
75                .and_then(|v| v.checked_add(4))
76                .ok_or(ParseError::InvalidGlyphFormat)?;
77            if usize::from(instance_size) < needed {
78                return Err(ParseError::InvalidGlyphFormat);
79            }
80        }
81        Ok(Self {
82            data,
83            axis_count,
84            axis_size,
85            instance_count,
86            instance_size,
87            data_offset,
88        })
89    }
90
91    /// Raw table bytes.
92    #[must_use]
93    pub fn as_bytes(&self) -> &'a [u8] {
94        self.data
95    }
96
97    /// Table version.
98    ///
99    /// # Errors
100    /// Truncation (impossible post-[`parse`](Self::parse)).
101    pub fn version(&self) -> Result<u32, ParseError> {
102        be_u32_at(self.data, 0, FVAR)
103    }
104
105    /// Number of design axes.
106    #[must_use]
107    pub const fn axis_count(&self) -> u16 {
108        self.axis_count
109    }
110
111    /// All design axes.
112    ///
113    /// # Errors
114    /// [`ParseError::TruncatedTable`] when the axis array is short.
115    pub fn axes(&self) -> Result<Vec<VariationAxis>, ParseError> {
116        let mut out = Vec::with_capacity(usize::from(self.axis_count));
117        for i in 0..usize::from(self.axis_count) {
118            let at = usize::from(self.data_offset) + i * usize::from(self.axis_size);
119            let tag = be_u32_at(self.data, at, FVAR)?;
120            let min = Fixed::from_bits(be_i32_at(self.data, at + 4, FVAR)?);
121            let default = Fixed::from_bits(be_i32_at(self.data, at + 8, FVAR)?);
122            let max = Fixed::from_bits(be_i32_at(self.data, at + 12, FVAR)?);
123            let flags = be_u16_at(self.data, at + 16, FVAR)?;
124            let name_id = be_u16_at(self.data, at + 18, FVAR)?;
125            out.push(VariationAxis {
126                tag: Tag::new(&tag.to_be_bytes()),
127                min,
128                default,
129                max,
130                flags,
131                name_id,
132            });
133        }
134        Ok(out)
135    }
136
137    /// All named instances.
138    ///
139    /// # Errors
140    /// [`ParseError::TruncatedTable`] when the instance array is short.
141    pub fn instances(&self) -> Result<Vec<VarInstance>, ParseError> {
142        let mut out = Vec::with_capacity(usize::from(self.instance_count));
143        let base = usize::from(self.data_offset)
144            + usize::from(self.axis_count) * usize::from(self.axis_size);
145        for i in 0..usize::from(self.instance_count) {
146            let at = base + i * usize::from(self.instance_size);
147            let name_id = be_u16_at(self.data, at, FVAR)?;
148            let flags = be_u16_at(self.data, at + 2, FVAR)?;
149            let mut coordinates = Vec::with_capacity(usize::from(self.axis_count));
150            for a in 0..usize::from(self.axis_count) {
151                let raw = be_i32_at(self.data, at + 4 + a * 4, FVAR)?;
152                coordinates.push(Fixed::from_bits(raw));
153            }
154            out.push(VarInstance {
155                name_id,
156                flags,
157                coordinates,
158            });
159        }
160        Ok(out)
161    }
162}
163
164/// One axis segment map: sorted (from, to) normalization pairs.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct SegmentMap {
167    /// Breakpoint pairs, ascending by `from`.
168    pub pairs: Vec<(F2Dot14, F2Dot14)>,
169}
170
171impl SegmentMap {
172    /// Apply the map: piecewise-linear interpolation between breakpoints.
173    /// Identity outside the declared range (spec requires a mapping for the
174    /// full -1..1 domain; unsorted/short maps degrade to identity).
175    #[must_use]
176    pub fn map(&self, value: F2Dot14) -> F2Dot14 {
177        if self.pairs.is_empty() {
178            return value; // identity for absent/empty maps
179        }
180        let v = value.to_bits();
181        let mut prev = (0i16, 0i16);
182        let mut have_prev = false;
183        for &(from, to) in &self.pairs {
184            let (x, y) = (from.to_bits(), to.to_bits());
185            if v <= x {
186                if !have_prev {
187                    // Before the first breakpoint: clamp to its target.
188                    return F2Dot14::from_bits(y);
189                }
190                if x == prev.0 {
191                    return F2Dot14::from_bits(y);
192                }
193                // Piecewise-linear interpolation between prev and (x, y).
194                let t = f32::from(v - prev.0) / f32::from(x - prev.0);
195                let y_out = f32::from(prev.1) + t * (f32::from(y) - f32::from(prev.1));
196                // Round half away from zero (core has no f32::round); the
197                // float->int cast truncates toward zero.
198                let shifted = if y_out < 0.0 {
199                    y_out - 0.5
200                } else {
201                    y_out + 0.5
202                };
203                return F2Dot14::from_bits(shifted as i16);
204            }
205            prev = (x, y);
206            have_prev = true;
207        }
208        // Beyond the last breakpoint: clamp to its target.
209        F2Dot14::from_bits(prev.1)
210    }
211}
212
213/// Zero-copy view over the `avar` table.
214#[derive(Debug, Clone, Copy)]
215pub struct AvarTable<'a> {
216    data: &'a [u8],
217    axis_count: u16,
218}
219
220impl<'a> AvarTable<'a> {
221    /// Parse and validate the `avar` table.
222    ///
223    /// # Errors
224    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
225    /// for short or inconsistent tables.
226    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
227        if data.len() < 8 {
228            return Err(ParseError::TruncatedTable {
229                tag: AVAR,
230                expected: 8,
231                got: data.len(),
232            });
233        }
234        // Layout: version u32, reserved u16 (historically the axis count),
235        // axisCount u16 at offset 6.
236        let axis_count = be_u16_at(data, 6, AVAR)?;
237        Ok(Self { data, axis_count })
238    }
239
240    /// Raw table bytes.
241    #[must_use]
242    pub fn as_bytes(&self) -> &'a [u8] {
243        self.data
244    }
245
246    /// Declared axis count of the segment map array.
247    #[must_use]
248    pub const fn axis_count(&self) -> u16 {
249        self.axis_count
250    }
251
252    /// The per-axis segment maps.
253    ///
254    /// # Errors
255    /// [`ParseError::TruncatedTable`] when a map is short.
256    pub fn segment_maps(&self) -> Result<Vec<SegmentMap>, ParseError> {
257        let mut out = Vec::with_capacity(usize::from(self.axis_count));
258        let mut at = 8usize;
259        for _ in 0..usize::from(self.axis_count) {
260            let count = usize::from(be_u16_at(self.data, at, AVAR)?);
261            at += 2;
262            let mut pairs = Vec::with_capacity(count);
263            for _ in 0..count {
264                let from = F2Dot14::from_bits(crate::reader::be_i16_at(self.data, at, AVAR)?);
265                let to = F2Dot14::from_bits(crate::reader::be_i16_at(self.data, at + 2, AVAR)?);
266                pairs.push((from, to));
267                at += 4;
268            }
269            out.push(SegmentMap { pairs });
270        }
271        Ok(out)
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
278
279    use super::{AvarTable, FvarTable, SegmentMap};
280    use crate::error::ParseError;
281    use alloc::vec;
282    use alloc::vec::Vec;
283    use font_types::{F2Dot14, Tag};
284
285    /// fvar: 1 axis (wght 400..900 default 400), 1 instance (600) with a
286    /// postScriptNameID.
287    fn fvar() -> Vec<u8> {
288        let mut d = Vec::new();
289        d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // version
290        d.extend_from_slice(&16u16.to_be_bytes()); // offsetToData
291        d.extend_from_slice(&2u16.to_be_bytes()); // countSizePairs
292        d.extend_from_slice(&1u16.to_be_bytes()); // fontAxisCount
293        d.extend_from_slice(&20u16.to_be_bytes()); // axisSize
294        d.extend_from_slice(&1u16.to_be_bytes()); // fontInstanceCount
295        d.extend_from_slice(&12u16.to_be_bytes()); // instanceSize (incl. psNameID)
296                                                   // Axis @16: tag, min, default, max, flags, nameID
297        d.extend_from_slice(b"wght");
298        d.extend_from_slice(&400i32.to_be_bytes()); // min (Fixed)
299        d.extend_from_slice(&400i32.to_be_bytes()); // default
300        d.extend_from_slice(&900i32.to_be_bytes()); // max
301        d.extend_from_slice(&0u16.to_be_bytes()); // flags
302        d.extend_from_slice(&256u16.to_be_bytes()); // nameID
303                                                    // Instance @36: subfamilyNameID, flags, coords, psNameID
304        d.extend_from_slice(&257u16.to_be_bytes());
305        d.extend_from_slice(&0u16.to_be_bytes());
306        d.extend_from_slice(&600i32.to_be_bytes());
307        d.extend_from_slice(&291u16.to_be_bytes());
308        d
309    }
310
311    #[test]
312    fn fvar_axes_and_instances() {
313        let d = fvar();
314        let t = FvarTable::parse(&d).unwrap();
315        assert_eq!(t.version().unwrap(), 0x0001_0000);
316        assert_eq!(t.axis_count(), 1);
317        let axes = t.axes().unwrap();
318        assert_eq!(axes.len(), 1);
319        let a = &axes[0];
320        assert_eq!(a.tag, Tag::new(b"wght"));
321        assert_eq!(a.min.to_bits(), 400);
322        assert_eq!(a.default.to_bits(), 400);
323        assert_eq!(a.max.to_bits(), 900);
324        assert_eq!(a.name_id, 256);
325        let instances = t.instances().unwrap();
326        assert_eq!(instances.len(), 1);
327        assert_eq!(instances[0].name_id, 257);
328        assert_eq!(instances[0].coordinates[0].to_bits(), 600);
329        assert_eq!(t.as_bytes().len(), d.len());
330    }
331
332    #[test]
333    fn fvar_errors() {
334        assert!(matches!(
335            FvarTable::parse(&[0u8; 15]),
336            Err(ParseError::TruncatedTable { .. })
337        ));
338        // Zero axes.
339        let mut d = fvar();
340        d[8..10].copy_from_slice(&0u16.to_be_bytes());
341        assert_eq!(
342            FvarTable::parse(&d).unwrap_err(),
343            ParseError::InvalidGlyphFormat
344        );
345        // axisSize below 20.
346        let mut d = fvar();
347        d[10..12].copy_from_slice(&8u16.to_be_bytes());
348        assert_eq!(
349            FvarTable::parse(&d).unwrap_err(),
350            ParseError::InvalidGlyphFormat
351        );
352        // Instance too small for the axis count.
353        let mut d = fvar();
354        d[14..16].copy_from_slice(&6u16.to_be_bytes());
355        assert_eq!(
356            FvarTable::parse(&d).unwrap_err(),
357            ParseError::InvalidGlyphFormat
358        );
359        // Truncated axis array surfaces from axes().
360        let mut d = fvar();
361        d.truncate(30);
362        let t = FvarTable::parse(&d).unwrap();
363        assert!(t.axes().is_err());
364    }
365
366    #[test]
367    fn avar_maps_and_interpolation() {
368        let mut d = Vec::new();
369        d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // version
370        d.extend_from_slice(&0u16.to_be_bytes()); // reserved
371        d.extend_from_slice(&1u16.to_be_bytes()); // axisCount
372                                                  // Axis 0 map: 4 pairs.
373        d.extend_from_slice(&4u16.to_be_bytes());
374        for (from, to) in [(-1.0f32, -1.0), (0.0, 0.0), (0.5, 0.6), (1.0, 1.0)] {
375            d.extend_from_slice(&F2Dot14::from_f32(from).to_bits().to_be_bytes());
376            d.extend_from_slice(&F2Dot14::from_f32(to).to_bits().to_be_bytes());
377        }
378        let t = AvarTable::parse(&d).unwrap();
379        assert_eq!(t.axis_count(), 1);
380        let maps: Vec<SegmentMap> = t.segment_maps().unwrap();
381        assert_eq!(maps.len(), 1);
382        let m = &maps[0];
383        assert_eq!(m.pairs.len(), 4);
384        let f2 = |v: f32| F2Dot14::from_f32(v);
385        assert_eq!(m.map(f2(-1.0)), f2(-1.0));
386        assert_eq!(m.map(f2(0.0)), f2(0.0));
387        assert_eq!(m.map(f2(1.0)), f2(1.0));
388        let mapped = m.map(f2(0.5));
389        assert!((mapped.to_f32() - 0.6).abs() < 0.001);
390        // Identity for empty maps (below the pair minimum).
391        let empty = SegmentMap { pairs: vec![] };
392        assert_eq!(empty.map(f2(0.5)), f2(0.5));
393        // Clamp below the first breakpoint.
394        assert_eq!(m.map(f2(-2.0)), f2(-1.0));
395        assert_eq!(m.map(f2(2.0)), f2(1.0));
396    }
397
398    #[test]
399    fn avar_errors() {
400        assert!(matches!(
401            AvarTable::parse(&[0u8; 7]),
402            Err(ParseError::TruncatedTable { .. })
403        ));
404        // Map truncated mid-pairs.
405        let mut d = Vec::new();
406        d.extend_from_slice(&0x0001_0000u32.to_be_bytes());
407        d.extend_from_slice(&0u16.to_be_bytes());
408        d.extend_from_slice(&1u16.to_be_bytes());
409        d.extend_from_slice(&2u16.to_be_bytes()); // 2 pairs but only 1 present
410        d.extend_from_slice(&[0xC0, 0x00, 0xC0, 0x00]);
411        let t = AvarTable::parse(&d).unwrap();
412        assert!(t.segment_maps().is_err());
413    }
414}