Skip to main content

read_fonts/
lib.rs

1//! Reading OpenType tables
2//!
3//! This crate provides memory safe zero-allocation parsing of font files.
4//! It is unopinionated, and attempts to provide raw access to the underlying
5//! font data as it is described in the [OpenType specification][spec].
6//!
7//! This crate is intended for use by other parts of a font stack, such as a
8//! shaping engine or a glyph rasterizer.
9//!
10//! In addition to raw data access, this crate may also provide reference
11//! implementations of algorithms for interpreting that data, where such an
12//! implementation is required for the data to be useful. For instance, we
13//! provide functions for [mapping codepoints to glyph identifiers][cmap-impl]
14//! using the `cmap` table, or for [decoding entries in the `name` table][NameString].
15//!
16//! For higher level/more ergonomic access to font data, you may want to look
17//! into using [`skrifa`] instead.
18//!
19//! ## Structure & codegen
20//!
21//! The root [`tables`] module contains a submodule for each supported
22//! [table][table-directory], and that submodule contains items for each table,
23//! record, flagset or enum described in the relevant portion of the spec.
24//!
25//! The majority of the code in the tables module is auto-generated. For more
26//! information on our use of codegen, see the [codegen tour].
27//!
28//! # Related projects
29//!
30//! - [`write-fonts`] is a companion crate for creating/modifying font files
31//! - [`skrifa`] provides access to glyph outlines and metadata (in the same vein
32//!   as [freetype])
33//!
34//! # Example
35//!
36//! ```no_run
37//! # let path_to_my_font_file = std::path::Path::new("");
38//! use read_fonts::{FontRef, TableProvider};
39//! let font_bytes = std::fs::read(path_to_my_font_file).unwrap();
40//! // Single fonts only. for font collections (.ttc) use FontRef::from_index
41//! let font = FontRef::new(&font_bytes).expect("failed to read font data");
42//! let head = font.head().expect("missing 'head' table");
43//! let maxp = font.maxp().expect("missing 'maxp' table");
44//!
45//! println!("font version {} containing {} glyphs", head.font_revision(), maxp.num_glyphs());
46//! ```
47//!
48//!
49//! [spec]: https://learn.microsoft.com/en-us/typography/opentype/spec/
50//! [codegen-tour]: https://github.com/googlefonts/fontations/blob/main/docs/codegen-tour.md
51//! [cmap-impl]: tables::cmap::Cmap::map_codepoint
52//! [`write-fonts`]: https://docs.rs/write-fonts/
53//! [`skrifa`]: https://docs.rs/skrifa/
54//! [freetype]: http://freetype.org
55//! [codegen tour]: https://github.com/googlefonts/fontations/blob/main/docs/codegen-tour.md
56//! [NameString]: tables::name::NameString
57//! [table-directory]: https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory
58
59#![cfg_attr(docsrs, feature(doc_cfg))]
60#![forbid(unsafe_code)]
61#![deny(rustdoc::broken_intra_doc_links)]
62#![cfg_attr(not(feature = "std"), no_std)]
63
64#[cfg(any(feature = "std", test))]
65#[macro_use]
66extern crate std;
67
68#[cfg(all(not(feature = "std"), not(test)))]
69#[macro_use]
70extern crate core as std;
71
72// Always depend on alloc. Perhaps make this a feature if someone really needs
73// heapless read-fonts.
74extern crate alloc;
75
76pub mod array;
77pub(crate) use array::impl_font_read_at;
78#[cfg(any(test, feature = "codegen_test"))]
79pub mod codegen_test;
80pub mod collections;
81mod font_data;
82pub mod limits;
83pub mod mem;
84pub mod model;
85mod offset;
86mod offset_array;
87pub mod ps;
88mod read;
89mod table_provider;
90mod table_ref;
91pub mod tables;
92
93pub use font_data::FontData;
94pub use offset::{Offset, ResolveNullableOffset, ResolveOffset};
95pub use offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
96pub use read::{ComputeSize, FontRead, FontReadAt, ReadArgs, ReadError, VarSize};
97pub use table_provider::{TableProvider, TopLevelTable};
98pub use table_ref::MinByteRange;
99
100/// Public re-export of the font-types crate.
101pub extern crate font_types as types;
102
103/// All the types that may be referenced in auto-generated code.
104#[doc(hidden)]
105pub(crate) mod codegen_prelude {
106    pub use crate::array::{ComputedArray, VarLenArray};
107    pub use crate::font_data::{Cursor, FontData};
108    pub use crate::offset::{Offset, ResolveNullableOffset, ResolveOffset};
109    pub use crate::offset_array::{ArrayOfNullableOffsets, ArrayOfOffsets};
110    pub use crate::read::{
111        ComputeSize, Discriminant, FontRead, FontReadAt, Format, ReadArgs, ReadError, VarSize,
112    };
113    pub use crate::table_provider::TopLevelTable;
114    pub use crate::table_ref::MinByteRange;
115    pub use std::ops::Range;
116
117    pub use types::*;
118
119    /// named transforms used in 'count', e.g
120    pub(crate) mod transforms {
121        pub fn to_usize<T: TryInto<usize>>(value: T) -> usize {
122            value.try_into().unwrap_or_default()
123        }
124
125        pub fn subtract<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
126            lhs.try_into()
127                .unwrap_or_default()
128                .saturating_sub(rhs.try_into().unwrap_or_default())
129        }
130
131        pub fn add<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
132            lhs.try_into()
133                .unwrap_or_default()
134                .saturating_add(rhs.try_into().unwrap_or_default())
135        }
136
137        #[allow(dead_code)]
138        pub fn bitmap_len<T: TryInto<usize>>(count: T) -> usize {
139            count.try_into().unwrap_or_default().div_ceil(8)
140        }
141
142        pub fn add_multiply<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
143            a: T,
144            b: U,
145            c: V,
146        ) -> usize {
147            a.try_into()
148                .unwrap_or_default()
149                .saturating_add(b.try_into().unwrap_or_default())
150                .saturating_mul(c.try_into().unwrap_or_default())
151        }
152
153        #[cfg(feature = "ift")]
154        pub fn multiply_add<T: TryInto<usize>, U: TryInto<usize>, V: TryInto<usize>>(
155            a: T,
156            b: U,
157            c: V,
158        ) -> usize {
159            a.try_into()
160                .unwrap_or_default()
161                .saturating_mul(b.try_into().unwrap_or_default())
162                .saturating_add(c.try_into().unwrap_or_default())
163        }
164
165        pub fn half<T: TryInto<usize>>(val: T) -> usize {
166            val.try_into().unwrap_or_default() / 2
167        }
168
169        pub fn subtract_add_two<T: TryInto<usize>, U: TryInto<usize>>(lhs: T, rhs: U) -> usize {
170            lhs.try_into()
171                .unwrap_or_default()
172                .saturating_sub(rhs.try_into().unwrap_or_default())
173                .saturating_add(2)
174        }
175    }
176
177    macro_rules! basic_table_impls {
178        (impl_the_methods) => {
179            /// Resolve the provided offset from the start of this table.
180            pub fn resolve_offset<O: Offset, R: FontRead<'a, Args = ()>>(
181                &self,
182                offset: O,
183            ) -> Result<R, ReadError> {
184                offset.resolve(self.offset_data())
185            }
186
187            /// Return a reference to this table's raw data.
188            ///
189            /// We use this in the compile crate to resolve offsets.
190            #[inline(always)]
191            pub fn offset_data(&self) -> FontData<'a> {
192                FontData::new(self.data.data())
193            }
194
195            /// Return a reference to the table's 'Shape' struct.
196            ///
197            /// This is a low level implementation detail, but it can be useful in
198            /// some cases where you want to know things about a table's layout, such
199            /// as the byte offsets of specific fields.
200            #[deprecated(note = "just use the base type directly")]
201            pub fn shape(&self) -> &Self {
202                &self
203            }
204        };
205    }
206
207    pub(crate) use basic_table_impls;
208}
209
210include!("../generated/font.rs");
211
212#[derive(Clone)]
213/// Reference to the content of a font or font collection file.
214pub enum FileRef<'a> {
215    /// A single font.
216    Font(FontRef<'a>),
217    /// A collection of fonts.
218    Collection(CollectionRef<'a>),
219}
220
221impl<'a> FileRef<'a> {
222    /// Creates a new reference to a file representing a font or font collection.
223    pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
224        Ok(if let Ok(collection) = CollectionRef::new(data) {
225            Self::Collection(collection)
226        } else {
227            Self::Font(FontRef::new(data)?)
228        })
229    }
230
231    /// Returns an iterator over the fonts contained in the file.
232    pub fn fonts(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
233        let (iter_one, iter_two) = match self {
234            Self::Font(font) => (Some(Ok(font.clone())), None),
235            Self::Collection(collection) => (None, Some(collection.iter())),
236        };
237        iter_two.into_iter().flatten().chain(iter_one)
238    }
239}
240
241/// Reference to the content of a font collection file.
242#[derive(Clone)]
243pub struct CollectionRef<'a> {
244    data: FontData<'a>,
245    offsets: &'a [types::BigEndian<u32>],
246}
247
248impl<'a> CollectionRef<'a> {
249    /// Creates a new reference to a font collection.
250    pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
251        let data = FontData::new(data);
252        let header = TTCHeader::read(data)?;
253        if header.ttc_tag() != TTC_HEADER_TAG {
254            Err(ReadError::InvalidTtc(header.ttc_tag()))
255        } else {
256            let legacy_end = usize::try_from(header.num_fonts())
257                .ok()
258                .and_then(|count| count.checked_mul(4))
259                .and_then(|size| size.checked_add(12))
260                .ok_or(ReadError::OutOfBounds)?;
261            let version = header.version();
262            let offsets = if matches!(version.major, 1 | 2) && version.minor >= 1 {
263                // ISO/IEC 14496-22:2026 places the extended directory list
264                // after the original list and, for version 2.1, the three DSIG
265                // fields.
266                let count_pos = legacy_end
267                    .checked_add(if version.major == 2 { 12 } else { 0 })
268                    .ok_or(ReadError::OutOfBounds)?;
269                let count = data.read_at::<u32>(count_pos)?;
270                let start = count_pos.checked_add(4).ok_or(ReadError::OutOfBounds)?;
271                let end = usize::try_from(count)
272                    .ok()
273                    .and_then(|count| count.checked_mul(4))
274                    .and_then(|size| start.checked_add(size))
275                    .ok_or(ReadError::OutOfBounds)?;
276                data.read_array(start..end)?
277            } else {
278                data.read_array(12..legacy_end)?
279            };
280            Ok(Self { data, offsets })
281        }
282    }
283
284    /// Returns the number of fonts in the collection.
285    pub fn len(&self) -> u32 {
286        self.offsets.len() as u32
287    }
288
289    /// Returns true if the collection is empty.
290    pub fn is_empty(&self) -> bool {
291        self.len() == 0
292    }
293
294    /// Returns the font in the collection at the specified index.
295    pub fn get(&self, index: u32) -> Result<FontRef<'a>, ReadError> {
296        let offset = self
297            .offsets
298            .get(index as usize)
299            .ok_or(ReadError::InvalidCollectionIndex(index))?
300            .get() as usize;
301        let table_dir_data = self.data.slice(offset..).ok_or(ReadError::OutOfBounds)?;
302        FontRef::with_table_directory(
303            self.data,
304            TableDirectory::read(table_dir_data)?,
305            Some(index),
306        )
307    }
308
309    /// Returns an iterator over the fonts in the collection.
310    pub fn iter(&self) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
311        let copy = self.clone();
312        (0..self.len()).map(move |ix| copy.get(ix))
313    }
314}
315
316impl TableDirectory<'_> {
317    fn is_sorted(&self) -> bool {
318        let mut last_tag = Tag::new(&[0u8; 4]);
319
320        for tag in self.table_records().iter().map(|rec| rec.tag()) {
321            if tag <= last_tag {
322                return false;
323            }
324
325            last_tag = tag;
326        }
327
328        true
329    }
330}
331
332/// Reference to an in-memory font.
333///
334/// This is a simple implementation of the [`TableProvider`] trait backed
335/// by a borrowed slice containing font data.
336#[derive(Clone)]
337pub struct FontRef<'a> {
338    data: FontData<'a>,
339    pub table_directory: TableDirectory<'a>,
340    /// The index of this font in a TrueType collection
341    ttc_index: u32,
342    /// Whether this font is a member of a TrueType collection.
343    ///
344    /// We use a bool rather than an Option to avoid bloating the struct
345    /// size.
346    in_ttc: bool,
347    // Whether the table directory is sorted and thus we can use binary search for
348    // finding table records. In principle, fonts are required to have a sorted
349    // table directory, but certain fonts don't seem to follow that requirement.
350    table_directory_sorted: bool,
351}
352
353impl<'a> FontRef<'a> {
354    /// Creates a new reference to an in-memory font backed by the given data.
355    ///
356    /// The data must be a single font (not a font collection) and must begin with a
357    /// [table directory] to be considered valid.
358    ///
359    /// To load a font from a font collection, use [`FontRef::from_index`] instead.
360    ///
361    /// [table directory]: https://github.com/googlefonts/fontations/pull/549
362    pub fn new(data: &'a [u8]) -> Result<Self, ReadError> {
363        let data = FontData::new(data);
364        Self::with_table_directory(data, TableDirectory::read(data)?, None)
365    }
366
367    /// Creates a new reference to an in-memory font at the specified index
368    /// backed by the given data.
369    ///
370    /// The data slice must begin with either a
371    /// [table directory](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
372    /// or a [ttc header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
373    /// to be considered valid.
374    ///
375    /// In other words, this accepts either font collection (ttc) or single
376    /// font (ttf/otf) files. If a single font file is provided, the index
377    /// parameter must be 0.
378    pub fn from_index(data: &'a [u8], index: u32) -> Result<Self, ReadError> {
379        let file = FileRef::new(data)?;
380        match file {
381            FileRef::Font(font) => {
382                if index == 0 {
383                    Ok(font)
384                } else {
385                    Err(ReadError::InvalidCollectionIndex(index))
386                }
387            }
388            FileRef::Collection(collection) => collection.get(index),
389        }
390    }
391
392    /// Returns the underlying font data.
393    ///
394    /// This is the base from which tables are loaded, meaning that for
395    /// TrueType collection files, this will be the entire font file data.
396    pub fn data(&self) -> FontData<'a> {
397        self.data
398    }
399
400    /// If the font is in a TrueType collection (ttc) file, returns the index
401    /// of the font in that collection.
402    pub fn ttc_index(&self) -> Option<u32> {
403        self.in_ttc.then_some(self.ttc_index)
404    }
405
406    /// Returns the associated table directory.
407    pub fn table_directory(&self) -> &TableDirectory<'a> {
408        &self.table_directory
409    }
410
411    /// Returns the data for the table with the specified tag, if present.
412    pub fn table_data(&self, tag: Tag) -> Option<FontData<'a>> {
413        let entry = if self.table_directory_sorted {
414            self.table_directory
415                .table_records()
416                .binary_search_by(|rec| rec.tag.get().cmp(&tag))
417                .ok()
418        } else {
419            self.table_directory
420                .table_records()
421                .iter()
422                .position(|rec| rec.tag.get().eq(&tag))
423        };
424
425        entry
426            .and_then(|idx| self.table_directory.table_records().get(idx))
427            .and_then(|record| {
428                let start = Offset32::new(record.offset()).non_null()?;
429                let len = record.length() as usize;
430                self.data.slice(start..start.checked_add(len)?)
431            })
432    }
433
434    /// Returns an iterator over all of the available fonts in
435    /// the given font data.
436    pub fn fonts(
437        data: &'a [u8],
438    ) -> impl Iterator<Item = Result<FontRef<'a>, ReadError>> + 'a + Clone {
439        let count = match FileRef::new(data) {
440            Ok(FileRef::Font(_)) => 1,
441            Ok(FileRef::Collection(ttc)) => ttc.len(),
442            _ => 0,
443        };
444        (0..count).map(|idx| FontRef::from_index(data, idx))
445    }
446
447    fn with_table_directory(
448        data: FontData<'a>,
449        table_directory: TableDirectory<'a>,
450        ttc_index: Option<u32>,
451    ) -> Result<Self, ReadError> {
452        if [TT_SFNT_VERSION, CFF_SFNT_VERSION, TRUE_SFNT_VERSION]
453            .contains(&table_directory.sfnt_version())
454        {
455            let table_directory_sorted = table_directory.is_sorted();
456
457            Ok(FontRef {
458                data,
459                table_directory,
460                ttc_index: ttc_index.unwrap_or_default(),
461                in_ttc: ttc_index.is_some(),
462                table_directory_sorted,
463            })
464        } else {
465            Err(ReadError::InvalidSfnt(table_directory.sfnt_version()))
466        }
467    }
468}
469
470impl<'a> TableProvider<'a> for FontRef<'a> {
471    fn data_for_tag(&self, tag: Tag) -> Option<FontData<'a>> {
472        self.table_data(tag)
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use font_test_data::{be_buffer, bebuffer::BeBuffer, ttc::TTC, AHEM};
479    use types::{Tag, TT_SFNT_VERSION};
480
481    use crate::{FileRef, FontRef};
482
483    #[test]
484    fn file_ref_non_collection() {
485        assert!(matches!(FileRef::new(AHEM), Ok(FileRef::Font(_))));
486    }
487
488    #[test]
489    fn file_ref_collection() {
490        let Ok(FileRef::Collection(collection)) = FileRef::new(TTC) else {
491            panic!("Expected a collection");
492        };
493        assert_eq!(2, collection.len());
494        assert!(!collection.is_empty());
495    }
496
497    #[test]
498    fn extended_ttc_directory_list_takes_precedence() {
499        for major in [1u16, 2] {
500            for legacy_count in [0u32, 1] {
501                let extended_start =
502                    12 + legacy_count as usize * 4 + if major == 2 { 12 } else { 0 };
503                let first_directory = extended_start + 12;
504                let second_directory = first_directory + 12;
505                let mut bytes = b"ttcf".to_vec();
506                bytes.extend_from_slice(&major.to_be_bytes());
507                bytes.extend_from_slice(&1u16.to_be_bytes());
508                bytes.extend_from_slice(&legacy_count.to_be_bytes());
509                if legacy_count != 0 {
510                    bytes.extend_from_slice(&(first_directory as u32).to_be_bytes());
511                }
512                if major == 2 {
513                    // Nonzero DSIG fields must not be confused with numFonts2.
514                    bytes.extend_from_slice(&0x44534947u32.to_be_bytes());
515                    bytes.extend_from_slice(&8u32.to_be_bytes());
516                    bytes.extend_from_slice(&((second_directory + 12) as u32).to_be_bytes());
517                }
518                bytes.extend_from_slice(&2u32.to_be_bytes());
519                bytes.extend_from_slice(&(second_directory as u32).to_be_bytes());
520                bytes.extend_from_slice(&(first_directory as u32).to_be_bytes());
521                bytes.extend_from_slice(&TT_SFNT_VERSION.to_be_bytes());
522                bytes.extend_from_slice(&[0; 8]);
523                bytes.extend_from_slice(&0x4F54544Fu32.to_be_bytes());
524                bytes.extend_from_slice(&[0; 8]);
525                bytes.extend_from_slice(&[0; 8]);
526                let collection = crate::CollectionRef::new(&bytes).unwrap();
527                assert_eq!(collection.len(), 2);
528                assert_eq!(
529                    collection.get(0).unwrap().table_directory().sfnt_version(),
530                    0x4F54544F
531                );
532                assert_eq!(
533                    collection.get(1).unwrap().table_directory().sfnt_version(),
534                    TT_SFNT_VERSION
535                );
536                assert_eq!(FontRef::fonts(&bytes).count(), 2);
537                assert_eq!(
538                    FontRef::from_index(&bytes, 0)
539                        .unwrap()
540                        .table_directory()
541                        .sfnt_version(),
542                    0x4F54544F
543                );
544                // A missing extended list is malformed, not a legacy fallback.
545                for len in extended_start..first_directory {
546                    assert!(crate::CollectionRef::new(&bytes[..len]).is_err());
547                }
548                let mut empty = bytes.clone();
549                empty[extended_start..extended_start + 4].copy_from_slice(&0u32.to_be_bytes());
550                assert!(crate::CollectionRef::new(&empty).unwrap().is_empty());
551                let mut huge = bytes.clone();
552                huge[extended_start..extended_start + 4].copy_from_slice(&u32::MAX.to_be_bytes());
553                assert!(crate::CollectionRef::new(&huge).is_err());
554            }
555        }
556    }
557
558    #[test]
559    fn font_ref_fonts_iter() {
560        assert_eq!(FontRef::fonts(AHEM).count(), 1);
561        assert_eq!(FontRef::fonts(TTC).count(), 2);
562        assert_eq!(FontRef::fonts(b"NOT_A_FONT").count(), 0);
563    }
564
565    #[test]
566    fn ttc_index() {
567        for (idx, font) in FontRef::fonts(TTC).map(|font| font.unwrap()).enumerate() {
568            assert_eq!(font.ttc_index(), Some(idx as u32));
569        }
570        assert!(FontRef::new(AHEM).unwrap().ttc_index().is_none());
571    }
572
573    #[test]
574    fn unsorted_table_directory() {
575        let cff2_data = font_test_data::cff2::EXAMPLE;
576        let post_data = font_test_data::post::SIMPLE;
577        let gdef_data = [
578            font_test_data::gdef::GDEF_HEADER,
579            font_test_data::gdef::GLYPHCLASSDEF_TABLE,
580        ]
581        .concat();
582        let gpos_data = font_test_data::gpos::SINGLEPOSFORMAT1;
583
584        let font_data = be_buffer! {
585            TT_SFNT_VERSION,
586            4u16,    // num tables
587            64u16,   // search range
588            2u16,    // entry selector
589            0u16,    // range shift
590
591            (Tag::new(b"post")),
592            0u32,    // checksum
593            76u32,   // offset
594            (post_data.len() as u32),
595
596            (Tag::new(b"GPOS")),
597            0u32,    // checksum
598            108u32,  // offset
599            (gpos_data.len() as u32),
600
601            (Tag::new(b"GDEF")),
602            0u32,    // checksum
603            128u32,  // offset
604            (gdef_data.len() as u32),
605
606            (Tag::new(b"CFF2")),
607            0u32,    // checksum
608            160u32,  // offset
609            (cff2_data.len() as u32)
610        };
611
612        let mut full_font = font_data.to_vec();
613
614        full_font.extend_from_slice(post_data);
615        full_font.extend_from_slice(gpos_data);
616        full_font.extend_from_slice(&gdef_data);
617        full_font.extend_from_slice(cff2_data);
618
619        let font = FontRef::new(&full_font).unwrap();
620
621        assert!(!font.table_directory_sorted);
622
623        assert!(font.table_data(Tag::new(b"CFF2")).is_some());
624        assert!(font.table_data(Tag::new(b"GDEF")).is_some());
625        assert!(font.table_data(Tag::new(b"GPOS")).is_some());
626        assert!(font.table_data(Tag::new(b"post")).is_some());
627    }
628}