Skip to main content

read_fonts/generated/
generated_hmtx.rs

1// THIS FILE IS AUTOGENERATED.
2// Any changes to this file will be overwritten.
3// For more information about how codegen works, see font-codegen/README.md
4
5#[allow(unused_imports)]
6use crate::codegen_prelude::*;
7
8impl<'a> MinByteRange<'a> for Hmtx<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.left_side_bearings_byte_range().end
11    }
12    fn min_table_bytes(&self) -> &'a [u8] {
13        let range = self.min_byte_range();
14        self.data.as_bytes().get(range).unwrap_or_default()
15    }
16}
17
18impl TopLevelTable for Hmtx<'_> {
19    /// `hmtx`
20    const TAG: Tag = Tag::new(b"hmtx");
21}
22
23impl ReadArgs for Hmtx<'_> {
24    type Args = u16;
25}
26
27impl<'a> FontReadWithArgs<'a> for Hmtx<'a> {
28    fn read_with_args(data: FontData<'a>, args: &u16) -> Result<Self, ReadError> {
29        let number_of_h_metrics = *args;
30
31        #[allow(clippy::absurd_extreme_comparisons)]
32        if data.len() < Self::MIN_SIZE {
33            return Err(ReadError::OutOfBounds);
34        }
35        Ok(Self {
36            data,
37            number_of_h_metrics,
38        })
39    }
40}
41
42impl<'a> Hmtx<'a> {
43    /// A constructor that requires additional arguments.
44    ///
45    /// This type requires some external state in order to be
46    /// parsed.
47    pub fn read(data: FontData<'a>, number_of_h_metrics: u16) -> Result<Self, ReadError> {
48        let args = number_of_h_metrics;
49        Self::read_with_args(data, &args)
50    }
51}
52
53/// The [hmtx (Horizontal Metrics)](https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx) table
54#[derive(Clone)]
55pub struct Hmtx<'a> {
56    data: FontData<'a>,
57    number_of_h_metrics: u16,
58}
59
60#[allow(clippy::needless_lifetimes)]
61impl<'a> Hmtx<'a> {
62    pub const MIN_SIZE: usize = 0;
63    basic_table_impls!(impl_the_methods);
64
65    /// Paired advance width/height and left/top side bearing values for each
66    /// glyph. Records are indexed by glyph ID.
67    pub fn h_metrics(&self) -> &'a [LongMetric] {
68        let range = self.h_metrics_byte_range();
69        self.data.read_array(range).ok().unwrap_or_default()
70    }
71
72    /// Leading (left/top) side bearings for glyph IDs greater than or equal to
73    /// numberOfLongMetrics.
74    pub fn left_side_bearings(&self) -> &'a [BigEndian<i16>] {
75        let range = self.left_side_bearings_byte_range();
76        self.data.read_array(range).ok().unwrap_or_default()
77    }
78
79    pub(crate) fn number_of_h_metrics(&self) -> u16 {
80        self.number_of_h_metrics
81    }
82
83    pub fn h_metrics_byte_range(&self) -> Range<usize> {
84        let number_of_h_metrics = self.number_of_h_metrics();
85        let start = 0;
86        let end = start
87            + (transforms::to_usize(number_of_h_metrics)).saturating_mul(LongMetric::RAW_BYTE_LEN);
88        start..end
89    }
90
91    pub fn left_side_bearings_byte_range(&self) -> Range<usize> {
92        let start = self.h_metrics_byte_range().end;
93        let end =
94            start + self.data.len().saturating_sub(start) / i16::RAW_BYTE_LEN * i16::RAW_BYTE_LEN;
95        start..end
96    }
97}
98
99#[allow(clippy::absurd_extreme_comparisons)]
100const _: () = assert!(FontData::default_data_long_enough(Hmtx::MIN_SIZE));
101
102impl Default for Hmtx<'_> {
103    fn default() -> Self {
104        Self {
105            data: FontData::default_table_data(),
106            number_of_h_metrics: Default::default(),
107        }
108    }
109}
110
111#[cfg(feature = "experimental_traverse")]
112impl<'a> SomeTable<'a> for Hmtx<'a> {
113    fn type_name(&self) -> &str {
114        "Hmtx"
115    }
116    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
117        match idx {
118            0usize => Some(Field::new(
119                "h_metrics",
120                traversal::FieldType::array_of_records(
121                    stringify!(LongMetric),
122                    self.h_metrics(),
123                    self.offset_data(),
124                ),
125            )),
126            1usize => Some(Field::new("left_side_bearings", self.left_side_bearings())),
127            _ => None,
128        }
129    }
130}
131
132#[cfg(feature = "experimental_traverse")]
133#[allow(clippy::needless_lifetimes)]
134impl<'a> std::fmt::Debug for Hmtx<'a> {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        (self as &dyn SomeTable<'a>).fmt(f)
137    }
138}
139
140#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
141#[repr(C)]
142#[repr(packed)]
143pub struct LongMetric {
144    /// Advance width/height, in font design units.
145    pub advance: BigEndian<u16>,
146    /// Glyph leading (left/top) side bearing, in font design units.
147    pub side_bearing: BigEndian<i16>,
148}
149
150impl LongMetric {
151    /// Advance width/height, in font design units.
152    pub fn advance(&self) -> u16 {
153        self.advance.get()
154    }
155
156    /// Glyph leading (left/top) side bearing, in font design units.
157    pub fn side_bearing(&self) -> i16 {
158        self.side_bearing.get()
159    }
160}
161
162impl FixedSize for LongMetric {
163    const RAW_BYTE_LEN: usize = u16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN;
164}
165
166#[cfg(feature = "experimental_traverse")]
167impl<'a> SomeRecord<'a> for LongMetric {
168    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
169        RecordResolver {
170            name: "LongMetric",
171            get_field: Box::new(move |idx, _data| match idx {
172                0usize => Some(Field::new("advance", self.advance())),
173                1usize => Some(Field::new("side_bearing", self.side_bearing())),
174                _ => None,
175            }),
176            data,
177        }
178    }
179}