Skip to main content

font_parse/
font.rs

1//! Font containers: [`FontRef`] (zero-copy), [`OwnedFont`], and
2//! [`FontCollection`] (TTC).
3
4use crate::error::{ParseError, RawTag};
5use crate::reader::Reader;
6use crate::tables;
7use crate::tables::glyf::{GlyphOutline, GlyphRef, MAX_COMPONENT_DEPTH, MAX_OUTLINE_POINTS};
8use crate::tables::{Cmap, HeadTable};
9use crate::tag::TableTag;
10use alloc::vec::Vec;
11use font_types::{F2Dot14, GlyphId, Tag};
12
13const SFNT_VERSION_TRUE: u32 = 0x0001_0000;
14const SFNT_VERSION_OTTO: u32 = 0x4F54_544F; // 'OTTO'
15const SFNT_VERSION_TRUE_APPLE: u32 = 0x7472_7565; // 'true'
16const TTC_TAG: RawTag = *b"ttcf";
17const SFNT_TAG: RawTag = *b"sfnt";
18
19/// Directory-entry size.
20const ENTRY: usize = 16;
21
22fn is_known_sfnt_version(version: u32) -> bool {
23    matches!(
24        version,
25        SFNT_VERSION_TRUE | SFNT_VERSION_OTTO | SFNT_VERSION_TRUE_APPLE
26    )
27}
28
29/// Zero-copy reference over an SFNT font.
30///
31/// The reference borrows the whole byte buffer; table access is a lifetime-
32/// bound slice — nothing is copied, nothing is allocated. Views obtained
33/// from it (typed tables, outlines) die with the borrow.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct FontRef<'a> {
36    data: &'a [u8],
37    /// Offset of the 12-byte offset table within `data` (non-zero for fonts
38    /// inside a TTC, whose table offsets are file-relative).
39    dir_offset: usize,
40    num_tables: u16,
41    sfnt_version: u32,
42}
43
44impl<'a> FontRef<'a> {
45    /// Parse and validate the SFNT offset table and every table-directory
46    /// entry.
47    ///
48    /// Accepts TrueType (`0x00010000`, `'true'`) and CFF-flavored (`'OTTO'`)
49    /// fonts; for collections ('ttcf') use [`FontCollection`].
50    ///
51    /// # Errors
52    /// [`ParseError::InvalidSfnt`] for a bad signature or zero table count;
53    /// [`ParseError::TruncatedTable`] for a truncated directory or an entry
54    /// whose `offset + length` exceeds the buffer.
55    pub fn new(data: &'a [u8]) -> Result<Self, ParseError> {
56        let mut r = Reader::new(data, SFNT_TAG);
57        let version = r.u32()?;
58        if !is_known_sfnt_version(version) {
59            return Err(ParseError::InvalidSfnt);
60        }
61        let num_tables = r.u16()?;
62        if num_tables == 0 {
63            return Err(ParseError::InvalidSfnt);
64        }
65        r.skip(6)?; // searchRange, entrySelector, rangeShift (informational)
66        validate_directory(data, 0, num_tables)?;
67        Ok(Self {
68            data,
69            dir_offset: 0,
70            num_tables,
71            sfnt_version: version,
72        })
73    }
74
75    /// The whole borrowed buffer.
76    #[must_use]
77    pub fn as_bytes(&self) -> &'a [u8] {
78        self.data
79    }
80
81    /// The `sfntVersion` field (`0x00010000`, `'OTTO'`, `'true'`).
82    #[must_use]
83    pub const fn sfnt_version(&self) -> u32 {
84        self.sfnt_version
85    }
86
87    /// True for CFF-outline ('OTTO') fonts — `glyf`/`loca` are absent.
88    #[must_use]
89    pub const fn is_cff(&self) -> bool {
90        self.sfnt_version == SFNT_VERSION_OTTO
91    }
92
93    /// True when the font declares variable-font tables (`fvar`).
94    #[must_use]
95    pub fn is_variable(&self) -> bool {
96        self.table(TableTag::Fvar).is_some()
97    }
98
99    /// Number of directory entries.
100    #[must_use]
101    pub const fn num_tables(&self) -> u16 {
102        self.num_tables
103    }
104
105    /// Raw bytes of a known table (`None` when absent).
106    #[must_use]
107    pub fn table(&self, tag: TableTag) -> Option<&'a [u8]> {
108        self.table_by_tag(tag.to_tag())
109    }
110
111    /// Raw bytes of an arbitrary table by raw tag.
112    #[must_use]
113    pub fn table_by_tag(&self, tag: Tag) -> Option<&'a [u8]> {
114        let want = tag.to_be_bytes();
115        for i in 0..usize::from(self.num_tables) {
116            let at = self.dir_offset + 12 + i * ENTRY;
117            let found = crate::reader::slice_at(self.data, at, 4, SFNT_TAG).ok()?;
118            if found == want {
119                let offset = crate::reader::be_u32_at(self.data, at + 8, SFNT_TAG).ok()?;
120                let length = crate::reader::be_u32_at(self.data, at + 12, SFNT_TAG).ok()?;
121                let offset = usize::try_from(offset).ok()?;
122                let length = usize::try_from(length).ok()?;
123                let end = offset.checked_add(length)?;
124                return self.data.get(offset..end);
125            }
126        }
127        None
128    }
129
130    /// All directory entries as `(tag, checksum, offset, length)`, in
131    /// directory order. Tags are raw four-byte values (known or not).
132    #[must_use]
133    pub fn table_directory(&self) -> Vec<(RawTag, u32, u32, u32)> {
134        let mut out = Vec::with_capacity(usize::from(self.num_tables));
135        for i in 0..usize::from(self.num_tables) {
136            let at = self.dir_offset + 12 + i * ENTRY;
137            let (Ok(raw_tag), Ok(checksum), Ok(offset), Ok(length)) = (
138                crate::reader::be_u32_at(self.data, at, SFNT_TAG),
139                crate::reader::be_u32_at(self.data, at + 4, SFNT_TAG),
140                crate::reader::be_u32_at(self.data, at + 8, SFNT_TAG),
141                crate::reader::be_u32_at(self.data, at + 12, SFNT_TAG),
142            ) else {
143                continue;
144            };
145            out.push((raw_tag.to_be_bytes(), checksum, offset, length));
146        }
147        out
148    }
149
150    // -- typed required tables ------------------------------------------
151
152    fn table_or_err(&self, tag: TableTag) -> Result<&'a [u8], ParseError> {
153        self.table(tag)
154            .ok_or(ParseError::UnknownTableTag(tag.to_bytes()))
155    }
156
157    /// `head` — units per em, loca format, style flags.
158    ///
159    /// # Errors
160    /// Missing table ([`ParseError::UnknownTableTag`]) or parse errors.
161    pub fn head(&self) -> Result<HeadTable<'a>, ParseError> {
162        HeadTable::parse(self.table_or_err(TableTag::Head)?)
163    }
164
165    /// `hhea` — horizontal header.
166    ///
167    /// # Errors
168    /// Missing table or parse errors.
169    pub fn hhea(&self) -> Result<tables::HheaTable<'a>, ParseError> {
170        tables::HheaTable::parse(self.table_or_err(TableTag::Hhea)?)
171    }
172
173    /// `hmtx` — advance widths and side bearings (wired to `hhea` + `maxp`).
174    ///
175    /// # Errors
176    /// Missing tables or parse errors.
177    pub fn hmtx(&self) -> Result<tables::HmtxTable<'a>, ParseError> {
178        let num_h_metrics = self.hhea()?.number_of_h_metrics()?;
179        tables::HmtxTable::parse(
180            self.table_or_err(TableTag::Hmtx)?,
181            num_h_metrics,
182            self.num_glyphs(),
183        )
184    }
185
186    /// `maxp` — glyph count and memory hints.
187    ///
188    /// # Errors
189    /// Missing table or parse errors.
190    pub fn maxp(&self) -> Result<tables::MaxpTable<'a>, ParseError> {
191        tables::MaxpTable::parse(self.table_or_err(TableTag::Maxp)?)
192    }
193
194    /// Glyph count (0 when `maxp` is absent or invalid).
195    #[must_use]
196    pub fn num_glyphs(&self) -> u16 {
197        self.table(TableTag::Maxp)
198            .and_then(|d| tables::MaxpTable::parse(d).ok())
199            .map_or(0, |m| m.num_glyphs())
200    }
201
202    /// `cmap` — character-to-glyph mapping.
203    ///
204    /// # Errors
205    /// Missing table or parse errors.
206    pub fn cmap(&self) -> Result<Cmap<'a>, ParseError> {
207        Cmap::parse(self.table_or_err(TableTag::Cmap)?)
208    }
209
210    /// `name` — naming table.
211    ///
212    /// # Errors
213    /// Missing table or parse errors.
214    pub fn name(&self) -> Result<tables::NameTable<'a>, ParseError> {
215        tables::NameTable::parse(self.table_or_err(TableTag::Name)?)
216    }
217
218    /// `OS/2` — weight/width classes and metrics.
219    ///
220    /// # Errors
221    /// Missing table or parse errors.
222    pub fn os2(&self) -> Result<tables::Os2Table<'a>, ParseError> {
223        tables::Os2Table::parse(self.table_or_err(TableTag::Os2)?)
224    }
225
226    /// `post` — PostScript names and italic angle.
227    ///
228    /// # Errors
229    /// Missing table or parse errors.
230    pub fn post(&self) -> Result<tables::PostTable<'a>, ParseError> {
231        tables::PostTable::parse(self.table_or_err(TableTag::Post)?)
232    }
233
234    // -- optional tables -------------------------------------------------
235
236    /// `stat` — style attributes.
237    ///
238    /// # Errors
239    /// Missing table or parse errors.
240    pub fn stat(&self) -> Result<tables::StatTable<'a>, ParseError> {
241        tables::StatTable::parse(self.table_or_err(TableTag::Stat)?)
242    }
243
244    /// `DSIG` — digital signature (header only).
245    ///
246    /// # Errors
247    /// Missing table or parse errors.
248    pub fn dsig(&self) -> Result<tables::DsigTable<'a>, ParseError> {
249        tables::DsigTable::parse(self.table_or_err(TableTag::Dsig)?)
250    }
251
252    /// `GSUB`/`GPOS` layout structure by kind.
253    ///
254    /// # Errors
255    /// Missing table ([`ParseError::UnknownTableTag`]) or parse errors.
256    pub fn layout(&self, kind: tables::LayoutKind) -> Result<tables::LayoutTable<'a>, ParseError> {
257        let tag = kind.tag();
258        let data = self
259            .table_by_tag(Tag::new(&tag))
260            .ok_or(ParseError::UnknownTableTag(tag))?;
261        tables::LayoutTable::parse(data, kind)
262    }
263
264    /// `fvar` + optional `avar`/`gvar` — the variable-font view.
265    ///
266    /// # Errors
267    /// Missing `fvar` or parse errors.
268    pub fn variable(&self) -> Result<VariableFont<'a>, ParseError> {
269        let fvar = tables::FvarTable::parse(self.table_or_err(TableTag::Fvar)?)?;
270        let avar = self
271            .table(TableTag::Avar)
272            .map(tables::AvarTable::parse)
273            .transpose()?;
274        let gvar = self
275            .table(TableTag::Gvar)
276            .map(|d| tables::GvarTable::parse(d, self.num_glyphs()))
277            .transpose()?;
278        Ok(VariableFont {
279            font: *self,
280            fvar,
281            avar,
282            gvar,
283        })
284    }
285
286    // -- glyph access -----------------------------------------------------
287
288    /// Byte range of glyph `gid` within `glyf` (`None` = empty glyph or an
289    /// id beyond `numGlyphs`).
290    ///
291    /// # Errors
292    /// Missing `glyf`/`loca` tables or malformed loca entries.
293    pub fn glyph_data(&self, gid: GlyphId) -> Result<Option<&'a [u8]>, ParseError> {
294        let Some(range) = self.locus(gid)? else {
295            return Ok(None);
296        };
297        let glyf = self.table_or_err(TableTag::Glyf)?;
298        Ok(glyf.get(range.start..range.end))
299    }
300
301    /// Parse glyph `gid` (simple or composite view; `None` = empty).
302    ///
303    /// # Errors
304    /// Missing tables or malformed glyph records.
305    pub fn glyph(&self, gid: GlyphId) -> Result<Option<GlyphRef<'a>>, ParseError> {
306        match self.glyph_data(gid)? {
307            None => Ok(None),
308            Some(data) => GlyphRef::parse(data),
309        }
310    }
311
312    /// The `loca` table wired to `head` + `maxp`.
313    fn loca(&self) -> Result<tables::LocaTable<'a>, ParseError> {
314        let long = self.head()?.index_to_loc_format()? == 1;
315        tables::LocaTable::parse(self.table_or_err(TableTag::Loca)?, self.num_glyphs(), long)
316    }
317
318    /// Resolve `gid` to a byte range in `glyf`, or `None` for empty or
319    /// out-of-range ids (ids beyond `u16::MAX` included).
320    fn locus(&self, gid: GlyphId) -> Result<Option<core::ops::Range<usize>>, ParseError> {
321        let Ok(id) = u16::try_from(gid.to_u32()) else {
322            return Ok(None);
323        };
324        self.loca()?.glyph_range(id)
325    }
326
327    /// Advance width for `gid` via `hmtx`.
328    ///
329    /// # Errors
330    /// Missing tables or malformed `hmtx`.
331    pub fn advance_width(&self, gid: GlyphId) -> Result<u16, ParseError> {
332        let Ok(id) = u16::try_from(gid.to_u32()) else {
333            return Ok(0); // glyph 0 (.notdef) convention for absurd ids
334        };
335        self.hmtx()?.advance(id)
336    }
337
338    /// Fully resolved outline for `gid`: composite components (with their
339    /// 2x2 transforms and offsets) are applied recursively.
340    ///
341    /// Returns `None` for empty glyphs or ids beyond `numGlyphs`. The result
342    /// is allocated (points in font units); table access stays zero-copy.
343    /// Point-matched composites (no `ARGS_ARE_XY_VALUES`) place components
344    /// at the origin — full point matching is a rendering concern and out of
345    /// scope for a parser.
346    ///
347    /// # Errors
348    /// Malformed glyph records, or a composite nest that exceeds the depth
349    /// cap ([`MAX_COMPONENT_DEPTH`]) or the point budget
350    /// ([`MAX_OUTLINE_POINTS`]).
351    pub fn outline(&self, gid: GlyphId) -> Result<Option<GlyphOutline>, ParseError> {
352        self.outline_bounded(gid, 0, &mut 0)
353    }
354
355    fn outline_bounded(
356        &self,
357        gid: GlyphId,
358        depth: u8,
359        budget: &mut usize,
360    ) -> Result<Option<GlyphOutline>, ParseError> {
361        if depth > MAX_COMPONENT_DEPTH {
362            return Err(ParseError::InvalidGlyphFormat);
363        }
364        let Some(glyph) = self.glyph(gid)? else {
365            return Ok(None);
366        };
367        match glyph {
368            GlyphRef::Simple(simple) => {
369                let outline = simple.outline()?;
370                *budget = budget.saturating_add(outline.point_count());
371                if *budget > MAX_OUTLINE_POINTS {
372                    return Err(ParseError::InvalidGlyphFormat);
373                }
374                Ok(Some(outline))
375            }
376            GlyphRef::Composite(composite) => {
377                let mut contours = Vec::new();
378                for component in composite.components()? {
379                    *budget = budget.saturating_add(1);
380                    if *budget > MAX_OUTLINE_POINTS {
381                        return Err(ParseError::InvalidGlyphFormat);
382                    }
383                    let Some(inner) = self.outline_bounded(component.glyph, depth + 1, budget)?
384                    else {
385                        continue;
386                    };
387                    let (dx, dy) = if component.args_are_offsets() {
388                        (
389                            f32::from(i16::try_from(component.args.0).unwrap_or(0)),
390                            f32::from(i16::try_from(component.args.1).unwrap_or(0)),
391                        )
392                    } else {
393                        // Point-matched components: see `outline` docs.
394                        (0.0, 0.0)
395                    };
396                    let [a, b, c, d] = component.transform;
397                    for mut contour in inner.contours {
398                        for pt in &mut contour.points {
399                            let x = a * pt.x + c * pt.y + dx;
400                            let y = b * pt.x + d * pt.y + dy;
401                            pt.x = x;
402                            pt.y = y;
403                        }
404                        contours.push(contour);
405                    }
406                }
407                Ok(Some(GlyphOutline { contours }))
408            }
409        }
410    }
411
412    /// Variable-font deltas for `gid` via `gvar` (empty vec when the font is
413    /// not variable or the glyph has no deltas). The glyph's point count is
414    /// resolved from `glyf` automatically.
415    ///
416    /// # Errors
417    /// Malformed gvar data.
418    pub fn gvar_deltas(&self, gid: GlyphId) -> Result<Vec<tables::TupleVariation>, ParseError> {
419        let Some(gvar) = self.table(TableTag::Gvar) else {
420            return Ok(Vec::new());
421        };
422        let point_count = self.outline_point_count(gid)?;
423        let gvar = tables::GvarTable::parse(gvar, self.num_glyphs())?;
424        let Ok(id) = u16::try_from(gid.to_u32()) else {
425            return Ok(Vec::new());
426        };
427        gvar.glyph_deltas(id, point_count)
428    }
429
430    /// Point count of `gid`'s glyph record for gvar sizing: outline points
431    /// (components for composites) **plus the 4 phantom points** every glyph
432    /// carries in variation data ("apply to all points" tuples encode a
433    /// delta for each of them).
434    fn outline_point_count(&self, gid: GlyphId) -> Result<u16, ParseError> {
435        let Some(data) = self.glyph_data(gid)? else {
436            return Ok(4); // empty glyph: phantom points only
437        };
438        let n = match GlyphRef::parse(data)? {
439            None => 0,
440            Some(GlyphRef::Simple(s)) => {
441                let pts = s.points()?;
442                usize::from(u16::try_from(pts.len()).map_err(|_| ParseError::InvalidGlyphFormat)?)
443            }
444            Some(GlyphRef::Composite(c)) => {
445                let comps = c.components()?;
446                usize::from(u16::try_from(comps.len()).map_err(|_| ParseError::InvalidGlyphFormat)?)
447            }
448        };
449        u16::try_from(n + 4).map_err(|_| ParseError::InvalidGlyphFormat)
450    }
451}
452
453/// An owned font buffer, validated at construction.
454///
455/// The allocating counterpart of [`FontRef`]: produced by SFNT validation of
456/// an owned buffer, WOFF/WOFF2 decoding, or extraction from a collection.
457/// Access the zero-copy view with [`as_font_ref`](Self::as_font_ref).
458#[derive(Debug, Clone)]
459pub struct OwnedFont {
460    data: Vec<u8>,
461}
462
463impl OwnedFont {
464    /// Validate an owned SFNT buffer.
465    ///
466    /// # Errors
467    /// See [`FontRef::new`].
468    pub fn from_sfnt(data: Vec<u8>) -> Result<Self, ParseError> {
469        FontRef::new(&data)?;
470        Ok(Self { data })
471    }
472
473    /// Decode a WOFF 1.0 container (feature `woff`).
474    ///
475    /// # Errors
476    /// [`ParseError::InvalidSfnt`] for a bad header, table, or zlib stream.
477    #[cfg(feature = "woff")]
478    pub fn from_woff(data: &[u8]) -> Result<Self, ParseError> {
479        crate::woff::decode(data)
480    }
481
482    /// Decode a WOFF 2.0 container, reversing the glyf/loca/hmtx transforms
483    /// (feature `woff2`).
484    ///
485    /// # Errors
486    /// [`ParseError::InvalidSfnt`] for container errors;
487    /// [`ParseError::UnsupportedWoff2Transform`] for undefined transform
488    /// versions; [`ParseError::InvalidGlyphFormat`] for glyph-transform
489    /// inconsistencies.
490    #[cfg(feature = "woff2")]
491    pub fn from_woff2(data: &[u8]) -> Result<Self, ParseError> {
492        crate::woff2::decode(data)
493    }
494
495    /// Extract font `index` from a TTC collection into a standalone SFNT.
496    ///
497    /// # Errors
498    /// [`ParseError::InvalidSfnt`] for a bad TTC header;
499    /// [`ParseError::CollectionIndexOutOfBounds`] when `index` is beyond the
500    /// declared font count.
501    pub fn from_collection(data: &[u8], index: usize) -> Result<Self, ParseError> {
502        let collection = FontCollection::parse(data)?;
503        let font = collection.font(index)?;
504        let mut tables_to_build: Vec<(RawTag, Vec<u8>)> = Vec::new();
505        for (tag, _checksum, offset, length) in font.table_directory() {
506            let off = usize::try_from(offset).map_err(|_| ParseError::InvalidSfnt)?;
507            let len = usize::try_from(length).map_err(|_| ParseError::InvalidSfnt)?;
508            let bytes = crate::reader::slice_at(font.data, off, len, tag)?;
509            tables_to_build.push((tag, bytes.to_vec()));
510        }
511        let flavor = font.sfnt_version();
512        build_sfnt(flavor, &mut tables_to_build).map(|data| Self { data })
513    }
514
515    /// The zero-copy view over the owned buffer.
516    ///
517    /// # Errors
518    /// [`ParseError::InvalidSfnt`] — structurally impossible (the buffer was
519    /// validated at construction), kept for API symmetry with fallible
520    /// constructors.
521    pub fn as_font_ref(&self) -> Result<FontRef<'_>, ParseError> {
522        FontRef::new(&self.data)
523    }
524
525    /// The owned buffer.
526    #[must_use]
527    pub fn as_slice(&self) -> &[u8] {
528        &self.data
529    }
530
531    /// Consume into the raw buffer.
532    #[must_use]
533    pub fn into_vec(self) -> Vec<u8> {
534        self.data
535    }
536}
537
538/// A parsed TTC collection: N font directories sharing table data.
539#[derive(Debug, Clone)]
540pub struct FontCollection<'a> {
541    data: &'a [u8],
542    offsets: Vec<usize>,
543    version: u32,
544}
545
546impl<'a> FontCollection<'a> {
547    /// Parse and validate the TTC header.
548    ///
549    /// # Errors
550    /// [`ParseError::InvalidSfnt`] for a bad signature or version;
551    /// [`ParseError::TruncatedTable`] when the offset array is short.
552    pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
553        if data.len() < 12 {
554            return Err(ParseError::TruncatedTable {
555                tag: TTC_TAG,
556                expected: 12,
557                got: data.len(),
558            });
559        }
560        let tag = crate::reader::slice_at(data, 0, 4, TTC_TAG)?;
561        if tag != TTC_TAG.as_slice() {
562            return Err(ParseError::InvalidSfnt);
563        }
564        let version = crate::reader::be_u32_at(data, 4, TTC_TAG)?;
565        let num = crate::reader::be_u32_at(data, 8, TTC_TAG)?;
566        let num = usize::try_from(num).map_err(|_| ParseError::InvalidSfnt)?;
567        let end = 12usize
568            .checked_add(num.checked_mul(4).ok_or(ParseError::InvalidSfnt)?)
569            .ok_or(ParseError::InvalidSfnt)?;
570        if data.len() < end {
571            return Err(ParseError::TruncatedTable {
572                tag: TTC_TAG,
573                expected: end,
574                got: data.len(),
575            });
576        }
577        let mut offsets = Vec::with_capacity(num);
578        for i in 0..num {
579            let off = crate::reader::be_u32_at(data, 12 + i * 4, TTC_TAG)?;
580            let off = usize::try_from(off).map_err(|_| ParseError::InvalidSfnt)?;
581            offsets.push(off);
582        }
583        Ok(Self {
584            data,
585            offsets,
586            version,
587        })
588    }
589
590    /// The TTC version (`0x00010000` or `0x00020000`).
591    #[must_use]
592    pub const fn version(&self) -> u32 {
593        self.version
594    }
595
596    /// Number of fonts in the collection.
597    #[must_use]
598    pub fn len(&self) -> usize {
599        self.offsets.len()
600    }
601
602    /// True when the collection declares no fonts.
603    #[must_use]
604    pub fn is_empty(&self) -> bool {
605        self.offsets.is_empty()
606    }
607
608    /// Font `index` as a zero-copy reference over the whole collection
609    /// buffer (TTC table offsets are file-relative, so sharing works).
610    ///
611    /// # Errors
612    /// [`ParseError::CollectionIndexOutOfBounds`] beyond the font count;
613    /// [`ParseError::InvalidSfnt`] / [`ParseError::TruncatedTable`] for a
614    /// malformed directory.
615    pub fn font(&self, index: usize) -> Result<FontRef<'a>, ParseError> {
616        let dir_offset =
617            *self
618                .offsets
619                .get(index)
620                .ok_or(ParseError::CollectionIndexOutOfBounds {
621                    index,
622                    count: self.offsets.len(),
623                })?;
624        let sub = self.data.get(dir_offset..).ok_or(ParseError::InvalidSfnt)?;
625        let mut r = Reader::new(sub, TTC_TAG);
626        let version = r.u32()?;
627        if !is_known_sfnt_version(version) {
628            return Err(ParseError::InvalidSfnt);
629        }
630        let num_tables = r.u16()?;
631        if num_tables == 0 {
632            return Err(ParseError::InvalidSfnt);
633        }
634        r.skip(6)?;
635        validate_directory(self.data, dir_offset, num_tables)?;
636        Ok(FontRef {
637            data: self.data,
638            dir_offset,
639            num_tables,
640            sfnt_version: version,
641        })
642    }
643
644    /// All fonts (see [`font`](Self::font)).
645    ///
646    /// # Errors
647    /// First error from any font directory.
648    pub fn fonts(&self) -> Result<Vec<FontRef<'a>>, ParseError> {
649        let mut out = Vec::with_capacity(self.offsets.len());
650        for i in 0..self.offsets.len() {
651            out.push(self.font(i)?);
652        }
653        Ok(out)
654    }
655
656    /// One-shot parse of a TTC buffer into font references.
657    ///
658    /// # Errors
659    /// See [`FontCollection::parse`] / [`fonts`](Self::fonts).
660    pub fn fonts_in(data: &'a [u8]) -> Result<Vec<FontRef<'a>>, ParseError> {
661        Self::parse(data)?.fonts()
662    }
663}
664
665/// Validate a table directory (at `dir_offset` in `data`) entry by entry.
666fn validate_directory(data: &[u8], dir_offset: usize, num_tables: u16) -> Result<(), ParseError> {
667    let dir_end = dir_offset
668        .checked_add(12 + usize::from(num_tables) * ENTRY)
669        .ok_or(ParseError::InvalidSfnt)?;
670    if data.len() < dir_end {
671        return Err(ParseError::TruncatedTable {
672            tag: SFNT_TAG,
673            expected: dir_end,
674            got: data.len(),
675        });
676    }
677    for i in 0..usize::from(num_tables) {
678        let at = dir_offset + 12 + i * ENTRY;
679        let offset = crate::reader::be_u32_at(data, at + 8, SFNT_TAG)?;
680        let length = crate::reader::be_u32_at(data, at + 12, SFNT_TAG)?;
681        let offset = usize::try_from(offset).map_err(|_| ParseError::InvalidSfnt)?;
682        let length = usize::try_from(length).map_err(|_| ParseError::InvalidSfnt)?;
683        let end = offset.checked_add(length).ok_or(ParseError::InvalidSfnt)?;
684        if end > data.len() {
685            let mut tag: RawTag = *b"????";
686            if let Some(found) = data.get(at..at + 4) {
687                tag.copy_from_slice(found);
688            }
689            return Err(ParseError::TruncatedTable {
690                tag,
691                expected: end,
692                got: data.len(),
693            });
694        }
695    }
696    Ok(())
697}
698
699/// The variable-font view: `fvar` axes and instances plus optional `avar`
700/// segment maps and `gvar` glyph deltas.
701#[derive(Debug, Clone, Copy)]
702pub struct VariableFont<'a> {
703    font: FontRef<'a>,
704    fvar: tables::FvarTable<'a>,
705    avar: Option<tables::AvarTable<'a>>,
706    gvar: Option<tables::GvarTable<'a>>,
707}
708
709impl<'a> VariableFont<'a> {
710    /// Design axes (tag, min, default, max, flags, name id).
711    ///
712    /// # Errors
713    /// Truncated axis array.
714    pub fn axes(&self) -> Result<Vec<tables::VariationAxis>, ParseError> {
715        self.fvar.axes()
716    }
717
718    /// Named instances (name id + per-axis coordinates).
719    ///
720    /// # Errors
721    /// Truncated instance array.
722    pub fn instances(&self) -> Result<Vec<tables::VarInstance>, ParseError> {
723        self.fvar.instances()
724    }
725
726    /// The `avar` table, when present.
727    #[must_use]
728    pub const fn avar(&self) -> Option<tables::AvarTable<'a>> {
729        self.avar
730    }
731
732    /// The `gvar` table, when present.
733    #[must_use]
734    pub const fn gvar(&self) -> Option<tables::GvarTable<'a>> {
735        self.gvar
736    }
737
738    /// The underlying font reference.
739    #[must_use]
740    pub const fn font(&self) -> FontRef<'a> {
741        self.font
742    }
743
744    /// Normalize a user coordinate to the [-1, 1] (`F2Dot14`) design-space
745    /// scale, applying `avar` segment mapping when present.
746    ///
747    /// # Errors
748    /// [`ParseError::InvalidGlyphFormat`] for an out-of-range axis index;
749    /// truncated `avar` maps otherwise.
750    pub fn normalize(&self, axis: usize, value: font_types::Fixed) -> Result<F2Dot14, ParseError> {
751        let axes = self.fvar.axes()?;
752        let axis_rec = axes.get(axis).ok_or(ParseError::InvalidGlyphFormat)?;
753        let min = axis_rec.min.to_f64();
754        let def = axis_rec.default.to_f64();
755        let max = axis_rec.max.to_f64();
756        let v = value.to_f64();
757        // Spec normalization: lower half then upper half, clamped to [-1, 1].
758        // Degenerate halves pin to the extreme (fontTools varLib convention).
759        let normalized: f64 = if v < def {
760            if (def - min).abs() < f64::EPSILON {
761                -1.0
762            } else {
763                (v - def) / (def - min)
764            }
765        } else if (max - def).abs() < f64::EPSILON {
766            1.0
767        } else {
768            (v - def) / (max - def)
769        };
770        // Round half away from zero without std: the float->int `as` cast
771        // truncates toward zero, and core has no f64::round/trunc.
772        let scaled = normalized.clamp(-1.0, 1.0) * 16_384.0;
773        let shifted = if scaled < 0.0 {
774            scaled - 0.5
775        } else {
776            scaled + 0.5
777        };
778        let bits_wide = shifted as i64; // in [-16385, 16385); truncation = round
779        let bits = i16::try_from(bits_wide).map_err(|_| ParseError::InvalidGlyphFormat)?;
780        let coord = F2Dot14::from_bits(bits);
781        match self.avar {
782            Some(avar) => {
783                let maps = avar.segment_maps()?;
784                Ok(maps.get(axis).map_or(coord, |m| m.map(coord)))
785            }
786            None => Ok(coord),
787        }
788    }
789}
790
791/// Assemble a standalone SFNT from `(tag, bytes)` pairs: sorted directory,
792/// computed checksums, and a correct `head` checkSumAdjustment.
793pub(crate) fn build_sfnt(
794    flavor: u32,
795    tables_in: &mut [(RawTag, Vec<u8>)],
796) -> Result<Vec<u8>, ParseError> {
797    if tables_in.is_empty() {
798        return Err(ParseError::InvalidSfnt);
799    }
800    tables_in.sort_by_key(|t| t.0);
801    let n = tables_in.len();
802    let entry_selector = 31 - (n as u32).leading_zeros(); // floor(log2(n))
803    let search_range: u32 = 16 << entry_selector;
804    let range_shift = n as u32 * 16 - search_range;
805
806    let dir_len = 12 + n * ENTRY;
807    let mut out = Vec::with_capacity(dir_len + 1024);
808    out.extend_from_slice(&flavor.to_be_bytes());
809    out.extend_from_slice(&(n as u16).to_be_bytes());
810    out.extend_from_slice(&(search_range as u16).to_be_bytes());
811    out.extend_from_slice(&(entry_selector as u16).to_be_bytes());
812    out.extend_from_slice(&(range_shift as u16).to_be_bytes());
813
814    // Offsets: directory first, then 4-byte aligned tables.
815    let mut offset: u32 = dir_len as u32;
816    let mut entries = Vec::with_capacity(n);
817    for (tag, bytes) in tables_in.iter() {
818        entries.push((*tag, table_checksum(bytes), offset, bytes.len() as u32));
819        // Pad so the NEXT table starts 4-aligned (i.e. align this table's end).
820        let end = offset
821            .checked_add(bytes.len() as u32)
822            .ok_or(ParseError::InvalidSfnt)?;
823        let pad = (4 - (end % 4)) % 4;
824        offset = end.checked_add(pad).ok_or(ParseError::InvalidSfnt)?;
825    }
826    for (tag, checksum, off, len) in &entries {
827        out.extend_from_slice(tag);
828        out.extend_from_slice(&checksum.to_be_bytes());
829        out.extend_from_slice(&off.to_be_bytes());
830        out.extend_from_slice(&len.to_be_bytes());
831    }
832    for (_, bytes) in tables_in.iter() {
833        out.extend_from_slice(bytes);
834        while out.len() % 4 != 0 {
835            out.push(0);
836        }
837    }
838    // head.checkSumAdjustment: zero the field, checksum the whole font,
839    // store 0xB1B0AFBA - total.
840    let head_off = entries
841        .iter()
842        .find(|(t, _, _, _)| t == b"head")
843        .map(|(_, _, off, _)| *off as usize);
844    if let Some(head_at) = head_off {
845        set_bytes(&mut out, head_at + 8, &[0, 0, 0, 0])?;
846        let adjustment = 0xB1B0_AFBAu32.wrapping_sub(table_checksum(&out));
847        set_bytes(&mut out, head_at + 8, &adjustment.to_be_bytes())?;
848    }
849    Ok(out)
850}
851
852/// Write 4 bytes at `at`, bounds-checked (no panics).
853fn set_bytes(out: &mut [u8], at: usize, bytes: &[u8; 4]) -> Result<(), ParseError> {
854    out.get_mut(at..at + 4)
855        .ok_or(ParseError::InvalidSfnt)?
856        .copy_from_slice(bytes);
857    Ok(())
858}
859
860/// SFNT table checksum: u32 sum of big-endian words, zero-padded to 4.
861pub(crate) fn table_checksum(bytes: &[u8]) -> u32 {
862    let mut sum: u32 = 0;
863    let mut chunks = bytes.chunks_exact(4);
864    for c in chunks.by_ref() {
865        if let Ok(word) = <[u8; 4]>::try_from(c) {
866            sum = sum.wrapping_add(u32::from_be_bytes(word));
867        }
868    }
869    let rest = chunks.remainder();
870    if !rest.is_empty() {
871        let mut last = [0u8; 4];
872        for (i, &b) in rest.iter().enumerate() {
873            if let Some(slot) = last.get_mut(i) {
874                *slot = b;
875            }
876        }
877        sum = sum.wrapping_add(u32::from_be_bytes(last));
878    }
879    sum
880}