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