1use 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 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
29const BCD_OVERFLOW: Fixed = Fixed::from_bits(0x7FFFFFFF);
34const BCD_UNDERFLOW: Fixed = Fixed::ZERO;
36const BCD_NUMBER_LIMIT: i32 = 0xCCCCCCC;
39const BCD_INTEGER_LIMIT: i32 = 0x7FFF;
41
42pub(crate) const BCD_POWER_TENS: [i32; 10] = [
44 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000,
45];
46
47#[derive(Copy, Clone, PartialEq, Eq, Default, Debug)]
50pub struct BcdComponents {
51 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 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 '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 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 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 if integer_len < 0 {
202 number /= BCD_POWER_TENS[(-integer_len) as usize];
203 fraction_len += integer_len;
204 }
205 if fraction_len == 10 {
207 number /= 10;
208 fraction_len -= 1;
209 }
210 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 result = (Fixed::from_bits(result) / Fixed::from_i32(1000)).to_bits();
231 }
232 Fixed::from_bits(result * self.sign)
233 }
234
235 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 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
304pub(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 let empty = FontData::new(&[]);
347 let min_byte = FontData::new(&[0]);
348 let max_byte = FontData::new(&[255]);
349 assert_eq!(parse_int(&mut empty.cursor(), 32).unwrap(), -107);
351 assert_eq!(parse_int(&mut empty.cursor(), 246).unwrap(), 107);
352 assert_eq!(parse_int(&mut min_byte.cursor(), 247).unwrap(), 108);
354 assert_eq!(parse_int(&mut max_byte.cursor(), 250).unwrap(), 1131);
355 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 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 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 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 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 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 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 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 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 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 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 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 #[test]
477 fn blue_scale_fraction_length_of_0() {
478 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}