Skip to main content

read_fonts/generated/
generated_avar.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 Avar<'a> {
9    fn min_byte_range(&self) -> Range<usize> {
10        0..self.axis_segment_maps_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 Avar<'_> {
19    /// `avar`
20    const TAG: Tag = Tag::new(b"avar");
21}
22
23impl<'a> FontRead<'a> for Avar<'a> {
24    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
25        #[allow(clippy::absurd_extreme_comparisons)]
26        if data.len() < Self::MIN_SIZE {
27            return Err(ReadError::OutOfBounds);
28        }
29        Ok(Self { data })
30    }
31}
32
33/// The [avar (Axis Variations)](https://docs.microsoft.com/en-us/typography/opentype/spec/avar) table
34#[derive(Clone)]
35pub struct Avar<'a> {
36    data: FontData<'a>,
37}
38
39#[allow(clippy::needless_lifetimes)]
40impl<'a> Avar<'a> {
41    pub const MIN_SIZE: usize = (MajorMinor::RAW_BYTE_LEN + u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
42    basic_table_impls!(impl_the_methods);
43
44    /// Major version number of the axis variations table — set to 1 or 2.
45    /// Minor version number of the axis variations table — set to 0.
46    pub fn version(&self) -> MajorMinor {
47        let range = self.version_byte_range();
48        self.data.read_at(range.start).ok().unwrap()
49    }
50
51    /// The number of variation axes for this font. This must be the same number as axisCount in the 'fvar' table.
52    pub fn axis_count(&self) -> u16 {
53        let range = self.axis_count_byte_range();
54        self.data.read_at(range.start).ok().unwrap()
55    }
56
57    /// The segment maps array — one segment map for each axis, in the order of axes specified in the 'fvar' table.
58    pub fn axis_segment_maps(&self) -> VarLenArray<'a, SegmentMaps<'a>> {
59        let range = self.axis_segment_maps_byte_range();
60        self.data
61            .split_off(range.start)
62            .and_then(|d| VarLenArray::read(d).ok())
63            .unwrap_or_default()
64    }
65
66    /// Offset to DeltaSetIndexMap table (may be NULL).
67    pub fn axis_index_map_offset(&self) -> Option<Nullable<Offset32>> {
68        let range = self.axis_index_map_offset_byte_range();
69        (!range.is_empty())
70            .then(|| self.data.read_at(range.start).ok())
71            .flatten()
72    }
73
74    /// Attempt to resolve [`axis_index_map_offset`][Self::axis_index_map_offset].
75    pub fn axis_index_map(&self) -> Option<Result<DeltaSetIndexMap<'a>, ReadError>> {
76        let data = self.data;
77        self.axis_index_map_offset().map(|x| x.resolve(data))?
78    }
79
80    /// Offset to ItemVariationStore (may be NULL).
81    pub fn var_store_offset(&self) -> Option<Nullable<Offset32>> {
82        let range = self.var_store_offset_byte_range();
83        (!range.is_empty())
84            .then(|| self.data.read_at(range.start).ok())
85            .flatten()
86    }
87
88    /// Attempt to resolve [`var_store_offset`][Self::var_store_offset].
89    pub fn var_store(&self) -> Option<Result<ItemVariationStore<'a>, ReadError>> {
90        let data = self.data;
91        self.var_store_offset().map(|x| x.resolve(data))?
92    }
93
94    pub fn version_byte_range(&self) -> Range<usize> {
95        let start = 0;
96        start..start + MajorMinor::RAW_BYTE_LEN
97    }
98
99    pub fn _reserved_byte_range(&self) -> Range<usize> {
100        let start = self.version_byte_range().end;
101        start..start + u16::RAW_BYTE_LEN
102    }
103
104    pub fn axis_count_byte_range(&self) -> Range<usize> {
105        let start = self._reserved_byte_range().end;
106        start..start + u16::RAW_BYTE_LEN
107    }
108
109    pub fn axis_segment_maps_byte_range(&self) -> Range<usize> {
110        let axis_count = self.axis_count();
111        let start = self.axis_count_byte_range().end;
112        start..start + {
113            let data = self.data.split_off(start).unwrap_or_default();
114            <SegmentMaps as VarSize>::total_len_for_count(data, transforms::to_usize(axis_count))
115                .unwrap_or(0)
116        }
117    }
118
119    pub fn axis_index_map_offset_byte_range(&self) -> Range<usize> {
120        let start = self.axis_segment_maps_byte_range().end;
121        start
122            ..(self.version().compatible((2u16, 0u16)))
123                .then(|| start + Offset32::RAW_BYTE_LEN)
124                .unwrap_or(start)
125    }
126
127    pub fn var_store_offset_byte_range(&self) -> Range<usize> {
128        let start = self.axis_index_map_offset_byte_range().end;
129        start
130            ..(self.version().compatible((2u16, 0u16)))
131                .then(|| start + Offset32::RAW_BYTE_LEN)
132                .unwrap_or(start)
133    }
134}
135
136const _: () = assert!(FontData::default_data_long_enough(Avar::MIN_SIZE));
137
138impl Default for Avar<'_> {
139    fn default() -> Self {
140        Self {
141            data: FontData::default_table_data(),
142        }
143    }
144}
145
146#[cfg(feature = "experimental_traverse")]
147impl<'a> SomeTable<'a> for Avar<'a> {
148    fn type_name(&self) -> &str {
149        "Avar"
150    }
151    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
152        match idx {
153            0usize => Some(Field::new("version", self.version())),
154            1usize => Some(Field::new("axis_count", self.axis_count())),
155            2usize => Some(Field::new(
156                "axis_segment_maps",
157                traversal::FieldType::var_array(
158                    "SegmentMaps",
159                    self.axis_segment_maps(),
160                    self.offset_data(),
161                ),
162            )),
163            3usize if self.version().compatible((2u16, 0u16)) => Some(Field::new(
164                "axis_index_map_offset",
165                FieldType::offset(self.axis_index_map_offset().unwrap(), self.axis_index_map()),
166            )),
167            4usize if self.version().compatible((2u16, 0u16)) => Some(Field::new(
168                "var_store_offset",
169                FieldType::offset(self.var_store_offset().unwrap(), self.var_store()),
170            )),
171            _ => None,
172        }
173    }
174}
175
176#[cfg(feature = "experimental_traverse")]
177#[allow(clippy::needless_lifetimes)]
178impl<'a> std::fmt::Debug for Avar<'a> {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        (self as &dyn SomeTable<'a>).fmt(f)
181    }
182}
183
184/// [SegmentMaps](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
185#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
186pub struct SegmentMaps<'a> {
187    /// The number of correspondence pairs for this axis.
188    pub position_map_count: BigEndian<u16>,
189    /// The array of axis value map records for this axis.
190    pub axis_value_maps: &'a [AxisValueMap],
191}
192
193impl<'a> SegmentMaps<'a> {
194    /// The number of correspondence pairs for this axis.
195    pub fn position_map_count(&self) -> u16 {
196        self.position_map_count.get()
197    }
198
199    /// The array of axis value map records for this axis.
200    pub fn axis_value_maps(&self) -> &'a [AxisValueMap] {
201        self.axis_value_maps
202    }
203}
204
205#[cfg(feature = "experimental_traverse")]
206impl<'a> SomeRecord<'a> for SegmentMaps<'a> {
207    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
208        RecordResolver {
209            name: "SegmentMaps",
210            get_field: Box::new(move |idx, _data| match idx {
211                0usize => Some(Field::new("position_map_count", self.position_map_count())),
212                1usize => Some(Field::new(
213                    "axis_value_maps",
214                    traversal::FieldType::array_of_records(
215                        stringify!(AxisValueMap),
216                        self.axis_value_maps(),
217                        _data,
218                    ),
219                )),
220                _ => None,
221            }),
222            data,
223        }
224    }
225}
226
227/// [AxisValueMap](https://learn.microsoft.com/en-us/typography/opentype/spec/avar#table-formats) record
228#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
229#[repr(C)]
230#[repr(packed)]
231pub struct AxisValueMap {
232    /// A normalized coordinate value obtained using default normalization.
233    pub from_coordinate: BigEndian<F2Dot14>,
234    /// The modified, normalized coordinate value.
235    pub to_coordinate: BigEndian<F2Dot14>,
236}
237
238impl AxisValueMap {
239    /// A normalized coordinate value obtained using default normalization.
240    pub fn from_coordinate(&self) -> F2Dot14 {
241        self.from_coordinate.get()
242    }
243
244    /// The modified, normalized coordinate value.
245    pub fn to_coordinate(&self) -> F2Dot14 {
246        self.to_coordinate.get()
247    }
248}
249
250impl FixedSize for AxisValueMap {
251    const RAW_BYTE_LEN: usize = F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
252}
253
254#[cfg(feature = "experimental_traverse")]
255impl<'a> SomeRecord<'a> for AxisValueMap {
256    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
257        RecordResolver {
258            name: "AxisValueMap",
259            get_field: Box::new(move |idx, _data| match idx {
260                0usize => Some(Field::new("from_coordinate", self.from_coordinate())),
261                1usize => Some(Field::new("to_coordinate", self.to_coordinate())),
262                _ => None,
263            }),
264            data,
265        }
266    }
267}