Skip to main content

font_parse/tables/
layout.rs

1//! `GSUB`/`GPOS` — layout common structure: script, feature, and lookup
2//! lists (header structure only; lookup subtables are out of scope).
3
4use crate::error::{ParseError, RawTag};
5use crate::reader::Reader;
6use alloc::vec::Vec;
7use font_types::Tag;
8
9pub(crate) const GSUB: RawTag = *b"GSUB";
10pub(crate) const GPOS: RawTag = *b"GPOS";
11
12/// Which layout table a view wraps.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum LayoutKind {
15    /// Glyph substitution (`GSUB`).
16    Gsub,
17    /// Glyph positioning (`GPOS`).
18    Gpos,
19}
20
21impl LayoutKind {
22    /// Raw table tag.
23    #[must_use]
24    pub const fn tag(self) -> RawTag {
25        match self {
26            LayoutKind::Gsub => GSUB,
27            LayoutKind::Gpos => GPOS,
28        }
29    }
30}
31
32/// Zero-copy view over a `GSUB`/`GPOS` table.
33#[derive(Debug, Clone, Copy)]
34pub struct LayoutTable<'a> {
35    data: &'a [u8],
36    kind: LayoutKind,
37}
38
39impl<'a> LayoutTable<'a> {
40    /// Parse and validate the layout table header.
41    ///
42    /// # Errors
43    /// [`ParseError::TruncatedTable`] for short headers;
44    /// [`ParseError::InvalidGlyphFormat`] when the list offsets fall outside
45    /// the table.
46    pub fn parse(data: &'a [u8], kind: LayoutKind) -> Result<Self, ParseError> {
47        match crate::reader::be_u16_at(data, 0, kind.tag())? {
48            // Version 1.0: three u16 offsets. 1.1: adds a u32 offset — the
49            // base header size is the same through lookupListOffset.
50            1 => {}
51            _ => return Err(ParseError::InvalidGlyphFormat),
52        }
53        if data.len() < 10 {
54            return Err(ParseError::TruncatedTable {
55                tag: kind.tag(),
56                expected: 10,
57                got: data.len(),
58            });
59        }
60        for at in [4usize, 6, 8] {
61            let off = usize::from(crate::reader::be_u16_at(data, at, kind.tag())?);
62            if off != 0 && off >= data.len() {
63                return Err(ParseError::InvalidGlyphFormat);
64            }
65        }
66        Ok(Self { data, kind })
67    }
68
69    /// Raw table bytes.
70    #[must_use]
71    pub fn as_bytes(&self) -> &'a [u8] {
72        self.data
73    }
74
75    /// Which table this view wraps.
76    #[must_use]
77    pub const fn kind(&self) -> LayoutKind {
78        self.kind
79    }
80
81    /// Major/minor version (1.0 or 1.1).
82    ///
83    /// # Errors
84    /// Truncation (impossible post-[`parse`](Self::parse)).
85    pub fn version(&self) -> Result<(u16, u16), ParseError> {
86        Ok((
87            crate::reader::be_u16_at(self.data, 0, self.kind.tag())?,
88            crate::reader::be_u16_at(self.data, 2, self.kind.tag())?,
89        ))
90    }
91
92    /// The script list.
93    ///
94    /// # Errors
95    /// Parse errors from the list decoder.
96    pub fn script_list(&self) -> Result<ScriptList<'a>, ParseError> {
97        let off = usize::from(crate::reader::be_u16_at(self.data, 4, self.kind.tag())?);
98        if off == 0 {
99            return Err(ParseError::InvalidGlyphFormat);
100        }
101        ScriptList::parse(self.data, off, self.kind)
102    }
103
104    /// The feature list.
105    ///
106    /// # Errors
107    /// Parse errors from the list decoder.
108    pub fn feature_list(&self) -> Result<FeatureList<'a>, ParseError> {
109        let off = usize::from(crate::reader::be_u16_at(self.data, 6, self.kind.tag())?);
110        if off == 0 {
111            return Err(ParseError::InvalidGlyphFormat);
112        }
113        FeatureList::parse(self.data, off, self.kind)
114    }
115
116    /// The lookup list.
117    ///
118    /// # Errors
119    /// Parse errors from the list decoder.
120    pub fn lookup_list(&self) -> Result<LookupList<'a>, ParseError> {
121        let off = usize::from(crate::reader::be_u16_at(self.data, 8, self.kind.tag())?);
122        if off == 0 {
123            return Err(ParseError::InvalidGlyphFormat);
124        }
125        LookupList::parse(self.data, off, self.kind)
126    }
127}
128
129/// A record tag plus its offset within the list.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub(crate) struct ListRecord {
132    pub(crate) tag: Tag,
133    pub(crate) offset: u16,
134}
135
136/// Read a list header: `count: u16` followed by `(tag: u32, offset: u16)`
137/// records.
138fn read_list(data: &[u8], base: usize, tag: RawTag) -> Result<(u16, Vec<ListRecord>), ParseError> {
139    if base.checked_add(2).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
140        return Err(ParseError::TruncatedTable {
141            tag,
142            expected: base + 2,
143            got: data.len(),
144        });
145    }
146    let count = crate::reader::be_u16_at(data, base, tag)?;
147    let records_at = base + 2;
148    let end = records_at
149        .checked_add(usize::from(count) * 6)
150        .ok_or(ParseError::InvalidGlyphFormat)?;
151    if end > data.len() {
152        return Err(ParseError::TruncatedTable {
153            tag,
154            expected: end,
155            got: data.len(),
156        });
157    }
158    let mut records = Vec::with_capacity(usize::from(count));
159    for i in 0..usize::from(count) {
160        let at = records_at + i * 6;
161        let raw = crate::reader::be_u32_at(data, at, tag)?;
162        let offset = crate::reader::be_u16_at(data, at + 4, tag)?;
163        records.push(ListRecord {
164            tag: Tag::new(&raw.to_be_bytes()),
165            offset,
166        });
167    }
168    Ok((count, records))
169}
170
171/// The script list: script tags with their script tables.
172#[derive(Debug, Clone, Copy)]
173pub struct ScriptList<'a> {
174    data: &'a [u8],
175    base: usize,
176    kind: LayoutKind,
177}
178
179impl<'a> ScriptList<'a> {
180    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
181        read_list(data, base, kind.tag())?;
182        Ok(Self { data, base, kind })
183    }
184
185    /// Script tags in table order.
186    ///
187    /// # Errors
188    /// List decoding errors (validated at construction; cannot fail).
189    pub fn tags(&self) -> Result<Vec<Tag>, ParseError> {
190        Ok(read_list(self.data, self.base, self.kind.tag())?
191            .1
192            .into_iter()
193            .map(|r| r.tag)
194            .collect())
195    }
196
197    /// Decode script `tag`.
198    ///
199    /// # Errors
200    /// [`ParseError::InvalidGlyphFormat`] when the script offset is out of
201    /// range; parse errors from the script table.
202    pub fn script(&self, tag: Tag) -> Result<Option<Script<'a>>, ParseError> {
203        for r in read_list(self.data, self.base, self.kind.tag())?.1 {
204            if r.tag == tag {
205                return Script::parse(self.data, self.base + usize::from(r.offset), self.kind)
206                    .map(Some);
207            }
208        }
209        Ok(None)
210    }
211}
212
213/// One script: a default language system plus tagged alternates.
214#[derive(Debug, Clone, Copy)]
215pub struct Script<'a> {
216    data: &'a [u8],
217    base: usize,
218    kind: LayoutKind,
219}
220
221impl<'a> Script<'a> {
222    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
223        if base.checked_add(4).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
224            return Err(ParseError::TruncatedTable {
225                tag: kind.tag(),
226                expected: base + 4,
227                got: data.len(),
228            });
229        }
230        Ok(Self { data, base, kind })
231    }
232
233    fn read_lang_sys_list(&self) -> Result<(u16, Vec<ListRecord>), ParseError> {
234        let count = crate::reader::be_u16_at(self.data, self.base + 2, self.kind.tag())?;
235        let records_at = self.base + 4;
236        let end = records_at
237            .checked_add(usize::from(count) * 6)
238            .ok_or(ParseError::InvalidGlyphFormat)?;
239        if end > self.data.len() {
240            return Err(ParseError::TruncatedTable {
241                tag: self.kind.tag(),
242                expected: end,
243                got: self.data.len(),
244            });
245        }
246        let mut records = Vec::with_capacity(usize::from(count));
247        for i in 0..usize::from(count) {
248            let at = records_at + i * 6;
249            let raw = crate::reader::be_u32_at(self.data, at, self.kind.tag())?;
250            let offset = crate::reader::be_u16_at(self.data, at + 4, self.kind.tag())?;
251            records.push(ListRecord {
252                tag: Tag::new(&raw.to_be_bytes()),
253                offset,
254            });
255        }
256        Ok((count, records))
257    }
258
259    /// The default language system (offset 0 = none).
260    ///
261    /// # Errors
262    /// LangSys parse errors.
263    pub fn default_lang_sys(&self) -> Result<Option<LangSys<'a>>, ParseError> {
264        let off = crate::reader::be_u16_at(self.data, self.base, self.kind.tag())?;
265        if off == 0 {
266            return Ok(None);
267        }
268        LangSys::parse(self.data, self.base + usize::from(off), self.kind).map(Some)
269    }
270
271    /// Alternate language-system tags.
272    ///
273    /// # Errors
274    /// Truncation of the record array.
275    pub fn lang_sys_tags(&self) -> Result<Vec<Tag>, ParseError> {
276        Ok(self
277            .read_lang_sys_list()?
278            .1
279            .into_iter()
280            .map(|r| r.tag)
281            .collect())
282    }
283
284    /// Decode an alternate language system by tag.
285    ///
286    /// # Errors
287    /// LangSys parse errors.
288    pub fn lang_sys(&self, tag: Tag) -> Result<Option<LangSys<'a>>, ParseError> {
289        for r in self.read_lang_sys_list()?.1 {
290            if r.tag == tag {
291                return LangSys::parse(self.data, self.base + usize::from(r.offset), self.kind)
292                    .map(Some);
293            }
294        }
295        Ok(None)
296    }
297}
298
299/// A language system: required feature plus feature index list.
300#[derive(Debug, Clone, Copy)]
301pub struct LangSys<'a> {
302    data: &'a [u8],
303    base: usize,
304    kind: LayoutKind,
305}
306
307impl<'a> LangSys<'a> {
308    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
309        if base.checked_add(6).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
310            return Err(ParseError::TruncatedTable {
311                tag: kind.tag(),
312                expected: base + 6,
313                got: data.len(),
314            });
315        }
316        let count = crate::reader::be_u16_at(data, base + 4, kind.tag())?;
317        let end = base
318            .checked_add(6)
319            .and_then(|v| v.checked_add(usize::from(count) * 2))
320            .ok_or(ParseError::InvalidGlyphFormat)?;
321        if end > data.len() {
322            return Err(ParseError::TruncatedTable {
323                tag: kind.tag(),
324                expected: end,
325                got: data.len(),
326            });
327        }
328        Ok(Self { data, base, kind })
329    }
330
331    /// Required feature index (`0xFFFF` = none).
332    ///
333    /// # Errors
334    /// Truncation (impossible post-parse).
335    pub fn required_feature_index(&self) -> Result<u16, ParseError> {
336        crate::reader::be_u16_at(self.data, self.base + 2, self.kind.tag())
337    }
338
339    /// Feature indices, in table order.
340    ///
341    /// # Errors
342    /// Truncation (impossible post-parse).
343    pub fn feature_indices(&self) -> Result<Vec<u16>, ParseError> {
344        let count = usize::from(crate::reader::be_u16_at(
345            self.data,
346            self.base + 4,
347            self.kind.tag(),
348        )?);
349        let mut out = Vec::with_capacity(count);
350        for i in 0..count {
351            out.push(crate::reader::be_u16_at(
352                self.data,
353                self.base + 6 + i * 2,
354                self.kind.tag(),
355            )?);
356        }
357        Ok(out)
358    }
359}
360
361/// The feature list: feature tags with their feature tables.
362#[derive(Debug, Clone, Copy)]
363pub struct FeatureList<'a> {
364    data: &'a [u8],
365    base: usize,
366    kind: LayoutKind,
367}
368
369impl<'a> FeatureList<'a> {
370    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
371        read_list(data, base, kind.tag())?;
372        Ok(Self { data, base, kind })
373    }
374
375    /// Feature tags in table order.
376    ///
377    /// # Errors
378    /// List decoding errors (validated at construction; cannot fail).
379    pub fn tags(&self) -> Result<Vec<Tag>, ParseError> {
380        Ok(read_list(self.data, self.base, self.kind.tag())?
381            .1
382            .into_iter()
383            .map(|r| r.tag)
384            .collect())
385    }
386
387    /// Decode feature `tag` (first match).
388    ///
389    /// # Errors
390    /// Feature parse errors.
391    pub fn feature(&self, tag: Tag) -> Result<Option<Feature<'a>>, ParseError> {
392        for r in read_list(self.data, self.base, self.kind.tag())?.1 {
393            if r.tag == tag {
394                return Feature::parse(self.data, self.base + usize::from(r.offset), self.kind)
395                    .map(Some);
396            }
397        }
398        Ok(None)
399    }
400}
401
402/// One feature: the list of lookups it activates.
403#[derive(Debug, Clone, Copy)]
404pub struct Feature<'a> {
405    data: &'a [u8],
406    base: usize,
407    kind: LayoutKind,
408}
409
410impl<'a> Feature<'a> {
411    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
412        if base.checked_add(4).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
413            return Err(ParseError::TruncatedTable {
414                tag: kind.tag(),
415                expected: base + 4,
416                got: data.len(),
417            });
418        }
419        let count = crate::reader::be_u16_at(data, base + 2, kind.tag())?;
420        let end = base
421            .checked_add(4)
422            .and_then(|v| v.checked_add(usize::from(count) * 2))
423            .ok_or(ParseError::InvalidGlyphFormat)?;
424        if end > data.len() {
425            return Err(ParseError::TruncatedTable {
426                tag: kind.tag(),
427                expected: end,
428                got: data.len(),
429            });
430        }
431        Ok(Self { data, base, kind })
432    }
433
434    /// Lookup list indices, in table order.
435    ///
436    /// # Errors
437    /// Truncation (impossible post-parse).
438    pub fn lookup_indices(&self) -> Result<Vec<u16>, ParseError> {
439        let count = usize::from(crate::reader::be_u16_at(
440            self.data,
441            self.base + 2,
442            self.kind.tag(),
443        )?);
444        let mut out = Vec::with_capacity(count);
445        for i in 0..count {
446            out.push(crate::reader::be_u16_at(
447                self.data,
448                self.base + 4 + i * 2,
449                self.kind.tag(),
450            )?);
451        }
452        Ok(out)
453    }
454}
455
456/// The lookup list.
457#[derive(Debug, Clone, Copy)]
458pub struct LookupList<'a> {
459    data: &'a [u8],
460    base: usize,
461    kind: LayoutKind,
462    count: u16,
463}
464
465impl<'a> LookupList<'a> {
466    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
467        if base.checked_add(2).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
468            return Err(ParseError::TruncatedTable {
469                tag: kind.tag(),
470                expected: base + 2,
471                got: data.len(),
472            });
473        }
474        let count = crate::reader::be_u16_at(data, base, kind.tag())?;
475        let end = base
476            .checked_add(2)
477            .and_then(|v| v.checked_add(usize::from(count) * 2))
478            .ok_or(ParseError::InvalidGlyphFormat)?;
479        if end > data.len() {
480            return Err(ParseError::TruncatedTable {
481                tag: kind.tag(),
482                expected: end,
483                got: data.len(),
484            });
485        }
486        Ok(Self {
487            data,
488            base,
489            kind,
490            count,
491        })
492    }
493
494    /// Number of lookups.
495    #[must_use]
496    pub const fn count(&self) -> u16 {
497        self.count
498    }
499
500    /// Decode lookup `index`.
501    ///
502    /// # Errors
503    /// [`ParseError::InvalidGlyphFormat`] for out-of-range indices or bad
504    /// offsets; lookup parse errors otherwise.
505    pub fn lookup(&self, index: u16) -> Result<Lookup<'a>, ParseError> {
506        if index >= self.count {
507            return Err(ParseError::InvalidGlyphFormat);
508        }
509        let off = crate::reader::be_u16_at(
510            self.data,
511            self.base + 2 + usize::from(index) * 2,
512            self.kind.tag(),
513        )?;
514        Lookup::parse(self.data, self.base + usize::from(off), self.kind)
515    }
516}
517
518/// One lookup: type, flags, and subtable count (subtables themselves are out
519/// of scope for v1).
520#[derive(Debug, Clone, Copy)]
521pub struct Lookup<'a> {
522    data: &'a [u8],
523    base: usize,
524    kind: LayoutKind,
525    sub_table_count: u16,
526}
527
528impl<'a> Lookup<'a> {
529    fn parse(data: &'a [u8], base: usize, kind: LayoutKind) -> Result<Self, ParseError> {
530        if base.checked_add(6).ok_or(ParseError::InvalidGlyphFormat)? > data.len() {
531            return Err(ParseError::TruncatedTable {
532                tag: kind.tag(),
533                expected: base + 6,
534                got: data.len(),
535            });
536        }
537        let mut r = Reader::within(data, base, data.len(), kind.tag());
538        r.skip(4)?;
539        let sub_table_count = r.u16()?;
540        let end = base
541            .checked_add(6)
542            .and_then(|v| v.checked_add(usize::from(sub_table_count) * 2))
543            .ok_or(ParseError::InvalidGlyphFormat)?;
544        if end > data.len() {
545            return Err(ParseError::TruncatedTable {
546                tag: kind.tag(),
547                expected: end,
548                got: data.len(),
549            });
550        }
551        Ok(Self {
552            data,
553            base,
554            kind,
555            sub_table_count,
556        })
557    }
558
559    /// Lookup type (GSUB 1-8, GPOS 1-9).
560    ///
561    /// # Errors
562    /// Truncation (impossible post-parse).
563    pub fn lookup_type(&self) -> Result<u16, ParseError> {
564        crate::reader::be_u16_at(self.data, self.base, self.kind.tag())
565    }
566
567    /// Lookup flag (bit 4 marks a mark-filtering set; see
568    /// [`mark_filtering_set`](Self::mark_filtering_set)).
569    ///
570    /// # Errors
571    /// Truncation (impossible post-parse).
572    pub fn lookup_flag(&self) -> Result<u16, ParseError> {
573        crate::reader::be_u16_at(self.data, self.base + 2, self.kind.tag())
574    }
575
576    /// Number of subtables.
577    #[must_use]
578    pub const fn sub_table_count(&self) -> u16 {
579        self.sub_table_count
580    }
581
582    /// Mark-filtering set index, present only when the lookup flag has bit 4
583    /// (0x0010) set.
584    ///
585    /// # Errors
586    /// Truncation of the extended lookup header.
587    pub fn mark_filtering_set(&self) -> Result<Option<u16>, ParseError> {
588        if self.lookup_flag()? & 0x0010 == 0 {
589            return Ok(None);
590        }
591        let at = self.base + 6 + usize::from(self.sub_table_count) * 2;
592        Ok(Some(crate::reader::be_u16_at(
593            self.data,
594            at,
595            self.kind.tag(),
596        )?))
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
603
604    use super::{LayoutKind, LayoutTable, Tag};
605
606    /// Test hook for the internal list reader.
607    pub(crate) fn read_list_public(data: &[u8], base: usize) -> Result<(), ParseError> {
608        super::read_list(data, base, *b"GSUB").map(|_| ())
609    }
610    use crate::error::ParseError;
611    use alloc::vec;
612    use alloc::vec::Vec;
613
614    /// Minimal GSUB: one script (DFLT) with a default LangSys, one feature
615    /// "liga" -> lookup 0, one lookup (type 1).
616    fn gsub() -> Vec<u8> {
617        // Header (10 bytes) then three lists.
618        let script_list = 10u16;
619        let feature_list = 30u16;
620        let lookup_list = 44u16;
621
622        let mut d = Vec::new();
623        d.extend_from_slice(&1u16.to_be_bytes()); // major
624        d.extend_from_slice(&0u16.to_be_bytes()); // minor
625        d.extend_from_slice(&script_list.to_be_bytes());
626        d.extend_from_slice(&feature_list.to_be_bytes());
627        d.extend_from_slice(&lookup_list.to_be_bytes());
628
629        // ScriptList @10: count + record(tag, offset)
630        d.extend_from_slice(&1u16.to_be_bytes());
631        d.extend_from_slice(b"DFLT");
632        d.extend_from_slice(&8u16.to_be_bytes()); // script at +8
633                                                  // Script @18: defaultLangSys offset, langSysCount
634        d.extend_from_slice(&4u16.to_be_bytes()); // langsys at +4
635        d.extend_from_slice(&0u16.to_be_bytes()); // no alternates
636                                                  // LangSys @22: lookupOrder, required, count, indices[]
637        d.extend_from_slice(&0u16.to_be_bytes());
638        d.extend_from_slice(&0xFFFFu16.to_be_bytes()); // no required feature
639        d.extend_from_slice(&1u16.to_be_bytes());
640        d.extend_from_slice(&0u16.to_be_bytes()); // feature 0
641
642        // FeatureList @30: count + record
643        d.extend_from_slice(&1u16.to_be_bytes());
644        d.extend_from_slice(b"liga");
645        d.extend_from_slice(&8u16.to_be_bytes()); // feature at +8
646                                                  // Feature @38: params offset, lookup count, indices
647        d.extend_from_slice(&0u16.to_be_bytes());
648        d.extend_from_slice(&1u16.to_be_bytes());
649        d.extend_from_slice(&0u16.to_be_bytes()); // lookup 0
650
651        // LookupList @44: count + offsets
652        d.extend_from_slice(&1u16.to_be_bytes());
653        d.extend_from_slice(&4u16.to_be_bytes()); // lookup at +4
654                                                  // Lookup @48: type, flag, subtable count, subtable offsets[]
655        d.extend_from_slice(&1u16.to_be_bytes()); // type 1
656        d.extend_from_slice(&0u16.to_be_bytes()); // flag
657        d.extend_from_slice(&1u16.to_be_bytes()); // 1 subtable
658        d.extend_from_slice(&8u16.to_be_bytes()); // subtable at lookup+8
659        d.extend_from_slice(&[0u8; 4]); // subtable bytes @52
660        d
661    }
662
663    #[test]
664    fn gsub_structure_walk() {
665        let d = gsub();
666        let t = LayoutTable::parse(&d, LayoutKind::Gsub).unwrap();
667        assert_eq!(t.kind(), LayoutKind::Gsub);
668        assert_eq!(t.version().unwrap(), (1, 0));
669
670        let scripts = t.script_list().unwrap();
671        let tags = scripts.tags().unwrap();
672        assert_eq!(tags, vec![Tag::new(b"DFLT")]);
673        let script = scripts.script(Tag::new(b"DFLT")).unwrap().unwrap();
674        let lang = script.default_lang_sys().unwrap().unwrap();
675        assert_eq!(lang.required_feature_index().unwrap(), 0xFFFF);
676        assert_eq!(lang.feature_indices().unwrap(), vec![0]);
677        assert!(script.lang_sys_tags().unwrap().is_empty());
678
679        let features = t.feature_list().unwrap();
680        assert_eq!(features.tags().unwrap(), vec![Tag::new(b"liga")]);
681        let feature = features.feature(Tag::new(b"liga")).unwrap().unwrap();
682        assert_eq!(feature.lookup_indices().unwrap(), vec![0]);
683
684        let lookups = t.lookup_list().unwrap();
685        assert_eq!(lookups.count(), 1);
686        let lookup = lookups.lookup(0).unwrap();
687        assert_eq!(lookup.lookup_type().unwrap(), 1);
688        assert_eq!(lookup.lookup_flag().unwrap(), 0);
689        assert_eq!(lookup.sub_table_count(), 1);
690        assert_eq!(lookup.mark_filtering_set().unwrap(), None);
691    }
692
693    #[test]
694    fn gpos_lookup_with_mark_filter() {
695        // Reuse the gsub bytes but declare them GPOS, set the mark-filter
696        // flag, and append the set index after the subtable offsets.
697        let mut d = gsub();
698        let lookup = 48usize;
699        d[lookup + 2..lookup + 4].copy_from_slice(&0x0010u16.to_be_bytes());
700        // Insert the set index between the offsets and the subtable, then
701        // shift the subtable offset past it.
702        d[lookup + 6..lookup + 8].copy_from_slice(&10u16.to_be_bytes());
703        d.splice(lookup + 8..lookup + 8, [0u8, 7]);
704        let t = LayoutTable::parse(&d, LayoutKind::Gpos).unwrap();
705        assert_eq!(t.kind(), LayoutKind::Gpos);
706        let lookup = t.lookup_list().unwrap().lookup(0).unwrap();
707        assert_eq!(lookup.lookup_flag().unwrap(), 0x0010);
708        assert_eq!(lookup.mark_filtering_set().unwrap(), Some(7));
709    }
710
711    #[test]
712    fn errors() {
713        // Truncated header.
714        assert!(matches!(
715            LayoutTable::parse(&[0, 1, 0], LayoutKind::Gsub),
716            Err(ParseError::TruncatedTable { .. })
717        ));
718        // Bad version.
719        let mut d = gsub();
720        d[0..2].copy_from_slice(&3u16.to_be_bytes());
721        assert!(matches!(
722            LayoutTable::parse(&d, LayoutKind::Gsub),
723            Err(ParseError::InvalidGlyphFormat)
724        ));
725        // List offset out of range.
726        let mut d = gsub();
727        d[4..6].copy_from_slice(&0xFFFEu16.to_be_bytes());
728        assert!(matches!(
729            LayoutTable::parse(&d, LayoutKind::Gsub),
730            Err(ParseError::InvalidGlyphFormat)
731        ));
732        // Missing script.
733        let t = LayoutTable::parse(&d, LayoutKind::Gsub);
734        let _ = t.and_then(|t| t.script_list().unwrap().script(Tag::new(b"arab")));
735        // Lookup out of range.
736        let d = gsub();
737        let t = LayoutTable::parse(&d, LayoutKind::Gsub).unwrap();
738        assert!(matches!(
739            t.lookup_list().unwrap().lookup(9),
740            Err(ParseError::InvalidGlyphFormat)
741        ));
742    }
743}
744
745#[cfg(test)]
746mod edge_tests {
747    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
748
749    use super::{LayoutKind, LayoutTable, Tag};
750    use crate::error::ParseError;
751    use alloc::vec;
752    use alloc::vec::Vec;
753
754    /// Script with a default LangSys plus one alternate ( Armen).
755    fn script_with_alternate() -> Vec<u8> {
756        let mut d = Vec::new();
757        // Script: defaultLangSys at +8, langSysCount 1, record (tag, offset).
758        d.extend_from_slice(&8u16.to_be_bytes());
759        d.extend_from_slice(&1u16.to_be_bytes());
760        d.extend_from_slice(b"ARMN");
761        d.extend_from_slice(&16u16.to_be_bytes()); // alternate at +16
762                                                   // Default LangSys @8.
763        d.extend_from_slice(&0u16.to_be_bytes());
764        d.extend_from_slice(&0xFFFFu16.to_be_bytes());
765        d.extend_from_slice(&0u16.to_be_bytes());
766        // Alternate LangSys @20 (8 + 4 + 8 = 20): requires feature 3.
767        d.extend_from_slice(&0u16.to_be_bytes());
768        d.extend_from_slice(&2u16.to_be_bytes());
769        d.extend_from_slice(&1u16.to_be_bytes());
770        d.extend_from_slice(&3u16.to_be_bytes());
771        d
772    }
773
774    #[test]
775    fn alternate_lang_sys() {
776        let d = script_with_alternate();
777        // Wrap in a minimal single-script layout table.
778        let header = 10u16;
779        let script_list = header;
780        let mut t = Vec::new();
781        t.extend_from_slice(&1u16.to_be_bytes());
782        t.extend_from_slice(&0u16.to_be_bytes());
783        t.extend_from_slice(&script_list.to_be_bytes());
784        t.extend_from_slice(&0u16.to_be_bytes()); // no feature list
785        t.extend_from_slice(&0u16.to_be_bytes()); // no lookup list
786        t.extend_from_slice(&1u16.to_be_bytes());
787        t.extend_from_slice(b"DFLT");
788        t.extend_from_slice(&8u16.to_be_bytes()); // script at +8
789        t.extend_from_slice(&d);
790        let table = LayoutTable::parse(&t, LayoutKind::Gsub).unwrap();
791        let scripts = table.script_list().unwrap();
792        let script: super::Script = scripts.script(Tag::new(b"DFLT")).unwrap().unwrap();
793        assert_eq!(script.lang_sys_tags().unwrap(), vec![Tag::new(b"ARMN")]);
794        let alt = script.lang_sys(Tag::new(b"ARMN")).unwrap().unwrap();
795        assert_eq!(alt.required_feature_index().unwrap(), 2);
796        assert_eq!(alt.feature_indices().unwrap(), vec![3]);
797        // Unknown tag -> None.
798        assert!(script.lang_sys(Tag::new(b"kana")).unwrap().is_none());
799    }
800
801    #[test]
802    fn truncations() {
803        let d = script_with_alternate();
804        // Script table shorter than its header.
805        assert!(matches!(
806            super::Script::parse(&d, 0, LayoutKind::Gsub).and(Ok(())),
807            Ok(())
808        ));
809        // LangSys truncated.
810        assert!(super::LangSys::parse(&d, 8, LayoutKind::Gsub).is_err());
811        // Feature truncated (declared records exceed the buffer).
812        assert!(super::Feature::parse(&d[..2], 0, LayoutKind::Gsub).is_err());
813        // Feature with records beyond the buffer.
814        let mut f = vec![0u8; 4];
815        f[2..4].copy_from_slice(&9u16.to_be_bytes());
816        assert!(super::Feature::parse(&f, 0, LayoutKind::Gsub).is_err());
817        // Lookup truncated.
818        assert!(super::Lookup::parse(&d, 0, LayoutKind::Gsub).is_err());
819        // List record array truncated.
820        let mut short = vec![0u8; 4];
821        short[0..2].copy_from_slice(&3u16.to_be_bytes()); // 3 records, no bytes
822        assert!(matches!(
823            super::tests::read_list_public(&short, 0),
824            Err(ParseError::TruncatedTable { .. })
825        ));
826    }
827}