1use crate::error::{ParseError, RawTag};
4use crate::reader::{be_i32_at, be_u16_at, be_u32_at};
5use alloc::vec::Vec;
6use font_types::{F2Dot14, Fixed, Tag};
7
8pub(crate) const FVAR: RawTag = *b"fvar";
9pub(crate) const AVAR: RawTag = *b"avar";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct VariationAxis {
14 pub tag: Tag,
16 pub min: Fixed,
18 pub default: Fixed,
20 pub max: Fixed,
22 pub flags: u16,
24 pub name_id: u16,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct VarInstance {
31 pub name_id: u16,
33 pub flags: u16,
35 pub coordinates: Vec<Fixed>,
37}
38
39#[derive(Debug, Clone, Copy)]
41pub struct FvarTable<'a> {
42 data: &'a [u8],
43 axis_count: u16,
44 axis_size: u16,
45 instance_count: u16,
46 instance_size: u16,
47 data_offset: u16,
48}
49
50impl<'a> FvarTable<'a> {
51 pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
57 if data.len() < 16 {
58 return Err(ParseError::TruncatedTable {
59 tag: FVAR,
60 expected: 16,
61 got: data.len(),
62 });
63 }
64 let axis_count = be_u16_at(data, 8, FVAR)?;
65 let axis_size = be_u16_at(data, 10, FVAR)?;
66 let instance_count = be_u16_at(data, 12, FVAR)?;
67 let instance_size = be_u16_at(data, 14, FVAR)?;
68 let data_offset = be_u16_at(data, 4, FVAR)?;
69 if axis_count == 0 || axis_size < 20 {
70 return Err(ParseError::InvalidGlyphFormat);
71 }
72 if instance_count > 0 {
73 let needed = usize::from(axis_count)
74 .checked_mul(4)
75 .and_then(|v| v.checked_add(4))
76 .ok_or(ParseError::InvalidGlyphFormat)?;
77 if usize::from(instance_size) < needed {
78 return Err(ParseError::InvalidGlyphFormat);
79 }
80 }
81 Ok(Self {
82 data,
83 axis_count,
84 axis_size,
85 instance_count,
86 instance_size,
87 data_offset,
88 })
89 }
90
91 #[must_use]
93 pub fn as_bytes(&self) -> &'a [u8] {
94 self.data
95 }
96
97 pub fn version(&self) -> Result<u32, ParseError> {
102 be_u32_at(self.data, 0, FVAR)
103 }
104
105 #[must_use]
107 pub const fn axis_count(&self) -> u16 {
108 self.axis_count
109 }
110
111 pub fn axes(&self) -> Result<Vec<VariationAxis>, ParseError> {
116 let mut out = Vec::with_capacity(usize::from(self.axis_count));
117 for i in 0..usize::from(self.axis_count) {
118 let at = usize::from(self.data_offset) + i * usize::from(self.axis_size);
119 let tag = be_u32_at(self.data, at, FVAR)?;
120 let min = Fixed::from_bits(be_i32_at(self.data, at + 4, FVAR)?);
121 let default = Fixed::from_bits(be_i32_at(self.data, at + 8, FVAR)?);
122 let max = Fixed::from_bits(be_i32_at(self.data, at + 12, FVAR)?);
123 let flags = be_u16_at(self.data, at + 16, FVAR)?;
124 let name_id = be_u16_at(self.data, at + 18, FVAR)?;
125 out.push(VariationAxis {
126 tag: Tag::new(&tag.to_be_bytes()),
127 min,
128 default,
129 max,
130 flags,
131 name_id,
132 });
133 }
134 Ok(out)
135 }
136
137 pub fn instances(&self) -> Result<Vec<VarInstance>, ParseError> {
142 let mut out = Vec::with_capacity(usize::from(self.instance_count));
143 let base = usize::from(self.data_offset)
144 + usize::from(self.axis_count) * usize::from(self.axis_size);
145 for i in 0..usize::from(self.instance_count) {
146 let at = base + i * usize::from(self.instance_size);
147 let name_id = be_u16_at(self.data, at, FVAR)?;
148 let flags = be_u16_at(self.data, at + 2, FVAR)?;
149 let mut coordinates = Vec::with_capacity(usize::from(self.axis_count));
150 for a in 0..usize::from(self.axis_count) {
151 let raw = be_i32_at(self.data, at + 4 + a * 4, FVAR)?;
152 coordinates.push(Fixed::from_bits(raw));
153 }
154 out.push(VarInstance {
155 name_id,
156 flags,
157 coordinates,
158 });
159 }
160 Ok(out)
161 }
162}
163
164#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct SegmentMap {
167 pub pairs: Vec<(F2Dot14, F2Dot14)>,
169}
170
171impl SegmentMap {
172 #[must_use]
176 pub fn map(&self, value: F2Dot14) -> F2Dot14 {
177 if self.pairs.is_empty() {
178 return value; }
180 let v = value.to_bits();
181 let mut prev = (0i16, 0i16);
182 let mut have_prev = false;
183 for &(from, to) in &self.pairs {
184 let (x, y) = (from.to_bits(), to.to_bits());
185 if v <= x {
186 if !have_prev {
187 return F2Dot14::from_bits(y);
189 }
190 if x == prev.0 {
191 return F2Dot14::from_bits(y);
192 }
193 let t = f32::from(v - prev.0) / f32::from(x - prev.0);
195 let y_out = f32::from(prev.1) + t * (f32::from(y) - f32::from(prev.1));
196 let shifted = if y_out < 0.0 {
199 y_out - 0.5
200 } else {
201 y_out + 0.5
202 };
203 return F2Dot14::from_bits(shifted as i16);
204 }
205 prev = (x, y);
206 have_prev = true;
207 }
208 F2Dot14::from_bits(prev.1)
210 }
211}
212
213#[derive(Debug, Clone, Copy)]
215pub struct AvarTable<'a> {
216 data: &'a [u8],
217 axis_count: u16,
218}
219
220impl<'a> AvarTable<'a> {
221 pub fn parse(data: &'a [u8]) -> Result<Self, ParseError> {
227 if data.len() < 8 {
228 return Err(ParseError::TruncatedTable {
229 tag: AVAR,
230 expected: 8,
231 got: data.len(),
232 });
233 }
234 let axis_count = be_u16_at(data, 6, AVAR)?;
237 Ok(Self { data, axis_count })
238 }
239
240 #[must_use]
242 pub fn as_bytes(&self) -> &'a [u8] {
243 self.data
244 }
245
246 #[must_use]
248 pub const fn axis_count(&self) -> u16 {
249 self.axis_count
250 }
251
252 pub fn segment_maps(&self) -> Result<Vec<SegmentMap>, ParseError> {
257 let mut out = Vec::with_capacity(usize::from(self.axis_count));
258 let mut at = 8usize;
259 for _ in 0..usize::from(self.axis_count) {
260 let count = usize::from(be_u16_at(self.data, at, AVAR)?);
261 at += 2;
262 let mut pairs = Vec::with_capacity(count);
263 for _ in 0..count {
264 let from = F2Dot14::from_bits(crate::reader::be_i16_at(self.data, at, AVAR)?);
265 let to = F2Dot14::from_bits(crate::reader::be_i16_at(self.data, at + 2, AVAR)?);
266 pairs.push((from, to));
267 at += 4;
268 }
269 out.push(SegmentMap { pairs });
270 }
271 Ok(out)
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
278
279 use super::{AvarTable, FvarTable, SegmentMap};
280 use crate::error::ParseError;
281 use alloc::vec;
282 use alloc::vec::Vec;
283 use font_types::{F2Dot14, Tag};
284
285 fn fvar() -> Vec<u8> {
288 let mut d = Vec::new();
289 d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); d.extend_from_slice(&16u16.to_be_bytes()); d.extend_from_slice(&2u16.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&20u16.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&12u16.to_be_bytes()); d.extend_from_slice(b"wght");
298 d.extend_from_slice(&400i32.to_be_bytes()); d.extend_from_slice(&400i32.to_be_bytes()); d.extend_from_slice(&900i32.to_be_bytes()); d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&256u16.to_be_bytes()); d.extend_from_slice(&257u16.to_be_bytes());
305 d.extend_from_slice(&0u16.to_be_bytes());
306 d.extend_from_slice(&600i32.to_be_bytes());
307 d.extend_from_slice(&291u16.to_be_bytes());
308 d
309 }
310
311 #[test]
312 fn fvar_axes_and_instances() {
313 let d = fvar();
314 let t = FvarTable::parse(&d).unwrap();
315 assert_eq!(t.version().unwrap(), 0x0001_0000);
316 assert_eq!(t.axis_count(), 1);
317 let axes = t.axes().unwrap();
318 assert_eq!(axes.len(), 1);
319 let a = &axes[0];
320 assert_eq!(a.tag, Tag::new(b"wght"));
321 assert_eq!(a.min.to_bits(), 400);
322 assert_eq!(a.default.to_bits(), 400);
323 assert_eq!(a.max.to_bits(), 900);
324 assert_eq!(a.name_id, 256);
325 let instances = t.instances().unwrap();
326 assert_eq!(instances.len(), 1);
327 assert_eq!(instances[0].name_id, 257);
328 assert_eq!(instances[0].coordinates[0].to_bits(), 600);
329 assert_eq!(t.as_bytes().len(), d.len());
330 }
331
332 #[test]
333 fn fvar_errors() {
334 assert!(matches!(
335 FvarTable::parse(&[0u8; 15]),
336 Err(ParseError::TruncatedTable { .. })
337 ));
338 let mut d = fvar();
340 d[8..10].copy_from_slice(&0u16.to_be_bytes());
341 assert_eq!(
342 FvarTable::parse(&d).unwrap_err(),
343 ParseError::InvalidGlyphFormat
344 );
345 let mut d = fvar();
347 d[10..12].copy_from_slice(&8u16.to_be_bytes());
348 assert_eq!(
349 FvarTable::parse(&d).unwrap_err(),
350 ParseError::InvalidGlyphFormat
351 );
352 let mut d = fvar();
354 d[14..16].copy_from_slice(&6u16.to_be_bytes());
355 assert_eq!(
356 FvarTable::parse(&d).unwrap_err(),
357 ParseError::InvalidGlyphFormat
358 );
359 let mut d = fvar();
361 d.truncate(30);
362 let t = FvarTable::parse(&d).unwrap();
363 assert!(t.axes().is_err());
364 }
365
366 #[test]
367 fn avar_maps_and_interpolation() {
368 let mut d = Vec::new();
369 d.extend_from_slice(&0x0001_0000u32.to_be_bytes()); d.extend_from_slice(&0u16.to_be_bytes()); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&4u16.to_be_bytes());
374 for (from, to) in [(-1.0f32, -1.0), (0.0, 0.0), (0.5, 0.6), (1.0, 1.0)] {
375 d.extend_from_slice(&F2Dot14::from_f32(from).to_bits().to_be_bytes());
376 d.extend_from_slice(&F2Dot14::from_f32(to).to_bits().to_be_bytes());
377 }
378 let t = AvarTable::parse(&d).unwrap();
379 assert_eq!(t.axis_count(), 1);
380 let maps: Vec<SegmentMap> = t.segment_maps().unwrap();
381 assert_eq!(maps.len(), 1);
382 let m = &maps[0];
383 assert_eq!(m.pairs.len(), 4);
384 let f2 = |v: f32| F2Dot14::from_f32(v);
385 assert_eq!(m.map(f2(-1.0)), f2(-1.0));
386 assert_eq!(m.map(f2(0.0)), f2(0.0));
387 assert_eq!(m.map(f2(1.0)), f2(1.0));
388 let mapped = m.map(f2(0.5));
389 assert!((mapped.to_f32() - 0.6).abs() < 0.001);
390 let empty = SegmentMap { pairs: vec![] };
392 assert_eq!(empty.map(f2(0.5)), f2(0.5));
393 assert_eq!(m.map(f2(-2.0)), f2(-1.0));
395 assert_eq!(m.map(f2(2.0)), f2(1.0));
396 }
397
398 #[test]
399 fn avar_errors() {
400 assert!(matches!(
401 AvarTable::parse(&[0u8; 7]),
402 Err(ParseError::TruncatedTable { .. })
403 ));
404 let mut d = Vec::new();
406 d.extend_from_slice(&0x0001_0000u32.to_be_bytes());
407 d.extend_from_slice(&0u16.to_be_bytes());
408 d.extend_from_slice(&1u16.to_be_bytes());
409 d.extend_from_slice(&2u16.to_be_bytes()); d.extend_from_slice(&[0xC0, 0x00, 0xC0, 0x00]);
411 let t = AvarTable::parse(&d).unwrap();
412 assert!(t.segment_maps().is_err());
413 }
414}