Skip to main content

read_fonts/
table_provider.rs

1//! a trait for things that can serve font tables
2
3use types::{BigEndian, Tag};
4
5use crate::{tables, FontData, FontRead, ReadError};
6
7/// A table that has an associated tag.
8///
9/// This is true of top-level tables, but not their various subtables.
10pub trait TopLevelTable {
11    /// The table's tag.
12    const TAG: Tag;
13}
14
15pub(crate) fn prefer_extended<T>(
16    extended: Result<T, ReadError>,
17    tag: Tag,
18    original: impl FnOnce() -> Result<T, ReadError>,
19) -> Result<T, ReadError> {
20    match extended {
21        Err(ReadError::TableIsMissing(missing)) if missing == tag => original(),
22        result => result,
23    }
24}
25
26/// An interface for accessing tables from a font (or font-like object)
27pub trait TableProvider<'a> {
28    fn data_for_tag(&self, tag: Tag) -> Option<FontData<'a>>;
29
30    fn expect_data_for_tag(&self, tag: Tag) -> Result<FontData<'a>, ReadError> {
31        self.data_for_tag(tag).ok_or(ReadError::TableIsMissing(tag))
32    }
33
34    fn expect_table<T: TopLevelTable + FontRead<'a, Args = ()>>(&self) -> Result<T, ReadError> {
35        self.expect_data_for_tag(T::TAG).and_then(FontRead::read)
36    }
37
38    fn head(&self) -> Result<tables::head::Head<'a>, ReadError> {
39        self.expect_table()
40    }
41
42    fn name(&self) -> Result<tables::name::Name<'a>, ReadError> {
43        self.expect_table()
44    }
45
46    /// Reads the `hhea` table only. A font may carry its metrics header in
47    /// HHEA instead; [`selected_hhea`](Self::selected_hhea) chooses between them.
48    fn hhea(&self) -> Result<tables::hhea::Hhea<'a>, ReadError> {
49        self.expect_table()
50    }
51
52    /// Reads the `vhea` table only. A font may carry its vertical metrics
53    /// header in VHEA instead; [`selected_vhea`](Self::selected_vhea) chooses
54    /// between them.
55    fn vhea(&self) -> Result<tables::vhea::Vhea<'a>, ReadError> {
56        self.expect_table()
57    }
58
59    /// Reads the uppercase HHEA table.
60    fn hhea_extended(&self) -> Result<tables::hhea::HheaExtended<'a>, ReadError> {
61        self.expect_table()
62    }
63
64    /// Selects HHEA before hhea, independently of the outline tables.
65    fn selected_hhea(&self) -> Result<tables::hhea::SelectedHhea<'a>, ReadError> {
66        use tables::hhea::SelectedHhea;
67        prefer_extended(
68            self.hhea_extended().map(SelectedHhea::Extended),
69            Tag::new(b"HHEA"),
70            || self.hhea().map(SelectedHhea::Original),
71        )
72    }
73
74    /// Reads the uppercase VHEA table.
75    fn vhea_extended(&self) -> Result<tables::vhea::VheaExtended<'a>, ReadError> {
76        self.expect_table()
77    }
78
79    /// Selects VHEA before vhea, independently of the outline tables.
80    fn selected_vhea(&self) -> Result<tables::vhea::SelectedVhea<'a>, ReadError> {
81        use tables::vhea::SelectedVhea;
82        prefer_extended(
83            self.vhea_extended().map(SelectedVhea::Extended),
84            Tag::new(b"VHEA"),
85            || self.vhea().map(SelectedVhea::Original),
86        )
87    }
88
89    fn hmtx(&self) -> Result<tables::hmtx::Hmtx<'a>, ReadError> {
90        //FIXME: should we make the user pass these in?
91        let number_of_h_metrics = self.hhea().map(|hhea| hhea.number_of_h_metrics())?;
92        let data = self.expect_data_for_tag(tables::hmtx::Hmtx::TAG)?;
93        tables::hmtx::Hmtx::read(data, number_of_h_metrics)
94    }
95
96    /// Reads HMTX using the long-metric count from HHEA.
97    fn hmtx_extended(&self) -> Result<tables::hmtx::HmtxExtended<'a>, ReadError> {
98        let data = self.expect_data_for_tag(tables::hmtx::HmtxExtended::TAG)?;
99        let count = self.hhea_extended()?.number_of_h_metrics();
100        tables::hmtx::HmtxExtended::read(data, count)
101    }
102
103    /// Returns horizontal metrics records, selecting HMTX before hmtx
104    /// independently of the outline tables. No allocation is required.
105    fn h_glyph_metric_records(
106        &self,
107    ) -> Result<crate::tables::hmtx::GlyphMetricRecords<'a>, ReadError> {
108        crate::tables::hmtx::GlyphMetricRecords::read_horizontal(self)
109    }
110
111    fn hdmx(&self) -> Result<tables::hdmx::Hdmx<'a>, ReadError> {
112        let num_glyphs = self.selected_maxp()?.num_glyphs();
113        let data = self.expect_data_for_tag(tables::hdmx::Hdmx::TAG)?;
114        tables::hdmx::Hdmx::read(data, num_glyphs)
115    }
116
117    fn vmtx(&self) -> Result<tables::vmtx::Vmtx<'a>, ReadError> {
118        //FIXME: should we make the user pass these in?
119        let number_of_v_metrics = self.vhea().map(|vhea| vhea.number_of_long_ver_metrics())?;
120        let data = self.expect_data_for_tag(tables::vmtx::Vmtx::TAG)?;
121        tables::vmtx::Vmtx::read(data, number_of_v_metrics)
122    }
123
124    /// Reads VMTX using the long-metric count from VHEA.
125    fn vmtx_extended(&self) -> Result<tables::vmtx::VmtxExtended<'a>, ReadError> {
126        let data = self.expect_data_for_tag(tables::vmtx::VmtxExtended::TAG)?;
127        let count = self.vhea_extended()?.number_of_long_ver_metrics();
128        tables::vmtx::VmtxExtended::read(data, count)
129    }
130
131    /// Returns vertical metrics records, selecting VMTX before vmtx
132    /// independently of the outline tables. No allocation is required.
133    fn v_glyph_metric_records(
134        &self,
135    ) -> Result<crate::tables::hmtx::GlyphMetricRecords<'a>, ReadError> {
136        crate::tables::hmtx::GlyphMetricRecords::read_vertical(self)
137    }
138
139    fn vorg(&self) -> Result<tables::vorg::Vorg<'a>, ReadError> {
140        self.expect_table()
141    }
142
143    fn fvar(&self) -> Result<tables::fvar::Fvar<'a>, ReadError> {
144        self.expect_table()
145    }
146
147    fn avar(&self) -> Result<tables::avar::Avar<'a>, ReadError> {
148        self.expect_table()
149    }
150
151    fn hvar(&self) -> Result<tables::hvar::Hvar<'a>, ReadError> {
152        self.expect_table()
153    }
154
155    fn vvar(&self) -> Result<tables::vvar::Vvar<'a>, ReadError> {
156        self.expect_table()
157    }
158
159    fn mvar(&self) -> Result<tables::mvar::Mvar<'a>, ReadError> {
160        self.expect_table()
161    }
162
163    /// Reads the `maxp` table only. A font with more than 65535 glyphs
164    /// carries its glyph count in MAXP; [`selected_maxp`](Self::selected_maxp)
165    /// chooses between them.
166    fn maxp(&self) -> Result<tables::maxp::Maxp<'a>, ReadError> {
167        self.expect_table()
168    }
169
170    /// Reads the uppercase MAXP table with a 24-bit glyph count.
171    fn maxp_extended(&self) -> Result<tables::maxp::MaxpExtended<'a>, ReadError> {
172        self.expect_table()
173    }
174
175    /// Selects MAXP before maxp without narrowing its glyph count.
176    fn selected_maxp(&self) -> Result<tables::maxp::SelectedMaxp<'a>, ReadError> {
177        use tables::maxp::SelectedMaxp;
178        prefer_extended(
179            self.maxp_extended().map(SelectedMaxp::Extended),
180            Tag::new(b"MAXP"),
181            || self.maxp().map(SelectedMaxp::Original),
182        )
183    }
184
185    fn os2(&self) -> Result<tables::os2::Os2<'a>, ReadError> {
186        self.expect_table()
187    }
188
189    fn post(&self) -> Result<tables::post::Post<'a>, ReadError> {
190        self.expect_table()
191    }
192
193    fn gasp(&self) -> Result<tables::gasp::Gasp<'a>, ReadError> {
194        self.expect_table()
195    }
196
197    /// is_long can be optionally provided, if known, otherwise we look it up in head.
198    fn loca(&self, is_long: impl Into<Option<bool>>) -> Result<tables::loca::Loca<'a>, ReadError> {
199        let is_long = match is_long.into() {
200            Some(val) => val,
201            None => self.head()?.index_to_loc_format() == 1,
202        };
203        let data = self.expect_data_for_tag(tables::loca::Loca::TAG)?;
204        tables::loca::Loca::read(data, is_long)
205    }
206
207    /// Reads the `glyf` table only. A font may carry its outlines in GLYF and
208    /// LOCA instead; [`selected_glyf_loca`](Self::selected_glyf_loca) chooses
209    /// between the pairs.
210    fn glyf(&self) -> Result<tables::glyf::Glyf<'a>, ReadError> {
211        self.expect_table()
212    }
213
214    /// Reads GLYF using the shared glyph data representation.
215    fn glyf_extended(&self) -> Result<tables::glyf::Glyf<'a>, ReadError> {
216        tables::glyf::Glyf::read(self.expect_data_for_tag(Tag::new(b"GLYF"))?)
217    }
218
219    /// Reads LOCA; its format is shared with loca and specified in head.
220    fn loca_extended(
221        &self,
222        is_long: impl Into<Option<bool>>,
223    ) -> Result<tables::loca::Loca<'a>, ReadError> {
224        let data = self.expect_data_for_tag(Tag::new(b"LOCA"))?;
225        let is_long = match is_long.into() {
226            Some(val) => val,
227            None => self.head()?.index_to_loc_format() == 1,
228        };
229        tables::loca::Loca::read(data, is_long)
230    }
231
232    /// Selects GLYF/LOCA before glyf/loca, independently of metrics.
233    /// A present GLYF requires LOCA; it never uses the original loca offsets.
234    fn selected_glyf_loca(
235        &self,
236        is_long: impl Into<Option<bool>>,
237    ) -> Result<(tables::glyf::Glyf<'a>, tables::loca::Loca<'a>), ReadError> {
238        let is_long = is_long.into();
239        prefer_extended(
240            self.glyf_extended()
241                .and_then(|glyf| self.loca_extended(is_long).map(|loca| (glyf, loca))),
242            Tag::new(b"GLYF"),
243            || {
244                self.glyf()
245                    .and_then(|glyf| self.loca(is_long).map(|loca| (glyf, loca)))
246            },
247        )
248    }
249
250    /// Reads the `gvar` table only. A font may carry its glyph variations in
251    /// GVAR instead; [`selected_gvar`](Self::selected_gvar) chooses between
252    /// them.
253    fn gvar(&self) -> Result<tables::gvar::Gvar<'a>, ReadError> {
254        self.expect_table()
255    }
256
257    /// Reads the `GVAR` table only (ISO/IEC 14496-22:2026).
258    fn gvar_extended(&self) -> Result<tables::gvar::GvarExtended<'a>, ReadError> {
259        self.expect_table()
260    }
261
262    /// Selects GVAR before the original gvar table.
263    fn selected_gvar(&self) -> Result<tables::gvar::SelectedGvar<'a>, ReadError> {
264        prefer_extended(
265            self.gvar_extended()
266                .map(tables::gvar::SelectedGvar::Extended),
267            Tag::new(b"GVAR"),
268            || self.gvar().map(tables::gvar::SelectedGvar::Original),
269        )
270    }
271
272    /// Returns the array of entries for the control value table which is used
273    /// for TrueType hinting.
274    fn cvt(&self) -> Result<&'a [BigEndian<i16>], ReadError> {
275        let table_data = self.expect_data_for_tag(Tag::new(b"cvt "))?;
276        table_data.read_array(0..table_data.len())
277    }
278
279    /// Returns the font program, which contains the TrueType instructions
280    /// run once per font.
281    fn fpgm(&self) -> Result<&'a [u8], ReadError> {
282        self.expect_data_for_tag(Tag::new(b"fpgm"))
283            .map(|data| data.as_bytes())
284    }
285
286    /// Returns the control value program, which contains the TrueType
287    /// instructions run once per size.
288    fn prep(&self) -> Result<&'a [u8], ReadError> {
289        self.expect_data_for_tag(Tag::new(b"prep"))
290            .map(|data| data.as_bytes())
291    }
292
293    fn cvar(&self) -> Result<tables::cvar::Cvar<'a>, ReadError> {
294        self.expect_table()
295    }
296
297    fn cff(&self) -> Result<tables::cff::Cff<'a>, ReadError> {
298        self.expect_table()
299    }
300
301    fn cff2(&self) -> Result<tables::cff2::Cff2<'a>, ReadError> {
302        self.expect_table()
303    }
304
305    fn cmap(&self) -> Result<tables::cmap::Cmap<'a>, ReadError> {
306        self.expect_table()
307    }
308
309    /// Reads the `DMAP` table (ISO/IEC 14496-22:2026).
310    fn dmap(&self) -> Result<tables::cmap::Dmap<'a>, ReadError> {
311        self.expect_table()
312    }
313
314    fn gdef(&self) -> Result<tables::gdef::Gdef<'a>, ReadError> {
315        self.expect_table()
316    }
317
318    fn gpos(&self) -> Result<tables::gpos::Gpos<'a>, ReadError> {
319        self.expect_table()
320    }
321
322    fn gsub(&self) -> Result<tables::gsub::Gsub<'a>, ReadError> {
323        self.expect_table()
324    }
325
326    fn feat(&self) -> Result<tables::feat::Feat<'a>, ReadError> {
327        self.expect_table()
328    }
329
330    fn ltag(&self) -> Result<tables::ltag::Ltag<'a>, ReadError> {
331        self.expect_table()
332    }
333
334    fn ankr(&self) -> Result<tables::ankr::Ankr<'a>, ReadError> {
335        self.expect_table()
336    }
337
338    fn trak(&self) -> Result<tables::trak::Trak<'a>, ReadError> {
339        self.expect_table()
340    }
341
342    fn morx(&self) -> Result<tables::morx::Morx<'a>, ReadError> {
343        self.expect_table()
344    }
345
346    fn mort(&self) -> Result<tables::mort::Mort<'a>, ReadError> {
347        self.expect_table()
348    }
349
350    fn kerx(&self) -> Result<tables::kerx::Kerx<'a>, ReadError> {
351        self.expect_table()
352    }
353
354    fn kern(&self) -> Result<tables::kern::Kern<'a>, ReadError> {
355        self.expect_table()
356    }
357
358    fn colr(&self) -> Result<tables::colr::Colr<'a>, ReadError> {
359        self.expect_table()
360    }
361
362    fn cpal(&self) -> Result<tables::cpal::Cpal<'a>, ReadError> {
363        self.expect_table()
364    }
365
366    fn cblc(&self) -> Result<tables::cblc::Cblc<'a>, ReadError> {
367        self.expect_table()
368    }
369
370    fn cbdt(&self) -> Result<tables::cbdt::Cbdt<'a>, ReadError> {
371        self.expect_table()
372    }
373
374    fn eblc(&self) -> Result<tables::eblc::Eblc<'a>, ReadError> {
375        self.expect_table()
376    }
377
378    fn ebdt(&self) -> Result<tables::ebdt::Ebdt<'a>, ReadError> {
379        self.expect_table()
380    }
381
382    fn sbix(&self) -> Result<tables::sbix::Sbix<'a>, ReadError> {
383        // should we make the user pass this in?
384        let num_glyphs = self.selected_maxp()?.num_glyphs();
385        let data = self.expect_data_for_tag(tables::sbix::Sbix::TAG)?;
386        tables::sbix::Sbix::read(data, num_glyphs)
387    }
388
389    fn stat(&self) -> Result<tables::stat::Stat<'a>, ReadError> {
390        self.expect_table()
391    }
392
393    fn svg(&self) -> Result<tables::svg::Svg<'a>, ReadError> {
394        self.expect_table()
395    }
396
397    fn varc(&self) -> Result<tables::varc::Varc<'a>, ReadError> {
398        self.expect_table()
399    }
400
401    #[cfg(feature = "ift")]
402    fn ift(&self) -> Result<tables::ift::IftPatchMap<'a>, ReadError> {
403        self.expect_data_for_tag(tables::ift::IFT_TAG)
404            .and_then(FontRead::read)
405    }
406
407    #[cfg(feature = "ift")]
408    fn iftx(&self) -> Result<tables::ift::IftPatchMap<'a>, ReadError> {
409        self.expect_data_for_tag(tables::ift::IFTX_TAG)
410            .and_then(FontRead::read)
411    }
412
413    fn meta(&self) -> Result<tables::meta::Meta<'a>, ReadError> {
414        self.expect_table()
415    }
416
417    fn base(&self) -> Result<tables::base::Base<'a>, ReadError> {
418        self.expect_table()
419    }
420
421    fn dsig(&self) -> Result<tables::dsig::Dsig<'a>, ReadError> {
422        self.expect_table()
423    }
424
425    fn math(&self) -> Result<tables::math::Math<'a>, ReadError> {
426        self.expect_table()
427    }
428}
429
430#[cfg(test)]
431mod tests {
432
433    use super::*;
434
435    #[test]
436    fn extended_metrics_are_selected_independently_of_outlines() {
437        use crate::{types::GlyphId, FontRef};
438        use font_test_data::extended::metrics_font;
439        for outline in [None, Some(*b"glyf"), Some(*b"GLYF")] {
440            for (extended, legacy) in [(true, false), (true, true), (false, true)] {
441                let data = metrics_font(extended, legacy, outline);
442                let font = FontRef::new(&data).unwrap();
443                let expected_count = if extended { 70002 } else { 3 };
444                let long_count = if extended { 70000 } else { 2 };
445                assert_eq!(font.selected_maxp().unwrap().num_glyphs(), expected_count);
446                assert_eq!(
447                    font.selected_hhea().unwrap().number_of_h_metrics(),
448                    long_count
449                );
450                assert_eq!(
451                    font.selected_vhea().unwrap().number_of_long_ver_metrics(),
452                    long_count
453                );
454                let horizontal = font.h_glyph_metric_records().unwrap();
455                let vertical = font.v_glyph_metric_records().unwrap();
456                assert_eq!(horizontal.long_metrics().len() as u32, long_count);
457                assert_eq!(vertical.long_metrics().len() as u32, long_count);
458                assert_eq!(
459                    horizontal.side_bearings().len(),
460                    if extended { 2 } else { 1 }
461                );
462                assert_eq!(
463                    horizontal.advance(GlyphId::new(0)),
464                    Some(if extended { 1000 } else { 500 })
465                );
466                assert_eq!(
467                    vertical.advance(GlyphId::new(0)),
468                    Some(if extended { 1200 } else { 600 })
469                );
470                if extended {
471                    for gid in [65535, 65536, 69999] {
472                        assert_eq!(
473                            horizontal.advance(GlyphId::new(gid)),
474                            Some(1000 + (gid % 100) as u16)
475                        );
476                        assert_eq!(
477                            horizontal.side_bearing(GlyphId::new(gid)),
478                            Some(-((gid % 300) as i16))
479                        );
480                    }
481                    for gid in [70000, 70001] {
482                        assert_eq!(horizontal.advance(GlyphId::new(gid)), Some(1099));
483                        assert_eq!(vertical.advance(GlyphId::new(gid)), Some(1299));
484                        assert_eq!(
485                            horizontal.side_bearing(GlyphId::new(gid)),
486                            Some(-(10 + (gid - 70000) as i16))
487                        );
488                    }
489                    assert_eq!(horizontal.side_bearing(GlyphId::new(70002)), None);
490                }
491            }
492        }
493    }
494
495    #[test]
496    fn extended_glyph_count_does_not_require_extended_metrics() {
497        use crate::{types::GlyphId, FontRef};
498        use font_test_data::extended::{font, maxp, metric_data, metric_header};
499        let profile = maxp(70002, true);
500        let header = metric_header(2, false, false);
501        let records = metric_data(2, 1, 500);
502        let data = font(&[
503            (*b"MAXP", &profile),
504            (*b"hhea", &header),
505            (*b"hmtx", &records),
506        ]);
507        let font = FontRef::new(&data).unwrap();
508        assert_eq!(font.selected_maxp().unwrap().num_glyphs(), 70002);
509        let metrics = font.h_glyph_metric_records().unwrap();
510        assert_eq!(metrics.long_metrics().len(), 2);
511        assert_eq!(metrics.advance(GlyphId::new(2)), Some(501));
512        assert_eq!(metrics.side_bearing(GlyphId::new(2)), Some(-10));
513    }
514
515    #[test]
516    fn malformed_extended_tables_do_not_fall_back_to_legacy() {
517        use crate::{types::GlyphId, FontRef};
518        use font_test_data::extended::{font, maxp, metric_data, metric_header};
519        let profile = maxp(3, false);
520        let header = metric_header(2, false, false);
521        let records = metric_data(2, 1, 500);
522        let data = font(&[
523            (*b"MAXP", &[0, 0]),
524            (*b"maxp", &profile),
525            (*b"HHEA", &[0, 0]),
526            (*b"hhea", &header),
527            (*b"hmtx", &records),
528        ]);
529        let font_ref = FontRef::new(&data).unwrap();
530        assert!(font_ref.selected_maxp().is_err());
531        assert!(font_ref.selected_hhea().is_err());
532        // Metrics selection is independent of the malformed uppercase header
533        // when there is no HMTX table to use it.
534        assert_eq!(
535            font_ref
536                .h_glyph_metric_records()
537                .unwrap()
538                .advance(GlyphId::new(0)),
539            Some(500)
540        );
541        let data = font(&[
542            (*b"HMTX", &records),
543            (*b"hhea", &header),
544            (*b"hmtx", &records),
545        ]);
546        let font_ref = FontRef::new(&data).unwrap();
547        assert!(font_ref.h_glyph_metric_records().is_err());
548    }
549
550    #[test]
551    fn extended_metrics_with_truncated_or_extreme_counts() {
552        use crate::{types::GlyphId, FontRef};
553        use font_test_data::extended::{font, metric_data, metric_header};
554        let records = metric_data(2, 1, 500);
555        for count in [0, 3, u32::MAX] {
556            let horizontal = metric_header(count, true, false);
557            let vertical = metric_header(count, true, true);
558            let data = font(&[
559                (*b"HHEA", &horizontal),
560                (*b"HMTX", &records),
561                (*b"VHEA", &vertical),
562                (*b"VMTX", &records),
563            ]);
564            let font = FontRef::new(&data).unwrap();
565            // Like the legacy readers, truncated long-metric arrays read as
566            // empty rather than exposing a partial record array.
567            for metrics in [
568                font.h_glyph_metric_records().unwrap(),
569                font.v_glyph_metric_records().unwrap(),
570            ] {
571                assert!(metrics.long_metrics().is_empty());
572                assert_eq!(metrics.advance(GlyphId::new(0)), None);
573                assert_eq!(metrics.advance(GlyphId::new(u32::MAX)), None);
574                if count != 0 {
575                    assert!(metrics.side_bearings().is_empty());
576                    assert_eq!(metrics.side_bearing(GlyphId::new(0)), None);
577                }
578            }
579        }
580    }
581
582    #[test]
583    fn extended_outline_tables_are_selected_as_a_pair() {
584        use crate::{tables::glyf::Glyph, types::GlyphId, FontRef};
585        use font_test_data::extended::outlines_font;
586        for long_loca in [false, true] {
587            for legacy in [false, true] {
588                for extended_metrics in [false, true] {
589                    let data = outlines_font(true, legacy, extended_metrics, long_loca);
590                    let font = FontRef::new(&data).unwrap();
591                    let (glyf, loca) = font.selected_glyf_loca(None).unwrap();
592                    assert_eq!(loca.len(), 65537);
593                    let Glyph::Composite(composite) = loca
594                        .get(GlyphId::new(1), &glyf)
595                        .unwrap()
596                        .into_glyph()
597                        .unwrap()
598                    else {
599                        panic!("expected composite")
600                    };
601                    assert_eq!(
602                        composite.components().next().unwrap().glyph,
603                        GlyphId::new(65536)
604                    );
605                    assert_eq!(
606                        composite.component_glyphs_and_flags().next().unwrap().0,
607                        GlyphId::new(65536)
608                    );
609                    assert_eq!(composite.count_and_instructions(), (1, None));
610                    assert!(loca
611                        .get(GlyphId::new(65536), &glyf)
612                        .unwrap()
613                        .glyph()
614                        .is_some());
615                    assert!(loca.get(GlyphId::new(65537), &glyf).is_none());
616                }
617            }
618        }
619    }
620
621    #[test]
622    fn extended_outline_pair_does_not_use_legacy_locations() {
623        use crate::FontRef;
624        use font_test_data::extended::{font, outlines_font};
625        let data = outlines_font(true, true, true, true);
626        let source = FontRef::new(&data).unwrap();
627        let tables: Vec<_> = source
628            .table_directory()
629            .table_records()
630            .iter()
631            .filter(|record| record.tag() != Tag::new(b"LOCA"))
632            .map(|record| {
633                (
634                    record.tag().to_be_bytes(),
635                    source.table_data(record.tag()).unwrap().as_bytes(),
636                )
637            })
638            .collect();
639        let data = font(&tables);
640        let source = FontRef::new(&data).unwrap();
641        assert!(
642            matches!(source.selected_glyf_loca(None), Err(ReadError::TableIsMissing(tag)) if tag == Tag::new(b"LOCA"))
643        );
644        assert!(source.glyf().is_ok());
645        assert!(source.loca(None).is_ok());
646        let mut tables = tables;
647        tables.push((*b"LOCA", &[0]));
648        let data = font(&tables);
649        let source = FontRef::new(&data).unwrap();
650        assert!(source.selected_glyf_loca(None).is_err());
651    }
652
653    /// https://github.com/googlefonts/fontations/issues/105
654    #[test]
655    fn bug_105() {
656        // serve some dummy versions of the tables used to compute hmtx. The only
657        // fields that matter are maxp::num_glyphs and hhea::number_of_h_metrics,
658        // everything else is zero'd out
659        struct DummyProvider;
660        impl TableProvider<'static> for DummyProvider {
661            fn data_for_tag(&self, tag: Tag) -> Option<FontData<'static>> {
662                if tag == Tag::new(b"maxp") {
663                    Some(FontData::new(&[
664                        0, 0, 0x50, 0, // version 0.5
665                        0, 3, // num_glyphs = 3
666                    ]))
667                } else if tag == Tag::new(b"hhea") {
668                    Some(FontData::new(&[
669                        0, 1, 0, 0, // version 1.0
670                        0, 0, 0, 0, // ascender/descender
671                        0, 0, 0, 0, // line gap/advance width
672                        0, 0, 0, 0, // min left/right side bearing
673                        0, 0, 0, 0, // x_max, caret_slope_rise
674                        0, 0, 0, 0, // caret_slope_run, caret_offset
675                        0, 0, 0, 0, // reserved1/2
676                        0, 0, 0, 0, // reserved 3/4
677                        0, 0, 0, 1, // metric format, number_of_h_metrics
678                    ]))
679                } else if tag == Tag::new(b"hmtx") {
680                    Some(FontData::new(&[
681                        0, 4, 0, 6, // LongHorMetric: 4, 6
682                        0, 30, 0, 111, // two lsb entries
683                    ]))
684                } else {
685                    None
686                }
687            }
688        }
689
690        let number_of_h_metrics = DummyProvider.hhea().unwrap().number_of_h_metrics();
691        let num_glyphs = DummyProvider.maxp().unwrap().num_glyphs();
692        let hmtx = DummyProvider.hmtx().unwrap();
693
694        assert_eq!(number_of_h_metrics, 1);
695        assert_eq!(num_glyphs, 3);
696        assert_eq!(hmtx.h_metrics().len(), 1);
697        assert_eq!(hmtx.left_side_bearings().len(), 2);
698    }
699}