read_fonts/generated/
generated_varc.rs

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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
// 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::*;

/// [VARC](https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md) (Variable Composites / Components Table)
///
/// [FontTools VARC](https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3459-L3476)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VarcMarker {}

impl VarcMarker {
    pub fn version_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + MajorMinor::RAW_BYTE_LEN
    }

    pub fn coverage_offset_byte_range(&self) -> Range<usize> {
        let start = self.version_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn multi_var_store_offset_byte_range(&self) -> Range<usize> {
        let start = self.coverage_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn condition_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.multi_var_store_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn axis_indices_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.condition_list_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn var_composite_glyphs_offset_byte_range(&self) -> Range<usize> {
        let start = self.axis_indices_list_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }
}

impl TopLevelTable for Varc<'_> {
    /// `VARC`
    const TAG: Tag = Tag::new(b"VARC");
}

impl<'a> FontRead<'a> for Varc<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<MajorMinor>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.finish(VarcMarker {})
    }
}

/// [VARC](https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md) (Variable Composites / Components Table)
///
/// [FontTools VARC](https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3459-L3476)
pub type Varc<'a> = TableRef<'a, VarcMarker>;

impl<'a> Varc<'a> {
    /// Major/minor version number. Set to 1.0.
    pub fn version(&self) -> MajorMinor {
        let range = self.shape.version_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn coverage_offset(&self) -> Offset32 {
        let range = self.shape.coverage_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`coverage_offset`][Self::coverage_offset].
    pub fn coverage(&self) -> Result<CoverageTable<'a>, ReadError> {
        let data = self.data;
        self.coverage_offset().resolve(data)
    }

    pub fn multi_var_store_offset(&self) -> Nullable<Offset32> {
        let range = self.shape.multi_var_store_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`multi_var_store_offset`][Self::multi_var_store_offset].
    pub fn multi_var_store(&self) -> Option<Result<MultiItemVariationStore<'a>, ReadError>> {
        let data = self.data;
        self.multi_var_store_offset().resolve(data)
    }

    pub fn condition_list_offset(&self) -> Nullable<Offset32> {
        let range = self.shape.condition_list_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`condition_list_offset`][Self::condition_list_offset].
    pub fn condition_list(&self) -> Option<Result<ConditionList<'a>, ReadError>> {
        let data = self.data;
        self.condition_list_offset().resolve(data)
    }

    pub fn axis_indices_list_offset(&self) -> Nullable<Offset32> {
        let range = self.shape.axis_indices_list_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`axis_indices_list_offset`][Self::axis_indices_list_offset].
    pub fn axis_indices_list(&self) -> Option<Result<Index2<'a>, ReadError>> {
        let data = self.data;
        self.axis_indices_list_offset().resolve(data)
    }

    pub fn var_composite_glyphs_offset(&self) -> Offset32 {
        let range = self.shape.var_composite_glyphs_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`var_composite_glyphs_offset`][Self::var_composite_glyphs_offset].
    pub fn var_composite_glyphs(&self) -> Result<Index2<'a>, ReadError> {
        let data = self.data;
        self.var_composite_glyphs_offset().resolve(data)
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Varc<'a> {
    fn type_name(&self) -> &str {
        "Varc"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new(
                "coverage_offset",
                FieldType::offset(self.coverage_offset(), self.coverage()),
            )),
            2usize => Some(Field::new(
                "multi_var_store_offset",
                FieldType::offset(self.multi_var_store_offset(), self.multi_var_store()),
            )),
            3usize => Some(Field::new(
                "condition_list_offset",
                FieldType::offset(self.condition_list_offset(), self.condition_list()),
            )),
            4usize => Some(Field::new(
                "axis_indices_list_offset",
                FieldType::offset(self.axis_indices_list_offset(), self.axis_indices_list()),
            )),
            5usize => Some(Field::new(
                "var_composite_glyphs_offset",
                FieldType::offset(
                    self.var_composite_glyphs_offset(),
                    self.var_composite_glyphs(),
                ),
            )),
            _ => None,
        }
    }
}

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

impl Format<u16> for MultiItemVariationStoreMarker {
    const FORMAT: u16 = 1;
}

/// * <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3451-L3457>
/// * <https://github.com/harfbuzz/harfbuzz/blob/7be12b33e3f07067c159d8f516eb31df58c75876/src/hb-ot-layout-common.hh#L3517-L3520C3>
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MultiItemVariationStoreMarker {
    variation_data_offsets_byte_len: usize,
}

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

    pub fn region_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.format_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

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

    pub fn variation_data_offsets_byte_range(&self) -> Range<usize> {
        let start = self.variation_data_count_byte_range().end;
        start..start + self.variation_data_offsets_byte_len
    }
}

impl<'a> FontRead<'a> for MultiItemVariationStore<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u16>();
        cursor.advance::<Offset32>();
        let variation_data_count: u16 = cursor.read()?;
        let variation_data_offsets_byte_len = (variation_data_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(variation_data_offsets_byte_len);
        cursor.finish(MultiItemVariationStoreMarker {
            variation_data_offsets_byte_len,
        })
    }
}

/// * <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3451-L3457>
/// * <https://github.com/harfbuzz/harfbuzz/blob/7be12b33e3f07067c159d8f516eb31df58c75876/src/hb-ot-layout-common.hh#L3517-L3520C3>
pub type MultiItemVariationStore<'a> = TableRef<'a, MultiItemVariationStoreMarker>;

impl<'a> MultiItemVariationStore<'a> {
    pub fn format(&self) -> u16 {
        let range = self.shape.format_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn region_list_offset(&self) -> Offset32 {
        let range = self.shape.region_list_offset_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Attempt to resolve [`region_list_offset`][Self::region_list_offset].
    pub fn region_list(&self) -> Result<SparseVariationRegionList<'a>, ReadError> {
        let data = self.data;
        self.region_list_offset().resolve(data)
    }

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

    pub fn variation_data_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.shape.variation_data_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// A dynamically resolving wrapper for [`variation_data_offsets`][Self::variation_data_offsets].
    pub fn variation_data(&self) -> ArrayOfOffsets<'a, MultiItemVariationData<'a>, Offset32> {
        let data = self.data;
        let offsets = self.variation_data_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for MultiItemVariationStore<'a> {
    fn type_name(&self) -> &str {
        "MultiItemVariationStore"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("format", self.format())),
            1usize => Some(Field::new(
                "region_list_offset",
                FieldType::offset(self.region_list_offset(), self.region_list()),
            )),
            2usize => Some(Field::new(
                "variation_data_count",
                self.variation_data_count(),
            )),
            3usize => Some({
                let data = self.data;
                Field::new(
                    "variation_data_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<MultiItemVariationData>(),
                        self.variation_data_offsets(),
                        move |off| {
                            let target = off.get().resolve::<MultiItemVariationData>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => None,
        }
    }
}

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

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SparseVariationRegionListMarker {
    region_offsets_byte_len: usize,
}

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

    pub fn region_offsets_byte_range(&self) -> Range<usize> {
        let start = self.region_count_byte_range().end;
        start..start + self.region_offsets_byte_len
    }
}

impl<'a> FontRead<'a> for SparseVariationRegionList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let region_count: u16 = cursor.read()?;
        let region_offsets_byte_len = (region_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_offsets_byte_len);
        cursor.finish(SparseVariationRegionListMarker {
            region_offsets_byte_len,
        })
    }
}

pub type SparseVariationRegionList<'a> = TableRef<'a, SparseVariationRegionListMarker>;

impl<'a> SparseVariationRegionList<'a> {
    pub fn region_count(&self) -> u16 {
        let range = self.shape.region_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn region_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.shape.region_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// A dynamically resolving wrapper for [`region_offsets`][Self::region_offsets].
    pub fn regions(&self) -> ArrayOfOffsets<'a, SparseVariationRegion<'a>, Offset32> {
        let data = self.data;
        let offsets = self.region_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SparseVariationRegionList<'a> {
    fn type_name(&self) -> &str {
        "SparseVariationRegionList"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("region_count", self.region_count())),
            1usize => Some({
                let data = self.data;
                Field::new(
                    "region_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<SparseVariationRegion>(),
                        self.region_offsets(),
                        move |off| {
                            let target = off.get().resolve::<SparseVariationRegion>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => None,
        }
    }
}

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

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SparseVariationRegionMarker {
    region_axis_offsets_byte_len: usize,
}

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

    pub fn region_axis_offsets_byte_range(&self) -> Range<usize> {
        let start = self.region_axis_count_byte_range().end;
        start..start + self.region_axis_offsets_byte_len
    }
}

impl<'a> FontRead<'a> for SparseVariationRegion<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let region_axis_count: u16 = cursor.read()?;
        let region_axis_offsets_byte_len = (region_axis_count as usize)
            .checked_mul(SparseRegionAxisCoordinates::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_axis_offsets_byte_len);
        cursor.finish(SparseVariationRegionMarker {
            region_axis_offsets_byte_len,
        })
    }
}

pub type SparseVariationRegion<'a> = TableRef<'a, SparseVariationRegionMarker>;

impl<'a> SparseVariationRegion<'a> {
    pub fn region_axis_count(&self) -> u16 {
        let range = self.shape.region_axis_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn region_axis_offsets(&self) -> &'a [SparseRegionAxisCoordinates] {
        let range = self.shape.region_axis_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SparseVariationRegion<'a> {
    fn type_name(&self) -> &str {
        "SparseVariationRegion"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("region_axis_count", self.region_axis_count())),
            1usize => Some(Field::new(
                "region_axis_offsets",
                traversal::FieldType::array_of_records(
                    stringify!(SparseRegionAxisCoordinates),
                    self.region_axis_offsets(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> std::fmt::Debug for SparseVariationRegion<'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 SparseRegionAxisCoordinates {
    pub axis_index: BigEndian<u16>,
    pub start: BigEndian<F2Dot14>,
    pub peak: BigEndian<F2Dot14>,
    pub end: BigEndian<F2Dot14>,
}

impl SparseRegionAxisCoordinates {
    pub fn axis_index(&self) -> u16 {
        self.axis_index.get()
    }

    pub fn start(&self) -> F2Dot14 {
        self.start.get()
    }

    pub fn peak(&self) -> F2Dot14 {
        self.peak.get()
    }

    pub fn end(&self) -> F2Dot14 {
        self.end.get()
    }
}

impl FixedSize for SparseRegionAxisCoordinates {
    const RAW_BYTE_LEN: usize =
        u16::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
}

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

impl Format<u8> for MultiItemVariationDataMarker {
    const FORMAT: u8 = 1;
}

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MultiItemVariationDataMarker {
    region_indices_byte_len: usize,
    raw_delta_sets_byte_len: usize,
}

impl MultiItemVariationDataMarker {
    pub fn format_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u8::RAW_BYTE_LEN
    }

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

    pub fn region_indices_byte_range(&self) -> Range<usize> {
        let start = self.region_index_count_byte_range().end;
        start..start + self.region_indices_byte_len
    }

    pub fn raw_delta_sets_byte_range(&self) -> Range<usize> {
        let start = self.region_indices_byte_range().end;
        start..start + self.raw_delta_sets_byte_len
    }
}

impl<'a> FontRead<'a> for MultiItemVariationData<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u8>();
        let region_index_count: u16 = cursor.read()?;
        let region_indices_byte_len = (region_index_count as usize)
            .checked_mul(u16::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_indices_byte_len);
        let raw_delta_sets_byte_len =
            cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
        cursor.advance_by(raw_delta_sets_byte_len);
        cursor.finish(MultiItemVariationDataMarker {
            region_indices_byte_len,
            raw_delta_sets_byte_len,
        })
    }
}

pub type MultiItemVariationData<'a> = TableRef<'a, MultiItemVariationDataMarker>;

impl<'a> MultiItemVariationData<'a> {
    pub fn format(&self) -> u8 {
        let range = self.shape.format_byte_range();
        self.data.read_at(range.start).unwrap()
    }

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

    pub fn region_indices(&self) -> &'a [BigEndian<u16>] {
        let range = self.shape.region_indices_byte_range();
        self.data.read_array(range).unwrap()
    }

    pub fn raw_delta_sets(&self) -> &'a [u8] {
        let range = self.shape.raw_delta_sets_byte_range();
        self.data.read_array(range).unwrap()
    }
}

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

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

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct ConditionListMarker {
    condition_offsets_byte_len: usize,
}

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

    pub fn condition_offsets_byte_range(&self) -> Range<usize> {
        let start = self.condition_count_byte_range().end;
        start..start + self.condition_offsets_byte_len
    }
}

impl<'a> FontRead<'a> for ConditionList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let condition_count: u32 = cursor.read()?;
        let condition_offsets_byte_len = (condition_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(condition_offsets_byte_len);
        cursor.finish(ConditionListMarker {
            condition_offsets_byte_len,
        })
    }
}

pub type ConditionList<'a> = TableRef<'a, ConditionListMarker>;

impl<'a> ConditionList<'a> {
    pub fn condition_count(&self) -> u32 {
        let range = self.shape.condition_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn condition_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.shape.condition_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// A dynamically resolving wrapper for [`condition_offsets`][Self::condition_offsets].
    pub fn conditions(&self) -> ArrayOfOffsets<'a, Condition<'a>, Offset32> {
        let data = self.data;
        let offsets = self.condition_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for ConditionList<'a> {
    fn type_name(&self) -> &str {
        "ConditionList"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("condition_count", self.condition_count())),
            1usize => Some({
                let data = self.data;
                Field::new(
                    "condition_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<Condition>(),
                        self.condition_offsets(),
                        move |off| {
                            let target = off.get().resolve::<Condition>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => None,
        }
    }
}

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

/// Flags used in the [VarcComponent] byte stream
///
/// <https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-component-flags>
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct VarcFlags {
    bits: u32,
}

impl VarcFlags {
    pub const RESET_UNSPECIFIED_AXES: Self = Self {
        bits: 0b0000_0000_0000_0001,
    };

    pub const HAVE_AXES: Self = Self {
        bits: 0b0000_0000_0000_0010,
    };

    pub const AXIS_VALUES_HAVE_VARIATION: Self = Self {
        bits: 0b0000_0000_0000_0100,
    };

    pub const TRANSFORM_HAS_VARIATION: Self = Self {
        bits: 0b0000_0000_0000_1000,
    };

    pub const HAVE_TRANSLATE_X: Self = Self {
        bits: 0b0000_0000_0001_0000,
    };

    pub const HAVE_TRANSLATE_Y: Self = Self {
        bits: 0b0000_0000_0010_0000,
    };

    pub const HAVE_ROTATION: Self = Self {
        bits: 0b0000_0000_0100_0000,
    };

    pub const HAVE_CONDITION: Self = Self {
        bits: 0b0000_0000_1000_0000,
    };

    pub const HAVE_SCALE_X: Self = Self {
        bits: 0b0000_0001_0000_0000,
    };

    pub const HAVE_SCALE_Y: Self = Self {
        bits: 0b0000_0010_0000_0000,
    };

    pub const HAVE_TCENTER_X: Self = Self {
        bits: 0b0000_0100_0000_0000,
    };

    pub const HAVE_TCENTER_Y: Self = Self {
        bits: 0b0000_1000_0000_0000,
    };

    pub const GID_IS_24BIT: Self = Self {
        bits: 0b0001_0000_0000_0000,
    };

    pub const HAVE_SKEW_X: Self = Self {
        bits: 0b0010_0000_0000_0000,
    };

    pub const HAVE_SKEW_Y: Self = Self {
        bits: 0b0100_0000_0000_0000,
    };

    pub const RESERVED_MASK: Self = Self { bits: 0xFFFF8000 };
}

impl VarcFlags {
    ///  Returns an empty set of flags.
    #[inline]
    pub const fn empty() -> Self {
        Self { bits: 0 }
    }

    /// Returns the set containing all flags.
    #[inline]
    pub const fn all() -> Self {
        Self {
            bits: Self::RESET_UNSPECIFIED_AXES.bits
                | Self::HAVE_AXES.bits
                | Self::AXIS_VALUES_HAVE_VARIATION.bits
                | Self::TRANSFORM_HAS_VARIATION.bits
                | Self::HAVE_TRANSLATE_X.bits
                | Self::HAVE_TRANSLATE_Y.bits
                | Self::HAVE_ROTATION.bits
                | Self::HAVE_CONDITION.bits
                | Self::HAVE_SCALE_X.bits
                | Self::HAVE_SCALE_Y.bits
                | Self::HAVE_TCENTER_X.bits
                | Self::HAVE_TCENTER_Y.bits
                | Self::GID_IS_24BIT.bits
                | Self::HAVE_SKEW_X.bits
                | Self::HAVE_SKEW_Y.bits
                | Self::RESERVED_MASK.bits,
        }
    }

    /// Returns the raw value of the flags currently stored.
    #[inline]
    pub const fn bits(&self) -> u32 {
        self.bits
    }

    /// Convert from underlying bit representation, unless that
    /// representation contains bits that do not correspond to a flag.
    #[inline]
    pub const fn from_bits(bits: u32) -> Option<Self> {
        if (bits & !Self::all().bits()) == 0 {
            Some(Self { bits })
        } else {
            None
        }
    }

    /// Convert from underlying bit representation, dropping any bits
    /// that do not correspond to flags.
    #[inline]
    pub const fn from_bits_truncate(bits: u32) -> Self {
        Self {
            bits: bits & Self::all().bits,
        }
    }

    /// Returns `true` if no flags are currently stored.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.bits() == Self::empty().bits()
    }

    /// Returns `true` if there are flags common to both `self` and `other`.
    #[inline]
    pub const fn intersects(&self, other: Self) -> bool {
        !(Self {
            bits: self.bits & other.bits,
        })
        .is_empty()
    }

    /// Returns `true` if all of the flags in `other` are contained within `self`.
    #[inline]
    pub const fn contains(&self, other: Self) -> bool {
        (self.bits & other.bits) == other.bits
    }

    /// Inserts the specified flags in-place.
    #[inline]
    pub fn insert(&mut self, other: Self) {
        self.bits |= other.bits;
    }

    /// Removes the specified flags in-place.
    #[inline]
    pub fn remove(&mut self, other: Self) {
        self.bits &= !other.bits;
    }

    /// Toggles the specified flags in-place.
    #[inline]
    pub fn toggle(&mut self, other: Self) {
        self.bits ^= other.bits;
    }

    /// Returns the intersection between the flags in `self` and
    /// `other`.
    ///
    /// Specifically, the returned set contains only the flags which are
    /// present in *both* `self` *and* `other`.
    ///
    /// This is equivalent to using the `&` operator (e.g.
    /// [`ops::BitAnd`]), as in `flags & other`.
    ///
    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
    #[inline]
    #[must_use]
    pub const fn intersection(self, other: Self) -> Self {
        Self {
            bits: self.bits & other.bits,
        }
    }

    /// Returns the union of between the flags in `self` and `other`.
    ///
    /// Specifically, the returned set contains all flags which are
    /// present in *either* `self` *or* `other`, including any which are
    /// present in both.
    ///
    /// This is equivalent to using the `|` operator (e.g.
    /// [`ops::BitOr`]), as in `flags | other`.
    ///
    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
    #[inline]
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self {
            bits: self.bits | other.bits,
        }
    }

    /// Returns the difference between the flags in `self` and `other`.
    ///
    /// Specifically, the returned set contains all flags present in
    /// `self`, except for the ones present in `other`.
    ///
    /// It is also conceptually equivalent to the "bit-clear" operation:
    /// `flags & !other` (and this syntax is also supported).
    ///
    /// This is equivalent to using the `-` operator (e.g.
    /// [`ops::Sub`]), as in `flags - other`.
    ///
    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
    #[inline]
    #[must_use]
    pub const fn difference(self, other: Self) -> Self {
        Self {
            bits: self.bits & !other.bits,
        }
    }
}

impl std::ops::BitOr for VarcFlags {
    type Output = Self;

    /// Returns the union of the two sets of flags.
    #[inline]
    fn bitor(self, other: VarcFlags) -> Self {
        Self {
            bits: self.bits | other.bits,
        }
    }
}

impl std::ops::BitOrAssign for VarcFlags {
    /// Adds the set of flags.
    #[inline]
    fn bitor_assign(&mut self, other: Self) {
        self.bits |= other.bits;
    }
}

impl std::ops::BitXor for VarcFlags {
    type Output = Self;

    /// Returns the left flags, but with all the right flags toggled.
    #[inline]
    fn bitxor(self, other: Self) -> Self {
        Self {
            bits: self.bits ^ other.bits,
        }
    }
}

impl std::ops::BitXorAssign for VarcFlags {
    /// Toggles the set of flags.
    #[inline]
    fn bitxor_assign(&mut self, other: Self) {
        self.bits ^= other.bits;
    }
}

impl std::ops::BitAnd for VarcFlags {
    type Output = Self;

    /// Returns the intersection between the two sets of flags.
    #[inline]
    fn bitand(self, other: Self) -> Self {
        Self {
            bits: self.bits & other.bits,
        }
    }
}

impl std::ops::BitAndAssign for VarcFlags {
    /// Disables all flags disabled in the set.
    #[inline]
    fn bitand_assign(&mut self, other: Self) {
        self.bits &= other.bits;
    }
}

impl std::ops::Sub for VarcFlags {
    type Output = Self;

    /// Returns the set difference of the two sets of flags.
    #[inline]
    fn sub(self, other: Self) -> Self {
        Self {
            bits: self.bits & !other.bits,
        }
    }
}

impl std::ops::SubAssign for VarcFlags {
    /// Disables all flags enabled in the set.
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.bits &= !other.bits;
    }
}

impl std::ops::Not for VarcFlags {
    type Output = Self;

    /// Returns the complement of this set of flags.
    #[inline]
    fn not(self) -> Self {
        Self { bits: !self.bits } & Self::all()
    }
}

impl std::fmt::Debug for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let members: &[(&str, Self)] = &[
            ("RESET_UNSPECIFIED_AXES", Self::RESET_UNSPECIFIED_AXES),
            ("HAVE_AXES", Self::HAVE_AXES),
            (
                "AXIS_VALUES_HAVE_VARIATION",
                Self::AXIS_VALUES_HAVE_VARIATION,
            ),
            ("TRANSFORM_HAS_VARIATION", Self::TRANSFORM_HAS_VARIATION),
            ("HAVE_TRANSLATE_X", Self::HAVE_TRANSLATE_X),
            ("HAVE_TRANSLATE_Y", Self::HAVE_TRANSLATE_Y),
            ("HAVE_ROTATION", Self::HAVE_ROTATION),
            ("HAVE_CONDITION", Self::HAVE_CONDITION),
            ("HAVE_SCALE_X", Self::HAVE_SCALE_X),
            ("HAVE_SCALE_Y", Self::HAVE_SCALE_Y),
            ("HAVE_TCENTER_X", Self::HAVE_TCENTER_X),
            ("HAVE_TCENTER_Y", Self::HAVE_TCENTER_Y),
            ("GID_IS_24BIT", Self::GID_IS_24BIT),
            ("HAVE_SKEW_X", Self::HAVE_SKEW_X),
            ("HAVE_SKEW_Y", Self::HAVE_SKEW_Y),
            ("RESERVED_MASK", Self::RESERVED_MASK),
        ];
        let mut first = true;
        for (name, value) in members {
            if self.contains(*value) {
                if !first {
                    f.write_str(" | ")?;
                }
                first = false;
                f.write_str(name)?;
            }
        }
        if first {
            f.write_str("(empty)")?;
        }
        Ok(())
    }
}

impl std::fmt::Binary for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Binary::fmt(&self.bits, f)
    }
}

impl std::fmt::Octal for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Octal::fmt(&self.bits, f)
    }
}

impl std::fmt::LowerHex for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::LowerHex::fmt(&self.bits, f)
    }
}

impl std::fmt::UpperHex for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::UpperHex::fmt(&self.bits, f)
    }
}

impl font_types::Scalar for VarcFlags {
    type Raw = <u32 as font_types::Scalar>::Raw;
    fn to_raw(self) -> Self::Raw {
        self.bits().to_raw()
    }
    fn from_raw(raw: Self::Raw) -> Self {
        let t = <u32>::from_raw(raw);
        Self::from_bits_truncate(t)
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> From<VarcFlags> for FieldType<'a> {
    fn from(src: VarcFlags) -> FieldType<'a> {
        src.bits().into()
    }
}