Skip to main content

read_fonts/ps/
num.rs

1//! Various types of number parsers.
2
3use crate::model::Error;
4use crate::Cursor;
5use types::Fixed;
6
7#[inline]
8pub(crate) fn parse_int(cursor: &mut Cursor, b0: u8) -> Result<i32, Error> {
9    // Size   b0 range     Value range              Value calculation
10    //--------------------------------------------------------------------------------
11    // 1      32 to 246    -107 to +107             b0 - 139
12    // 2      247 to 250   +108 to +1131            (b0 - 247) * 256 + b1 + 108
13    // 2      251 to 254   -1131 to -108            -(b0 - 251) * 256 - b1 - 108
14    // 3      28           -32768 to +32767         b1 << 8 | b2
15    // 5      29           -(2^31) to +(2^31 - 1)   b1 << 24 | b2 << 16 | b3 << 8 | b4
16    // <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#table-3-operand-encoding>
17    Ok(match b0 {
18        32..=246 => b0 as i32 - 139,
19        247..=250 => (b0 as i32 - 247) * 256 + cursor.read::<u8>()? as i32 + 108,
20        251..=254 => -(b0 as i32 - 251) * 256 - cursor.read::<u8>()? as i32 - 108,
21        28 => cursor.read::<i16>()? as i32,
22        29 => cursor.read::<i32>()?,
23        _ => {
24            return Err(Error::Malformed);
25        }
26    })
27}
28
29// Various unnamed constants inlined in FreeType's cff_parse_real function
30// <<https://gitlab.freedesktop.org/freetype/freetype/-/blob/82090e67c24259c343c83fd9cefe6ff0be7a7eca/src/cff/cffparse.c#L183>>
31
32// Value returned on overflow
33const BCD_OVERFLOW: Fixed = Fixed::from_bits(0x7FFFFFFF);
34// Value returned on underflow
35const BCD_UNDERFLOW: Fixed = Fixed::ZERO;
36// Limit at which we stop accumulating `number` and increase
37// the exponent instead
38const BCD_NUMBER_LIMIT: i32 = 0xCCCCCCC;
39// Limit for the integral part of the result
40const BCD_INTEGER_LIMIT: i32 = 0x7FFF;
41
42// <https://gitlab.freedesktop.org/freetype/freetype/-/blob/82090e67c24259c343c83fd9cefe6ff0be7a7eca/src/cff/cffparse.c#L150>
43pub(crate) const BCD_POWER_TENS: [i32; 10] = [
44    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
45];
46
47/// Components for computing a fixed point value for a binary coded decimal
48/// number.
49#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
50pub struct BcdComponents {
51    /// If overflow or underflow is detected early, then this
52    /// contains the resulting value and we skip further
53    /// processing.
54    error: Option<Fixed>,
55    number: i32,
56    sign: i32,
57    exponent: i32,
58    exponent_add: i32,
59    integer_len: i32,
60    fraction_len: i32,
61}
62
63impl BcdComponents {
64    /// Parse a binary coded decimal number.
65    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/82090e67c24259c343c83fd9cefe6ff0be7a7eca/src/cff/cffparse.c#L183>
66    pub(crate) fn parse(cursor: &mut Cursor) -> Result<Self, Error> {
67        enum Phase {
68            Integer,
69            Fraction,
70            Exponent,
71        }
72        let mut phase = Phase::Integer;
73        let mut sign = 1i32;
74        let mut exponent_sign = 1i32;
75        let mut number = 0i32;
76        let mut exponent = 0i32;
77        let mut exponent_add = 0i32;
78        let mut integer_len = 0;
79        let mut fraction_len = 0;
80        let mut have_overflow = false;
81        // Nibble value    Represents
82        //----------------------------------
83        // 0 to 9          0 to 9
84        // a               . (decimal point)
85        // b               E
86        // c               E-
87        // d               <reserved>
88        // e               - (minus)
89        // f               end of number
90        // <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#table-5-nibble-definitions>
91        'outer: loop {
92            let b = cursor.read::<u8>()?;
93            for nibble in [(b >> 4) & 0xF, b & 0xF] {
94                match phase {
95                    Phase::Integer => match nibble {
96                        0x0..=0x9 => {
97                            if number >= BCD_NUMBER_LIMIT {
98                                exponent_add += 1;
99                            } else if nibble != 0 || number != 0 {
100                                number = number * 10 + nibble as i32;
101                                integer_len += 1;
102                            }
103                        }
104                        0xE => sign = -1,
105                        0xA => {
106                            phase = Phase::Fraction;
107                        }
108                        0xB => {
109                            phase = Phase::Exponent;
110                        }
111                        0xC => {
112                            phase = Phase::Exponent;
113                            exponent_sign = -1;
114                        }
115                        _ => break 'outer,
116                    },
117                    Phase::Fraction => match nibble {
118                        0x0..=0x9 => {
119                            if nibble == 0 && number == 0 {
120                                exponent_add -= 1;
121                            } else if number < BCD_NUMBER_LIMIT && fraction_len < 9 {
122                                number = number * 10 + nibble as i32;
123                                fraction_len += 1;
124                            }
125                        }
126                        0xB => {
127                            phase = Phase::Exponent;
128                        }
129                        0xC => {
130                            phase = Phase::Exponent;
131                            exponent_sign = -1;
132                        }
133                        _ => break 'outer,
134                    },
135                    Phase::Exponent => {
136                        match nibble {
137                            0x0..=0x9 => {
138                                // Arbitrarily limit exponent. Keep consuming
139                                // nibbles so the cursor ends up after the
140                                // number
141                                if exponent > 1000 {
142                                    have_overflow = true;
143                                } else {
144                                    exponent = exponent * 10 + nibble as i32;
145                                }
146                            }
147                            _ => break 'outer,
148                        }
149                    }
150                }
151            }
152        }
153        if have_overflow && number != 0 {
154            let error = if exponent_sign == -1 {
155                BCD_UNDERFLOW
156            } else {
157                Fixed::from_bits(BCD_OVERFLOW.to_bits() * sign)
158            };
159            return Ok(error.into());
160        }
161        exponent *= exponent_sign;
162        Ok(Self {
163            error: None,
164            number,
165            sign,
166            exponent,
167            exponent_add,
168            integer_len,
169            fraction_len,
170        })
171    }
172
173    /// Returns the fixed point value for the precomputed components,
174    /// optionally using an internal scale factor of 1000 to
175    /// increase fractional precision.
176    pub fn value(&self, scale_by_1000: bool) -> Fixed {
177        if let Some(error) = self.error {
178            return error;
179        }
180        let mut number = self.number;
181        if number == 0 {
182            return Fixed::ZERO;
183        }
184        let mut exponent = self.exponent;
185        let mut integer_len = self.integer_len;
186        let mut fraction_len = self.fraction_len;
187        if scale_by_1000 {
188            exponent += 3 + self.exponent_add;
189        } else {
190            exponent += self.exponent_add;
191        }
192        integer_len += exponent;
193        fraction_len -= exponent;
194        if integer_len > 5 {
195            return BCD_OVERFLOW;
196        }
197        if integer_len < -5 {
198            return BCD_UNDERFLOW;
199        }
200        // Remove non-significant digits
201        if integer_len < 0 {
202            number /= BCD_POWER_TENS[(-integer_len) as usize];
203            fraction_len += integer_len;
204        }
205        // Can only happen if exponent was non-zero
206        if fraction_len == 10 {
207            number /= 10;
208            fraction_len -= 1;
209        }
210        // Convert to fixed
211        let mut result = if fraction_len > 0 {
212            let b = BCD_POWER_TENS[fraction_len as usize];
213            if number / b > BCD_INTEGER_LIMIT {
214                0
215            } else {
216                (Fixed::from_bits(number) / Fixed::from_bits(b)).to_bits()
217            }
218        } else {
219            number = number.wrapping_mul(BCD_POWER_TENS[-fraction_len as usize]);
220            if number > BCD_INTEGER_LIMIT {
221                return BCD_OVERFLOW;
222            } else {
223                number << 16
224            }
225        };
226        if scale_by_1000 {
227            // FreeType stores the scaled value and does a fixed division by
228            // 1000 when the blue metrics are requested. We just do it here
229            // See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/f1cd6dbfa0c98f352b698448f40ac27e8fb3832e/src/psaux/psft.c#L554>
230            result = (Fixed::from_bits(result) / Fixed::from_i32(1000)).to_bits();
231        }
232        Fixed::from_bits(result * self.sign)
233    }
234
235    /// Returns the fixed point value for the components along with a
236    /// dynamically determined scale factor.
237    ///
238    /// Use for processing FontMatrix components.
239    ///
240    /// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/f1cd6dbfa0c98f352b698448f40ac27e8fb3832e/src/cff/cffparse.c#L332>
241    pub(crate) fn dynamically_scaled_value(&self) -> (Fixed, i32) {
242        if let Some(error) = self.error {
243            return (error, 0);
244        }
245        let mut number = self.number;
246        if number == 0 {
247            return (Fixed::ZERO, 0);
248        }
249        let mut exponent = self.exponent;
250        let integer_len = self.integer_len;
251        let mut fraction_len = self.fraction_len;
252        exponent += self.exponent_add;
253        fraction_len += integer_len;
254        exponent += integer_len;
255        let result;
256        let scaling;
257        if fraction_len <= 5 {
258            if number > BCD_INTEGER_LIMIT {
259                result = Fixed::from_bits(number) / Fixed::from_bits(10);
260                scaling = exponent - fraction_len + 1;
261            } else {
262                if exponent > 0 {
263                    // Make scaling as small as possible
264                    let new_fraction_len = exponent.min(5);
265                    let shift = new_fraction_len - fraction_len;
266                    if shift > 0 {
267                        exponent -= new_fraction_len;
268                        number *= BCD_POWER_TENS[shift as usize];
269                        if number > BCD_INTEGER_LIMIT {
270                            number /= 10;
271                            exponent += 1;
272                        }
273                    } else {
274                        exponent -= fraction_len;
275                    }
276                } else {
277                    exponent -= fraction_len;
278                }
279                result = Fixed::from_bits(number << 16);
280                scaling = exponent;
281            }
282        } else if (number / BCD_POWER_TENS[fraction_len as usize - 5]) > BCD_INTEGER_LIMIT {
283            result = Fixed::from_bits(number)
284                / Fixed::from_bits(BCD_POWER_TENS[fraction_len as usize - 4]);
285            scaling = exponent - 4;
286        } else {
287            result = Fixed::from_bits(number)
288                / Fixed::from_bits(BCD_POWER_TENS[fraction_len as usize - 5]);
289            scaling = exponent - 5;
290        }
291        (Fixed::from_bits(result.to_bits() * self.sign), scaling)
292    }
293}
294
295impl From<Fixed> for BcdComponents {
296    fn from(value: Fixed) -> Self {
297        Self {
298            error: Some(value),
299            ..Default::default()
300        }
301    }
302}
303
304/// Parse a fixed point value with a dynamic scaling factor.
305///
306/// See <https://gitlab.freedesktop.org/freetype/freetype/-/blob/f1cd6dbfa0c98f352b698448f40ac27e8fb3832e/src/cff/cffparse.c#L580>
307pub(crate) fn parse_fixed_dynamic(cursor: &mut Cursor) -> Result<(Fixed, i32), Error> {
308    let b0 = cursor.read::<u8>()?;
309    match b0 {
310        30 => Ok(BcdComponents::parse(cursor)?.dynamically_scaled_value()),
311        28 | 29 | 32..=254 => {
312            let num = parse_int(cursor, b0)?;
313            let mut int_len = 10;
314            if num > BCD_INTEGER_LIMIT {
315                for (i, power_ten) in BCD_POWER_TENS.iter().enumerate().skip(5) {
316                    if num < *power_ten {
317                        int_len = i;
318                        break;
319                    }
320                }
321                let scaling = if (num - BCD_POWER_TENS[int_len - 5]) > BCD_INTEGER_LIMIT {
322                    int_len - 4
323                } else {
324                    int_len - 5
325                };
326                Ok((
327                    Fixed::from_bits(num) / Fixed::from_bits(BCD_POWER_TENS[scaling]),
328                    scaling as i32,
329                ))
330            } else {
331                Ok((Fixed::from_bits(num << 16), 0))
332            }
333        }
334        _ => Err(Error::Malformed),
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341    use crate::FontData;
342
343    #[test]
344    fn int_operands() {
345        // Test the boundary conditions of the ranged int operators
346        let empty = FontData::new(&[]);
347        let min_byte = FontData::new(&[0]);
348        let max_byte = FontData::new(&[255]);
349        // 32..=246 => -107..=107
350        assert_eq!(parse_int(&mut empty.cursor(), 32).unwrap(), -107);
351        assert_eq!(parse_int(&mut empty.cursor(), 246).unwrap(), 107);
352        // 247..=250 => +108 to +1131
353        assert_eq!(parse_int(&mut min_byte.cursor(), 247).unwrap(), 108);
354        assert_eq!(parse_int(&mut max_byte.cursor(), 250).unwrap(), 1131);
355        // 251..=254 => -1131 to -108
356        assert_eq!(parse_int(&mut min_byte.cursor(), 251).unwrap(), -108);
357        assert_eq!(parse_int(&mut max_byte.cursor(), 254).unwrap(), -1131);
358    }
359
360    #[test]
361    fn binary_coded_decimal_operands() {
362        // From <https://learn.microsoft.com/en-us/typography/opentype/spec/cff2#table-5-nibble-definitions>:
363        //
364        // "A real number is terminated by one (or two) 0xf nibbles so that it is always padded
365        // to a full byte. Thus, the value -2.25 is encoded by the byte sequence (1e e2 a2 5f)
366        // and the value 0.140541E-3 by the sequence (1e 0a 14 05 41 c3 ff)."
367        //
368        // The initial 1e byte in the examples above is the dictionary operator to trigger
369        // parsing of BCD so it is dropped in the tests here.
370        let bytes = FontData::new(&[0xe2, 0xa2, 0x5f]);
371        assert_eq!(
372            BcdComponents::parse(&mut bytes.cursor())
373                .unwrap()
374                .value(false),
375            Fixed::from_f64(-2.25)
376        );
377        let bytes = FontData::new(&[0x0a, 0x14, 0x05, 0x41, 0xc3, 0xff]);
378        assert_eq!(
379            BcdComponents::parse(&mut bytes.cursor())
380                .unwrap()
381                .value(false),
382            Fixed::from_f64(0.140541E-3)
383        );
384        // Check that we match FreeType for 375e-4.
385        // Note: we used to parse 0.0375... but the new FT matching code
386        // has less precision
387        let bytes = FontData::new(&[0x37, 0x5c, 0x4f]);
388        assert_eq!(
389            BcdComponents::parse(&mut bytes.cursor())
390                .unwrap()
391                .value(false),
392            Fixed::from_f64(0.0370025634765625)
393        );
394    }
395
396    #[test]
397    fn scaled_binary_coded_decimal_operands() {
398        // For blue scale, we compute values with an internal factor of 1000 to match
399        // FreeType, which gives us more precision for fractional bits
400        let bytes = FontData::new(&[0xA, 0x06, 0x25, 0xf]);
401        assert_eq!(
402            BcdComponents::parse(&mut bytes.cursor())
403                .unwrap()
404                .value(true),
405            Fixed::from_f64(0.0625)
406        );
407        // Just an additional check to test increased precision. Compare to
408        // the test above where this value generates 0.0370...
409        let bytes = FontData::new(&[0x37, 0x5c, 0x4f]);
410        assert_eq!(
411            BcdComponents::parse(&mut bytes.cursor())
412                .unwrap()
413                .value(true),
414            Fixed::from_f64(0.037506103515625)
415        );
416    }
417
418    #[test]
419    fn dynamically_scaled_binary_coded_decimal_operands() {
420        // 0.0625
421        let bytes = FontData::new(&[0xA, 0x06, 0x25, 0xf]);
422        assert_eq!(
423            BcdComponents::parse(&mut bytes.cursor())
424                .unwrap()
425                .dynamically_scaled_value(),
426            (Fixed::from_f64(6250.0), -5)
427        );
428        // 0.0375
429        let bytes = FontData::new(&[0x37, 0x5c, 0x4f]);
430        assert_eq!(
431            BcdComponents::parse(&mut bytes.cursor())
432                .unwrap()
433                .dynamically_scaled_value(),
434            (Fixed::from_f64(375.0), -4)
435        );
436        // .001953125
437        let bytes = FontData::new(&[0xa0, 0x1, 0x95, 0x31, 0x25, 0xff]);
438        assert_eq!(
439            BcdComponents::parse(&mut bytes.cursor())
440                .unwrap()
441                .dynamically_scaled_value(),
442            (Fixed::from_bits(1280000000), -7)
443        );
444    }
445
446    #[test]
447    fn binary_coded_decimal_exponent_overflow_consumes_number() {
448        // 1E100100 followed by a byte that would otherwise decode as an
449        // operand
450        let bytes = FontData::new(&[0x1b, 0x10, 0x01, 0x00, 0xff, 0x8b]);
451        let mut cursor = bytes.cursor();
452        let components = BcdComponents::parse(&mut cursor).unwrap();
453        assert_eq!(components.value(false), BCD_OVERFLOW);
454        assert_eq!(cursor.position().unwrap(), 5);
455        // -1E100100
456        let bytes = FontData::new(&[0xe1, 0xb1, 0x00, 0x10, 0x0f]);
457        let mut cursor = bytes.cursor();
458        let components = BcdComponents::parse(&mut cursor).unwrap();
459        assert_eq!(components.value(false), -BCD_OVERFLOW);
460        assert_eq!(cursor.remaining_bytes(), 0);
461        // 1E-100100
462        let bytes = FontData::new(&[0x1c, 0x10, 0x01, 0x00, 0xff]);
463        let mut cursor = bytes.cursor();
464        let components = BcdComponents::parse(&mut cursor).unwrap();
465        assert_eq!(components.value(false), BCD_UNDERFLOW);
466        assert_eq!(cursor.remaining_bytes(), 0);
467        // 0E100100
468        let bytes = FontData::new(&[0x0b, 0x10, 0x01, 0x00, 0xff]);
469        let mut cursor = bytes.cursor();
470        let components = BcdComponents::parse(&mut cursor).unwrap();
471        assert_eq!(components.value(false), Fixed::ZERO);
472        assert_eq!(cursor.remaining_bytes(), 0);
473    }
474
475    /// See <https://github.com/googlefonts/fontations/issues/1617>
476    #[test]
477    fn blue_scale_fraction_length_of_0() {
478        // 0.0037
479        let bytes = FontData::new(&[0x37, 0xC3, 0xFF]);
480        assert_eq!(
481            BcdComponents::parse(&mut bytes.cursor())
482                .unwrap()
483                .value(true),
484            Fixed::from_f64(0.0370025634765625)
485        );
486    }
487}