Skip to main content

read_fonts/generated/
generated_glyf.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 TopLevelTable for Glyf<'_> {
9    /// `glyf`
10    const TAG: Tag = Tag::new(b"glyf");
11}
12
13impl<'a> FontRead<'a> for Glyf<'a> {
14    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
15        #[allow(clippy::absurd_extreme_comparisons)]
16        if data.len() < Self::MIN_SIZE {
17            return Err(ReadError::OutOfBounds);
18        }
19        Ok(Self { data })
20    }
21}
22
23/// The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
24#[derive(Clone)]
25pub struct Glyf<'a> {
26    data: FontData<'a>,
27}
28
29#[allow(clippy::needless_lifetimes)]
30impl<'a> Glyf<'a> {
31    pub const MIN_SIZE: usize = 0;
32    basic_table_impls!(impl_the_methods);
33}
34
35#[cfg(feature = "experimental_traverse")]
36impl<'a> SomeTable<'a> for Glyf<'a> {
37    fn type_name(&self) -> &str {
38        "Glyf"
39    }
40
41    #[allow(unused_variables)]
42    #[allow(clippy::match_single_binding)]
43    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
44        match idx {
45            _ => None,
46        }
47    }
48}
49
50#[cfg(feature = "experimental_traverse")]
51#[allow(clippy::needless_lifetimes)]
52impl<'a> std::fmt::Debug for Glyf<'a> {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        (self as &dyn SomeTable<'a>).fmt(f)
55    }
56}
57
58impl<'a> MinByteRange<'a> for SimpleGlyph<'a> {
59    fn min_byte_range(&self) -> Range<usize> {
60        0..self.glyph_data_byte_range().end
61    }
62    fn min_table_bytes(&self) -> &'a [u8] {
63        let range = self.min_byte_range();
64        self.data.as_bytes().get(range).unwrap_or_default()
65    }
66}
67
68impl<'a> FontRead<'a> for SimpleGlyph<'a> {
69    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
70        #[allow(clippy::absurd_extreme_comparisons)]
71        if data.len() < Self::MIN_SIZE {
72            return Err(ReadError::OutOfBounds);
73        }
74        Ok(Self { data })
75    }
76}
77
78/// The [Glyph Header](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
79#[derive(Clone)]
80pub struct SimpleGlyph<'a> {
81    data: FontData<'a>,
82}
83
84#[allow(clippy::needless_lifetimes)]
85impl<'a> SimpleGlyph<'a> {
86    pub const MIN_SIZE: usize = (i16::RAW_BYTE_LEN
87        + i16::RAW_BYTE_LEN
88        + i16::RAW_BYTE_LEN
89        + i16::RAW_BYTE_LEN
90        + i16::RAW_BYTE_LEN
91        + u16::RAW_BYTE_LEN);
92    basic_table_impls!(impl_the_methods);
93
94    /// If the number of contours is greater than or equal to zero,
95    /// this is a simple glyph. If negative, this is a composite glyph
96    /// — the value -1 should be used for composite glyphs.
97    pub fn number_of_contours(&self) -> i16 {
98        let range = self.number_of_contours_byte_range();
99        self.data.read_at(range.start).ok().unwrap()
100    }
101
102    /// Minimum x for coordinate data.
103    pub fn x_min(&self) -> i16 {
104        let range = self.x_min_byte_range();
105        self.data.read_at(range.start).ok().unwrap()
106    }
107
108    /// Minimum y for coordinate data.
109    pub fn y_min(&self) -> i16 {
110        let range = self.y_min_byte_range();
111        self.data.read_at(range.start).ok().unwrap()
112    }
113
114    /// Maximum x for coordinate data.
115    pub fn x_max(&self) -> i16 {
116        let range = self.x_max_byte_range();
117        self.data.read_at(range.start).ok().unwrap()
118    }
119
120    /// Maximum y for coordinate data.
121    pub fn y_max(&self) -> i16 {
122        let range = self.y_max_byte_range();
123        self.data.read_at(range.start).ok().unwrap()
124    }
125
126    /// Array of point indices for the last point of each contour,
127    /// in increasing numeric order
128    pub fn end_pts_of_contours(&self) -> &'a [BigEndian<u16>] {
129        let range = self.end_pts_of_contours_byte_range();
130        self.data.read_array(range).ok().unwrap_or_default()
131    }
132
133    /// Total number of bytes for instructions. If instructionLength is
134    /// zero, no instructions are present for this glyph, and this
135    /// field is followed directly by the flags field.
136    pub fn instruction_length(&self) -> u16 {
137        let range = self.instruction_length_byte_range();
138        self.data.read_at(range.start).ok().unwrap_or_default()
139    }
140
141    /// Array of instruction byte code for the glyph.
142    pub fn instructions(&self) -> &'a [u8] {
143        let range = self.instructions_byte_range();
144        self.data.read_array(range).ok().unwrap_or_default()
145    }
146
147    /// the raw data for flags & x/y coordinates
148    pub fn glyph_data(&self) -> &'a [u8] {
149        let range = self.glyph_data_byte_range();
150        self.data.read_array(range).ok().unwrap_or_default()
151    }
152
153    pub fn number_of_contours_byte_range(&self) -> Range<usize> {
154        let start = 0;
155        start..start + i16::RAW_BYTE_LEN
156    }
157
158    pub fn x_min_byte_range(&self) -> Range<usize> {
159        let start = self.number_of_contours_byte_range().end;
160        start..start + i16::RAW_BYTE_LEN
161    }
162
163    pub fn y_min_byte_range(&self) -> Range<usize> {
164        let start = self.x_min_byte_range().end;
165        start..start + i16::RAW_BYTE_LEN
166    }
167
168    pub fn x_max_byte_range(&self) -> Range<usize> {
169        let start = self.y_min_byte_range().end;
170        start..start + i16::RAW_BYTE_LEN
171    }
172
173    pub fn y_max_byte_range(&self) -> Range<usize> {
174        let start = self.x_max_byte_range().end;
175        start..start + i16::RAW_BYTE_LEN
176    }
177
178    pub fn end_pts_of_contours_byte_range(&self) -> Range<usize> {
179        let number_of_contours = self.number_of_contours();
180        let start = self.y_max_byte_range().end;
181        start..start + (number_of_contours as usize).saturating_mul(u16::RAW_BYTE_LEN)
182    }
183
184    pub fn instruction_length_byte_range(&self) -> Range<usize> {
185        let start = self.end_pts_of_contours_byte_range().end;
186        start..start + u16::RAW_BYTE_LEN
187    }
188
189    pub fn instructions_byte_range(&self) -> Range<usize> {
190        let instruction_length = self.instruction_length();
191        let start = self.instruction_length_byte_range().end;
192        start..start + (instruction_length as usize).saturating_mul(u8::RAW_BYTE_LEN)
193    }
194
195    pub fn glyph_data_byte_range(&self) -> Range<usize> {
196        let start = self.instructions_byte_range().end;
197        start..start + self.data.len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN
198    }
199}
200
201#[cfg(feature = "experimental_traverse")]
202impl<'a> SomeTable<'a> for SimpleGlyph<'a> {
203    fn type_name(&self) -> &str {
204        "SimpleGlyph"
205    }
206    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
207        match idx {
208            0usize => Some(Field::new("number_of_contours", self.number_of_contours())),
209            1usize => Some(Field::new("x_min", self.x_min())),
210            2usize => Some(Field::new("y_min", self.y_min())),
211            3usize => Some(Field::new("x_max", self.x_max())),
212            4usize => Some(Field::new("y_max", self.y_max())),
213            5usize => Some(Field::new(
214                "end_pts_of_contours",
215                self.end_pts_of_contours(),
216            )),
217            6usize => Some(Field::new("instruction_length", self.instruction_length())),
218            7usize => Some(Field::new("instructions", self.instructions())),
219            8usize => Some(Field::new("glyph_data", self.glyph_data())),
220            _ => None,
221        }
222    }
223}
224
225#[cfg(feature = "experimental_traverse")]
226#[allow(clippy::needless_lifetimes)]
227impl<'a> std::fmt::Debug for SimpleGlyph<'a> {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        (self as &dyn SomeTable<'a>).fmt(f)
230    }
231}
232
233/// Flags used in [SimpleGlyph]
234#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
236#[repr(transparent)]
237pub struct SimpleGlyphFlags {
238    bits: u8,
239}
240
241impl SimpleGlyphFlags {
242    /// Bit 0: If set, the point is on the curve; otherwise, it is off
243    /// the curve.
244    pub const ON_CURVE_POINT: Self = Self { bits: 0x01 };
245
246    /// Bit 1: If set, the corresponding x-coordinate is 1 byte long,
247    /// and the sign is determined by the
248    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag. If not set, its
249    /// interpretation depends on the
250    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag: If that other flag
251    /// is set, the x-coordinate is the same as the previous
252    /// x-coordinate, and no element is added to the xCoordinates
253    /// array. If both flags are not set, the corresponding element in
254    /// the xCoordinates array is two bytes and interpreted as a signed
255    /// integer. See the description of the
256    /// X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR flag for additional
257    /// information.
258    pub const X_SHORT_VECTOR: Self = Self { bits: 0x02 };
259
260    /// Bit 2: If set, the corresponding y-coordinate is 1 byte long,
261    /// and the sign is determined by the
262    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag. If not set, its
263    /// interpretation depends on the
264    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag: If that other flag
265    /// is set, the y-coordinate is the same as the previous
266    /// y-coordinate, and no element is added to the yCoordinates
267    /// array. If both flags are not set, the corresponding element in
268    /// the yCoordinates array is two bytes and interpreted as a signed
269    /// integer. See the description of the
270    /// Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR flag for additional
271    /// information.
272    pub const Y_SHORT_VECTOR: Self = Self { bits: 0x04 };
273
274    /// Bit 3: If set, the next byte (read as unsigned) specifies the
275    /// number of additional times this flag byte is to be repeated in
276    /// the logical flags array — that is, the number of additional
277    /// logical flag entries inserted after this entry. (In the
278    /// expanded logical array, this bit is ignored.) In this way, the
279    /// number of flags listed can be smaller than the number of points
280    /// in the glyph description.
281    pub const REPEAT_FLAG: Self = Self { bits: 0x08 };
282
283    /// Bit 4: This flag has two meanings, depending on how the
284    /// X_SHORT_VECTOR flag is set. If X_SHORT_VECTOR is set, this bit
285    /// describes the sign of the value, with 1 equalling positive and
286    /// 0 negative. If X_SHORT_VECTOR is not set and this bit is set,
287    /// then the current x-coordinate is the same as the previous
288    /// x-coordinate. If X_SHORT_VECTOR is not set and this bit is also
289    /// not set, the current x-coordinate is a signed 16-bit delta
290    /// vector.
291    pub const X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR: Self = Self { bits: 0x10 };
292
293    /// Bit 5: This flag has two meanings, depending on how the
294    /// Y_SHORT_VECTOR flag is set. If Y_SHORT_VECTOR is set, this bit
295    /// describes the sign of the value, with 1 equalling positive and
296    /// 0 negative. If Y_SHORT_VECTOR is not set and this bit is set,
297    /// then the current y-coordinate is the same as the previous
298    /// y-coordinate. If Y_SHORT_VECTOR is not set and this bit is also
299    /// not set, the current y-coordinate is a signed 16-bit delta
300    /// vector.
301    pub const Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR: Self = Self { bits: 0x20 };
302
303    /// Bit 6: If set, contours in the glyph description may overlap.
304    /// Use of this flag is not required in OpenType — that is, it is
305    /// valid to have contours overlap without having this flag set. It
306    /// may affect behaviors in some platforms, however. (See the
307    /// discussion of “Overlapping contours” in Apple’s
308    /// specification for details regarding behavior in Apple
309    /// platforms.) When used, it must be set on the first flag byte
310    /// for the glyph. See additional details below.
311    pub const OVERLAP_SIMPLE: Self = Self { bits: 0x40 };
312
313    /// Bit 7: Off-curve point belongs to a cubic-Bezier segment
314    ///
315    /// * [Spec](https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1-cubicOutlines.md)
316    /// * [harfbuzz](https://github.com/harfbuzz/harfbuzz/blob/c1ca46e4ebb6457dfe00a5441d52a4a66134ac58/src/OT/glyf/SimpleGlyph.hh#L23)
317    pub const CUBIC: Self = Self { bits: 0x80 };
318}
319
320impl SimpleGlyphFlags {
321    ///  Returns an empty set of flags.
322    #[inline]
323    pub const fn empty() -> Self {
324        Self { bits: 0 }
325    }
326
327    /// Returns the set containing all flags.
328    #[inline]
329    pub const fn all() -> Self {
330        Self {
331            bits: Self::ON_CURVE_POINT.bits
332                | Self::X_SHORT_VECTOR.bits
333                | Self::Y_SHORT_VECTOR.bits
334                | Self::REPEAT_FLAG.bits
335                | Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR.bits
336                | Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR.bits
337                | Self::OVERLAP_SIMPLE.bits
338                | Self::CUBIC.bits,
339        }
340    }
341
342    /// Returns the raw value of the flags currently stored.
343    #[inline]
344    pub const fn bits(&self) -> u8 {
345        self.bits
346    }
347
348    /// Convert from underlying bit representation, unless that
349    /// representation contains bits that do not correspond to a flag.
350    #[inline]
351    pub const fn from_bits(bits: u8) -> Option<Self> {
352        if (bits & !Self::all().bits()) == 0 {
353            Some(Self { bits })
354        } else {
355            None
356        }
357    }
358
359    /// Convert from underlying bit representation, dropping any bits
360    /// that do not correspond to flags.
361    #[inline]
362    pub const fn from_bits_truncate(bits: u8) -> Self {
363        Self {
364            bits: bits & Self::all().bits,
365        }
366    }
367
368    /// Returns `true` if no flags are currently stored.
369    #[inline]
370    pub const fn is_empty(&self) -> bool {
371        self.bits() == Self::empty().bits()
372    }
373
374    /// Returns `true` if there are flags common to both `self` and `other`.
375    #[inline]
376    pub const fn intersects(&self, other: Self) -> bool {
377        !(Self {
378            bits: self.bits & other.bits,
379        })
380        .is_empty()
381    }
382
383    /// Returns `true` if all of the flags in `other` are contained within `self`.
384    #[inline]
385    pub const fn contains(&self, other: Self) -> bool {
386        (self.bits & other.bits) == other.bits
387    }
388
389    /// Inserts the specified flags in-place.
390    #[inline]
391    pub fn insert(&mut self, other: Self) {
392        self.bits |= other.bits;
393    }
394
395    /// Removes the specified flags in-place.
396    #[inline]
397    pub fn remove(&mut self, other: Self) {
398        self.bits &= !other.bits;
399    }
400
401    /// Toggles the specified flags in-place.
402    #[inline]
403    pub fn toggle(&mut self, other: Self) {
404        self.bits ^= other.bits;
405    }
406
407    /// Returns the intersection between the flags in `self` and
408    /// `other`.
409    ///
410    /// Specifically, the returned set contains only the flags which are
411    /// present in *both* `self` *and* `other`.
412    ///
413    /// This is equivalent to using the `&` operator (e.g.
414    /// [`ops::BitAnd`]), as in `flags & other`.
415    ///
416    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
417    #[inline]
418    #[must_use]
419    pub const fn intersection(self, other: Self) -> Self {
420        Self {
421            bits: self.bits & other.bits,
422        }
423    }
424
425    /// Returns the union of between the flags in `self` and `other`.
426    ///
427    /// Specifically, the returned set contains all flags which are
428    /// present in *either* `self` *or* `other`, including any which are
429    /// present in both.
430    ///
431    /// This is equivalent to using the `|` operator (e.g.
432    /// [`ops::BitOr`]), as in `flags | other`.
433    ///
434    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
435    #[inline]
436    #[must_use]
437    pub const fn union(self, other: Self) -> Self {
438        Self {
439            bits: self.bits | other.bits,
440        }
441    }
442
443    /// Returns the difference between the flags in `self` and `other`.
444    ///
445    /// Specifically, the returned set contains all flags present in
446    /// `self`, except for the ones present in `other`.
447    ///
448    /// It is also conceptually equivalent to the "bit-clear" operation:
449    /// `flags & !other` (and this syntax is also supported).
450    ///
451    /// This is equivalent to using the `-` operator (e.g.
452    /// [`ops::Sub`]), as in `flags - other`.
453    ///
454    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
455    #[inline]
456    #[must_use]
457    pub const fn difference(self, other: Self) -> Self {
458        Self {
459            bits: self.bits & !other.bits,
460        }
461    }
462}
463
464impl std::ops::BitOr for SimpleGlyphFlags {
465    type Output = Self;
466
467    /// Returns the union of the two sets of flags.
468    #[inline]
469    fn bitor(self, other: SimpleGlyphFlags) -> Self {
470        Self {
471            bits: self.bits | other.bits,
472        }
473    }
474}
475
476impl std::ops::BitOrAssign for SimpleGlyphFlags {
477    /// Adds the set of flags.
478    #[inline]
479    fn bitor_assign(&mut self, other: Self) {
480        self.bits |= other.bits;
481    }
482}
483
484impl std::ops::BitXor for SimpleGlyphFlags {
485    type Output = Self;
486
487    /// Returns the left flags, but with all the right flags toggled.
488    #[inline]
489    fn bitxor(self, other: Self) -> Self {
490        Self {
491            bits: self.bits ^ other.bits,
492        }
493    }
494}
495
496impl std::ops::BitXorAssign for SimpleGlyphFlags {
497    /// Toggles the set of flags.
498    #[inline]
499    fn bitxor_assign(&mut self, other: Self) {
500        self.bits ^= other.bits;
501    }
502}
503
504impl std::ops::BitAnd for SimpleGlyphFlags {
505    type Output = Self;
506
507    /// Returns the intersection between the two sets of flags.
508    #[inline]
509    fn bitand(self, other: Self) -> Self {
510        Self {
511            bits: self.bits & other.bits,
512        }
513    }
514}
515
516impl std::ops::BitAndAssign for SimpleGlyphFlags {
517    /// Disables all flags disabled in the set.
518    #[inline]
519    fn bitand_assign(&mut self, other: Self) {
520        self.bits &= other.bits;
521    }
522}
523
524impl std::ops::Sub for SimpleGlyphFlags {
525    type Output = Self;
526
527    /// Returns the set difference of the two sets of flags.
528    #[inline]
529    fn sub(self, other: Self) -> Self {
530        Self {
531            bits: self.bits & !other.bits,
532        }
533    }
534}
535
536impl std::ops::SubAssign for SimpleGlyphFlags {
537    /// Disables all flags enabled in the set.
538    #[inline]
539    fn sub_assign(&mut self, other: Self) {
540        self.bits &= !other.bits;
541    }
542}
543
544impl std::ops::Not for SimpleGlyphFlags {
545    type Output = Self;
546
547    /// Returns the complement of this set of flags.
548    #[inline]
549    fn not(self) -> Self {
550        Self { bits: !self.bits } & Self::all()
551    }
552}
553
554impl std::fmt::Debug for SimpleGlyphFlags {
555    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
556        let members: &[(&str, Self)] = &[
557            ("ON_CURVE_POINT", Self::ON_CURVE_POINT),
558            ("X_SHORT_VECTOR", Self::X_SHORT_VECTOR),
559            ("Y_SHORT_VECTOR", Self::Y_SHORT_VECTOR),
560            ("REPEAT_FLAG", Self::REPEAT_FLAG),
561            (
562                "X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR",
563                Self::X_IS_SAME_OR_POSITIVE_X_SHORT_VECTOR,
564            ),
565            (
566                "Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR",
567                Self::Y_IS_SAME_OR_POSITIVE_Y_SHORT_VECTOR,
568            ),
569            ("OVERLAP_SIMPLE", Self::OVERLAP_SIMPLE),
570            ("CUBIC", Self::CUBIC),
571        ];
572        let mut first = true;
573        for (name, value) in members {
574            if self.contains(*value) {
575                if !first {
576                    f.write_str(" | ")?;
577                }
578                first = false;
579                f.write_str(name)?;
580            }
581        }
582        if first {
583            f.write_str("(empty)")?;
584        }
585        Ok(())
586    }
587}
588
589impl std::fmt::Binary for SimpleGlyphFlags {
590    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
591        std::fmt::Binary::fmt(&self.bits, f)
592    }
593}
594
595impl std::fmt::Octal for SimpleGlyphFlags {
596    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
597        std::fmt::Octal::fmt(&self.bits, f)
598    }
599}
600
601impl std::fmt::LowerHex for SimpleGlyphFlags {
602    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
603        std::fmt::LowerHex::fmt(&self.bits, f)
604    }
605}
606
607impl std::fmt::UpperHex for SimpleGlyphFlags {
608    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
609        std::fmt::UpperHex::fmt(&self.bits, f)
610    }
611}
612
613impl font_types::Scalar for SimpleGlyphFlags {
614    type Raw = <u8 as font_types::Scalar>::Raw;
615    fn to_raw(self) -> Self::Raw {
616        self.bits().to_raw()
617    }
618    fn from_raw(raw: Self::Raw) -> Self {
619        let t = <u8>::from_raw(raw);
620        Self::from_bits_truncate(t)
621    }
622}
623
624#[cfg(feature = "experimental_traverse")]
625impl<'a> From<SimpleGlyphFlags> for FieldType<'a> {
626    fn from(src: SimpleGlyphFlags) -> FieldType<'a> {
627        src.bits().into()
628    }
629}
630
631impl<'a> MinByteRange<'a> for CompositeGlyph<'a> {
632    fn min_byte_range(&self) -> Range<usize> {
633        0..self.component_data_byte_range().end
634    }
635    fn min_table_bytes(&self) -> &'a [u8] {
636        let range = self.min_byte_range();
637        self.data.as_bytes().get(range).unwrap_or_default()
638    }
639}
640
641impl<'a> FontRead<'a> for CompositeGlyph<'a> {
642    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
643        #[allow(clippy::absurd_extreme_comparisons)]
644        if data.len() < Self::MIN_SIZE {
645            return Err(ReadError::OutOfBounds);
646        }
647        Ok(Self { data })
648    }
649}
650
651/// [CompositeGlyph](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#glyph-headers)
652#[derive(Clone)]
653pub struct CompositeGlyph<'a> {
654    data: FontData<'a>,
655}
656
657#[allow(clippy::needless_lifetimes)]
658impl<'a> CompositeGlyph<'a> {
659    pub const MIN_SIZE: usize = (i16::RAW_BYTE_LEN
660        + i16::RAW_BYTE_LEN
661        + i16::RAW_BYTE_LEN
662        + i16::RAW_BYTE_LEN
663        + i16::RAW_BYTE_LEN);
664    basic_table_impls!(impl_the_methods);
665
666    /// If the number of contours is greater than or equal to zero,
667    /// this is a simple glyph. If negative, this is a composite glyph
668    /// — the value -1 should be used for composite glyphs.
669    pub fn number_of_contours(&self) -> i16 {
670        let range = self.number_of_contours_byte_range();
671        self.data.read_at(range.start).ok().unwrap()
672    }
673
674    /// Minimum x for coordinate data.
675    pub fn x_min(&self) -> i16 {
676        let range = self.x_min_byte_range();
677        self.data.read_at(range.start).ok().unwrap()
678    }
679
680    /// Minimum y for coordinate data.
681    pub fn y_min(&self) -> i16 {
682        let range = self.y_min_byte_range();
683        self.data.read_at(range.start).ok().unwrap()
684    }
685
686    /// Maximum x for coordinate data.
687    pub fn x_max(&self) -> i16 {
688        let range = self.x_max_byte_range();
689        self.data.read_at(range.start).ok().unwrap()
690    }
691
692    /// Maximum y for coordinate data.
693    pub fn y_max(&self) -> i16 {
694        let range = self.y_max_byte_range();
695        self.data.read_at(range.start).ok().unwrap()
696    }
697
698    /// component flag
699    /// glyph index of component
700    pub fn component_data(&self) -> &'a [u8] {
701        let range = self.component_data_byte_range();
702        self.data.read_array(range).ok().unwrap_or_default()
703    }
704
705    pub fn number_of_contours_byte_range(&self) -> Range<usize> {
706        let start = 0;
707        start..start + i16::RAW_BYTE_LEN
708    }
709
710    pub fn x_min_byte_range(&self) -> Range<usize> {
711        let start = self.number_of_contours_byte_range().end;
712        start..start + i16::RAW_BYTE_LEN
713    }
714
715    pub fn y_min_byte_range(&self) -> Range<usize> {
716        let start = self.x_min_byte_range().end;
717        start..start + i16::RAW_BYTE_LEN
718    }
719
720    pub fn x_max_byte_range(&self) -> Range<usize> {
721        let start = self.y_min_byte_range().end;
722        start..start + i16::RAW_BYTE_LEN
723    }
724
725    pub fn y_max_byte_range(&self) -> Range<usize> {
726        let start = self.x_max_byte_range().end;
727        start..start + i16::RAW_BYTE_LEN
728    }
729
730    pub fn component_data_byte_range(&self) -> Range<usize> {
731        let start = self.y_max_byte_range().end;
732        start..start + self.data.len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN
733    }
734}
735
736#[cfg(feature = "experimental_traverse")]
737impl<'a> SomeTable<'a> for CompositeGlyph<'a> {
738    fn type_name(&self) -> &str {
739        "CompositeGlyph"
740    }
741    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
742        match idx {
743            0usize => Some(Field::new("number_of_contours", self.number_of_contours())),
744            1usize => Some(Field::new("x_min", self.x_min())),
745            2usize => Some(Field::new("y_min", self.y_min())),
746            3usize => Some(Field::new("x_max", self.x_max())),
747            4usize => Some(Field::new("y_max", self.y_max())),
748            5usize => Some(Field::new("component_data", self.component_data())),
749            _ => None,
750        }
751    }
752}
753
754#[cfg(feature = "experimental_traverse")]
755#[allow(clippy::needless_lifetimes)]
756impl<'a> std::fmt::Debug for CompositeGlyph<'a> {
757    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
758        (self as &dyn SomeTable<'a>).fmt(f)
759    }
760}
761
762/// Flags used in [CompositeGlyph]
763#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
764#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
765#[repr(transparent)]
766pub struct CompositeGlyphFlags {
767    bits: u16,
768}
769
770impl CompositeGlyphFlags {
771    /// Bit 0: If this is set, the arguments are 16-bit (uint16 or
772    /// int16); otherwise, they are bytes (uint8 or int8).
773    pub const ARG_1_AND_2_ARE_WORDS: Self = Self { bits: 0x0001 };
774
775    /// Bit 1: If this is set, the arguments are signed xy values,
776    /// otherwise, they are unsigned point numbers.
777    pub const ARGS_ARE_XY_VALUES: Self = Self { bits: 0x0002 };
778
779    /// Bit 2: If set and ARGS_ARE_XY_VALUES is also set, the xy values
780    /// are rounded to the nearest grid line. Ignored if
781    /// ARGS_ARE_XY_VALUES is not set.
782    pub const ROUND_XY_TO_GRID: Self = Self { bits: 0x0004 };
783
784    /// Bit 3: This indicates that there is a simple scale for the
785    /// component. Otherwise, scale = 1.0.
786    pub const WE_HAVE_A_SCALE: Self = Self { bits: 0x0008 };
787
788    /// Bit 5: Indicates at least one more glyph after this one.
789    pub const MORE_COMPONENTS: Self = Self { bits: 0x0020 };
790
791    /// Bit 6: The x direction will use a different scale from the y
792    /// direction.
793    pub const WE_HAVE_AN_X_AND_Y_SCALE: Self = Self { bits: 0x0040 };
794
795    /// Bit 7: There is a 2 by 2 transformation that will be used to
796    /// scale the component.
797    pub const WE_HAVE_A_TWO_BY_TWO: Self = Self { bits: 0x0080 };
798
799    /// Bit 8: Following the last component are instructions for the
800    /// composite character.
801    pub const WE_HAVE_INSTRUCTIONS: Self = Self { bits: 0x0100 };
802
803    /// Bit 9: If set, this forces the aw and lsb (and rsb) for the
804    /// composite to be equal to those from this component glyph. This
805    /// works for hinted and unhinted glyphs.
806    pub const USE_MY_METRICS: Self = Self { bits: 0x0200 };
807
808    /// Bit 10: If set, the components of the compound glyph overlap.
809    /// Use of this flag is not required in OpenType — that is, it is
810    /// valid to have components overlap without having this flag set.
811    /// It may affect behaviors in some platforms, however. (See
812    /// Apple’s specification for details regarding behavior in Apple
813    /// platforms.) When used, it must be set on the flag word for the
814    /// first component. See additional remarks, above, for the similar
815    /// OVERLAP_SIMPLE flag used in simple-glyph descriptions.
816    pub const OVERLAP_COMPOUND: Self = Self { bits: 0x0400 };
817
818    /// Bit 11: The composite is designed to have the component offset
819    /// scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
820    pub const SCALED_COMPONENT_OFFSET: Self = Self { bits: 0x0800 };
821
822    /// Bit 12: The composite is designed not to have the component
823    /// offset scaled. Ignored if ARGS_ARE_XY_VALUES is not set.
824    pub const UNSCALED_COMPONENT_OFFSET: Self = Self { bits: 0x1000 };
825}
826
827impl CompositeGlyphFlags {
828    ///  Returns an empty set of flags.
829    #[inline]
830    pub const fn empty() -> Self {
831        Self { bits: 0 }
832    }
833
834    /// Returns the set containing all flags.
835    #[inline]
836    pub const fn all() -> Self {
837        Self {
838            bits: Self::ARG_1_AND_2_ARE_WORDS.bits
839                | Self::ARGS_ARE_XY_VALUES.bits
840                | Self::ROUND_XY_TO_GRID.bits
841                | Self::WE_HAVE_A_SCALE.bits
842                | Self::MORE_COMPONENTS.bits
843                | Self::WE_HAVE_AN_X_AND_Y_SCALE.bits
844                | Self::WE_HAVE_A_TWO_BY_TWO.bits
845                | Self::WE_HAVE_INSTRUCTIONS.bits
846                | Self::USE_MY_METRICS.bits
847                | Self::OVERLAP_COMPOUND.bits
848                | Self::SCALED_COMPONENT_OFFSET.bits
849                | Self::UNSCALED_COMPONENT_OFFSET.bits,
850        }
851    }
852
853    /// Returns the raw value of the flags currently stored.
854    #[inline]
855    pub const fn bits(&self) -> u16 {
856        self.bits
857    }
858
859    /// Convert from underlying bit representation, unless that
860    /// representation contains bits that do not correspond to a flag.
861    #[inline]
862    pub const fn from_bits(bits: u16) -> Option<Self> {
863        if (bits & !Self::all().bits()) == 0 {
864            Some(Self { bits })
865        } else {
866            None
867        }
868    }
869
870    /// Convert from underlying bit representation, dropping any bits
871    /// that do not correspond to flags.
872    #[inline]
873    pub const fn from_bits_truncate(bits: u16) -> Self {
874        Self {
875            bits: bits & Self::all().bits,
876        }
877    }
878
879    /// Returns `true` if no flags are currently stored.
880    #[inline]
881    pub const fn is_empty(&self) -> bool {
882        self.bits() == Self::empty().bits()
883    }
884
885    /// Returns `true` if there are flags common to both `self` and `other`.
886    #[inline]
887    pub const fn intersects(&self, other: Self) -> bool {
888        !(Self {
889            bits: self.bits & other.bits,
890        })
891        .is_empty()
892    }
893
894    /// Returns `true` if all of the flags in `other` are contained within `self`.
895    #[inline]
896    pub const fn contains(&self, other: Self) -> bool {
897        (self.bits & other.bits) == other.bits
898    }
899
900    /// Inserts the specified flags in-place.
901    #[inline]
902    pub fn insert(&mut self, other: Self) {
903        self.bits |= other.bits;
904    }
905
906    /// Removes the specified flags in-place.
907    #[inline]
908    pub fn remove(&mut self, other: Self) {
909        self.bits &= !other.bits;
910    }
911
912    /// Toggles the specified flags in-place.
913    #[inline]
914    pub fn toggle(&mut self, other: Self) {
915        self.bits ^= other.bits;
916    }
917
918    /// Returns the intersection between the flags in `self` and
919    /// `other`.
920    ///
921    /// Specifically, the returned set contains only the flags which are
922    /// present in *both* `self` *and* `other`.
923    ///
924    /// This is equivalent to using the `&` operator (e.g.
925    /// [`ops::BitAnd`]), as in `flags & other`.
926    ///
927    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
928    #[inline]
929    #[must_use]
930    pub const fn intersection(self, other: Self) -> Self {
931        Self {
932            bits: self.bits & other.bits,
933        }
934    }
935
936    /// Returns the union of between the flags in `self` and `other`.
937    ///
938    /// Specifically, the returned set contains all flags which are
939    /// present in *either* `self` *or* `other`, including any which are
940    /// present in both.
941    ///
942    /// This is equivalent to using the `|` operator (e.g.
943    /// [`ops::BitOr`]), as in `flags | other`.
944    ///
945    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
946    #[inline]
947    #[must_use]
948    pub const fn union(self, other: Self) -> Self {
949        Self {
950            bits: self.bits | other.bits,
951        }
952    }
953
954    /// Returns the difference between the flags in `self` and `other`.
955    ///
956    /// Specifically, the returned set contains all flags present in
957    /// `self`, except for the ones present in `other`.
958    ///
959    /// It is also conceptually equivalent to the "bit-clear" operation:
960    /// `flags & !other` (and this syntax is also supported).
961    ///
962    /// This is equivalent to using the `-` operator (e.g.
963    /// [`ops::Sub`]), as in `flags - other`.
964    ///
965    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
966    #[inline]
967    #[must_use]
968    pub const fn difference(self, other: Self) -> Self {
969        Self {
970            bits: self.bits & !other.bits,
971        }
972    }
973}
974
975impl std::ops::BitOr for CompositeGlyphFlags {
976    type Output = Self;
977
978    /// Returns the union of the two sets of flags.
979    #[inline]
980    fn bitor(self, other: CompositeGlyphFlags) -> Self {
981        Self {
982            bits: self.bits | other.bits,
983        }
984    }
985}
986
987impl std::ops::BitOrAssign for CompositeGlyphFlags {
988    /// Adds the set of flags.
989    #[inline]
990    fn bitor_assign(&mut self, other: Self) {
991        self.bits |= other.bits;
992    }
993}
994
995impl std::ops::BitXor for CompositeGlyphFlags {
996    type Output = Self;
997
998    /// Returns the left flags, but with all the right flags toggled.
999    #[inline]
1000    fn bitxor(self, other: Self) -> Self {
1001        Self {
1002            bits: self.bits ^ other.bits,
1003        }
1004    }
1005}
1006
1007impl std::ops::BitXorAssign for CompositeGlyphFlags {
1008    /// Toggles the set of flags.
1009    #[inline]
1010    fn bitxor_assign(&mut self, other: Self) {
1011        self.bits ^= other.bits;
1012    }
1013}
1014
1015impl std::ops::BitAnd for CompositeGlyphFlags {
1016    type Output = Self;
1017
1018    /// Returns the intersection between the two sets of flags.
1019    #[inline]
1020    fn bitand(self, other: Self) -> Self {
1021        Self {
1022            bits: self.bits & other.bits,
1023        }
1024    }
1025}
1026
1027impl std::ops::BitAndAssign for CompositeGlyphFlags {
1028    /// Disables all flags disabled in the set.
1029    #[inline]
1030    fn bitand_assign(&mut self, other: Self) {
1031        self.bits &= other.bits;
1032    }
1033}
1034
1035impl std::ops::Sub for CompositeGlyphFlags {
1036    type Output = Self;
1037
1038    /// Returns the set difference of the two sets of flags.
1039    #[inline]
1040    fn sub(self, other: Self) -> Self {
1041        Self {
1042            bits: self.bits & !other.bits,
1043        }
1044    }
1045}
1046
1047impl std::ops::SubAssign for CompositeGlyphFlags {
1048    /// Disables all flags enabled in the set.
1049    #[inline]
1050    fn sub_assign(&mut self, other: Self) {
1051        self.bits &= !other.bits;
1052    }
1053}
1054
1055impl std::ops::Not for CompositeGlyphFlags {
1056    type Output = Self;
1057
1058    /// Returns the complement of this set of flags.
1059    #[inline]
1060    fn not(self) -> Self {
1061        Self { bits: !self.bits } & Self::all()
1062    }
1063}
1064
1065impl std::fmt::Debug for CompositeGlyphFlags {
1066    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1067        let members: &[(&str, Self)] = &[
1068            ("ARG_1_AND_2_ARE_WORDS", Self::ARG_1_AND_2_ARE_WORDS),
1069            ("ARGS_ARE_XY_VALUES", Self::ARGS_ARE_XY_VALUES),
1070            ("ROUND_XY_TO_GRID", Self::ROUND_XY_TO_GRID),
1071            ("WE_HAVE_A_SCALE", Self::WE_HAVE_A_SCALE),
1072            ("MORE_COMPONENTS", Self::MORE_COMPONENTS),
1073            ("WE_HAVE_AN_X_AND_Y_SCALE", Self::WE_HAVE_AN_X_AND_Y_SCALE),
1074            ("WE_HAVE_A_TWO_BY_TWO", Self::WE_HAVE_A_TWO_BY_TWO),
1075            ("WE_HAVE_INSTRUCTIONS", Self::WE_HAVE_INSTRUCTIONS),
1076            ("USE_MY_METRICS", Self::USE_MY_METRICS),
1077            ("OVERLAP_COMPOUND", Self::OVERLAP_COMPOUND),
1078            ("SCALED_COMPONENT_OFFSET", Self::SCALED_COMPONENT_OFFSET),
1079            ("UNSCALED_COMPONENT_OFFSET", Self::UNSCALED_COMPONENT_OFFSET),
1080        ];
1081        let mut first = true;
1082        for (name, value) in members {
1083            if self.contains(*value) {
1084                if !first {
1085                    f.write_str(" | ")?;
1086                }
1087                first = false;
1088                f.write_str(name)?;
1089            }
1090        }
1091        if first {
1092            f.write_str("(empty)")?;
1093        }
1094        Ok(())
1095    }
1096}
1097
1098impl std::fmt::Binary for CompositeGlyphFlags {
1099    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1100        std::fmt::Binary::fmt(&self.bits, f)
1101    }
1102}
1103
1104impl std::fmt::Octal for CompositeGlyphFlags {
1105    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1106        std::fmt::Octal::fmt(&self.bits, f)
1107    }
1108}
1109
1110impl std::fmt::LowerHex for CompositeGlyphFlags {
1111    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1112        std::fmt::LowerHex::fmt(&self.bits, f)
1113    }
1114}
1115
1116impl std::fmt::UpperHex for CompositeGlyphFlags {
1117    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1118        std::fmt::UpperHex::fmt(&self.bits, f)
1119    }
1120}
1121
1122impl font_types::Scalar for CompositeGlyphFlags {
1123    type Raw = <u16 as font_types::Scalar>::Raw;
1124    fn to_raw(self) -> Self::Raw {
1125        self.bits().to_raw()
1126    }
1127    fn from_raw(raw: Self::Raw) -> Self {
1128        let t = <u16>::from_raw(raw);
1129        Self::from_bits_truncate(t)
1130    }
1131}
1132
1133#[cfg(feature = "experimental_traverse")]
1134impl<'a> From<CompositeGlyphFlags> for FieldType<'a> {
1135    fn from(src: CompositeGlyphFlags) -> FieldType<'a> {
1136        src.bits().into()
1137    }
1138}
1139
1140/// Simple or composite glyph.
1141#[derive(Clone)]
1142pub enum Glyph<'a> {
1143    Simple(SimpleGlyph<'a>),
1144    Composite(CompositeGlyph<'a>),
1145}
1146
1147impl<'a> Glyph<'a> {
1148    ///Return the `FontData` used to resolve offsets for this table.
1149    pub fn offset_data(&self) -> FontData<'a> {
1150        match self {
1151            Self::Simple(item) => item.offset_data(),
1152            Self::Composite(item) => item.offset_data(),
1153        }
1154    }
1155
1156    /// If the number of contours is greater than or equal to zero,
1157    /// this is a simple glyph. If negative, this is a composite glyph
1158    /// — the value -1 should be used for composite glyphs.
1159    pub fn number_of_contours(&self) -> i16 {
1160        match self {
1161            Self::Simple(item) => item.number_of_contours(),
1162            Self::Composite(item) => item.number_of_contours(),
1163        }
1164    }
1165
1166    /// Minimum x for coordinate data.
1167    pub fn x_min(&self) -> i16 {
1168        match self {
1169            Self::Simple(item) => item.x_min(),
1170            Self::Composite(item) => item.x_min(),
1171        }
1172    }
1173
1174    /// Minimum y for coordinate data.
1175    pub fn y_min(&self) -> i16 {
1176        match self {
1177            Self::Simple(item) => item.y_min(),
1178            Self::Composite(item) => item.y_min(),
1179        }
1180    }
1181
1182    /// Maximum x for coordinate data.
1183    pub fn x_max(&self) -> i16 {
1184        match self {
1185            Self::Simple(item) => item.x_max(),
1186            Self::Composite(item) => item.x_max(),
1187        }
1188    }
1189
1190    /// Maximum y for coordinate data.
1191    pub fn y_max(&self) -> i16 {
1192        match self {
1193            Self::Simple(item) => item.y_max(),
1194            Self::Composite(item) => item.y_max(),
1195        }
1196    }
1197}
1198
1199impl<'a> FontRead<'a> for Glyph<'a> {
1200    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
1201        let format: i16 = data.read_at(0usize)?;
1202
1203        #[allow(clippy::redundant_guards)]
1204        match format {
1205            format if format >= 0 => Ok(Self::Simple(FontRead::read(data)?)),
1206            format if format < 0 => Ok(Self::Composite(FontRead::read(data)?)),
1207            other => Err(ReadError::InvalidFormat(other.into())),
1208        }
1209    }
1210}
1211
1212impl<'a> MinByteRange<'a> for Glyph<'a> {
1213    fn min_byte_range(&self) -> Range<usize> {
1214        match self {
1215            Self::Simple(item) => item.min_byte_range(),
1216            Self::Composite(item) => item.min_byte_range(),
1217        }
1218    }
1219    fn min_table_bytes(&self) -> &'a [u8] {
1220        match self {
1221            Self::Simple(item) => item.min_table_bytes(),
1222            Self::Composite(item) => item.min_table_bytes(),
1223        }
1224    }
1225}
1226
1227#[cfg(feature = "experimental_traverse")]
1228impl<'a> Glyph<'a> {
1229    fn dyn_inner<'b>(&'b self) -> &'b dyn SomeTable<'a> {
1230        match self {
1231            Self::Simple(table) => table,
1232            Self::Composite(table) => table,
1233        }
1234    }
1235}
1236
1237#[cfg(feature = "experimental_traverse")]
1238impl std::fmt::Debug for Glyph<'_> {
1239    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1240        self.dyn_inner().fmt(f)
1241    }
1242}
1243
1244#[cfg(feature = "experimental_traverse")]
1245impl<'a> SomeTable<'a> for Glyph<'a> {
1246    fn type_name(&self) -> &str {
1247        self.dyn_inner().type_name()
1248    }
1249    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
1250        self.dyn_inner().get_field(idx)
1251    }
1252}