1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// THIS FILE IS AUTOGENERATED.
// Any changes to this file will be overwritten.
// For more information about how codegen works, see font-codegen/README.md

#[allow(unused_imports)]
use crate::codegen_prelude::*;

/// The OpenType [Table Directory](https://docs.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TableDirectoryMarker {
    table_records_byte_len: usize,
}

impl TableDirectoryMarker {
    fn sfnt_version_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u32::RAW_BYTE_LEN
    }
    fn num_tables_byte_range(&self) -> Range<usize> {
        let start = self.sfnt_version_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
    fn search_range_byte_range(&self) -> Range<usize> {
        let start = self.num_tables_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
    fn entry_selector_byte_range(&self) -> Range<usize> {
        let start = self.search_range_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
    fn range_shift_byte_range(&self) -> Range<usize> {
        let start = self.entry_selector_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
    fn table_records_byte_range(&self) -> Range<usize> {
        let start = self.range_shift_byte_range().end;
        start..start + self.table_records_byte_len
    }
}

impl<'a> FontRead<'a> for TableDirectory<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u32>();
        let num_tables: u16 = cursor.read()?;
        cursor.advance::<u16>();
        cursor.advance::<u16>();
        cursor.advance::<u16>();
        let table_records_byte_len = num_tables as usize * TableRecord::RAW_BYTE_LEN;
        cursor.advance_by(table_records_byte_len);
        cursor.finish(TableDirectoryMarker {
            table_records_byte_len,
        })
    }
}

/// The OpenType [Table Directory](https://docs.microsoft.com/en-us/typography/opentype/spec/otff#table-directory)
pub type TableDirectory<'a> = TableRef<'a, TableDirectoryMarker>;

impl<'a> TableDirectory<'a> {
    /// 0x00010000 or 0x4F54544F
    pub fn sfnt_version(&self) -> u32 {
        let range = self.shape.sfnt_version_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Number of tables.
    pub fn num_tables(&self) -> u16 {
        let range = self.shape.num_tables_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn search_range(&self) -> u16 {
        let range = self.shape.search_range_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn entry_selector(&self) -> u16 {
        let range = self.shape.entry_selector_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn range_shift(&self) -> u16 {
        let range = self.shape.range_shift_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Table records array—one for each top-level table in the font
    pub fn table_records(&self) -> &'a [TableRecord] {
        let range = self.shape.table_records_byte_range();
        self.data.read_array(range).unwrap()
    }
}

#[cfg(feature = "traversal")]
impl<'a> SomeTable<'a> for TableDirectory<'a> {
    fn type_name(&self) -> &str {
        "TableDirectory"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("sfnt_version", self.sfnt_version())),
            1usize => Some(Field::new("num_tables", self.num_tables())),
            2usize => Some(Field::new("search_range", self.search_range())),
            3usize => Some(Field::new("entry_selector", self.entry_selector())),
            4usize => Some(Field::new("range_shift", self.range_shift())),
            5usize => Some(Field::new(
                "table_records",
                traversal::FieldType::array_of_records(
                    stringify!(TableRecord),
                    self.table_records(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "traversal")]
impl<'a> std::fmt::Debug for TableDirectory<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

/// Record for a table in a font.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct TableRecord {
    /// Table identifier.
    pub tag: BigEndian<Tag>,
    /// Checksum for the table.
    pub checksum: BigEndian<u32>,
    /// Offset from the beginning of the font data.
    pub offset: BigEndian<u32>,
    /// Length of the table.
    pub length: BigEndian<u32>,
}

impl TableRecord {
    /// Table identifier.
    pub fn tag(&self) -> Tag {
        self.tag.get()
    }

    /// Checksum for the table.
    pub fn checksum(&self) -> u32 {
        self.checksum.get()
    }

    /// Offset from the beginning of the font data.
    pub fn offset(&self) -> u32 {
        self.offset.get()
    }

    /// Length of the table.
    pub fn length(&self) -> u32 {
        self.length.get()
    }
}

impl FixedSize for TableRecord {
    const RAW_BYTE_LEN: usize =
        Tag::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}

#[cfg(feature = "traversal")]
impl<'a> SomeRecord<'a> for TableRecord {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "TableRecord",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("tag", self.tag())),
                1usize => Some(Field::new("checksum", self.checksum())),
                2usize => Some(Field::new("offset", self.offset())),
                3usize => Some(Field::new("length", self.length())),
                _ => None,
            }),
            data,
        }
    }
}

/// [TTC Header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct TTCHeaderMarker {
    table_directory_offsets_byte_len: usize,
    dsig_tag_byte_start: Option<usize>,
    dsig_length_byte_start: Option<usize>,
    dsig_offset_byte_start: Option<usize>,
}

impl TTCHeaderMarker {
    fn ttc_tag_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + Tag::RAW_BYTE_LEN
    }
    fn version_byte_range(&self) -> Range<usize> {
        let start = self.ttc_tag_byte_range().end;
        start..start + MajorMinor::RAW_BYTE_LEN
    }
    fn num_fonts_byte_range(&self) -> Range<usize> {
        let start = self.version_byte_range().end;
        start..start + u32::RAW_BYTE_LEN
    }
    fn table_directory_offsets_byte_range(&self) -> Range<usize> {
        let start = self.num_fonts_byte_range().end;
        start..start + self.table_directory_offsets_byte_len
    }
    fn dsig_tag_byte_range(&self) -> Option<Range<usize>> {
        let start = self.dsig_tag_byte_start?;
        Some(start..start + u32::RAW_BYTE_LEN)
    }
    fn dsig_length_byte_range(&self) -> Option<Range<usize>> {
        let start = self.dsig_length_byte_start?;
        Some(start..start + u32::RAW_BYTE_LEN)
    }
    fn dsig_offset_byte_range(&self) -> Option<Range<usize>> {
        let start = self.dsig_offset_byte_start?;
        Some(start..start + u32::RAW_BYTE_LEN)
    }
}

impl<'a> FontRead<'a> for TTCHeader<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<Tag>();
        let version: MajorMinor = cursor.read()?;
        let num_fonts: u32 = cursor.read()?;
        let table_directory_offsets_byte_len = num_fonts as usize * u32::RAW_BYTE_LEN;
        cursor.advance_by(table_directory_offsets_byte_len);
        let dsig_tag_byte_start = version
            .compatible((2, 0))
            .then(|| cursor.position())
            .transpose()?;
        version.compatible((2, 0)).then(|| cursor.advance::<u32>());
        let dsig_length_byte_start = version
            .compatible((2, 0))
            .then(|| cursor.position())
            .transpose()?;
        version.compatible((2, 0)).then(|| cursor.advance::<u32>());
        let dsig_offset_byte_start = version
            .compatible((2, 0))
            .then(|| cursor.position())
            .transpose()?;
        version.compatible((2, 0)).then(|| cursor.advance::<u32>());
        cursor.finish(TTCHeaderMarker {
            table_directory_offsets_byte_len,
            dsig_tag_byte_start,
            dsig_length_byte_start,
            dsig_offset_byte_start,
        })
    }
}

/// [TTC Header](https://learn.microsoft.com/en-us/typography/opentype/spec/otff#ttc-header)
pub type TTCHeader<'a> = TableRef<'a, TTCHeaderMarker>;

impl<'a> TTCHeader<'a> {
    /// Font Collection ID string: \"ttcf\"
    pub fn ttc_tag(&self) -> Tag {
        let range = self.shape.ttc_tag_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Major/minor version of the TTC Header
    pub fn version(&self) -> MajorMinor {
        let range = self.shape.version_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Number of fonts in TTC
    pub fn num_fonts(&self) -> u32 {
        let range = self.shape.num_fonts_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Array of offsets to the TableDirectory for each font from the beginning of the file
    pub fn table_directory_offsets(&self) -> &'a [BigEndian<u32>] {
        let range = self.shape.table_directory_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// Tag indicating that a DSIG table exists, 0x44534947 ('DSIG') (null if no signature)
    pub fn dsig_tag(&self) -> Option<u32> {
        let range = self.shape.dsig_tag_byte_range()?;
        Some(self.data.read_at(range.start).unwrap())
    }

    /// The length (in bytes) of the DSIG table (null if no signature)
    pub fn dsig_length(&self) -> Option<u32> {
        let range = self.shape.dsig_length_byte_range()?;
        Some(self.data.read_at(range.start).unwrap())
    }

    /// The offset (in bytes) of the DSIG table from the beginning of the TTC file (null if no signature)
    pub fn dsig_offset(&self) -> Option<u32> {
        let range = self.shape.dsig_offset_byte_range()?;
        Some(self.data.read_at(range.start).unwrap())
    }
}

#[cfg(feature = "traversal")]
impl<'a> SomeTable<'a> for TTCHeader<'a> {
    fn type_name(&self) -> &str {
        "TTCHeader"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        let version = self.version();
        match idx {
            0usize => Some(Field::new("ttc_tag", self.ttc_tag())),
            1usize => Some(Field::new("version", self.version())),
            2usize => Some(Field::new("num_fonts", self.num_fonts())),
            3usize => Some(Field::new(
                "table_directory_offsets",
                self.table_directory_offsets(),
            )),
            4usize if version.compatible((2, 0)) => {
                Some(Field::new("dsig_tag", self.dsig_tag().unwrap()))
            }
            5usize if version.compatible((2, 0)) => {
                Some(Field::new("dsig_length", self.dsig_length().unwrap()))
            }
            6usize if version.compatible((2, 0)) => {
                Some(Field::new("dsig_offset", self.dsig_offset().unwrap()))
            }
            _ => None,
        }
    }
}

#[cfg(feature = "traversal")]
impl<'a> std::fmt::Debug for TTCHeader<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}