Skip to main content

read_fonts/generated/
generated_varc.rs

1// THIS FILE IS AUTOGENERATED.
2// Any changes to this file will be overwritten.
3// For more information about how codegen works, see font-codegen/README.md
4
5#[allow(unused_imports)]
6use crate::codegen_prelude::*;
7
8impl<'a> MinByteRange<'a> for Varc<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.var_composite_glyphs_offset_byte_range().end
11    }
12    fn min_table_bytes(&self) -> &'a [u8] {
13        let range = self.min_byte_range();
14        self.data.as_bytes().get(range).unwrap_or_default()
15    }
16}
17
18impl TopLevelTable for Varc<'_> {
19    /// `VARC`
20    const TAG: Tag = Tag::new(b"VARC");
21}
22
23impl<'a> FontRead<'a> for Varc<'a> {
24    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
25        #[allow(clippy::absurd_extreme_comparisons)]
26        if data.len() < Self::MIN_SIZE {
27            return Err(ReadError::OutOfBounds);
28        }
29        Ok(Self { data })
30    }
31}
32
33/// [VARC](https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md) (Variable Composites / Components Table)
34///
35/// [FontTools VARC](https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3459-L3476)
36#[derive(Clone)]
37pub struct Varc<'a> {
38    data: FontData<'a>,
39}
40
41#[allow(clippy::needless_lifetimes)]
42impl<'a> Varc<'a> {
43    pub const MIN_SIZE: usize = (MajorMinor::RAW_BYTE_LEN
44        + Offset32::RAW_BYTE_LEN
45        + Offset32::RAW_BYTE_LEN
46        + Offset32::RAW_BYTE_LEN
47        + Offset32::RAW_BYTE_LEN
48        + Offset32::RAW_BYTE_LEN);
49    basic_table_impls!(impl_the_methods);
50
51    /// Major/minor version number. Set to 1.0.
52    pub fn version(&self) -> MajorMinor {
53        let range = self.version_byte_range();
54        self.data.read_at(range.start).ok().unwrap()
55    }
56
57    pub fn coverage_offset(&self) -> Offset32 {
58        let range = self.coverage_offset_byte_range();
59        self.data.read_at(range.start).ok().unwrap()
60    }
61
62    /// Attempt to resolve [`coverage_offset`][Self::coverage_offset].
63    pub fn coverage(&self) -> Result<CoverageTable<'a>, ReadError> {
64        let data = self.data;
65        self.coverage_offset().resolve(data)
66    }
67
68    pub fn multi_var_store_offset(&self) -> Nullable<Offset32> {
69        let range = self.multi_var_store_offset_byte_range();
70        self.data.read_at(range.start).ok().unwrap()
71    }
72
73    /// Attempt to resolve [`multi_var_store_offset`][Self::multi_var_store_offset].
74    pub fn multi_var_store(&self) -> Option<Result<MultiItemVariationStore<'a>, ReadError>> {
75        let data = self.data;
76        self.multi_var_store_offset().resolve(data)
77    }
78
79    pub fn condition_list_offset(&self) -> Nullable<Offset32> {
80        let range = self.condition_list_offset_byte_range();
81        self.data.read_at(range.start).ok().unwrap()
82    }
83
84    /// Attempt to resolve [`condition_list_offset`][Self::condition_list_offset].
85    pub fn condition_list(&self) -> Option<Result<ConditionList<'a>, ReadError>> {
86        let data = self.data;
87        self.condition_list_offset().resolve(data)
88    }
89
90    pub fn axis_indices_list_offset(&self) -> Nullable<Offset32> {
91        let range = self.axis_indices_list_offset_byte_range();
92        self.data.read_at(range.start).ok().unwrap()
93    }
94
95    /// Attempt to resolve [`axis_indices_list_offset`][Self::axis_indices_list_offset].
96    pub fn axis_indices_list(&self) -> Option<Result<Index2<'a>, ReadError>> {
97        let data = self.data;
98        self.axis_indices_list_offset().resolve(data)
99    }
100
101    pub fn var_composite_glyphs_offset(&self) -> Offset32 {
102        let range = self.var_composite_glyphs_offset_byte_range();
103        self.data.read_at(range.start).ok().unwrap()
104    }
105
106    /// Attempt to resolve [`var_composite_glyphs_offset`][Self::var_composite_glyphs_offset].
107    pub fn var_composite_glyphs(&self) -> Result<Index2<'a>, ReadError> {
108        let data = self.data;
109        self.var_composite_glyphs_offset().resolve(data)
110    }
111
112    pub fn version_byte_range(&self) -> Range<usize> {
113        let start = 0;
114        start..start + MajorMinor::RAW_BYTE_LEN
115    }
116
117    pub fn coverage_offset_byte_range(&self) -> Range<usize> {
118        let start = self.version_byte_range().end;
119        start..start + Offset32::RAW_BYTE_LEN
120    }
121
122    pub fn multi_var_store_offset_byte_range(&self) -> Range<usize> {
123        let start = self.coverage_offset_byte_range().end;
124        start..start + Offset32::RAW_BYTE_LEN
125    }
126
127    pub fn condition_list_offset_byte_range(&self) -> Range<usize> {
128        let start = self.multi_var_store_offset_byte_range().end;
129        start..start + Offset32::RAW_BYTE_LEN
130    }
131
132    pub fn axis_indices_list_offset_byte_range(&self) -> Range<usize> {
133        let start = self.condition_list_offset_byte_range().end;
134        start..start + Offset32::RAW_BYTE_LEN
135    }
136
137    pub fn var_composite_glyphs_offset_byte_range(&self) -> Range<usize> {
138        let start = self.axis_indices_list_offset_byte_range().end;
139        start..start + Offset32::RAW_BYTE_LEN
140    }
141}
142
143#[cfg(feature = "experimental_traverse")]
144impl<'a> SomeTable<'a> for Varc<'a> {
145    fn type_name(&self) -> &str {
146        "Varc"
147    }
148    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
149        match idx {
150            0usize => Some(Field::new("version", self.version())),
151            1usize => Some(Field::new(
152                "coverage_offset",
153                FieldType::offset(self.coverage_offset(), self.coverage()),
154            )),
155            2usize => Some(Field::new(
156                "multi_var_store_offset",
157                FieldType::offset(self.multi_var_store_offset(), self.multi_var_store()),
158            )),
159            3usize => Some(Field::new(
160                "condition_list_offset",
161                FieldType::offset(self.condition_list_offset(), self.condition_list()),
162            )),
163            4usize => Some(Field::new(
164                "axis_indices_list_offset",
165                FieldType::offset(self.axis_indices_list_offset(), self.axis_indices_list()),
166            )),
167            5usize => Some(Field::new(
168                "var_composite_glyphs_offset",
169                FieldType::offset(
170                    self.var_composite_glyphs_offset(),
171                    self.var_composite_glyphs(),
172                ),
173            )),
174            _ => None,
175        }
176    }
177}
178
179#[cfg(feature = "experimental_traverse")]
180#[allow(clippy::needless_lifetimes)]
181impl<'a> std::fmt::Debug for Varc<'a> {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        (self as &dyn SomeTable<'a>).fmt(f)
184    }
185}
186
187impl Format<u16> for MultiItemVariationStore<'_> {
188    const FORMAT: u16 = 1;
189}
190
191impl<'a> MinByteRange<'a> for MultiItemVariationStore<'a> {
192    fn min_byte_range(&self) -> Range<usize> {
193        0..self.variation_data_offsets_byte_range().end
194    }
195    fn min_table_bytes(&self) -> &'a [u8] {
196        let range = self.min_byte_range();
197        self.data.as_bytes().get(range).unwrap_or_default()
198    }
199}
200
201impl<'a> FontRead<'a> for MultiItemVariationStore<'a> {
202    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
203        #[allow(clippy::absurd_extreme_comparisons)]
204        if data.len() < Self::MIN_SIZE {
205            return Err(ReadError::OutOfBounds);
206        }
207        Ok(Self { data })
208    }
209}
210
211/// * <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3451-L3457>
212/// * <https://github.com/harfbuzz/harfbuzz/blob/7be12b33e3f07067c159d8f516eb31df58c75876/src/hb-ot-layout-common.hh#L3517-L3520C3>
213#[derive(Clone)]
214pub struct MultiItemVariationStore<'a> {
215    data: FontData<'a>,
216}
217
218#[allow(clippy::needless_lifetimes)]
219impl<'a> MultiItemVariationStore<'a> {
220    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + Offset32::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
221    basic_table_impls!(impl_the_methods);
222
223    pub fn format(&self) -> u16 {
224        let range = self.format_byte_range();
225        self.data.read_at(range.start).ok().unwrap()
226    }
227
228    pub fn region_list_offset(&self) -> Offset32 {
229        let range = self.region_list_offset_byte_range();
230        self.data.read_at(range.start).ok().unwrap()
231    }
232
233    /// Attempt to resolve [`region_list_offset`][Self::region_list_offset].
234    pub fn region_list(&self) -> Result<SparseVariationRegionList<'a>, ReadError> {
235        let data = self.data;
236        self.region_list_offset().resolve(data)
237    }
238
239    pub fn variation_data_count(&self) -> u16 {
240        let range = self.variation_data_count_byte_range();
241        self.data.read_at(range.start).ok().unwrap()
242    }
243
244    pub fn variation_data_offsets(&self) -> &'a [BigEndian<Offset32>] {
245        let range = self.variation_data_offsets_byte_range();
246        self.data.read_array(range).ok().unwrap_or_default()
247    }
248
249    /// A dynamically resolving wrapper for [`variation_data_offsets`][Self::variation_data_offsets].
250    pub fn variation_data(&self) -> ArrayOfOffsets<'a, MultiItemVariationData<'a>, Offset32> {
251        let data = self.data;
252        let offsets = self.variation_data_offsets();
253        ArrayOfOffsets::new(offsets, data, ())
254    }
255
256    pub fn format_byte_range(&self) -> Range<usize> {
257        let start = 0;
258        start..start + u16::RAW_BYTE_LEN
259    }
260
261    pub fn region_list_offset_byte_range(&self) -> Range<usize> {
262        let start = self.format_byte_range().end;
263        start..start + Offset32::RAW_BYTE_LEN
264    }
265
266    pub fn variation_data_count_byte_range(&self) -> Range<usize> {
267        let start = self.region_list_offset_byte_range().end;
268        start..start + u16::RAW_BYTE_LEN
269    }
270
271    pub fn variation_data_offsets_byte_range(&self) -> Range<usize> {
272        let variation_data_count = self.variation_data_count();
273        let start = self.variation_data_count_byte_range().end;
274        start..start + (variation_data_count as usize).saturating_mul(Offset32::RAW_BYTE_LEN)
275    }
276}
277
278#[cfg(feature = "experimental_traverse")]
279impl<'a> SomeTable<'a> for MultiItemVariationStore<'a> {
280    fn type_name(&self) -> &str {
281        "MultiItemVariationStore"
282    }
283    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
284        match idx {
285            0usize => Some(Field::new("format", self.format())),
286            1usize => Some(Field::new(
287                "region_list_offset",
288                FieldType::offset(self.region_list_offset(), self.region_list()),
289            )),
290            2usize => Some(Field::new(
291                "variation_data_count",
292                self.variation_data_count(),
293            )),
294            3usize => Some({
295                let data = self.data;
296                Field::new(
297                    "variation_data_offsets",
298                    FieldType::array_of_offsets(
299                        better_type_name::<MultiItemVariationData>(),
300                        self.variation_data_offsets(),
301                        move |off| {
302                            let target = off.get().resolve::<MultiItemVariationData>(data);
303                            FieldType::offset(off.get(), target)
304                        },
305                    ),
306                )
307            }),
308            _ => None,
309        }
310    }
311}
312
313#[cfg(feature = "experimental_traverse")]
314#[allow(clippy::needless_lifetimes)]
315impl<'a> std::fmt::Debug for MultiItemVariationStore<'a> {
316    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317        (self as &dyn SomeTable<'a>).fmt(f)
318    }
319}
320
321impl<'a> MinByteRange<'a> for SparseVariationRegionList<'a> {
322    fn min_byte_range(&self) -> Range<usize> {
323        0..self.region_offsets_byte_range().end
324    }
325    fn min_table_bytes(&self) -> &'a [u8] {
326        let range = self.min_byte_range();
327        self.data.as_bytes().get(range).unwrap_or_default()
328    }
329}
330
331impl<'a> FontRead<'a> for SparseVariationRegionList<'a> {
332    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
333        #[allow(clippy::absurd_extreme_comparisons)]
334        if data.len() < Self::MIN_SIZE {
335            return Err(ReadError::OutOfBounds);
336        }
337        Ok(Self { data })
338    }
339}
340
341#[derive(Clone)]
342pub struct SparseVariationRegionList<'a> {
343    data: FontData<'a>,
344}
345
346#[allow(clippy::needless_lifetimes)]
347impl<'a> SparseVariationRegionList<'a> {
348    pub const MIN_SIZE: usize = u16::RAW_BYTE_LEN;
349    basic_table_impls!(impl_the_methods);
350
351    pub fn region_count(&self) -> u16 {
352        let range = self.region_count_byte_range();
353        self.data.read_at(range.start).ok().unwrap()
354    }
355
356    pub fn region_offsets(&self) -> &'a [BigEndian<Offset32>] {
357        let range = self.region_offsets_byte_range();
358        self.data.read_array(range).ok().unwrap_or_default()
359    }
360
361    /// A dynamically resolving wrapper for [`region_offsets`][Self::region_offsets].
362    pub fn regions(&self) -> ArrayOfOffsets<'a, SparseVariationRegion<'a>, Offset32> {
363        let data = self.data;
364        let offsets = self.region_offsets();
365        ArrayOfOffsets::new(offsets, data, ())
366    }
367
368    pub fn region_count_byte_range(&self) -> Range<usize> {
369        let start = 0;
370        start..start + u16::RAW_BYTE_LEN
371    }
372
373    pub fn region_offsets_byte_range(&self) -> Range<usize> {
374        let region_count = self.region_count();
375        let start = self.region_count_byte_range().end;
376        start..start + (region_count as usize).saturating_mul(Offset32::RAW_BYTE_LEN)
377    }
378}
379
380#[cfg(feature = "experimental_traverse")]
381impl<'a> SomeTable<'a> for SparseVariationRegionList<'a> {
382    fn type_name(&self) -> &str {
383        "SparseVariationRegionList"
384    }
385    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
386        match idx {
387            0usize => Some(Field::new("region_count", self.region_count())),
388            1usize => Some({
389                let data = self.data;
390                Field::new(
391                    "region_offsets",
392                    FieldType::array_of_offsets(
393                        better_type_name::<SparseVariationRegion>(),
394                        self.region_offsets(),
395                        move |off| {
396                            let target = off.get().resolve::<SparseVariationRegion>(data);
397                            FieldType::offset(off.get(), target)
398                        },
399                    ),
400                )
401            }),
402            _ => None,
403        }
404    }
405}
406
407#[cfg(feature = "experimental_traverse")]
408#[allow(clippy::needless_lifetimes)]
409impl<'a> std::fmt::Debug for SparseVariationRegionList<'a> {
410    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
411        (self as &dyn SomeTable<'a>).fmt(f)
412    }
413}
414
415impl<'a> MinByteRange<'a> for SparseVariationRegion<'a> {
416    fn min_byte_range(&self) -> Range<usize> {
417        0..self.region_axes_byte_range().end
418    }
419    fn min_table_bytes(&self) -> &'a [u8] {
420        let range = self.min_byte_range();
421        self.data.as_bytes().get(range).unwrap_or_default()
422    }
423}
424
425impl<'a> FontRead<'a> for SparseVariationRegion<'a> {
426    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
427        #[allow(clippy::absurd_extreme_comparisons)]
428        if data.len() < Self::MIN_SIZE {
429            return Err(ReadError::OutOfBounds);
430        }
431        Ok(Self { data })
432    }
433}
434
435#[derive(Clone)]
436pub struct SparseVariationRegion<'a> {
437    data: FontData<'a>,
438}
439
440#[allow(clippy::needless_lifetimes)]
441impl<'a> SparseVariationRegion<'a> {
442    pub const MIN_SIZE: usize = u16::RAW_BYTE_LEN;
443    basic_table_impls!(impl_the_methods);
444
445    pub fn region_axis_count(&self) -> u16 {
446        let range = self.region_axis_count_byte_range();
447        self.data.read_at(range.start).ok().unwrap()
448    }
449
450    pub fn region_axes(&self) -> &'a [SparseRegionAxisCoordinates] {
451        let range = self.region_axes_byte_range();
452        self.data.read_array(range).ok().unwrap_or_default()
453    }
454
455    pub fn region_axis_count_byte_range(&self) -> Range<usize> {
456        let start = 0;
457        start..start + u16::RAW_BYTE_LEN
458    }
459
460    pub fn region_axes_byte_range(&self) -> Range<usize> {
461        let region_axis_count = self.region_axis_count();
462        let start = self.region_axis_count_byte_range().end;
463        start
464            ..start
465                + (region_axis_count as usize)
466                    .saturating_mul(SparseRegionAxisCoordinates::RAW_BYTE_LEN)
467    }
468}
469
470#[cfg(feature = "experimental_traverse")]
471impl<'a> SomeTable<'a> for SparseVariationRegion<'a> {
472    fn type_name(&self) -> &str {
473        "SparseVariationRegion"
474    }
475    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
476        match idx {
477            0usize => Some(Field::new("region_axis_count", self.region_axis_count())),
478            1usize => Some(Field::new(
479                "region_axes",
480                traversal::FieldType::array_of_records(
481                    stringify!(SparseRegionAxisCoordinates),
482                    self.region_axes(),
483                    self.offset_data(),
484                ),
485            )),
486            _ => None,
487        }
488    }
489}
490
491#[cfg(feature = "experimental_traverse")]
492#[allow(clippy::needless_lifetimes)]
493impl<'a> std::fmt::Debug for SparseVariationRegion<'a> {
494    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495        (self as &dyn SomeTable<'a>).fmt(f)
496    }
497}
498
499#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
500#[repr(C)]
501#[repr(packed)]
502pub struct SparseRegionAxisCoordinates {
503    pub axis_index: BigEndian<u16>,
504    pub start: BigEndian<F2Dot14>,
505    pub peak: BigEndian<F2Dot14>,
506    pub end: BigEndian<F2Dot14>,
507}
508
509impl SparseRegionAxisCoordinates {
510    pub fn axis_index(&self) -> u16 {
511        self.axis_index.get()
512    }
513
514    pub fn start(&self) -> F2Dot14 {
515        self.start.get()
516    }
517
518    pub fn peak(&self) -> F2Dot14 {
519        self.peak.get()
520    }
521
522    pub fn end(&self) -> F2Dot14 {
523        self.end.get()
524    }
525}
526
527impl FixedSize for SparseRegionAxisCoordinates {
528    const RAW_BYTE_LEN: usize =
529        u16::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
530}
531
532#[cfg(feature = "experimental_traverse")]
533impl<'a> SomeRecord<'a> for SparseRegionAxisCoordinates {
534    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
535        RecordResolver {
536            name: "SparseRegionAxisCoordinates",
537            get_field: Box::new(move |idx, _data| match idx {
538                0usize => Some(Field::new("axis_index", self.axis_index())),
539                1usize => Some(Field::new("start", self.start())),
540                2usize => Some(Field::new("peak", self.peak())),
541                3usize => Some(Field::new("end", self.end())),
542                _ => None,
543            }),
544            data,
545        }
546    }
547}
548
549impl Format<u8> for MultiItemVariationData<'_> {
550    const FORMAT: u8 = 1;
551}
552
553impl<'a> MinByteRange<'a> for MultiItemVariationData<'a> {
554    fn min_byte_range(&self) -> Range<usize> {
555        0..self.raw_delta_sets_byte_range().end
556    }
557    fn min_table_bytes(&self) -> &'a [u8] {
558        let range = self.min_byte_range();
559        self.data.as_bytes().get(range).unwrap_or_default()
560    }
561}
562
563impl<'a> FontRead<'a> for MultiItemVariationData<'a> {
564    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
565        #[allow(clippy::absurd_extreme_comparisons)]
566        if data.len() < Self::MIN_SIZE {
567            return Err(ReadError::OutOfBounds);
568        }
569        Ok(Self { data })
570    }
571}
572
573#[derive(Clone)]
574pub struct MultiItemVariationData<'a> {
575    data: FontData<'a>,
576}
577
578#[allow(clippy::needless_lifetimes)]
579impl<'a> MultiItemVariationData<'a> {
580    pub const MIN_SIZE: usize = (u8::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
581    basic_table_impls!(impl_the_methods);
582
583    pub fn format(&self) -> u8 {
584        let range = self.format_byte_range();
585        self.data.read_at(range.start).ok().unwrap()
586    }
587
588    pub fn region_index_count(&self) -> u16 {
589        let range = self.region_index_count_byte_range();
590        self.data.read_at(range.start).ok().unwrap()
591    }
592
593    pub fn region_indices(&self) -> &'a [BigEndian<u16>] {
594        let range = self.region_indices_byte_range();
595        self.data.read_array(range).ok().unwrap_or_default()
596    }
597
598    pub fn raw_delta_sets(&self) -> &'a [u8] {
599        let range = self.raw_delta_sets_byte_range();
600        self.data.read_array(range).ok().unwrap_or_default()
601    }
602
603    pub fn format_byte_range(&self) -> Range<usize> {
604        let start = 0;
605        start..start + u8::RAW_BYTE_LEN
606    }
607
608    pub fn region_index_count_byte_range(&self) -> Range<usize> {
609        let start = self.format_byte_range().end;
610        start..start + u16::RAW_BYTE_LEN
611    }
612
613    pub fn region_indices_byte_range(&self) -> Range<usize> {
614        let region_index_count = self.region_index_count();
615        let start = self.region_index_count_byte_range().end;
616        start..start + (region_index_count as usize).saturating_mul(u16::RAW_BYTE_LEN)
617    }
618
619    pub fn raw_delta_sets_byte_range(&self) -> Range<usize> {
620        let start = self.region_indices_byte_range().end;
621        start..start + self.data.len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN
622    }
623}
624
625#[cfg(feature = "experimental_traverse")]
626impl<'a> SomeTable<'a> for MultiItemVariationData<'a> {
627    fn type_name(&self) -> &str {
628        "MultiItemVariationData"
629    }
630    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
631        match idx {
632            0usize => Some(Field::new("format", self.format())),
633            1usize => Some(Field::new("region_index_count", self.region_index_count())),
634            2usize => Some(Field::new("region_indices", self.region_indices())),
635            3usize => Some(Field::new("raw_delta_sets", self.raw_delta_sets())),
636            _ => None,
637        }
638    }
639}
640
641#[cfg(feature = "experimental_traverse")]
642#[allow(clippy::needless_lifetimes)]
643impl<'a> std::fmt::Debug for MultiItemVariationData<'a> {
644    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
645        (self as &dyn SomeTable<'a>).fmt(f)
646    }
647}
648
649impl<'a> MinByteRange<'a> for ConditionList<'a> {
650    fn min_byte_range(&self) -> Range<usize> {
651        0..self.condition_offsets_byte_range().end
652    }
653    fn min_table_bytes(&self) -> &'a [u8] {
654        let range = self.min_byte_range();
655        self.data.as_bytes().get(range).unwrap_or_default()
656    }
657}
658
659impl<'a> FontRead<'a> for ConditionList<'a> {
660    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
661        #[allow(clippy::absurd_extreme_comparisons)]
662        if data.len() < Self::MIN_SIZE {
663            return Err(ReadError::OutOfBounds);
664        }
665        Ok(Self { data })
666    }
667}
668
669#[derive(Clone)]
670pub struct ConditionList<'a> {
671    data: FontData<'a>,
672}
673
674#[allow(clippy::needless_lifetimes)]
675impl<'a> ConditionList<'a> {
676    pub const MIN_SIZE: usize = u32::RAW_BYTE_LEN;
677    basic_table_impls!(impl_the_methods);
678
679    pub fn condition_count(&self) -> u32 {
680        let range = self.condition_count_byte_range();
681        self.data.read_at(range.start).ok().unwrap()
682    }
683
684    pub fn condition_offsets(&self) -> &'a [BigEndian<Offset32>] {
685        let range = self.condition_offsets_byte_range();
686        self.data.read_array(range).ok().unwrap_or_default()
687    }
688
689    /// A dynamically resolving wrapper for [`condition_offsets`][Self::condition_offsets].
690    pub fn conditions(&self) -> ArrayOfOffsets<'a, Condition<'a>, Offset32> {
691        let data = self.data;
692        let offsets = self.condition_offsets();
693        ArrayOfOffsets::new(offsets, data, ())
694    }
695
696    pub fn condition_count_byte_range(&self) -> Range<usize> {
697        let start = 0;
698        start..start + u32::RAW_BYTE_LEN
699    }
700
701    pub fn condition_offsets_byte_range(&self) -> Range<usize> {
702        let condition_count = self.condition_count();
703        let start = self.condition_count_byte_range().end;
704        start..start + (condition_count as usize).saturating_mul(Offset32::RAW_BYTE_LEN)
705    }
706}
707
708#[cfg(feature = "experimental_traverse")]
709impl<'a> SomeTable<'a> for ConditionList<'a> {
710    fn type_name(&self) -> &str {
711        "ConditionList"
712    }
713    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
714        match idx {
715            0usize => Some(Field::new("condition_count", self.condition_count())),
716            1usize => Some({
717                let data = self.data;
718                Field::new(
719                    "condition_offsets",
720                    FieldType::array_of_offsets(
721                        better_type_name::<Condition>(),
722                        self.condition_offsets(),
723                        move |off| {
724                            let target = off.get().resolve::<Condition>(data);
725                            FieldType::offset(off.get(), target)
726                        },
727                    ),
728                )
729            }),
730            _ => None,
731        }
732    }
733}
734
735#[cfg(feature = "experimental_traverse")]
736#[allow(clippy::needless_lifetimes)]
737impl<'a> std::fmt::Debug for ConditionList<'a> {
738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
739        (self as &dyn SomeTable<'a>).fmt(f)
740    }
741}
742
743/// Flags used in the [VarcComponent] byte stream
744///
745/// <https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-component-flags>
746#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
747#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
748#[repr(transparent)]
749pub struct VarcFlags {
750    bits: u32,
751}
752
753impl VarcFlags {
754    pub const RESET_UNSPECIFIED_AXES: Self = Self {
755        bits: 0b0000_0000_0000_0001,
756    };
757
758    pub const HAVE_AXES: Self = Self {
759        bits: 0b0000_0000_0000_0010,
760    };
761
762    pub const AXIS_VALUES_HAVE_VARIATION: Self = Self {
763        bits: 0b0000_0000_0000_0100,
764    };
765
766    pub const TRANSFORM_HAS_VARIATION: Self = Self {
767        bits: 0b0000_0000_0000_1000,
768    };
769
770    pub const HAVE_TRANSLATE_X: Self = Self {
771        bits: 0b0000_0000_0001_0000,
772    };
773
774    pub const HAVE_TRANSLATE_Y: Self = Self {
775        bits: 0b0000_0000_0010_0000,
776    };
777
778    pub const HAVE_ROTATION: Self = Self {
779        bits: 0b0000_0000_0100_0000,
780    };
781
782    pub const HAVE_CONDITION: Self = Self {
783        bits: 0b0000_0000_1000_0000,
784    };
785
786    pub const HAVE_SCALE_X: Self = Self {
787        bits: 0b0000_0001_0000_0000,
788    };
789
790    pub const HAVE_SCALE_Y: Self = Self {
791        bits: 0b0000_0010_0000_0000,
792    };
793
794    pub const HAVE_TCENTER_X: Self = Self {
795        bits: 0b0000_0100_0000_0000,
796    };
797
798    pub const HAVE_TCENTER_Y: Self = Self {
799        bits: 0b0000_1000_0000_0000,
800    };
801
802    pub const GID_IS_24BIT: Self = Self {
803        bits: 0b0001_0000_0000_0000,
804    };
805
806    pub const HAVE_SKEW_X: Self = Self {
807        bits: 0b0010_0000_0000_0000,
808    };
809
810    pub const HAVE_SKEW_Y: Self = Self {
811        bits: 0b0100_0000_0000_0000,
812    };
813
814    pub const RESERVED_MASK: Self = Self { bits: 0xFFFF8000 };
815}
816
817impl VarcFlags {
818    ///  Returns an empty set of flags.
819    #[inline]
820    pub const fn empty() -> Self {
821        Self { bits: 0 }
822    }
823
824    /// Returns the set containing all flags.
825    #[inline]
826    pub const fn all() -> Self {
827        Self {
828            bits: Self::RESET_UNSPECIFIED_AXES.bits
829                | Self::HAVE_AXES.bits
830                | Self::AXIS_VALUES_HAVE_VARIATION.bits
831                | Self::TRANSFORM_HAS_VARIATION.bits
832                | Self::HAVE_TRANSLATE_X.bits
833                | Self::HAVE_TRANSLATE_Y.bits
834                | Self::HAVE_ROTATION.bits
835                | Self::HAVE_CONDITION.bits
836                | Self::HAVE_SCALE_X.bits
837                | Self::HAVE_SCALE_Y.bits
838                | Self::HAVE_TCENTER_X.bits
839                | Self::HAVE_TCENTER_Y.bits
840                | Self::GID_IS_24BIT.bits
841                | Self::HAVE_SKEW_X.bits
842                | Self::HAVE_SKEW_Y.bits
843                | Self::RESERVED_MASK.bits,
844        }
845    }
846
847    /// Returns the raw value of the flags currently stored.
848    #[inline]
849    pub const fn bits(&self) -> u32 {
850        self.bits
851    }
852
853    /// Convert from underlying bit representation, unless that
854    /// representation contains bits that do not correspond to a flag.
855    #[inline]
856    pub const fn from_bits(bits: u32) -> Option<Self> {
857        if (bits & !Self::all().bits()) == 0 {
858            Some(Self { bits })
859        } else {
860            None
861        }
862    }
863
864    /// Convert from underlying bit representation, dropping any bits
865    /// that do not correspond to flags.
866    #[inline]
867    pub const fn from_bits_truncate(bits: u32) -> Self {
868        Self {
869            bits: bits & Self::all().bits,
870        }
871    }
872
873    /// Returns `true` if no flags are currently stored.
874    #[inline]
875    pub const fn is_empty(&self) -> bool {
876        self.bits() == Self::empty().bits()
877    }
878
879    /// Returns `true` if there are flags common to both `self` and `other`.
880    #[inline]
881    pub const fn intersects(&self, other: Self) -> bool {
882        !(Self {
883            bits: self.bits & other.bits,
884        })
885        .is_empty()
886    }
887
888    /// Returns `true` if all of the flags in `other` are contained within `self`.
889    #[inline]
890    pub const fn contains(&self, other: Self) -> bool {
891        (self.bits & other.bits) == other.bits
892    }
893
894    /// Inserts the specified flags in-place.
895    #[inline]
896    pub fn insert(&mut self, other: Self) {
897        self.bits |= other.bits;
898    }
899
900    /// Removes the specified flags in-place.
901    #[inline]
902    pub fn remove(&mut self, other: Self) {
903        self.bits &= !other.bits;
904    }
905
906    /// Toggles the specified flags in-place.
907    #[inline]
908    pub fn toggle(&mut self, other: Self) {
909        self.bits ^= other.bits;
910    }
911
912    /// Returns the intersection between the flags in `self` and
913    /// `other`.
914    ///
915    /// Specifically, the returned set contains only the flags which are
916    /// present in *both* `self` *and* `other`.
917    ///
918    /// This is equivalent to using the `&` operator (e.g.
919    /// [`ops::BitAnd`]), as in `flags & other`.
920    ///
921    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
922    #[inline]
923    #[must_use]
924    pub const fn intersection(self, other: Self) -> Self {
925        Self {
926            bits: self.bits & other.bits,
927        }
928    }
929
930    /// Returns the union of between the flags in `self` and `other`.
931    ///
932    /// Specifically, the returned set contains all flags which are
933    /// present in *either* `self` *or* `other`, including any which are
934    /// present in both.
935    ///
936    /// This is equivalent to using the `|` operator (e.g.
937    /// [`ops::BitOr`]), as in `flags | other`.
938    ///
939    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
940    #[inline]
941    #[must_use]
942    pub const fn union(self, other: Self) -> Self {
943        Self {
944            bits: self.bits | other.bits,
945        }
946    }
947
948    /// Returns the difference between the flags in `self` and `other`.
949    ///
950    /// Specifically, the returned set contains all flags present in
951    /// `self`, except for the ones present in `other`.
952    ///
953    /// It is also conceptually equivalent to the "bit-clear" operation:
954    /// `flags & !other` (and this syntax is also supported).
955    ///
956    /// This is equivalent to using the `-` operator (e.g.
957    /// [`ops::Sub`]), as in `flags - other`.
958    ///
959    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
960    #[inline]
961    #[must_use]
962    pub const fn difference(self, other: Self) -> Self {
963        Self {
964            bits: self.bits & !other.bits,
965        }
966    }
967}
968
969impl std::ops::BitOr for VarcFlags {
970    type Output = Self;
971
972    /// Returns the union of the two sets of flags.
973    #[inline]
974    fn bitor(self, other: VarcFlags) -> Self {
975        Self {
976            bits: self.bits | other.bits,
977        }
978    }
979}
980
981impl std::ops::BitOrAssign for VarcFlags {
982    /// Adds the set of flags.
983    #[inline]
984    fn bitor_assign(&mut self, other: Self) {
985        self.bits |= other.bits;
986    }
987}
988
989impl std::ops::BitXor for VarcFlags {
990    type Output = Self;
991
992    /// Returns the left flags, but with all the right flags toggled.
993    #[inline]
994    fn bitxor(self, other: Self) -> Self {
995        Self {
996            bits: self.bits ^ other.bits,
997        }
998    }
999}
1000
1001impl std::ops::BitXorAssign for VarcFlags {
1002    /// Toggles the set of flags.
1003    #[inline]
1004    fn bitxor_assign(&mut self, other: Self) {
1005        self.bits ^= other.bits;
1006    }
1007}
1008
1009impl std::ops::BitAnd for VarcFlags {
1010    type Output = Self;
1011
1012    /// Returns the intersection between the two sets of flags.
1013    #[inline]
1014    fn bitand(self, other: Self) -> Self {
1015        Self {
1016            bits: self.bits & other.bits,
1017        }
1018    }
1019}
1020
1021impl std::ops::BitAndAssign for VarcFlags {
1022    /// Disables all flags disabled in the set.
1023    #[inline]
1024    fn bitand_assign(&mut self, other: Self) {
1025        self.bits &= other.bits;
1026    }
1027}
1028
1029impl std::ops::Sub for VarcFlags {
1030    type Output = Self;
1031
1032    /// Returns the set difference of the two sets of flags.
1033    #[inline]
1034    fn sub(self, other: Self) -> Self {
1035        Self {
1036            bits: self.bits & !other.bits,
1037        }
1038    }
1039}
1040
1041impl std::ops::SubAssign for VarcFlags {
1042    /// Disables all flags enabled in the set.
1043    #[inline]
1044    fn sub_assign(&mut self, other: Self) {
1045        self.bits &= !other.bits;
1046    }
1047}
1048
1049impl std::ops::Not for VarcFlags {
1050    type Output = Self;
1051
1052    /// Returns the complement of this set of flags.
1053    #[inline]
1054    fn not(self) -> Self {
1055        Self { bits: !self.bits } & Self::all()
1056    }
1057}
1058
1059impl std::fmt::Debug for VarcFlags {
1060    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1061        let members: &[(&str, Self)] = &[
1062            ("RESET_UNSPECIFIED_AXES", Self::RESET_UNSPECIFIED_AXES),
1063            ("HAVE_AXES", Self::HAVE_AXES),
1064            (
1065                "AXIS_VALUES_HAVE_VARIATION",
1066                Self::AXIS_VALUES_HAVE_VARIATION,
1067            ),
1068            ("TRANSFORM_HAS_VARIATION", Self::TRANSFORM_HAS_VARIATION),
1069            ("HAVE_TRANSLATE_X", Self::HAVE_TRANSLATE_X),
1070            ("HAVE_TRANSLATE_Y", Self::HAVE_TRANSLATE_Y),
1071            ("HAVE_ROTATION", Self::HAVE_ROTATION),
1072            ("HAVE_CONDITION", Self::HAVE_CONDITION),
1073            ("HAVE_SCALE_X", Self::HAVE_SCALE_X),
1074            ("HAVE_SCALE_Y", Self::HAVE_SCALE_Y),
1075            ("HAVE_TCENTER_X", Self::HAVE_TCENTER_X),
1076            ("HAVE_TCENTER_Y", Self::HAVE_TCENTER_Y),
1077            ("GID_IS_24BIT", Self::GID_IS_24BIT),
1078            ("HAVE_SKEW_X", Self::HAVE_SKEW_X),
1079            ("HAVE_SKEW_Y", Self::HAVE_SKEW_Y),
1080            ("RESERVED_MASK", Self::RESERVED_MASK),
1081        ];
1082        let mut first = true;
1083        for (name, value) in members {
1084            if self.contains(*value) {
1085                if !first {
1086                    f.write_str(" | ")?;
1087                }
1088                first = false;
1089                f.write_str(name)?;
1090            }
1091        }
1092        if first {
1093            f.write_str("(empty)")?;
1094        }
1095        Ok(())
1096    }
1097}
1098
1099impl std::fmt::Binary for VarcFlags {
1100    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1101        std::fmt::Binary::fmt(&self.bits, f)
1102    }
1103}
1104
1105impl std::fmt::Octal for VarcFlags {
1106    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1107        std::fmt::Octal::fmt(&self.bits, f)
1108    }
1109}
1110
1111impl std::fmt::LowerHex for VarcFlags {
1112    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1113        std::fmt::LowerHex::fmt(&self.bits, f)
1114    }
1115}
1116
1117impl std::fmt::UpperHex for VarcFlags {
1118    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1119        std::fmt::UpperHex::fmt(&self.bits, f)
1120    }
1121}
1122
1123impl font_types::Scalar for VarcFlags {
1124    type Raw = <u32 as font_types::Scalar>::Raw;
1125    fn to_raw(self) -> Self::Raw {
1126        self.bits().to_raw()
1127    }
1128    fn from_raw(raw: Self::Raw) -> Self {
1129        let t = <u32>::from_raw(raw);
1130        Self::from_bits_truncate(t)
1131    }
1132}
1133
1134#[cfg(feature = "experimental_traverse")]
1135impl<'a> From<VarcFlags> for FieldType<'a> {
1136    fn from(src: VarcFlags) -> FieldType<'a> {
1137        src.bits().into()
1138    }
1139}