read-fonts 0.43.0

Reading OpenType font files.
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
// 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::*;

impl<'a> MinByteRange<'a> for BasicTable<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.array_records_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl ReadArgs for BasicTable<'_> {
    type Args = ();
}

impl<'a> FontRead<'a> for BasicTable<'a> {
    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

#[derive(Clone)]
pub struct BasicTable<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> BasicTable<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    pub fn simple_count(&self) -> u16 {
        let range = self.simple_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn simple_records(&self) -> &'a [SimpleRecord] {
        let range = self.simple_records_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    pub fn arrays_inner_count(&self) -> u16 {
        let range = self.arrays_inner_count_byte_range();
        self.data.read_at(range.start).ok().unwrap_or_default()
    }

    pub fn array_records_count(&self) -> u32 {
        let range = self.array_records_count_byte_range();
        self.data.read_at(range.start).ok().unwrap_or_default()
    }

    pub fn array_records(&self) -> ComputedArray<'a, ContainsArrays<'a>> {
        let range = self.array_records_byte_range();
        self.data
            .read_with_args(range, self.arrays_inner_count())
            .unwrap_or_default()
    }

    pub fn simple_count_byte_range(&self) -> Range<usize> {
        let start = 0;
        let end = start + u16::RAW_BYTE_LEN;
        start..end
    }

    pub fn simple_records_byte_range(&self) -> Range<usize> {
        let simple_count = self.simple_count();
        let start = self.simple_count_byte_range().end;
        let end =
            start + (transforms::to_usize(simple_count)).saturating_mul(SimpleRecord::RAW_BYTE_LEN);
        start..end
    }

    pub fn arrays_inner_count_byte_range(&self) -> Range<usize> {
        let start = self.simple_records_byte_range().end;
        let end = start + u16::RAW_BYTE_LEN;
        start..end
    }

    pub fn array_records_count_byte_range(&self) -> Range<usize> {
        let start = self.arrays_inner_count_byte_range().end;
        let end = start + u32::RAW_BYTE_LEN;
        start..end
    }

    pub fn array_records_byte_range(&self) -> Range<usize> {
        let array_records_count = self.array_records_count();
        let start = self.array_records_count_byte_range().end;
        let end = start
            + (transforms::to_usize(array_records_count)).saturating_mul(
                <ContainsArrays as ComputeSize>::compute_size(self.arrays_inner_count())
                    .unwrap_or(0),
            );
        start..end
    }
}

const _: () = assert!(FontData::default_data_long_enough(BasicTable::MIN_SIZE));

impl Default for BasicTable<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for BasicTable<'a> {
    fn type_name(&self) -> &str {
        "BasicTable"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("simple_count", self.simple_count())),
            1usize => Some(Field::new(
                "simple_records",
                traversal::FieldType::array_of_records(
                    stringify!(SimpleRecord),
                    self.simple_records(),
                    self.offset_data(),
                ),
            )),
            2usize => Some(Field::new("arrays_inner_count", self.arrays_inner_count())),
            3usize => Some(Field::new(
                "array_records_count",
                self.array_records_count(),
            )),
            4usize => Some(Field::new(
                "array_records",
                traversal::FieldType::computed_array(
                    "ContainsArrays",
                    self.array_records(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

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

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct SimpleRecord {
    pub val1: BigEndian<u16>,
    pub va2: BigEndian<u32>,
}

impl SimpleRecord {
    pub fn val1(&self) -> u16 {
        self.val1.get()
    }

    pub fn va2(&self) -> u32 {
        self.va2.get()
    }
}

impl FixedSize for SimpleRecord {
    const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + u32::RAW_BYTE_LEN;
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SimpleRecord {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "SimpleRecord",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("val1", self.val1())),
                1usize => Some(Field::new("va2", self.va2())),
                _ => None,
            }),
            data,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ContainsArrays<'a> {
    pub scalars: &'a [BigEndian<u16>],
    pub records: &'a [SimpleRecord],
}

impl<'a> ContainsArrays<'a> {
    pub fn scalars(&self) -> &'a [BigEndian<u16>] {
        self.scalars
    }

    pub fn records(&self) -> &'a [SimpleRecord] {
        self.records
    }
}

impl ReadArgs for ContainsArrays<'_> {
    type Args = u16;
}

impl ComputeSize for ContainsArrays<'_> {
    #[allow(clippy::needless_question_mark)]
    fn compute_size(args: u16) -> Result<usize, ReadError> {
        let array_len = args;
        let mut result = 0usize;
        result = result
            .checked_add((transforms::to_usize(array_len)).saturating_mul(u16::RAW_BYTE_LEN))
            .ok_or(ReadError::OutOfBounds)?;
        result = result
            .checked_add(
                (transforms::to_usize(array_len)).saturating_mul(SimpleRecord::RAW_BYTE_LEN),
            )
            .ok_or(ReadError::OutOfBounds)?;
        Ok(result)
    }
}

impl<'a> FontRead<'a> for ContainsArrays<'a> {
    fn read_with_args(data: FontData<'a>, args: u16) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let array_len = args;
        Ok(Self {
            scalars: cursor.read_array(transforms::to_usize(array_len))?,
            records: cursor.read_array(transforms::to_usize(array_len))?,
        })
    }
}

#[allow(clippy::needless_lifetimes)]
impl<'a> ContainsArrays<'a> {
    /// A constructor that requires additional arguments.
    ///
    /// This type requires some external state in order to be
    /// parsed.
    pub fn read(data: FontData<'a>, array_len: u16) -> Result<Self, ReadError> {
        let args = array_len;
        Self::read_with_args(data, args)
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ContainsArrays<'a> {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "ContainsArrays",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("scalars", self.scalars())),
                1usize => Some(Field::new(
                    "records",
                    traversal::FieldType::array_of_records(
                        stringify!(SimpleRecord),
                        self.records(),
                        _data,
                    ),
                )),
                _ => None,
            }),
            data,
        }
    }
}

#[derive(Clone, Debug, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct ContainsOffsets {
    pub off_array_count: BigEndian<u16>,
    pub array_offset: BigEndian<Offset16>,
    pub other_offset: BigEndian<Offset32>,
}

impl ContainsOffsets {
    pub fn off_array_count(&self) -> u16 {
        self.off_array_count.get()
    }

    pub fn array_offset(&self) -> Offset16 {
        self.array_offset.get()
    }

    ///
    /// The `data` argument should be retrieved from the parent table
    /// By calling its `offset_data` method.
    pub fn array<'a>(&self, data: FontData<'a>) -> Result<&'a [SimpleRecord], ReadError> {
        let args = self.off_array_count();
        self.array_offset().resolve_with_args(data, args)
    }

    pub fn other_offset(&self) -> Offset32 {
        self.other_offset.get()
    }

    ///
    /// The `data` argument should be retrieved from the parent table
    /// By calling its `offset_data` method.
    pub fn other<'a>(&self, data: FontData<'a>) -> Result<BasicTable<'a>, ReadError> {
        self.other_offset().resolve(data)
    }
}

impl FixedSize for ContainsOffsets {
    const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + Offset16::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN;
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for ContainsOffsets {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "ContainsOffsets",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("off_array_count", self.off_array_count())),
                1usize => Some(Field::new(
                    "array_offset",
                    traversal::FieldType::offset_to_array_of_records(
                        self.array_offset(),
                        self.array(_data),
                        stringify!(SimpleRecord),
                        _data,
                    ),
                )),
                2usize => Some(Field::new(
                    "other_offset",
                    FieldType::offset(self.other_offset(), self.other(_data)),
                )),
                _ => None,
            }),
            data,
        }
    }
}

impl<'a> MinByteRange<'a> for VarLenItem<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.data_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl ReadArgs for VarLenItem<'_> {
    type Args = ();
}

impl<'a> FontRead<'a> for VarLenItem<'a> {
    fn read_with_args(data: FontData<'a>, _: ()) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

#[derive(Clone)]
pub struct VarLenItem<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> VarLenItem<'a> {
    pub const MIN_SIZE: usize = u32::RAW_BYTE_LEN;
    basic_table_impls!(impl_the_methods);

    pub fn length(&self) -> u32 {
        let range = self.length_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn data(&self) -> &'a [u8] {
        let range = self.data_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    pub fn length_byte_range(&self) -> Range<usize> {
        let start = 0;
        let end = start + u32::RAW_BYTE_LEN;
        start..end
    }

    pub fn data_byte_range(&self) -> Range<usize> {
        let start = self.length_byte_range().end;
        let end =
            start + self.data.len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
        start..end
    }
}

const _: () = assert!(FontData::default_data_long_enough(VarLenItem::MIN_SIZE));

impl Default for VarLenItem<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for VarLenItem<'a> {
    fn type_name(&self) -> &str {
        "VarLenItem"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("length", self.length())),
            1usize => Some(Field::new("data", self.data())),
            _ => None,
        }
    }
}

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