Skip to main content

font_parse/tables/
gvar.rs

1//! `gvar` — glyph variation data: per-glyph delta tuples for variable fonts.
2//!
3//! Packed encodings (per the OpenType spec and the reference `fontTools`
4//! decompiler): point-number runs accumulate relative increments into
5//! absolute indices; delta runs are control-byte framed
6//! (`bits 6-7`: size — 1-byte, 2-byte, zeros, 4-byte; `bits 0-5`: run count
7//! minus 1) and are **not** cumulative.
8
9use crate::error::{ParseError, RawTag};
10use crate::reader::{be_u16_at, be_u32_at, Reader};
11use alloc::vec::Vec;
12use font_types::F2Dot14;
13
14pub(crate) const TAG: RawTag = *b"gvar";
15
16const EMBEDDED_PEAK: u16 = 0x8000;
17const INTERMEDIATE_REGION: u16 = 0x4000;
18const PRIVATE_POINTS: u16 = 0x2000;
19const SHARED_POINTS: u16 = 0x8000;
20const LONG_OFFSETS: u16 = 0x0001;
21
22const DELTAS_SIZE_MASK: u8 = 0xC0;
23const DELTAS_ONE_BYTE: u8 = 0x00;
24const DELTAS_ARE_WORDS: u8 = 0x40;
25const DELTAS_ARE_ZERO: u8 = 0x80;
26const DELTAS_ARE_LONGS: u8 = 0xC0;
27const DELTA_RUN_COUNT_MASK: u8 = 0x3F;
28
29const POINTS_ARE_WORDS: u8 = 0x80;
30const POINT_RUN_COUNT_MASK: u8 = 0x7F;
31
32/// One variation tuple: peak coordinates plus resolved x/y deltas.
33///
34/// Deltas apply to the outline points listed in `point_numbers`, or to
35/// **all** points of the glyph when `point_numbers` is `None`.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct TupleVariation {
38    /// Peak coordinates per axis (embedded, shared-indexed, or empty).
39    pub peak: Vec<F2Dot14>,
40    /// Index into the shared-tuples array when the peak is not embedded.
41    pub shared_peak_index: u16,
42    /// Intermediate region start coordinates, when declared.
43    pub start: Option<Vec<F2Dot14>>,
44    /// Intermediate region end coordinates, when declared.
45    pub end: Option<Vec<F2Dot14>>,
46    /// Point indices the deltas apply to (`None` = all points).
47    pub point_numbers: Option<Vec<u16>>,
48    /// Per-point x deltas, run-decoded (not cumulative).
49    pub x_deltas: Vec<i32>,
50    /// Per-point y deltas.
51    pub y_deltas: Vec<i32>,
52}
53
54impl TupleVariation {
55    /// True when the tuple carries its own packed point numbers.
56    #[must_use]
57    pub const fn has_private_points(&self) -> bool {
58        self.point_numbers.is_some()
59    }
60}
61
62/// Zero-copy view over the `gvar` table.
63#[derive(Debug, Clone, Copy)]
64pub struct GvarTable<'a> {
65    data: &'a [u8],
66    axis_count: u16,
67    glyph_count: u16,
68    long_offsets: bool,
69    glyph_data_array_offset: u32,
70    offsets_array_at: usize,
71    shared_tuples_offset: u32,
72    shared_tuple_count: u16,
73}
74
75impl<'a> GvarTable<'a> {
76    /// Parse and validate the `gvar` header and offsets array.
77    ///
78    /// `glyph_count` must come from `maxp`.
79    ///
80    /// # Errors
81    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
82    /// for short or inconsistent tables.
83    pub fn parse(data: &'a [u8], glyph_count: u16) -> Result<Self, ParseError> {
84        if data.len() < 20 {
85            return Err(ParseError::TruncatedTable {
86                tag: TAG,
87                expected: 20,
88                got: data.len(),
89            });
90        }
91        let axis_count = be_u16_at(data, 4, TAG)?;
92        let shared_tuple_count = be_u16_at(data, 6, TAG)?;
93        let shared_tuples_offset = be_u32_at(data, 8, TAG)?;
94        let glyph_data_array_offset = be_u32_at(data, 16, TAG)?;
95        let flags = be_u16_at(data, 14, TAG)?;
96        let long_offsets = flags & LONG_OFFSETS != 0;
97        if axis_count == 0 {
98            return Err(ParseError::InvalidGlyphFormat);
99        }
100        let offsets_array_at = 20usize;
101        let offsets_len = (usize::from(glyph_count) + 1)
102            .checked_mul(if long_offsets { 4 } else { 2 })
103            .ok_or(ParseError::InvalidGlyphFormat)?;
104        let needed = offsets_array_at
105            .checked_add(offsets_len)
106            .ok_or(ParseError::InvalidGlyphFormat)?;
107        if data.len() < needed {
108            return Err(ParseError::TruncatedTable {
109                tag: TAG,
110                expected: needed,
111                got: data.len(),
112            });
113        }
114        Ok(Self {
115            data,
116            axis_count,
117            glyph_count,
118            long_offsets,
119            glyph_data_array_offset,
120            offsets_array_at,
121            shared_tuples_offset,
122            shared_tuple_count,
123        })
124    }
125
126    /// Raw offset entry `i` from the glyph-variation-data offsets array.
127    /// Short offsets are stored divided by two (per the FreeType-derived
128    /// convention fontTools documents); long offsets are raw.
129    fn glyph_offset(&self, i: u16) -> Result<usize, ParseError> {
130        if self.long_offsets {
131            let v = be_u32_at(self.data, self.offsets_array_at + usize::from(i) * 4, TAG)?;
132            usize::try_from(v).map_err(|_| ParseError::InvalidGlyphFormat)
133        } else {
134            let v = be_u16_at(self.data, self.offsets_array_at + usize::from(i) * 2, TAG)?;
135            usize::from(v)
136                .checked_mul(2)
137                .ok_or(ParseError::InvalidGlyphFormat)
138        }
139    }
140
141    /// Raw table bytes.
142    #[must_use]
143    pub fn as_bytes(&self) -> &'a [u8] {
144        self.data
145    }
146
147    /// Axis count shared by every tuple.
148    #[must_use]
149    pub const fn axis_count(&self) -> u16 {
150        self.axis_count
151    }
152
153    /// Shared tuple coordinates, in declared order.
154    ///
155    /// # Errors
156    /// [`ParseError::TruncatedTable`] when the array is short.
157    pub fn shared_tuples(&self) -> Result<Vec<Vec<F2Dot14>>, ParseError> {
158        let mut out = Vec::with_capacity(usize::from(self.shared_tuple_count));
159        let mut r = Reader::within(
160            self.data,
161            usize::try_from(self.shared_tuples_offset)
162                .map_err(|_| ParseError::InvalidGlyphFormat)?,
163            self.data.len(),
164            TAG,
165        );
166        for _ in 0..self.shared_tuple_count {
167            let mut tuple = Vec::with_capacity(usize::from(self.axis_count));
168            for _ in 0..self.axis_count {
169                tuple.push(F2Dot14::from_bits(r.i16()?));
170            }
171            out.push(tuple);
172        }
173        Ok(out)
174    }
175
176    /// Byte range of glyph `gid`'s variation data (`None` = no variation
177    /// data / id out of range).
178    fn glyph_data_range(&self, gid: u16) -> Result<Option<core::ops::Range<usize>>, ParseError> {
179        if gid >= self.glyph_count {
180            return Ok(None);
181        }
182        let base = usize::try_from(self.glyph_data_array_offset)
183            .map_err(|_| ParseError::InvalidGlyphFormat)?;
184        let next = gid.checked_add(1).ok_or(ParseError::InvalidGlyphFormat)?;
185        let start = base
186            .checked_add(self.glyph_offset(gid)?)
187            .ok_or(ParseError::InvalidGlyphFormat)?;
188        let end = base
189            .checked_add(self.glyph_offset(next)?)
190            .ok_or(ParseError::InvalidGlyphFormat)?;
191        if end >= start && end <= self.data.len() {
192            if start == end {
193                Ok(None)
194            } else {
195                Ok(Some(start..end))
196            }
197        } else {
198            Err(ParseError::InvalidGlyphFormat)
199        }
200    }
201
202    /// All variation tuples for `gid`.
203    ///
204    /// `point_count` is the glyph's variation point count — outline points
205    /// (components for composites) **plus the 4 phantom points** — which
206    /// sizes "apply to all points" tuples whose delta count the table does
207    /// not store.
208    ///
209    /// # Errors
210    /// [`ParseError::InvalidGlyphFormat`] / [`ParseError::TruncatedTable`]
211    /// for malformed tuple data.
212    pub fn glyph_deltas(
213        &self,
214        gid: u16,
215        point_count: u16,
216    ) -> Result<Vec<TupleVariation>, ParseError> {
217        let mut tuples = Vec::new();
218        let Some(range) = self.glyph_data_range(gid)? else {
219            return Ok(tuples);
220        };
221        let data = crate::reader::slice_at(self.data, range.start, range.end - range.start, TAG)?;
222        if data.len() < 4 {
223            return Err(ParseError::InvalidGlyphFormat);
224        }
225        let tuple_var_count = be_u16_at(data, 0, TAG)?;
226        let count = usize::from(tuple_var_count & 0x0FFF);
227        let has_shared_points = tuple_var_count & SHARED_POINTS != 0;
228        let data_offset = usize::from(be_u16_at(data, 2, TAG)?);
229        if data_offset > data.len() {
230            return Err(ParseError::InvalidGlyphFormat);
231        }
232        // Headers live in [4, data_offset); serialized tuples follow.
233        let mut hr = Reader::within(data, 4, data_offset, TAG);
234        let mut sr_pos = data_offset;
235        // Shared packed points precede the tuple data when flagged.
236        let mut shared_points: Option<Vec<u16>> = None;
237        if has_shared_points {
238            let mut pr = Reader::within(data, sr_pos, data.len(), TAG);
239            let pts = read_packed_points(&mut pr, usize::from(point_count))?;
240            sr_pos = sr_pos.saturating_add(pr.pos());
241            shared_points = Some(pts);
242        }
243        let shared_tuples = self.shared_tuples()?;
244        for _ in 0..count {
245            // Header: variationDataSize + tupleIndex [+ peak [+ region]].
246            let variation_data_size = usize::from(hr.u16()?);
247            let tuple_index = hr.u16()?;
248            let axis = usize::from(self.axis_count);
249            let (peak, shared_peak_index) = if tuple_index & EMBEDDED_PEAK != 0 {
250                let mut peak = Vec::with_capacity(axis);
251                for _ in 0..axis {
252                    peak.push(F2Dot14::from_bits(hr.i16()?));
253                }
254                (peak, u16::MAX)
255            } else {
256                let idx = tuple_index & 0x0FFF;
257                let peak = shared_tuples
258                    .get(usize::from(idx))
259                    .cloned()
260                    .unwrap_or_default();
261                (peak, idx)
262            };
263            let (start, end) = if tuple_index & INTERMEDIATE_REGION != 0 {
264                let mut s = Vec::with_capacity(axis);
265                for _ in 0..axis {
266                    s.push(F2Dot14::from_bits(hr.i16()?));
267                }
268                let mut e = Vec::with_capacity(axis);
269                for _ in 0..axis {
270                    e.push(F2Dot14::from_bits(hr.i16()?));
271                }
272                (Some(s), Some(e))
273            } else {
274                (None, None)
275            };
276            // Serialized window for this tuple.
277            let window = crate::reader::slice_at(data, sr_pos, variation_data_size, TAG)?;
278            sr_pos += variation_data_size;
279            let mut tr = Reader::new(window, TAG);
280            // Private point numbers, else shared, else all points.
281            let point_numbers = if tuple_index & PRIVATE_POINTS != 0 {
282                Some(read_packed_points(&mut tr, usize::from(point_count))?)
283            } else {
284                shared_points.clone()
285            };
286            let n = point_numbers
287                .as_ref()
288                .map_or(usize::from(point_count), Vec::len);
289            let x = read_packed_deltas(&mut tr, n)?;
290            let y = read_packed_deltas(&mut tr, n)?;
291            tuples.push(TupleVariation {
292                peak,
293                shared_peak_index,
294                start,
295                end,
296                point_numbers,
297                x_deltas: x,
298                y_deltas: y,
299            });
300        }
301        Ok(tuples)
302    }
303}
304
305/// Decode gvar packed point numbers: relative increments accumulated into
306/// absolute indices. An initial zero byte means "all points".
307fn read_packed_points(r: &mut Reader<'_>, outline_points: usize) -> Result<Vec<u16>, ParseError> {
308    let first = r.u8()?;
309    if first == 0 {
310        let n = outline_points.min(usize::from(u16::MAX));
311        return (0..n)
312            .map(u16::try_from)
313            .collect::<Result<Vec<u16>, _>>()
314            .map_err(|_| ParseError::InvalidGlyphFormat);
315    }
316    let count = if first & POINTS_ARE_WORDS != 0 {
317        let hi = usize::from(first & POINT_RUN_COUNT_MASK);
318        (hi << 8 | usize::from(r.u8()?)) + 1
319    } else {
320        usize::from(first) + 1
321    };
322    if count > outline_points {
323        return Err(ParseError::InvalidGlyphFormat);
324    }
325    let mut pts = Vec::with_capacity(count);
326    let mut cur: u32 = 0;
327    while pts.len() < count {
328        let control = r.u8()?;
329        let run_len = usize::from(control & POINT_RUN_COUNT_MASK) + 1;
330        for _ in 0..run_len {
331            if pts.len() >= count {
332                return Err(ParseError::InvalidGlyphFormat);
333            }
334            let inc = if control & POINTS_ARE_WORDS != 0 {
335                u32::from(r.u16()?)
336            } else {
337                u32::from(r.u8()?)
338            };
339            cur = cur.saturating_add(inc);
340            let idx = u16::try_from(cur).map_err(|_| ParseError::InvalidGlyphFormat)?;
341            pts.push(idx);
342        }
343    }
344    Ok(pts)
345}
346
347/// Decode gvar packed deltas: control-byte framed runs; values are used
348/// directly (never cumulative).
349fn read_packed_deltas(r: &mut Reader<'_>, count: usize) -> Result<Vec<i32>, ParseError> {
350    let mut out = Vec::with_capacity(count);
351    while out.len() < count {
352        let control = r.u8()?;
353        let run_len = usize::from(control & DELTA_RUN_COUNT_MASK) + 1;
354        for _ in 0..run_len {
355            if out.len() >= count {
356                return Err(ParseError::InvalidGlyphFormat);
357            }
358            match control & DELTAS_SIZE_MASK {
359                DELTAS_ONE_BYTE => out.push(i32::from(r.i8()?)),
360                DELTAS_ARE_WORDS => out.push(i32::from(r.i16()?)),
361                DELTAS_ARE_ZERO => out.push(0),
362                DELTAS_ARE_LONGS => out.push(r.i32()?),
363                _ => return Err(ParseError::InvalidGlyphFormat),
364            }
365        }
366    }
367    Ok(out)
368}
369
370#[cfg(test)]
371mod tests {
372    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
373
374    use super::{GvarTable, TupleVariation};
375    use crate::error::ParseError;
376    use alloc::vec;
377    use alloc::vec::Vec;
378    use font_types::F2Dot14;
379
380    /// Hand-built gvar for 3 glyphs, 1 axis, 1 shared tuple (peak 1.0):
381    /// gid 0: one tuple, shared points (all 6 points), mixed delta runs.
382    /// gid 1: no data.
383    /// gid 2: private points [0, 3] (of 6), embedded peak 0.5, intermediate
384    /// region, x deltas [10, 20], zero y deltas.
385    fn gvar() -> Vec<u8> {
386        // Serialized data for gid 0: shared "all points" byte, x runs
387        // ([50, 50] then zeros to 6), y runs ([5, 5] then zeros).
388        let ser0: [u8; 9] = [
389            0x00, // shared points: all points
390            0x01, 50, 50,   // x: 1-byte deltas, count 2
391            0x83, // x: zeros, count 4
392            0x01, 5, 5,    // y: 1-byte deltas, count 2
393            0x83, // y: zeros, count 4
394        ];
395        let gid0: [u8; 17] = [
396            0x80, 0x01, // tupleVariationCount: shared points + 1 tuple
397            0x00, 0x08, // dataOffset 8
398            0x00, 0x09, // dataSize 9
399            0x00, 0x00, // tupleIndex 0 -> shared tuple 0
400            ser0[0], ser0[1], ser0[2], ser0[3], ser0[4], ser0[5], ser0[6], ser0[7], ser0[8],
401        ];
402        // Serialized data for gid 2: private points [0, 3], x [10, 20],
403        // y zeros (2).
404        let ser2: [u8; 9] = [
405            0x01, // point count: (0x01 & 0x7F) + 1 = 2
406            0x00, 0x00, // run of 1 one-byte increment: +0 -> point 0
407            0x00, 0x03, // run of 1 one-byte increment: +3 -> point 3
408            0x01, 10, 20,   // x: 1-byte deltas, count 2
409            0x81, // y: zeros, count 2
410        ];
411        let mut gid2: Vec<u8> = Vec::new();
412        gid2.extend_from_slice(&0x0001u16.to_be_bytes()); // 1 tuple, no shared points
413                                                          // dataOffset: headers run [4, 14): dataSize, tupleIndex, peak,
414                                                          // start, end (embedded peak + intermediate region extend the header).
415        gid2.extend_from_slice(&14u16.to_be_bytes());
416        gid2.extend_from_slice(&(ser2.len() as u16).to_be_bytes()); // dataSize
417        gid2.extend_from_slice(&0xE000u16.to_be_bytes()); // embedded peak + intermediate + private points
418        gid2.extend_from_slice(&0x2000i16.to_be_bytes()); // peak 0.5
419        gid2.extend_from_slice(&0x1000i16.to_be_bytes()); // intermediate start 0.25
420        gid2.extend_from_slice(&0x3000i16.to_be_bytes()); // intermediate end 0.75
421        gid2.extend_from_slice(&ser2);
422        debug_assert_eq!(gid2.len(), 14 + ser2.len());
423        if gid2.len() % 2 != 0 {
424            gid2.push(0);
425        }
426        // Layout: header 20, short offsets 8 (20..28), shared tuple @28,
427        // glyph variation data array @32. Offsets are relative to the array.
428        let mut d = Vec::new();
429        d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // version
430        d.extend_from_slice(&1u16.to_be_bytes()); // axisCount
431        d.extend_from_slice(&1u16.to_be_bytes()); // sharedTupleCount
432        d.extend_from_slice(&28u32.to_be_bytes()); // sharedTuplesOffset
433        d.extend_from_slice(&3u16.to_be_bytes()); // glyphCount
434        d.extend_from_slice(&0u16.to_be_bytes()); // flags: short offsets
435        d.extend_from_slice(&32u32.to_be_bytes()); // data array offset
436                                                   // Offsets (raw, stored halved): [0, 20, 20, 20 + gid2.len()]
437        let end = (17 + 1 + gid2.len()) as u16; // gid0 padded to even
438        for v in [0u16, 9, 9, end / 2] {
439            d.extend_from_slice(&v.to_be_bytes());
440        }
441        // Shared tuple @28: peak 1.0 (0x4000) + pad to the data array @32.
442        d.extend_from_slice(&0x4000i16.to_be_bytes());
443        d.extend_from_slice(&[0u8; 2]);
444        d.extend_from_slice(&gid0);
445        if d.len() % 2 != 0 {
446            d.push(0); // gid0's even pad (accounted in the offsets)
447        }
448        d.extend_from_slice(&gid2);
449        if d.len() % 2 != 0 {
450            d.push(0);
451        }
452        d
453    }
454
455    #[test]
456    fn header_offsets_and_shared_tuples() {
457        let d = gvar();
458        let t = GvarTable::parse(&d, 3).unwrap();
459        assert_eq!(t.axis_count(), 1);
460        let shared = t.shared_tuples().unwrap();
461        assert_eq!(shared.len(), 1);
462        assert_eq!(shared[0][0].to_bits(), 0x4000);
463    }
464
465    #[test]
466    fn shared_points_tuple() {
467        let d = gvar();
468        let t = GvarTable::parse(&d, 3).unwrap();
469        let tuples: Vec<TupleVariation> = t.glyph_deltas(0, 6).unwrap();
470        assert_eq!(tuples.len(), 1);
471        let t0 = &tuples[0];
472        // Shared point numbers materialize as a concrete list.
473        assert_eq!(
474            t0.point_numbers.as_deref(),
475            Some(&[0u16, 1, 2, 3, 4, 5][..])
476        );
477        assert_eq!(t0.x_deltas, vec![50, 50, 0, 0, 0, 0]);
478        assert_eq!(t0.y_deltas, vec![5, 5, 0, 0, 0, 0]);
479        // Peak from the shared tuple.
480        assert_eq!(t0.shared_peak_index, 0);
481        assert_eq!(t0.peak, vec![F2Dot14::from_bits(0x4000)]);
482        assert!(t0.start.is_none());
483        // gid 1 has no data.
484        assert!(t.glyph_deltas(1, 6).unwrap().is_empty());
485    }
486
487    #[test]
488    fn private_points_embedded_peak_intermediate() {
489        let d = gvar();
490        let t = GvarTable::parse(&d, 3).unwrap();
491        let tuples = t.glyph_deltas(2, 6).unwrap();
492        assert_eq!(tuples.len(), 1);
493        let t2 = &tuples[0];
494        assert!(t2.has_private_points());
495        assert_eq!(t2.point_numbers, Some(vec![0, 3]));
496        assert_eq!(t2.x_deltas, vec![10, 20]);
497        assert_eq!(t2.y_deltas, vec![0, 0]);
498        assert_eq!(t2.shared_peak_index, u16::MAX);
499        assert_eq!(t2.peak, vec![F2Dot14::from_bits(0x2000)]);
500        assert_eq!(t2.start.as_ref().map(|s| s[0].to_bits()), Some(0x1000));
501        assert_eq!(t2.end.as_ref().map(|s| s[0].to_bits()), Some(0x3000));
502    }
503
504    #[test]
505    fn errors() {
506        // Truncated header.
507        assert!(matches!(
508            GvarTable::parse(&[0u8; 19], 3),
509            Err(ParseError::TruncatedTable { .. })
510        ));
511        // Zero axis count.
512        let mut d = gvar();
513        d[4..6].copy_from_slice(&0u16.to_be_bytes());
514        assert_eq!(
515            GvarTable::parse(&d, 3).unwrap_err(),
516            ParseError::InvalidGlyphFormat
517        );
518        // Offsets array short for the declared glyph count.
519        let d = gvar();
520        assert!(matches!(
521            GvarTable::parse(&d, 200),
522            Err(ParseError::TruncatedTable { .. })
523        ));
524        // Out-of-range gid -> no data.
525        let d = gvar();
526        let t = GvarTable::parse(&d, 3).unwrap();
527        assert!(t.glyph_deltas(9, 6).unwrap().is_empty());
528        // gid 1 genuinely has no data (empty offset range).
529        // Glyph range beyond the table -> invalid.
530        let mut d = gvar();
531        let n = d.len();
532        d.truncate(n - 5);
533        let t = GvarTable::parse(&d, 3).unwrap();
534        assert_eq!(
535            t.glyph_deltas(2, 6).unwrap_err(),
536            ParseError::InvalidGlyphFormat
537        );
538    }
539}