Skip to main content

read_fonts/model/font/
tables.rs

1//! Table validation, caching and access.
2
3use super::{super::once::Once, Blob, Source};
4use crate::{tables, types::Tag, FontRead, ReadError, TableProvider, TopLevelTable};
5use alloc::{boxed::Box, sync::Arc};
6use core::sync::atomic::{AtomicU8, Ordering};
7
8include!("../../../data/generated/generated_tables.rs");
9
10/// A single table in a font blob.
11#[derive(Default)]
12struct BlobTableEntry {
13    /// Holds validation state.
14    flag: AtomicU8,
15    start: u32,
16    end: u32,
17}
18
19/// Blob and associated metadata for all tables.
20struct BlobTables {
21    blob: Blob,
22    tables: Box<PerTableData<BlobTableEntry>>,
23}
24
25impl<'a> TableDataProvider<'a> for &'a BlobTables {
26    type Entry = BlobTableEntry;
27
28    fn tables(&self) -> &'a PerTableData<Self::Entry> {
29        &self.tables
30    }
31
32    fn table_state(&self, _tag: Tag, entry: &'a Self::Entry) -> Option<TableState<'a>> {
33        self.blob
34            .get(entry.start as usize..entry.end as usize)
35            .map(|data| TableState {
36                flag: &entry.flag,
37                data,
38            })
39    }
40}
41
42/// Entry for a single table provided by a callback.
43type TableFunctionEntry = Once<Option<(AtomicU8, Blob)>>;
44
45/// Lazy, per table font data provided by a function.
46#[derive(Clone)]
47pub struct TableFunction {
48    table_fn: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync>,
49    tables: Arc<PerTableData<TableFunctionEntry>>,
50}
51
52impl TableFunction {
53    /// Creates a new font table function with the given callback that should
54    /// return a blob containing the table data for the requested tag.
55    pub fn new(table_fn: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync>) -> Self {
56        Self {
57            table_fn,
58            tables: Arc::new(PerTableData::default()),
59        }
60    }
61}
62
63impl<'a> TableDataProvider<'a> for &'a TableFunction {
64    type Entry = TableFunctionEntry;
65
66    fn tables(&self) -> &'a PerTableData<Self::Entry> {
67        &self.tables
68    }
69
70    fn table_state(&self, tag: Tag, entry: &'a Self::Entry) -> Option<TableState<'a>> {
71        entry
72            .get_or_init(|| (self.table_fn)(tag).map(|blob| (AtomicU8::new(0), blob)))
73            .as_ref()
74            .map(|(flag, data)| TableState {
75                flag,
76                data: data.as_ref(),
77            })
78    }
79}
80
81/// Source for a set of font tables.
82enum TableSource {
83    None,
84    Blob(BlobTables),
85    Function(TableFunction),
86}
87
88/// Reference to the validation flag and data for a table.
89#[derive(Copy, Clone)]
90struct TableState<'a> {
91    flag: &'a AtomicU8,
92    data: &'a [u8],
93}
94
95impl<'a> TableState<'a> {
96    const UNCHECKED: u8 = 0;
97    const VALID: u8 = 1;
98    const INVALID: u8 = 2;
99
100    fn try_load<T>(
101        &self,
102        sanitize_fn: impl Fn(&'a [u8]) -> Result<T, ReadError>,
103        load_fn: impl Fn(&'a [u8]) -> Result<T, ReadError>,
104    ) -> Result<T, ReadError> {
105        match self.flag.load(Ordering::Acquire) {
106            Self::UNCHECKED => {
107                if let Ok(table) = sanitize_fn(self.data) {
108                    self.flag.store(Self::VALID, Ordering::Release);
109                    Ok(table)
110                } else {
111                    self.flag.store(Self::INVALID, Ordering::Release);
112                    Err(ReadError::ValidationError)
113                }
114            }
115            Self::VALID => load_fn(self.data),
116            // Assume any other bit pattern is invalid
117            _ => Err(ReadError::ValidationError),
118        }
119    }
120}
121
122/// Individual font table access.
123pub struct Tables(TableSource);
124
125impl Tables {
126    /// Creates a new set of font tables for the given source.
127    pub fn new(source: impl Into<Source>, index: u32) -> Result<Self, ReadError> {
128        let source = source.into();
129        match source {
130            Source::Blob(blob) => {
131                let font_ref = crate::FontRef::from_index(&blob, index)?;
132                let mut tables = PerTableData::default();
133                let table_records = font_ref.table_directory().table_records();
134                tables.init_all(|tag, entry: &mut BlobTableEntry| {
135                    // Ensure missing entries report as a missing table rather
136                    // than returning an empty slice
137                    entry.start = u32::MAX;
138                    let Ok(idx) = table_records.binary_search_by_key(&tag, |rec| rec.tag()) else {
139                        return;
140                    };
141                    let record = &table_records[idx];
142                    let start = record.offset();
143                    let Some(end) = start.checked_add(record.length()) else {
144                        return;
145                    };
146                    if blob.get(start as usize..end as usize).is_none() {
147                        return;
148                    }
149                    *entry = BlobTableEntry {
150                        flag: AtomicU8::new(0),
151                        start,
152                        end,
153                    };
154                });
155                Ok(Self(TableSource::Blob(BlobTables {
156                    blob,
157                    tables: Box::new(tables),
158                })))
159            }
160            Source::TableFunction(func) => Ok(Self(TableSource::Function(func))),
161        }
162    }
163}
164
165impl Tables {
166    fn load_table<'a, T: TopLevelTable + FontRead<'a, Args = ()>>(
167        &'a self,
168        state: Option<TableState<'a>>,
169    ) -> Result<T, ReadError> {
170        self.load_table_with_tag(state, T::TAG)
171    }
172
173    fn load_table_with_tag<'a, T: FontRead<'a, Args = ()>>(
174        &'a self,
175        state: Option<TableState<'a>>,
176        tag: Tag,
177    ) -> Result<T, ReadError> {
178        let state = state.ok_or(ReadError::TableIsMissing(tag))?;
179        state.try_load(
180            |data| FontRead::read(data.into()),
181            |data| FontRead::read(data.into()),
182        )
183    }
184
185    fn load_table_with_args<'a, T: TopLevelTable + FontRead<'a>>(
186        &'a self,
187        state: Option<TableState<'a>>,
188        args: T::Args,
189    ) -> Result<T, ReadError> {
190        let state = state.ok_or(ReadError::TableIsMissing(T::TAG))?;
191        state.try_load(
192            |data| FontRead::read_with_args(data.into(), args),
193            |data| FontRead::read_with_args(data.into(), args),
194        )
195    }
196}
197
198pub(super) static EMPTY_FONT_TABLES: Tables = Tables(TableSource::None);
199
200impl<'a> TableProvider<'a> for &'a Tables {
201    fn data_for_tag(&self, _tag: Tag) -> Option<crate::FontData<'a>> {
202        None
203    }
204
205    fn head(&self) -> Result<tables::head::Head<'a>, ReadError> {
206        self.load_table(self.head_state())
207    }
208
209    fn name(&self) -> Result<tables::name::Name<'a>, ReadError> {
210        self.load_table(self.name_state())
211    }
212
213    fn hhea(&self) -> Result<tables::hhea::Hhea<'a>, ReadError> {
214        self.load_table(self.hhea_state())
215    }
216
217    fn vhea(&self) -> Result<tables::vhea::Vhea<'a>, ReadError> {
218        self.load_table(self.vhea_state())
219    }
220
221    fn hmtx(&self) -> Result<tables::hmtx::Hmtx<'a>, ReadError> {
222        //FIXME: should we make the user pass these in?
223        let number_of_h_metrics = self.hhea().map(|hhea| hhea.number_of_h_metrics())?;
224        self.load_table_with_args(self.hmtx_state(), number_of_h_metrics)
225    }
226
227    fn hdmx(&self) -> Result<tables::hdmx::Hdmx<'a>, ReadError> {
228        let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
229        self.load_table_with_args(self.hdmx_state(), num_glyphs)
230    }
231
232    fn vmtx(&self) -> Result<tables::vmtx::Vmtx<'a>, ReadError> {
233        //FIXME: should we make the user pass these in?
234        let number_of_v_metrics = self.vhea().map(|vhea| vhea.number_of_long_ver_metrics())?;
235        self.load_table_with_args(self.vmtx_state(), number_of_v_metrics)
236    }
237
238    fn vorg(&self) -> Result<tables::vorg::Vorg<'a>, ReadError> {
239        self.load_table(self.vorg_state())
240    }
241
242    fn fvar(&self) -> Result<tables::fvar::Fvar<'a>, ReadError> {
243        self.load_table(self.fvar_state())
244    }
245
246    fn avar(&self) -> Result<tables::avar::Avar<'a>, ReadError> {
247        self.load_table(self.avar_state())
248    }
249
250    fn hvar(&self) -> Result<tables::hvar::Hvar<'a>, ReadError> {
251        self.load_table(self.hvar_state())
252    }
253
254    fn vvar(&self) -> Result<tables::vvar::Vvar<'a>, ReadError> {
255        self.load_table(self.vvar_state())
256    }
257
258    fn mvar(&self) -> Result<tables::mvar::Mvar<'a>, ReadError> {
259        self.load_table(self.mvar_state())
260    }
261
262    fn maxp(&self) -> Result<tables::maxp::Maxp<'a>, ReadError> {
263        self.load_table(self.maxp_state())
264    }
265
266    fn os2(&self) -> Result<tables::os2::Os2<'a>, ReadError> {
267        self.load_table(self.os2_state())
268    }
269
270    fn post(&self) -> Result<tables::post::Post<'a>, ReadError> {
271        self.load_table(self.post_state())
272    }
273
274    fn gasp(&self) -> Result<tables::gasp::Gasp<'a>, ReadError> {
275        self.load_table(self.gasp_state())
276    }
277
278    /// is_long can be optionally provided, if known, otherwise we look it up in head.
279    fn loca(&self, is_long: impl Into<Option<bool>>) -> Result<tables::loca::Loca<'a>, ReadError> {
280        let is_long = match is_long.into() {
281            Some(val) => val,
282            None => self.head()?.index_to_loc_format() == 1,
283        };
284        self.load_table_with_args(self.loca_state(), is_long)
285    }
286
287    fn glyf(&self) -> Result<tables::glyf::Glyf<'a>, ReadError> {
288        self.load_table(self.glyf_state())
289    }
290
291    fn gvar(&self) -> Result<tables::gvar::Gvar<'a>, ReadError> {
292        self.load_table(self.gvar_state())
293    }
294
295    /// Returns the array of entries for the control value table which is used
296    /// for TrueType hinting.
297    fn cvt(&self) -> Result<&'a [types::BigEndian<i16>], ReadError> {
298        let table_data = crate::FontData::new(
299            self.cvt_data()
300                .ok_or(ReadError::TableIsMissing(Tag::new(b"cvt ")))?,
301        );
302        table_data.read_array(0..table_data.len())
303    }
304
305    fn cvar(&self) -> Result<tables::cvar::Cvar<'a>, ReadError> {
306        self.load_table(self.cvar_state())
307    }
308
309    fn cff(&self) -> Result<tables::cff::Cff<'a>, ReadError> {
310        self.load_table(self.cff_state())
311    }
312
313    fn cff2(&self) -> Result<tables::cff2::Cff2<'a>, ReadError> {
314        self.load_table(self.cff2_state())
315    }
316
317    fn cmap(&self) -> Result<tables::cmap::Cmap<'a>, ReadError> {
318        self.load_table(self.cmap_state())
319    }
320
321    fn gdef(&self) -> Result<tables::gdef::Gdef<'a>, ReadError> {
322        self.load_table(self.gdef_state())
323    }
324
325    fn gpos(&self) -> Result<tables::gpos::Gpos<'a>, ReadError> {
326        self.load_table(self.gpos_state())
327    }
328
329    fn gsub(&self) -> Result<tables::gsub::Gsub<'a>, ReadError> {
330        self.load_table(self.gsub_state())
331    }
332
333    fn feat(&self) -> Result<tables::feat::Feat<'a>, ReadError> {
334        self.load_table(self.feat_state())
335    }
336
337    fn ltag(&self) -> Result<tables::ltag::Ltag<'a>, ReadError> {
338        self.load_table(self.ltag_state())
339    }
340
341    fn ankr(&self) -> Result<tables::ankr::Ankr<'a>, ReadError> {
342        self.load_table(self.ankr_state())
343    }
344
345    fn trak(&self) -> Result<tables::trak::Trak<'a>, ReadError> {
346        self.load_table(self.trak_state())
347    }
348
349    fn morx(&self) -> Result<tables::morx::Morx<'a>, ReadError> {
350        self.load_table(self.morx_state())
351    }
352
353    fn mort(&self) -> Result<tables::mort::Mort<'a>, ReadError> {
354        self.load_table(self.mort_state())
355    }
356
357    fn kerx(&self) -> Result<tables::kerx::Kerx<'a>, ReadError> {
358        self.load_table(self.kerx_state())
359    }
360
361    fn kern(&self) -> Result<tables::kern::Kern<'a>, ReadError> {
362        self.load_table(self.kern_state())
363    }
364
365    fn colr(&self) -> Result<tables::colr::Colr<'a>, ReadError> {
366        self.load_table(self.colr_state())
367    }
368
369    fn cpal(&self) -> Result<tables::cpal::Cpal<'a>, ReadError> {
370        self.load_table(self.cpal_state())
371    }
372
373    fn cblc(&self) -> Result<tables::cblc::Cblc<'a>, ReadError> {
374        self.load_table(self.cblc_state())
375    }
376
377    fn cbdt(&self) -> Result<tables::cbdt::Cbdt<'a>, ReadError> {
378        self.load_table(self.cbdt_state())
379    }
380
381    fn eblc(&self) -> Result<tables::eblc::Eblc<'a>, ReadError> {
382        self.load_table(self.eblc_state())
383    }
384
385    fn ebdt(&self) -> Result<tables::ebdt::Ebdt<'a>, ReadError> {
386        self.load_table(self.ebdt_state())
387    }
388
389    fn sbix(&self) -> Result<tables::sbix::Sbix<'a>, ReadError> {
390        // should we make the user pass this in?
391        let num_glyphs = self.maxp().map(|maxp| maxp.num_glyphs())?;
392        self.load_table_with_args(self.sbix_state(), num_glyphs)
393    }
394
395    fn stat(&self) -> Result<tables::stat::Stat<'a>, ReadError> {
396        self.load_table(self.stat_state())
397    }
398
399    fn svg(&self) -> Result<tables::svg::Svg<'a>, ReadError> {
400        self.load_table(self.svg_state())
401    }
402
403    fn varc(&self) -> Result<tables::varc::Varc<'a>, ReadError> {
404        self.load_table(self.varc_state())
405    }
406
407    #[cfg(feature = "ift")]
408    fn ift(&self) -> Result<tables::ift::IftPatchMap<'a>, ReadError> {
409        self.load_table_with_tag(self.ift_state(), Tag::new(b"IFT "))
410    }
411
412    #[cfg(feature = "ift")]
413    fn iftx(&self) -> Result<tables::ift::IftPatchMap<'a>, ReadError> {
414        self.load_table_with_tag(self.iftx_state(), Tag::new(b"IFTX"))
415    }
416
417    fn meta(&self) -> Result<tables::meta::Meta<'a>, ReadError> {
418        self.load_table(self.meta_state())
419    }
420
421    fn base(&self) -> Result<tables::base::Base<'a>, ReadError> {
422        self.load_table(self.base_state())
423    }
424
425    fn dsig(&self) -> Result<tables::dsig::Dsig<'a>, ReadError> {
426        self.load_table(self.dsig_state())
427    }
428
429    fn math(&self) -> Result<tables::math::Math<'a>, ReadError> {
430        self.load_table(self.math_state())
431    }
432}
433
434#[cfg(test)]
435mod tests {
436    use crate::FontRef;
437
438    use super::*;
439
440    #[test]
441    fn missing_tables_are_missing() {
442        let tables = &Tables::new(font_test_data::AHEM, 0).unwrap();
443        assert!(matches!(tables.cbdt(), Err(ReadError::TableIsMissing(_))));
444        assert!(matches!(tables.cff(), Err(ReadError::TableIsMissing(_))));
445        assert!(matches!(tables.dsig(), Err(ReadError::TableIsMissing(_))));
446    }
447
448    #[test]
449    fn table_function_matches_font_ref() {
450        let font = FontRef::new(font_test_data::AHEM).unwrap();
451        let font_copy = font.clone();
452        let table_fn = TableFunction::new(Arc::new(move |tag| {
453            font_copy
454                .data_for_tag(tag)
455                .map(|data| Vec::from(data.as_bytes()).into())
456        }));
457        let tables = &Tables::new(table_fn, 0).unwrap();
458        for (data, tag) in [
459            (tables.gasp_data(), b"gasp"),
460            (tables.glyf_data(), b"glyf"),
461            (tables.hmtx_data(), b"hmtx"),
462        ] {
463            let font_ref_data = font.data_for_tag(Tag::new(tag)).map(|d| d.as_bytes());
464            assert_eq!(data, font_ref_data);
465        }
466    }
467}