Coverage Report

Created: 2026-12-01 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/read-fonts-0.47.0/src/tables/mvar.rs
Line
Count
Source
1
//! The [MVAR (Metrics Variation)](https://docs.microsoft.com/en-us/typography/opentype/spec/mvar) table
2
3
use super::variations::{DeltaSetIndex, ItemVariationStore};
4
use types::F48Dot16;
5
6
/// Four-byte tags used to represent particular metric or other values.
7
pub mod tags {
8
    use font_types::Tag;
9
10
    /// Horizontal ascender.
11
    pub const HASC: Tag = Tag::new(b"hasc");
12
    /// Horizontal descender.
13
    pub const HDSC: Tag = Tag::new(b"hdsc");
14
    /// Horizontal line gap.
15
    pub const HLGP: Tag = Tag::new(b"hlgp");
16
17
    /// Horizontal clipping ascent.
18
    pub const HCLA: Tag = Tag::new(b"hcla");
19
    /// Horizontal clipping descent.
20
    pub const HCLD: Tag = Tag::new(b"hcld");
21
22
    /// Vertical ascender.
23
    pub const VASC: Tag = Tag::new(b"vasc");
24
    /// Vertical descender.
25
    pub const VDSC: Tag = Tag::new(b"vdsc");
26
    /// Vertical line gap.
27
    pub const VLGP: Tag = Tag::new(b"vlgp");
28
29
    /// Horizontal caret rise.
30
    pub const HCRS: Tag = Tag::new(b"hcrs");
31
    /// Horizontal caret run.
32
    pub const HCRN: Tag = Tag::new(b"hcrn");
33
    /// Horizontal caret offset.
34
    pub const HCOF: Tag = Tag::new(b"hcof");
35
36
    /// Vertical caret rise.
37
    pub const VCRS: Tag = Tag::new(b"vcrs");
38
    /// Vertical caret run.
39
    pub const VCRN: Tag = Tag::new(b"vcrn");
40
    /// Vertical caret offset.
41
    pub const VCOF: Tag = Tag::new(b"vcof");
42
43
    /// X-height.
44
    pub const XHGT: Tag = Tag::new(b"xhgt");
45
    /// Cap height.
46
    pub const CPHT: Tag = Tag::new(b"cpht");
47
48
    /// Subscript em x-offset.
49
    pub const SBXO: Tag = Tag::new(b"sbxo");
50
    /// Subscript em y-offset.
51
    pub const SBYO: Tag = Tag::new(b"sbyo");
52
    /// Subscript em x-size.
53
    pub const SBXS: Tag = Tag::new(b"sbxs");
54
    /// Subscript em y-size.
55
    pub const SBYS: Tag = Tag::new(b"sbys");
56
57
    /// Superscript em x-offset.
58
    pub const SPXO: Tag = Tag::new(b"spxo");
59
    /// Superscript em y-offset.
60
    pub const SPYO: Tag = Tag::new(b"spyo");
61
    /// Superscript em x-size.
62
    pub const SPXS: Tag = Tag::new(b"spxs");
63
    /// Superscript em y-size.
64
    pub const SPYS: Tag = Tag::new(b"spys");
65
66
    /// Strikeout size.
67
    pub const STRS: Tag = Tag::new(b"strs");
68
    /// Strikeout offset.
69
    pub const STRO: Tag = Tag::new(b"stro");
70
71
    /// Underline size.
72
    pub const UNDS: Tag = Tag::new(b"unds");
73
    /// Underline offset.
74
    pub const UNDO: Tag = Tag::new(b"undo");
75
76
    /// GaspRange\[0\]
77
    pub const GSP0: Tag = Tag::new(b"gsp0");
78
    /// GaspRange\[1\]
79
    pub const GSP1: Tag = Tag::new(b"gsp1");
80
    /// GaspRange\[2\]
81
    pub const GSP2: Tag = Tag::new(b"gsp2");
82
    /// GaspRange\[3\]
83
    pub const GSP3: Tag = Tag::new(b"gsp3");
84
    /// GaspRange\[4\]
85
    pub const GSP4: Tag = Tag::new(b"gsp4");
86
    /// GaspRange\[5\]
87
    pub const GSP5: Tag = Tag::new(b"gsp5");
88
    /// GaspRange\[6\]
89
    pub const GSP6: Tag = Tag::new(b"gsp6");
90
    /// GaspRange\[7\]
91
    pub const GSP7: Tag = Tag::new(b"gsp7");
92
    /// GaspRange\[8\]
93
    pub const GSP8: Tag = Tag::new(b"gsp8");
94
    /// GaspRange\[9\]
95
    pub const GSP9: Tag = Tag::new(b"gsp9");
96
}
97
98
include!("../../generated/generated_mvar.rs");
99
100
impl ReadArgs for ValueRecord {
101
    type Args = u16;
102
}
103
104
impl ComputeSize for ValueRecord {
105
1.83k
    fn compute_size(value_record_size: u16) -> Result<usize, ReadError> {
106
1.83k
        let size = value_record_size as usize;
107
1.83k
        if size < Self::RAW_BYTE_LEN {
108
126
            return Err(ReadError::MalformedData(
109
126
                "MVAR value record size is too small",
110
126
            ));
111
1.71k
        }
112
        // The table may reserve trailing bytes for future record fields.
113
1.71k
        Ok(size)
114
1.83k
    }
115
}
116
117
crate::impl_font_read_at!(ValueRecord);
118
119
impl FontRead<'_> for ValueRecord {
120
272
    fn read_with_args(data: FontData<'_>, value_record_size: u16) -> Result<Self, ReadError> {
121
272
        let size = Self::compute_size(value_record_size)?;
122
272
        let data = data.slice(..size).ok_or(ReadError::OutOfBounds)?;
123
272
        data.read_ref_at(0).copied()
124
272
    }
125
}
126
127
/// Binary searches the records, which are in binary order of their tag.
128
243
fn value_record_for_tag(records: &ComputedArray<'_, ValueRecord>, tag: Tag) -> Option<ValueRecord> {
129
    use core::cmp::Ordering;
130
243
    let mut lo = 0usize;
131
243
    let mut hi = records.len();
132
511
    while lo < hi {
133
272
        let mid = lo + (hi - lo) / 2;
134
272
        let record = records.get(mid).ok()?;
135
272
        match tag.cmp(&record.value_tag()) {
136
132
            Ordering::Less => hi = mid,
137
136
            Ordering::Greater => lo = mid + 1,
138
4
            Ordering::Equal => return Some(record),
139
        }
140
    }
141
239
    None
142
243
}
143
144
/// `MVAR` at one location, with the variation store resolved once.
145
///
146
/// Prefer this over [`Mvar::metric_delta`] when reading more than one metric;
147
/// that resolves the store on every lookup.
148
pub struct MvarInstance<'a> {
149
    records: ComputedArray<'a, ValueRecord>,
150
    ivs: ItemVariationStore<'a>,
151
    coords: &'a [F2Dot14],
152
}
153
154
impl<'a> Mvar<'a> {
155
    /// Returns the table at a location.
156
    ///
157
    /// `None` at the default location, where every delta is zero, and for a
158
    /// font whose variation store cannot be read.
159
646
    pub fn at(&self, coords: &'a [F2Dot14]) -> Option<MvarInstance<'a>> {
160
646
        if coords.is_empty() {
161
0
            return None;
162
646
        }
163
        Some(MvarInstance {
164
646
            records: self.value_records(),
165
646
            ivs: self.item_variation_store()?.ok()?,
166
42
            coords,
167
        })
168
646
    }
169
}
170
171
impl MvarInstance<'_> {
172
    /// Returns the delta for a metric, or `None` for one the font does not
173
    /// vary.
174
    ///
175
    /// Tags are in the [`tags`] module. The delta is in design units, added
176
    /// to the value the metric's own table holds, and left unrounded so a
177
    /// caller can round it its own way.
178
243
    pub fn get(&self, tag: Tag) -> Option<F48Dot16> {
179
243
        let record = value_record_for_tag(&self.records, tag)?;
180
4
        self.ivs.compute_delta(
181
4
            DeltaSetIndex {
182
4
                outer: record.delta_set_outer_index(),
183
4
                inner: record.delta_set_inner_index(),
184
4
            },
185
4
            self.coords,
186
        )
187
243
    }
188
}
189
190
impl Mvar<'_> {
191
    /// Returns the metric delta for the specified tag and normalized
192
    /// variation coordinates. Possible tags are found in the [tags]
193
    /// module.
194
    ///
195
    /// `None` for a metric the font does not vary, and for one it states
196
    /// unreadably.
197
0
    pub fn metric_delta(&self, tag: Tag, coords: &[F2Dot14]) -> Option<Fixed> {
198
0
        let record = value_record_for_tag(&self.value_records(), tag)?;
199
0
        let ivs = self.item_variation_store()?.ok()?;
200
0
        Some(Fixed::from_i32(
201
0
            ivs.compute_delta(
202
0
                DeltaSetIndex {
203
0
                    outer: record.delta_set_outer_index(),
204
0
                    inner: record.delta_set_inner_index(),
205
0
                },
206
0
                coords,
207
0
            )?
208
0
            .to_i32(),
209
        ))
210
0
    }
211
}
212
213
#[cfg(test)]
214
mod tests {
215
    use super::*;
216
    use crate::{FontData, FontRef, TableProvider};
217
    use font_test_data::bebuffer::BeBuffer;
218
    use types::F2Dot14;
219
220
    /// Twelve axes, and an `MVAR` varying several metrics.
221
    const VAR: &[u8] = font_test_data::AMSTELVAR_AVAR2_A;
222
223
    fn far() -> [F2Dot14; 12] {
224
        [F2Dot14::from_f32(1.0); 12]
225
    }
226
227
    #[test]
228
    fn the_default_location_has_no_instance() {
229
        // Every delta is zero there, so there is nothing to resolve.
230
        let font = FontRef::new(VAR).unwrap();
231
        assert!(font.mvar().unwrap().at(&[]).is_none());
232
    }
233
234
    #[test]
235
    fn an_instance_agrees_with_the_single_metric_accessor() {
236
        let font = FontRef::new(VAR).unwrap();
237
        let mvar = font.mvar().unwrap();
238
        let coords = far();
239
        let instance = mvar.at(&coords).expect("a location away from the default");
240
        let mut varied = 0;
241
        for record in mvar.value_records().iter() {
242
            let record = record.unwrap();
243
            let tag = record.value_tag();
244
            let exact = instance.get(tag).expect("a tag the table states");
245
            let rounded = mvar.metric_delta(tag, &coords).unwrap();
246
            assert_eq!(exact.to_i32(), rounded.to_i32(), "{tag}");
247
            varied += (exact != F48Dot16::ZERO) as u32;
248
        }
249
        assert!(varied > 0, "no metric moved at the far end of every axis");
250
    }
251
252
    #[test]
253
    fn a_tag_the_font_does_not_state_is_absent() {
254
        let font = FontRef::new(VAR).unwrap();
255
        let mvar = font.mvar().unwrap();
256
        let coords = far();
257
        let instance = mvar.at(&coords).unwrap();
258
        assert!(instance.get(Tag::new(b"zzzz")).is_none());
259
    }
260
261
    #[test]
262
    fn an_instance_keeps_a_fraction_the_single_accessor_drops() {
263
        // `metric_delta` reports whole design units; the instance reports
264
        // what the variation store computed.
265
        let font = FontRef::new(VAR).unwrap();
266
        let mvar = font.mvar().unwrap();
267
        let coords = [F2Dot14::from_f32(0.37); 12];
268
        let instance = mvar.at(&coords).unwrap();
269
        let fractional = mvar
270
            .value_records()
271
            .iter()
272
            .map(Result::unwrap)
273
            .filter_map(|record| instance.get(record.value_tag()))
274
            .any(|delta| delta.to_bits() & 0xFFFF != 0);
275
        assert!(fractional, "no metric delta carried a fraction");
276
    }
277
278
    // Builds an `MVAR` with three value records (`hasc`, `hdsc`, `hlgp`, in
279
    // binary tag order) whose stride is `value_record_size`. The spec lets
280
    // that exceed the eight bytes the record defines; the trailing bytes here
281
    // are a nonzero sentinel, so a read that strides by the fixed record size
282
    // instead of `valueRecordSize` lands on them and sees an invalid tag.
283
    //
284
    // The item variation store has one axis and one region peaking at 1.0,
285
    // with one delta per record: 100, -50 and 25. At the far end of the axis
286
    // each metric's delta is therefore its own stored value.
287
    fn mvar_with_stride(value_record_size: u16) -> BeBuffer {
288
        let stride = value_record_size as usize;
289
        assert!(stride >= ValueRecord::RAW_BYTE_LEN);
290
        let pad = stride - ValueRecord::RAW_BYTE_LEN;
291
        // The fixed header is 12 bytes; the store follows the record array.
292
        let store_offset = 12 + 3 * stride;
293
294
        let mut buf = BeBuffer::new()
295
            .push(MajorMinor::VERSION_1_0)
296
            .push(0u16) // reserved
297
            .push(value_record_size)
298
            .push(3u16) // value record count
299
            .push(store_offset as u16); // item variation store offset
300
301
        for (tag, inner) in [(b"hasc", 0u16), (b"hdsc", 1u16), (b"hlgp", 2u16)] {
302
            buf = buf
303
                .push(Tag::new(tag))
304
                .push(0u16) // delta-set outer index
305
                .push(inner) // delta-set inner index
306
                .extend(std::iter::repeat_n(0xFFu8, pad));
307
        }
308
309
        buf.push(1u16) // item variation store format
310
            .push(12u32) // region list offset
311
            .push(1u16) // variation data count
312
            .push(22u32) // variation data offset
313
            .push(1u16) // axis count
314
            .push(1u16) // region count
315
            .extend([F2Dot14::ZERO, F2Dot14::ONE, F2Dot14::ONE]) // start/peak/end
316
            .push(3u16) // item count
317
            .push(1u16) // word delta count
318
            .push(1u16) // region index count
319
            .push(0u16) // region index
320
            .extend([100i16, -50, 25])
321
    }
322
323
    #[test]
324
    fn value_records_honor_the_declared_stride() {
325
        for stride in [8, 9, 12, 32] {
326
            let bytes = mvar_with_stride(stride);
327
            let mvar = Mvar::read(FontData::new(bytes.as_slice())).unwrap();
328
            let records = mvar.value_records();
329
            assert_eq!(records.len(), 3);
330
            assert_eq!(
331
                mvar.value_records_byte_range(),
332
                12..12 + 3 * stride as usize
333
            );
334
335
            let iterated = records.iter().collect::<Result<Vec<_>, _>>().unwrap();
336
            for (i, tag) in [b"hasc", b"hdsc", b"hlgp"].iter().enumerate() {
337
                let record = records.get(i).unwrap();
338
                assert_eq!(record.value_tag(), Tag::new(tag));
339
                assert_eq!(record.delta_set_outer_index(), 0);
340
                assert_eq!(record.delta_set_inner_index(), i as u16);
341
                assert_eq!(iterated[i], record);
342
            }
343
            assert!(records.get(3).is_err());
344
        }
345
    }
346
347
    #[test]
348
    fn a_wide_value_record_size_still_finds_every_record() {
349
        // Striding by the fixed record size rather than `valueRecordSize`
350
        // would read every record after the first at the wrong offset and
351
        // drop its delta.
352
        let bytes = mvar_with_stride(12);
353
        let mvar = Mvar::read(FontData::new(bytes.as_slice())).unwrap();
354
        assert_eq!(mvar.value_record_size(), 12);
355
        let coords = [F2Dot14::from_f32(1.0)];
356
        let instance = mvar.at(&coords).expect("a location away from the default");
357
        for (tag, expected) in [
358
            (Tag::new(b"hasc"), 100),
359
            (Tag::new(b"hdsc"), -50),
360
            (Tag::new(b"hlgp"), 25),
361
        ] {
362
            assert_eq!(
363
                mvar.metric_delta(tag, &coords).unwrap().to_i32(),
364
                expected,
365
                "metric_delta {tag}"
366
            );
367
            assert_eq!(
368
                instance.get(tag).unwrap().to_i32(),
369
                expected,
370
                "instance {tag}"
371
            );
372
        }
373
    }
374
375
    #[test]
376
    fn the_common_eight_byte_stride_agrees() {
377
        // The same records at the spec's usual stride, through the same code.
378
        let bytes = mvar_with_stride(8);
379
        let mvar = Mvar::read(FontData::new(bytes.as_slice())).unwrap();
380
        assert_eq!(mvar.value_record_size(), 8);
381
        let coords = [F2Dot14::from_f32(1.0)];
382
        let instance = mvar.at(&coords).unwrap();
383
        for (tag, expected) in [
384
            (Tag::new(b"hasc"), 100),
385
            (Tag::new(b"hdsc"), -50),
386
            (Tag::new(b"hlgp"), 25),
387
        ] {
388
            assert_eq!(mvar.metric_delta(tag, &coords).unwrap().to_i32(), expected);
389
            assert_eq!(instance.get(tag).unwrap().to_i32(), expected);
390
        }
391
    }
392
393
    #[test]
394
    fn a_value_record_size_below_the_record_is_malformed() {
395
        // `valueRecordSize` must be at least the defined record size; a smaller
396
        // one is rejected without reading past the array or panicking.
397
        let mut bytes = mvar_with_stride(12).as_slice().to_vec();
398
        for size in 0..8u16 {
399
            bytes[6..8].copy_from_slice(&size.to_be_bytes());
400
            let mvar = Mvar::read(FontData::new(&bytes)).unwrap();
401
            assert_eq!(mvar.value_record_size(), size);
402
            let records = mvar.value_records();
403
            assert!(records.is_empty());
404
            assert!(records.get(0).is_err());
405
            assert_eq!(records.iter().count(), 0);
406
            let coords = [F2Dot14::ONE];
407
            assert!(mvar.metric_delta(Tag::new(b"hasc"), &coords).is_none());
408
            let instance = mvar.at(&coords).unwrap();
409
            assert!(instance.get(Tag::new(b"hasc")).is_none());
410
        }
411
    }
412
413
    #[test]
414
    fn truncated_value_records_are_not_read() {
415
        let bytes = mvar_with_stride(12);
416
        // All defined fields are present, but the last record's padding is cut off.
417
        let data = &bytes.as_slice()[..12 + 3 * 12 - 1];
418
        let mvar = Mvar::read(FontData::new(data)).unwrap();
419
        assert!(mvar.value_records().is_empty());
420
        assert!(mvar.metric_delta(tags::HASC, &[F2Dot14::ONE]).is_none());
421
    }
422
}