Skip to main content

font_parse/tables/
glyf.rs

1//! `glyf` — glyph outlines: simple glyphs, composite glyphs, contour points.
2
3use crate::error::{ParseError, RawTag};
4use crate::reader::Reader;
5use alloc::vec::Vec;
6use font_types::{F2Dot14, GlyphId};
7
8pub(crate) const TAG: RawTag = *b"glyf";
9
10/// Simple-glyph flag: point is on the curve.
11pub(crate) const FLAG_ON_CURVE: u8 = 0x01;
12/// Simple-glyph flag: x delta is one byte.
13pub(crate) const FLAG_X_SHORT: u8 = 0x02;
14/// Simple-glyph flag: y delta is one byte.
15pub(crate) const FLAG_Y_SHORT: u8 = 0x04;
16/// Simple-glyph flag: next byte repeats this flag.
17pub(crate) const FLAG_REPEAT: u8 = 0x08;
18/// Simple-glyph flag: x is same (long form) / positive (short form).
19pub(crate) const FLAG_X_SAME_OR_POS: u8 = 0x10;
20/// Simple-glyph flag: y is same (long form) / positive (short form).
21pub(crate) const FLAG_Y_SAME_OR_POS: u8 = 0x20;
22/// Simple-glyph overlap flag (bit 6).
23#[cfg(feature = "woff2")]
24pub(crate) const FLAG_OVERLAP_SIMPLE: u8 = 0x40;
25
26/// Composite-glyph flag: arguments are 16-bit words.
27pub(crate) const ARG_1_AND_2_ARE_WORDS: u16 = 0x0001;
28/// Composite-glyph flag: arguments are x/y offsets (not point indices).
29pub(crate) const ARGS_ARE_XY_VALUES: u16 = 0x0002;
30/// Composite-glyph flag: more components follow.
31pub(crate) const MORE_COMPONENTS: u16 = 0x0020;
32/// Composite-glyph flag: scale is present (a == d).
33pub(crate) const WE_HAVE_A_SCALE: u16 = 0x0008;
34/// Composite-glyph flag: x/y scale present.
35pub(crate) const WE_HAVE_AN_X_AND_Y_SCALE: u16 = 0x0040;
36/// Composite-glyph flag: full 2x2 matrix present.
37pub(crate) const WE_HAVE_A_TWO_BY_TWO: u16 = 0x0080;
38/// Composite-glyph flag: glyph instructions follow the components.
39#[cfg(feature = "woff2")]
40pub(crate) const WE_HAVE_INSTRUCTIONS: u16 = 0x0100;
41
42/// Hard cap on composite nesting depth (spec recommends <= 13; malformed
43/// fonts can declare cycles).
44pub(crate) const MAX_COMPONENT_DEPTH: u8 = 16;
45/// Hard cap on resolved outline points/components per glyph — bounds the
46/// composite expansion of hostile inputs.
47pub(crate) const MAX_OUTLINE_POINTS: usize = 1 << 20;
48
49/// A resolved outline point: font-unit coordinates plus curve membership.
50#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct OutlinePoint {
52    /// X coordinate in font units.
53    pub x: f32,
54    /// Y coordinate in font units.
55    pub y: f32,
56    /// True for on-curve points; False marks quadratic control points.
57    pub on_curve: bool,
58}
59
60/// One contour of an outline: an ordered run of points.
61#[derive(Debug, Clone, PartialEq)]
62pub struct Contour {
63    /// Contour points, in outline order.
64    pub points: Vec<OutlinePoint>,
65}
66
67/// A fully resolved glyph outline (composite components applied).
68///
69/// Extracting an outline allocates; table access itself stays zero-copy.
70#[derive(Debug, Clone, PartialEq, Default)]
71pub struct GlyphOutline {
72    /// Contours in glyph order.
73    pub contours: Vec<Contour>,
74}
75
76impl GlyphOutline {
77    /// Total point count across all contours.
78    #[must_use]
79    pub fn point_count(&self) -> usize {
80        self.contours.iter().map(|c| c.points.len()).sum()
81    }
82
83    /// True when the outline has no contours (space-like glyph).
84    #[must_use]
85    pub fn is_empty(&self) -> bool {
86        self.contours.is_empty()
87    }
88}
89
90/// A zero-copy view over one glyph record of the `glyf` table.
91#[derive(Debug, Clone, Copy)]
92pub enum GlyphRef<'a> {
93    /// A simple glyph: raw contours with delta-coded coordinates.
94    Simple(SimpleGlyph<'a>),
95    /// A composite glyph: references to component glyphs plus transforms.
96    Composite(CompositeGlyph<'a>),
97}
98
99impl<'a> GlyphRef<'a> {
100    /// Parse one glyph record (a `loca`-resolved byte range).
101    ///
102    /// An empty range decodes to `Ok(None)` (empty glyph).
103    ///
104    /// # Errors
105    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
106    /// for malformed records.
107    pub fn parse(data: &'a [u8]) -> Result<Option<Self>, ParseError> {
108        if data.is_empty() {
109            return Ok(None);
110        }
111        if data.len() < 10 {
112            return Err(ParseError::TruncatedTable {
113                tag: TAG,
114                expected: 10,
115                got: data.len(),
116            });
117        }
118        let n_contours = crate::reader::be_i16_at(data, 0, TAG)?;
119        if n_contours >= 0 {
120            Ok(Some(Self::Simple(SimpleGlyph::parse(data)?)))
121        } else if n_contours == -1 {
122            Ok(Some(Self::Composite(CompositeGlyph::parse(data)?)))
123        } else {
124            Err(ParseError::InvalidGlyphFormat)
125        }
126    }
127
128    /// The declared bounding box (`xMin, yMin, xMax, yMax`).
129    ///
130    /// # Errors
131    /// Truncation (impossible post-[`parse`](Self::parse)).
132    pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
133        match self {
134            Self::Simple(g) => g.bounds(),
135            Self::Composite(g) => g.bounds(),
136        }
137    }
138}
139
140/// A simple (non-composite) glyph record.
141#[derive(Debug, Clone, Copy)]
142pub struct SimpleGlyph<'a> {
143    data: &'a [u8],
144    n_contours: u16,
145}
146
147impl<'a> SimpleGlyph<'a> {
148    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
149        let n = crate::reader::be_u16_at(data, 0, TAG)?;
150        Ok(Self {
151            data,
152            n_contours: n,
153        })
154    }
155
156    /// Raw record bytes.
157    #[must_use]
158    pub fn as_bytes(&self) -> &'a [u8] {
159        self.data
160    }
161
162    /// Number of contours.
163    #[must_use]
164    pub const fn num_contours(&self) -> u16 {
165        self.n_contours
166    }
167
168    /// Declared bounding box.
169    ///
170    /// # Errors
171    /// Truncation (impossible post-[`parse`](Self::parse)).
172    pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
173        Ok([
174            crate::reader::be_i16_at(self.data, 2, TAG)?,
175            crate::reader::be_i16_at(self.data, 4, TAG)?,
176            crate::reader::be_i16_at(self.data, 6, TAG)?,
177            crate::reader::be_i16_at(self.data, 8, TAG)?,
178        ])
179    }
180
181    /// The `endPtsOfContours` array.
182    ///
183    /// # Errors
184    /// [`ParseError::TruncatedTable`] when the array exceeds the record.
185    pub fn end_points(&self) -> Result<Vec<u16>, ParseError> {
186        let n = usize::from(self.n_contours);
187        let at = 10usize;
188        let end = at
189            .checked_add(n * 2)
190            .ok_or(ParseError::InvalidGlyphFormat)?;
191        if self.data.len() < end {
192            return Err(ParseError::TruncatedTable {
193                tag: TAG,
194                expected: end,
195                got: self.data.len(),
196            });
197        }
198        let mut out = Vec::with_capacity(n);
199        for i in 0..n {
200            out.push(crate::reader::be_u16_at(self.data, at + i * 2, TAG)?);
201        }
202        Ok(out)
203    }
204
205    /// Decode contour points (flags expanded, delta coordinates resolved).
206    ///
207    /// # Errors
208    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
209    /// for short records or inconsistent coordinate streams.
210    pub fn points(&self) -> Result<Vec<OutlinePoint>, ParseError> {
211        let mut r = Reader::new(self.data, TAG);
212        r.skip(10)?;
213        let ends = self.end_points()?;
214        let n_points = ends.last().map_or(0, |&e| usize::from(e) + 1);
215        r.skip(ends.len() * 2)?;
216        // Instructions.
217        let instr_len = usize::from(r.u16()?);
218        r.skip(instr_len)?;
219        // Flags with repeat expansion.
220        let mut flags = Vec::with_capacity(n_points);
221        while flags.len() < n_points {
222            let flag = r.u8()?;
223            flags.push(flag);
224            if flag & FLAG_REPEAT != 0 {
225                let repeat = usize::from(r.u8()?);
226                for _ in 0..repeat {
227                    if flags.len() >= n_points {
228                        return Err(ParseError::InvalidGlyphFormat);
229                    }
230                    flags.push(flag);
231                }
232            }
233        }
234        // X coordinates (delta coded).
235        let mut xs = Vec::with_capacity(n_points);
236        let mut x: i32 = 0;
237        for &flag in &flags {
238            if flag & FLAG_X_SHORT != 0 {
239                let d = i32::from(r.u8()?);
240                x += if flag & FLAG_X_SAME_OR_POS != 0 {
241                    d
242                } else {
243                    -d
244                };
245            } else if flag & FLAG_X_SAME_OR_POS == 0 {
246                x += i32::from(r.i16()?);
247            }
248            xs.push(x);
249        }
250        // Y coordinates, zipped with the resolved X deltas.
251        let mut pts = Vec::with_capacity(n_points);
252        let mut y: i32 = 0;
253        for (i, &flag) in flags.iter().enumerate() {
254            if flag & FLAG_Y_SHORT != 0 {
255                let d = i32::from(r.u8()?);
256                y += if flag & FLAG_Y_SAME_OR_POS != 0 {
257                    d
258                } else {
259                    -d
260                };
261            } else if flag & FLAG_Y_SAME_OR_POS == 0 {
262                y += i32::from(r.i16()?);
263            }
264            if i >= MAX_OUTLINE_POINTS {
265                return Err(ParseError::InvalidGlyphFormat);
266            }
267            let x = *xs.get(i).unwrap_or(&0);
268            pts.push(OutlinePoint {
269                x: x as f32,
270                y: y as f32,
271                on_curve: flag & FLAG_ON_CURVE != 0,
272            });
273        }
274        Ok(pts)
275    }
276
277    /// Collect the glyph's contours into an outline.
278    ///
279    /// # Errors
280    /// See [`points`](Self::points).
281    pub fn outline(&self) -> Result<GlyphOutline, ParseError> {
282        let pts = self.points()?;
283        let ends = self.end_points()?;
284        let mut contours = Vec::with_capacity(ends.len());
285        let mut start = 0usize;
286        for &e in &ends {
287            let end = usize::from(e) + 1;
288            if end > pts.len() || start > end {
289                return Err(ParseError::InvalidGlyphFormat);
290            }
291            let slice = pts.get(start..end).ok_or(ParseError::InvalidGlyphFormat)?;
292            contours.push(Contour {
293                points: slice.to_vec(),
294            });
295            start = end;
296        }
297        Ok(GlyphOutline { contours })
298    }
299}
300
301/// One component of a composite glyph.
302#[derive(Debug, Clone, Copy, PartialEq)]
303pub struct Component {
304    /// Referenced glyph.
305    pub glyph: GlyphId,
306    /// Raw flag word.
307    pub flags: u16,
308    /// Arguments: x/y offsets (font units) when
309    /// `flags & ARGS_ARE_XY_VALUES`, else point indices.
310    pub args: (i32, i32),
311    /// 2x2 transform (`a b c d`): `x' = a*x + c*y + e`.
312    pub transform: [f32; 4],
313}
314
315impl Component {
316    /// True when the args are x/y placement offsets.
317    #[must_use]
318    pub const fn args_are_offsets(&self) -> bool {
319        self.flags & ARGS_ARE_XY_VALUES != 0
320    }
321}
322
323/// A composite glyph record.
324#[derive(Debug, Clone, Copy)]
325pub struct CompositeGlyph<'a> {
326    data: &'a [u8],
327}
328
329impl<'a> CompositeGlyph<'a> {
330    fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
331        Ok(Self { data })
332    }
333
334    /// Raw record bytes.
335    #[must_use]
336    pub fn as_bytes(&self) -> &'a [u8] {
337        self.data
338    }
339
340    /// Declared bounding box.
341    ///
342    /// # Errors
343    /// Truncation (impossible post-[`GlyphRef::parse`]).
344    pub fn bounds(&self) -> Result<[i16; 4], ParseError> {
345        Ok([
346            crate::reader::be_i16_at(self.data, 2, TAG)?,
347            crate::reader::be_i16_at(self.data, 4, TAG)?,
348            crate::reader::be_i16_at(self.data, 6, TAG)?,
349            crate::reader::be_i16_at(self.data, 8, TAG)?,
350        ])
351    }
352
353    /// Decode the component list (flags, args, transform matrices).
354    ///
355    /// # Errors
356    /// [`ParseError::TruncatedTable`] / [`ParseError::InvalidGlyphFormat`]
357    /// for truncated records or runaway component lists.
358    pub fn components(&self) -> Result<Vec<Component>, ParseError> {
359        let mut r = Reader::new(self.data, TAG);
360        r.skip(10)?;
361        let mut out = Vec::new();
362        loop {
363            if out.len() > MAX_OUTLINE_POINTS {
364                return Err(ParseError::InvalidGlyphFormat);
365            }
366            let flags = r.u16()?;
367            let glyph = GlyphId::new(u32::from(r.u16()?));
368            let (a1, a2) = if flags & ARG_1_AND_2_ARE_WORDS != 0 {
369                (i32::from(r.i16()?), i32::from(r.i16()?))
370            } else {
371                (i32::from(r.i8()?), i32::from(r.i8()?))
372            };
373            let scale = |r: &mut Reader<'a>| -> Result<F2Dot14, ParseError> { r.f2dot14() };
374            let transform = if flags & WE_HAVE_A_SCALE != 0 {
375                let a = scale(&mut r)?;
376                [a.to_f32(), 0.0, 0.0, a.to_f32()]
377            } else if flags & WE_HAVE_AN_X_AND_Y_SCALE != 0 {
378                let a = scale(&mut r)?;
379                let d = scale(&mut r)?;
380                [a.to_f32(), 0.0, 0.0, d.to_f32()]
381            } else if flags & WE_HAVE_A_TWO_BY_TWO != 0 {
382                let a = scale(&mut r)?;
383                let b = scale(&mut r)?;
384                let c = scale(&mut r)?;
385                let d = scale(&mut r)?;
386                [a.to_f32(), b.to_f32(), c.to_f32(), d.to_f32()]
387            } else {
388                [1.0, 0.0, 0.0, 1.0]
389            };
390            out.push(Component {
391                glyph,
392                flags,
393                args: (a1, a2),
394                transform,
395            });
396            if flags & MORE_COMPONENTS == 0 {
397                break;
398            }
399        }
400        Ok(out)
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    #![allow(
407        clippy::unwrap_used,
408        clippy::expect_used,
409        clippy::indexing_slicing,
410        clippy::panic
411    )]
412
413    use super::{Component, GlyphOutline, GlyphRef, OutlinePoint, SimpleGlyph};
414    use crate::error::ParseError;
415    use alloc::vec;
416    use alloc::vec::Vec;
417    use font_types::GlyphId;
418
419    /// One-contour triangle, 3 on-curve points, deltas: x (100, 0, 100),
420    /// y (0, 200, -200). Header + ends + instrLen(0) + flags + coords.
421    fn triangle() -> Vec<u8> {
422        let mut d = Vec::new();
423        d.extend_from_slice(&1i16.to_be_bytes()); // contours
424        d.extend_from_slice(&0i16.to_be_bytes());
425        d.extend_from_slice(&100i16.to_be_bytes());
426        d.extend_from_slice(&300i16.to_be_bytes());
427        d.extend_from_slice(&200i16.to_be_bytes());
428        d.extend_from_slice(&2u16.to_be_bytes()); // endPts [2]
429        d.extend_from_slice(&0u16.to_be_bytes()); // instructionLength
430                                                  // p0/p1: on-curve + x/y short positive (0x37); p2: y short negative
431                                                  // (0x17).
432        d.extend_from_slice(&[0x37, 0x37, 0x17]);
433        // x deltas: +100, +0, +100 (one unsigned byte each).
434        d.extend_from_slice(&[100, 0, 100]);
435        // y deltas: +0, +200, -200 (unsigned byte, sign from the flag).
436        d.extend_from_slice(&[0, 200, 200]);
437        d
438    }
439
440    #[test]
441    fn simple_glyph_points_and_contours() {
442        let d = triangle();
443        let g = GlyphRef::parse(&d).unwrap().unwrap();
444        let super::GlyphRef::Simple(simple) = g else {
445            panic!("expected simple glyph");
446        };
447        assert_eq!(simple.num_contours(), 1);
448        assert_eq!(simple.bounds().unwrap(), [0, 100, 300, 200]);
449        assert_eq!(simple.end_points().unwrap(), vec![2]);
450        let pts = simple.points().unwrap();
451        assert_eq!(
452            pts,
453            vec![
454                OutlinePoint {
455                    x: 100.0,
456                    y: 0.0,
457                    on_curve: true
458                },
459                OutlinePoint {
460                    x: 100.0,
461                    y: 200.0,
462                    on_curve: true
463                },
464                OutlinePoint {
465                    x: 200.0,
466                    y: 0.0,
467                    on_curve: true
468                },
469            ]
470        );
471        let outline: GlyphOutline = simple.outline().unwrap();
472        assert_eq!(outline.contours.len(), 1);
473        assert_eq!(outline.point_count(), 3);
474    }
475
476    #[test]
477    fn repeat_flags_and_off_curve() {
478        // Two points sharing coordinates via the flag repeat mechanism.
479        let mut g = Vec::new();
480        g.extend_from_slice(&1i16.to_be_bytes());
481        g.extend_from_slice(&0i16.to_be_bytes());
482        g.extend_from_slice(&0i16.to_be_bytes());
483        g.extend_from_slice(&200i16.to_be_bytes());
484        g.extend_from_slice(&100i16.to_be_bytes());
485        g.extend_from_slice(&1u16.to_be_bytes()); // endPts [1]
486        g.extend_from_slice(&0u16.to_be_bytes());
487        // 0x3F = on-curve + x/y short positive + repeat; one repeat -> 2 points.
488        g.extend_from_slice(&[0x3F, 1]);
489        g.extend_from_slice(&[100, 100]); // x short (per point)
490        g.extend_from_slice(&[200, 200]); // y short (per point)
491        let glyph = GlyphRef::parse(&g).unwrap().unwrap();
492        let super::GlyphRef::Simple(simple) = glyph else {
493            panic!("expected simple");
494        };
495        let pts = simple.points().unwrap();
496        // Deltas accumulate: p0 (100, 200), p1 (+100, +200).
497        assert_eq!(
498            pts,
499            vec![
500                OutlinePoint {
501                    x: 100.0,
502                    y: 200.0,
503                    on_curve: true
504                },
505                OutlinePoint {
506                    x: 200.0,
507                    y: 400.0,
508                    on_curve: true
509                },
510            ]
511        );
512    }
513
514    #[test]
515    fn composite_components_and_flags() {
516        // Composite referencing gid 7 with point-matched args (words) and a
517        // 2x2 transform.
518        let mut d = Vec::new();
519        d.extend_from_slice(&(-1i16).to_be_bytes());
520        d.extend_from_slice(&0i16.to_be_bytes());
521        d.extend_from_slice(&0i16.to_be_bytes());
522        d.extend_from_slice(&400i16.to_be_bytes());
523        d.extend_from_slice(&400i16.to_be_bytes());
524        // flags: ARGS_ARE_WORDS | WE_HAVE_A_TWO_BY_TWO (no MORE)
525        let flags: u16 = 0x0001 | 0x0080;
526        d.extend_from_slice(&(flags | 0x0100u16).to_be_bytes()); // + instructions
527        d.extend_from_slice(&7u16.to_be_bytes());
528        d.extend_from_slice(&3i16.to_be_bytes()); // arg1 (word, point index)
529        d.extend_from_slice(&9i16.to_be_bytes());
530        // 2x2 F2Dot14: a=1.0 (0x4000), b=0, c=0, d=0.5 (0x2000)
531        d.extend_from_slice(&0x4000i16.to_be_bytes());
532        d.extend_from_slice(&0i16.to_be_bytes());
533        d.extend_from_slice(&0i16.to_be_bytes());
534        d.extend_from_slice(&0x2000i16.to_be_bytes());
535        d.extend_from_slice(&2u16.to_be_bytes()); // instruction length
536        d.extend_from_slice(&[0xAA, 0xBB]);
537        let glyph = GlyphRef::parse(&d).unwrap().unwrap();
538        let super::GlyphRef::Composite(composite) = glyph else {
539            panic!("expected composite");
540        };
541        let comps: Vec<Component> = composite.components().unwrap();
542        assert_eq!(comps.len(), 1);
543        let c = comps[0];
544        assert_eq!(c.glyph, GlyphId::new(7));
545        assert!(!c.args_are_offsets());
546        assert_eq!(c.args, (3, 9));
547        assert!((c.transform[0] - 1.0).abs() < 1e-6);
548        assert!((c.transform[3] - 0.5).abs() < 1e-6);
549        assert_eq!(composite.bounds().unwrap(), [0, 0, 400, 400]);
550    }
551
552    #[test]
553    fn malformed_records() {
554        // nContours < -1 is invalid (after the 10-byte header).
555        let mut d = Vec::new();
556        d.extend_from_slice(&(-3i16).to_be_bytes());
557        d.extend_from_slice(&[0u8; 9]);
558        assert!(matches!(
559            GlyphRef::parse(&d),
560            Err(ParseError::InvalidGlyphFormat)
561        ));
562        // Short header.
563        assert!(matches!(
564            GlyphRef::parse(&[0, 1, 0]),
565            Err(ParseError::TruncatedTable { .. })
566        ));
567        // Empty record range -> None.
568        assert!(GlyphRef::parse(&[]).unwrap().is_none());
569        // Simple glyph whose endPts exceed the data.
570        let mut g = triangle();
571        g[10..12].copy_from_slice(&50u16.to_be_bytes()); // endPts [50]
572        let glyph = GlyphRef::parse(&g).unwrap().unwrap();
573        let super::GlyphRef::Simple(simple) = glyph else {
574            panic!("expected simple");
575        };
576        assert!(simple.points().is_err()); // flag/x stream runs off the record
577        let _ = SimpleGlyph::parse(&g).unwrap().num_contours();
578    }
579}