read_fonts/generated/
generated_glyf.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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
// THIS FILE IS AUTOGENERATED.
// Any changes to this file will be overwritten.
// For more information about how codegen works, see font-codegen/README.md

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

/// The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct GlyfMarker {}

impl GlyfMarker {}

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

impl<'a> FontRead<'a> for Glyf<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let cursor = data.cursor();
        cursor.finish(GlyfMarker {})
    }
}

/// The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
pub type Glyf<'a> = TableRef<'a, GlyfMarker>;

impl<'a> Glyf<'a> {}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Glyf<'a> {
    fn type_name(&self) -> &str {
        "Glyf"
    }

    #[allow(unused_variables)]
    #[allow(clippy::match_single_binding)]
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            _ => None,
        }
    }
}

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

/// The [Glyph Header](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SimpleGlyphMarker {
    end_pts_of_contours_byte_len: usize,
    instructions_byte_len: usize,
    glyph_data_byte_len: usize,
}

impl SimpleGlyphMarker {
    fn number_of_contours_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + i16::RAW_BYTE_LEN
    }
    fn x_min_byte_range(&self) -> Range<usize> {
        let start = self.number_of_contours_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn y_min_byte_range(&self) -> Range<usize> {
        let start = self.x_min_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn x_max_byte_range(&self) -> Range<usize> {
        let start = self.y_min_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn y_max_byte_range(&self) -> Range<usize> {
        let start = self.x_max_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn end_pts_of_contours_byte_range(&self) -> Range<usize> {
        let start = self.y_max_byte_range().end;
        start..start + self.end_pts_of_contours_byte_len
    }
    fn instruction_length_byte_range(&self) -> Range<usize> {
        let start = self.end_pts_of_contours_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
    fn instructions_byte_range(&self) -> Range<usize> {
        let start = self.instruction_length_byte_range().end;
        start..start + self.instructions_byte_len
    }
    fn glyph_data_byte_range(&self) -> Range<usize> {
        let start = self.instructions_byte_range().end;
        start..start + self.glyph_data_byte_len
    }
}

impl<'a> FontRead<'a> for SimpleGlyph<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let number_of_contours: i16 = cursor.read()?;
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        let end_pts_of_contours_byte_len = (number_of_contours as usize)
            .checked_mul(u16::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(end_pts_of_contours_byte_len);
        let instruction_length: u16 = cursor.read()?;
        let instructions_byte_len = (instruction_length as usize)
            .checked_mul(u8::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(instructions_byte_len);
        let glyph_data_byte_len = cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
        cursor.advance_by(glyph_data_byte_len);
        cursor.finish(SimpleGlyphMarker {
            end_pts_of_contours_byte_len,
            instructions_byte_len,
            glyph_data_byte_len,
        })
    }
}

/// The [Glyph Header](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
pub type SimpleGlyph<'a> = TableRef<'a, SimpleGlyphMarker>;

impl<'a> SimpleGlyph<'a> {
    /// If the number of contours is greater than or equal to zero,
    /// this is a simple glyph. If negative, this is a composite glyph
    /// — the value -1 should be used for composite glyphs.
    pub fn number_of_contours(&self) -> i16 {
        let range = self.shape.number_of_contours_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Minimum x for coordinate data.
    pub fn x_min(&self) -> i16 {
        let range = self.shape.x_min_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Minimum y for coordinate data.
    pub fn y_min(&self) -> i16 {
        let range = self.shape.y_min_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Maximum x for coordinate data.
    pub fn x_max(&self) -> i16 {
        let range = self.shape.x_max_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Maximum y for coordinate data.
    pub fn y_max(&self) -> i16 {
        let range = self.shape.y_max_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Array of point indices for the last point of each contour,
    /// in increasing numeric order
    pub fn end_pts_of_contours(&self) -> &'a [BigEndian<u16>] {
        let range = self.shape.end_pts_of_contours_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// Total number of bytes for instructions. If instructionLength is
    /// zero, no instructions are present for this glyph, and this
    /// field is followed directly by the flags field.
    pub fn instruction_length(&self) -> u16 {
        let range = self.shape.instruction_length_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Array of instruction byte code for the glyph.
    pub fn instructions(&self) -> &'a [u8] {
        let range = self.shape.instructions_byte_range();
        self.data.read_array(range).unwrap()
    }

    /// the raw data for flags & x/y coordinates
    pub fn glyph_data(&self) -> &'a [u8] {
        let range = self.shape.glyph_data_byte_range();
        self.data.read_array(range).unwrap()
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SimpleGlyph<'a> {
    fn type_name(&self) -> &str {
        "SimpleGlyph"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("number_of_contours", self.number_of_contours())),
            1usize => Some(Field::new("x_min", self.x_min())),
            2usize => Some(Field::new("y_min", self.y_min())),
            3usize => Some(Field::new("x_max", self.x_max())),
            4usize => Some(Field::new("y_max", self.y_max())),
            5usize => Some(Field::new(
                "end_pts_of_contours",
                self.end_pts_of_contours(),
            )),
            6usize => Some(Field::new("instruction_length", self.instruction_length())),
            7usize => Some(Field::new("instructions", self.instructions())),
            8usize => Some(Field::new("glyph_data", self.glyph_data())),
            _ => None,
        }
    }
}

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

/// Flags used in [SimpleGlyph]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct SimpleGlyphFlags {
    bits: u8,
}

impl SimpleGlyphFlags {
    /// Bit 0: If set, the point is on the curve; otherwise, it is off
    /// the curve.
    pub const ON_CURVE_POINT: Self = Self { bits: 0x01 };

    /// Bit 1: If set, the corresponding x-coordinate is 1 byte long,
    /// and the sign is determined by the
    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag. If not set, its
    /// interpretation depends on the
    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag: If that other flag
    /// is set, the x-coordinate is the same as the previous
    /// x-coordinate, and no element is added to the xCoordinates
    /// array. If both flags are not set, the corresponding element in
    /// the xCoordinates array is two bytes and interpreted as a signed
    /// integer. See the description of the
    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag for additional
    /// information.
    pub const X_SHORT_VECTOR: Self = Self { bits: 0x02 };

    /// Bit 2: If set, the corresponding y-coordinate is 1 byte long,
    /// and the sign is determined by the
    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag. If not set, its
    /// interpretation depends on the
    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag: If that other flag
    /// is set, the y-coordinate is the same as the previous
    /// y-coordinate, and no element is added to the yCoordinates
    /// array. If both flags are not set, the corresponding element in
    /// the yCoordinates array is two bytes and interpreted as a signed
    /// integer. See the description of the
    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag for additional
    /// information.
    pub const Y_SHORT_VECTOR: Self = Self { bits: 0x04 };

    /// Bit 3: If set, the next byte (read as unsigned) specifies the
    /// number of additional times this flag byte is to be repeated in
    /// the logical flags array — that is, the number of additional
    /// logical flag entries inserted after this entry. (In the
    /// expanded logical array, this bit is ignored.) In this way, the
    /// number of flags listed can be smaller than the number of points
    /// in the glyph description.
    pub const REPEAT_FLAG: Self = Self { bits: 0x08 };

    /// Bit 4: This flag has two meanings, depending on how the
    /// X_SHORT_VECTOR flag is set. If X_SHORT_VECTOR is set, this bit
    /// describes the sign of the value, with 1 equalling positive and
    /// 0 negative. If X_SHORT_VECTOR is not set and this bit is set,
    /// then the current x-coordinate is the same as the previous
    /// x-coordinate. If X_SHORT_VECTOR is not set and this bit is also
    /// not set, the current x-coordinate is a signed 16-bit delta
    /// vector.
    pub const X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR: Self = Self { bits: 0x10 };

    /// Bit 5: This flag has two meanings, depending on how the
    /// Y_SHORT_VECTOR flag is set. If Y_SHORT_VECTOR is set, this bit
    /// describes the sign of the value, with 1 equalling positive and
    /// 0 negative. If Y_SHORT_VECTOR is not set and this bit is set,
    /// then the current y-coordinate is the same as the previous
    /// y-coordinate. If Y_SHORT_VECTOR is not set and this bit is also
    /// not set, the current y-coordinate is a signed 16-bit delta
    /// vector.
    pub const Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR: Self = Self { bits: 0x20 };

    /// Bit 6: If set, contours in the glyph description may overlap.
    /// Use of this flag is not required in OpenType — that is, it is
    /// valid to have contours overlap without having this flag set. It
    /// may affect behaviors in some platforms, however. (See the
    /// discussion of “Overlapping contours” in Apple’s
    /// specification for details regarding behavior in Apple
    /// platforms.) When used, it must be set on the first flag byte
    /// for the glyph. See additional details below.
    pub const OVERLAP_SIMPLE: Self = Self { bits: 0x40 };

    /// Bit 7: Off-curve point belongs to a cubic-Bezier segment
    ///
    /// * [Spec](https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md)
    /// * [harfbuzz](https://github.com/harfbuzz/harfbuzz/blob/c1ca46e4ebb6457dfe00a5441d52a4a66134ac58/src/OT/glyf/SimpleGlyph.hh#L23)
    pub const CUBIC: Self = Self { bits: 0x80 };
}

impl SimpleGlyphFlags {
    ///  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::ON_CURVE_POINT.bits
                | Self::X_SHORT_VECTOR.bits
                | Self::Y_SHORT_VECTOR.bits
                | Self::REPEAT_FLAG.bits
                | Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR.bits
                | Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR.bits
                | Self::OVERLAP_SIMPLE.bits
                | Self::CUBIC.bits,
        }
    }

    /// Returns the raw value of the flags currently stored.
    #[inline]
    pub const fn bits(&self) -> u8 {
        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: u8) -> 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: u8) -> 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 SimpleGlyphFlags {
    type Output = Self;

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

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

impl std::ops::BitXor for SimpleGlyphFlags {
    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 SimpleGlyphFlags {
    /// Toggles the set of flags.
    #[inline]
    fn bitxor_assign(&mut self, other: Self) {
        self.bits ^= other.bits;
    }
}

impl std::ops::BitAnd for SimpleGlyphFlags {
    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 SimpleGlyphFlags {
    /// Disables all flags disabled in the set.
    #[inline]
    fn bitand_assign(&mut self, other: Self) {
        self.bits &= other.bits;
    }
}

impl std::ops::Sub for SimpleGlyphFlags {
    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 SimpleGlyphFlags {
    /// Disables all flags enabled in the set.
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.bits &= !other.bits;
    }
}

impl std::ops::Not for SimpleGlyphFlags {
    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 SimpleGlyphFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let members: &[(&str, Self)] = &[
            ("ON_CURVE_POINT", Self::ON_CURVE_POINT),
            ("X_SHORT_VECTOR", Self::X_SHORT_VECTOR),
            ("Y_SHORT_VECTOR", Self::Y_SHORT_VECTOR),
            ("REPEAT_FLAG", Self::REPEAT_FLAG),
            (
                "X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR",
                Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
            ),
            (
                "Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR",
                Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR,
            ),
            ("OVERLAP_SIMPLE", Self::OVERLAP_SIMPLE),
            ("CUBIC", Self::CUBIC),
        ];
        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 SimpleGlyphFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Binary::fmt(&self.bits, f)
    }
}

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

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

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

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

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

/// [CompositeGlyph](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct CompositeGlyphMarker {
    component_data_byte_len: usize,
}

impl CompositeGlyphMarker {
    fn number_of_contours_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + i16::RAW_BYTE_LEN
    }
    fn x_min_byte_range(&self) -> Range<usize> {
        let start = self.number_of_contours_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn y_min_byte_range(&self) -> Range<usize> {
        let start = self.x_min_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn x_max_byte_range(&self) -> Range<usize> {
        let start = self.y_min_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn y_max_byte_range(&self) -> Range<usize> {
        let start = self.x_max_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
    fn component_data_byte_range(&self) -> Range<usize> {
        let start = self.y_max_byte_range().end;
        start..start + self.component_data_byte_len
    }
}

impl<'a> FontRead<'a> for CompositeGlyph<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        cursor.advance::<i16>();
        let component_data_byte_len =
            cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
        cursor.advance_by(component_data_byte_len);
        cursor.finish(CompositeGlyphMarker {
            component_data_byte_len,
        })
    }
}

/// [CompositeGlyph](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
pub type CompositeGlyph<'a> = TableRef<'a, CompositeGlyphMarker>;

impl<'a> CompositeGlyph<'a> {
    /// If the number of contours is greater than or equal to zero,
    /// this is a simple glyph. If negative, this is a composite glyph
    /// — the value -1 should be used for composite glyphs.
    pub fn number_of_contours(&self) -> i16 {
        let range = self.shape.number_of_contours_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Minimum x for coordinate data.
    pub fn x_min(&self) -> i16 {
        let range = self.shape.x_min_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Minimum y for coordinate data.
    pub fn y_min(&self) -> i16 {
        let range = self.shape.y_min_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Maximum x for coordinate data.
    pub fn x_max(&self) -> i16 {
        let range = self.shape.x_max_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// Maximum y for coordinate data.
    pub fn y_max(&self) -> i16 {
        let range = self.shape.y_max_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    /// component flag
    /// glyph index of component
    pub fn component_data(&self) -> &'a [u8] {
        let range = self.shape.component_data_byte_range();
        self.data.read_array(range).unwrap()
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CompositeGlyph<'a> {
    fn type_name(&self) -> &str {
        "CompositeGlyph"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("number_of_contours", self.number_of_contours())),
            1usize => Some(Field::new("x_min", self.x_min())),
            2usize => Some(Field::new("y_min", self.y_min())),
            3usize => Some(Field::new("x_max", self.x_max())),
            4usize => Some(Field::new("y_max", self.y_max())),
            5usize => Some(Field::new("component_data", self.component_data())),
            _ => None,
        }
    }
}

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

/// Flags used in [CompositeGlyph]
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct CompositeGlyphFlags {
    bits: u16,
}

impl CompositeGlyphFlags {
    /// Bit 0: If this is set, the arguments are 16-bit (uint16 or
    /// int16); otherwise, they are bytes (uint8 or int8).
    pub const ARG_1_AND_2_ARE_WORDS: Self = Self { bits: 0x0001 };

    /// Bit 1: If this is set, the arguments are signed xy values;

    /// otherwise, they are unsigned point numbers.
    pub const ARGS_ARE_XY_VALUES: Self = Self { bits: 0x0002 };

    /// Bit 2: If set and ARGS_ARE_XY_VALUES is also set, the xy values
    /// are rounded to the nearest grid line. Ignored if
    /// ARGS_ARE_XY_VALUES is not set.
    pub const ROUND_XY_TO_GRID: Self = Self { bits: 0x0004 };

    /// Bit 3: This indicates that there is a simple scale for the
    /// component. Otherwise, scale = 1.0.
    pub const WE_HAVE_A_SCALE: Self = Self { bits: 0x0008 };

    /// Bit 5: Indicates at least one more glyph after this one.
    pub const MORE_COMPONENTS: Self = Self { bits: 0x0020 };

    /// Bit 6: The x direction will use a different scale from the y
    /// direction.
    pub const WE_HAVE_AN_X_AND_Y_SCALE: Self = Self { bits: 0x0040 };

    /// Bit 7: There is a 2 by 2 transformation that will be used to
    /// scale the component.
    pub const WE_HAVE_A_TWO_BY_TWO: Self = Self { bits: 0x0080 };

    /// Bit 8: Following the last component are instructions for the
    /// composite character.
    pub const WE_HAVE_INSTRUCTIONS: Self = Self { bits: 0x0100 };

    /// Bit 9: If set, this forces the aw and lsb (and rsb) for the
    /// composite to be equal to those from this component glyph. This
    /// works for hinted and unhinted glyphs.
    pub const USE_MY_METRICS: Self = Self { bits: 0x0200 };

    /// Bit 10: If set, the components of the compound glyph overlap.
    /// Use of this flag is not required in OpenType — that is, it is
    /// valid to have components overlap without having this flag set.
    /// It may affect behaviors in some platforms, however. (See
    /// Apple’s specification for details regarding behavior in Apple
    /// platforms.) When used, it must be set on the flag word for the
    /// first component. See additional remarks, above, for the similar
    /// OVERLAP_SIMPLE flag used in simple-glyph descriptions.
    pub const OVERLAP_COMPOUND: Self = Self { bits: 0x0400 };

    /// Bit 11: The composite is designed to have the component offset
    /// scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
    pub const SCALED_COMPONENT_OFFSET: Self = Self { bits: 0x0800 };

    /// Bit 12: The composite is designed not to have the component
    /// offset scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
    pub const UNSCALED_COMPONENT_OFFSET: Self = Self { bits: 0x1000 };
}

impl CompositeGlyphFlags {
    ///  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::ARG_1_AND_2_ARE_WORDS.bits
                | Self::ARGS_ARE_XY_VALUES.bits
                | Self::ROUND_XY_TO_GRID.bits
                | Self::WE_HAVE_A_SCALE.bits
                | Self::MORE_COMPONENTS.bits
                | Self::WE_HAVE_AN_X_AND_Y_SCALE.bits
                | Self::WE_HAVE_A_TWO_BY_TWO.bits
                | Self::WE_HAVE_INSTRUCTIONS.bits
                | Self::USE_MY_METRICS.bits
                | Self::OVERLAP_COMPOUND.bits
                | Self::SCALED_COMPONENT_OFFSET.bits
                | Self::UNSCALED_COMPONENT_OFFSET.bits,
        }
    }

    /// Returns the raw value of the flags currently stored.
    #[inline]
    pub const fn bits(&self) -> u16 {
        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: u16) -> 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: u16) -> 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 CompositeGlyphFlags {
    type Output = Self;

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

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

impl std::ops::BitXor for CompositeGlyphFlags {
    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 CompositeGlyphFlags {
    /// Toggles the set of flags.
    #[inline]
    fn bitxor_assign(&mut self, other: Self) {
        self.bits ^= other.bits;
    }
}

impl std::ops::BitAnd for CompositeGlyphFlags {
    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 CompositeGlyphFlags {
    /// Disables all flags disabled in the set.
    #[inline]
    fn bitand_assign(&mut self, other: Self) {
        self.bits &= other.bits;
    }
}

impl std::ops::Sub for CompositeGlyphFlags {
    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 CompositeGlyphFlags {
    /// Disables all flags enabled in the set.
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.bits &= !other.bits;
    }
}

impl std::ops::Not for CompositeGlyphFlags {
    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 CompositeGlyphFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let members: &[(&str, Self)] = &[
            ("ARG_1_AND_2_ARE_WORDS", Self::ARG_1_AND_2_ARE_WORDS),
            ("ARGS_ARE_XY_VALUES", Self::ARGS_ARE_XY_VALUES),
            ("ROUND_XY_TO_GRID", Self::ROUND_XY_TO_GRID),
            ("WE_HAVE_A_SCALE", Self::WE_HAVE_A_SCALE),
            ("MORE_COMPONENTS", Self::MORE_COMPONENTS),
            ("WE_HAVE_AN_X_AND_Y_SCALE", Self::WE_HAVE_AN_X_AND_Y_SCALE),
            ("WE_HAVE_A_TWO_BY_TWO", Self::WE_HAVE_A_TWO_BY_TWO),
            ("WE_HAVE_INSTRUCTIONS", Self::WE_HAVE_INSTRUCTIONS),
            ("USE_MY_METRICS", Self::USE_MY_METRICS),
            ("OVERLAP_COMPOUND", Self::OVERLAP_COMPOUND),
            ("SCALED_COMPONENT_OFFSET", Self::SCALED_COMPONENT_OFFSET),
            ("UNSCALED_COMPONENT_OFFSET", Self::UNSCALED_COMPONENT_OFFSET),
        ];
        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 CompositeGlyphFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Binary::fmt(&self.bits, f)
    }
}

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

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

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

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

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

/// Simple or composite glyph.
#[derive(Clone)]
pub enum Glyph<'a> {
    Simple(SimpleGlyph<'a>),
    Composite(CompositeGlyph<'a>),
}

impl<'a> Glyph<'a> {
    ///Return the `FontData` used to resolve offsets for this table.
    pub fn offset_data(&self) -> FontData<'a> {
        match self {
            Self::Simple(item) => item.offset_data(),
            Self::Composite(item) => item.offset_data(),
        }
    }

    /// If the number of contours is greater than or equal to zero,
    /// this is a simple glyph. If negative, this is a composite glyph
    /// — the value -1 should be used for composite glyphs.
    pub fn number_of_contours(&self) -> i16 {
        match self {
            Self::Simple(item) => item.number_of_contours(),
            Self::Composite(item) => item.number_of_contours(),
        }
    }

    /// Minimum x for coordinate data.
    pub fn x_min(&self) -> i16 {
        match self {
            Self::Simple(item) => item.x_min(),
            Self::Composite(item) => item.x_min(),
        }
    }

    /// Minimum y for coordinate data.
    pub fn y_min(&self) -> i16 {
        match self {
            Self::Simple(item) => item.y_min(),
            Self::Composite(item) => item.y_min(),
        }
    }

    /// Maximum x for coordinate data.
    pub fn x_max(&self) -> i16 {
        match self {
            Self::Simple(item) => item.x_max(),
            Self::Composite(item) => item.x_max(),
        }
    }

    /// Maximum y for coordinate data.
    pub fn y_max(&self) -> i16 {
        match self {
            Self::Simple(item) => item.y_max(),
            Self::Composite(item) => item.y_max(),
        }
    }
}

impl<'a> FontRead<'a> for Glyph<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let format: i16 = data.read_at(0usize)?;

        #[allow(clippy::redundant_guards)]
        match format {
            format if format >= 0 => Ok(Self::Simple(FontRead::read(data)?)),
            format if format < 0 => Ok(Self::Composite(FontRead::read(data)?)),
            other => Err(ReadError::InvalidFormat(other.into())),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> Glyph<'a> {
    fn dyn_inner<'b>(&'b self) -> &'b dyn SomeTable<'a> {
        match self {
            Self::Simple(table) => table,
            Self::Composite(table) => table,
        }
    }
}

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Glyph<'a> {
    fn type_name(&self) -> &str {
        self.dyn_inner().type_name()
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        self.dyn_inner().get_field(idx)
    }
}