f-office-units 0.2.2

Integer lengths and unit conversions for F-Office.
Documentation
//! The numbers of a length value in a file: a decimal number such as `11905.51`, and a
//! universal measure such as `21cm` or `12pt` (`ST_UniversalMeasure`, ECMA-376 Part 1,
//! 22.9.2.15), which WordprocessingML and DrawingML write in the same way. The reader of each
//! length type converts a universal measure into its own unit with [`universal_measure`], so
//! that the measure is parsed in one place.

use crate::div_round_i128;
use crate::scale::{
    POINTS_PER_INCH, POINTS_PER_PICA, TENTHS_OF_MM_PER_CM, TENTHS_OF_MM_PER_INCH,
    TENTHS_OF_MM_PER_MM, THOUSANDTHS, THOUSANDTHS_DIGITS,
};

/// The units of a universal measure, each with its size as a fraction of an inch: the
/// numerator and the denominator.
const UNITS: [(&str, i64, i64); 6] = [
    ("mm", TENTHS_OF_MM_PER_MM, TENTHS_OF_MM_PER_INCH),
    ("cm", TENTHS_OF_MM_PER_CM, TENTHS_OF_MM_PER_INCH),
    ("in", 1, 1),
    ("pt", 1, POINTS_PER_INCH),
    ("pc", POINTS_PER_PICA, POINTS_PER_INCH),
    ("pi", POINTS_PER_PICA, POINTS_PER_INCH),
];

/// Reads a universal measure, a decimal number followed by one of the units `mm`, `cm`, `in`,
/// `pt`, `pc` and `pi`, such as `2.54cm`, in the unit of which `per_inch` make one inch. The
/// number keeps three digits of its fraction, as [`decimal_thousandths`] reads it, and the
/// length is rounded to the nearest whole unit, a half towards positive infinity. `None` when
/// the value is no universal measure, such as a number without a unit or a measure with a
/// space, or when the length does not fit in an `i64`.
#[must_use]
pub fn universal_measure(value: &str, per_inch: i64) -> Option<i64> {
    let (number, numerator, denominator) =
        UNITS.iter().find_map(|(unit, numerator, denominator)| {
            value
                .strip_suffix(unit)
                .map(|number| (number, *numerator, *denominator))
        })?;
    let scaled =
        i128::from(decimal_thousandths(number)?) * i128::from(per_inch) * i128::from(numerator);
    i64::try_from(div_round_i128(
        scaled,
        i128::from(denominator * THOUSANDTHS),
    ))
    .ok()
}

/// Reads a decimal number such as `11905.51` or `-6.8` in thousandths, and drops the digits of
/// the fraction after the third: `1.23456` is 1,234. The number may have a sign and may leave
/// out the fraction; `None` when it has another character or does not fit in an `i64`.
#[must_use]
pub fn decimal_thousandths(text: &str) -> Option<i64> {
    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
    let negative = whole.starts_with('-');
    let whole: i64 = whole.trim_start_matches(['-', '+']).parse().ok()?;
    if !fraction.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }
    let digits: String = fraction.chars().take(THOUSANDTHS_DIGITS).collect();
    let thousandths = whole
        .checked_mul(THOUSANDTHS)?
        .checked_add(format!("{digits:0<3}").parse::<i64>().ok()?)?;
    Some(if negative { -thousandths } else { thousandths })
}

#[cfg(test)]
mod tests {
    use super::{decimal_thousandths, universal_measure};
    use crate::scale::{EMUS_PER_INCH, TWIPS_PER_INCH};

    #[test]
    fn reads_each_unit_of_a_universal_measure() {
        let cases = [
            ("1in", 1_440, 914_400),
            ("2.54cm", 1_440, 914_400),
            ("25.4mm", 1_440, 914_400),
            ("12pt", 240, 152_400),
            ("1pc", 240, 152_400),
            ("1pi", 240, 152_400),
            ("-0.5in", -720, -457_200),
        ];
        for (text, twips, emus) in cases {
            assert_eq!(
                universal_measure(text, TWIPS_PER_INCH),
                Some(twips),
                "{text}"
            );
            assert_eq!(universal_measure(text, EMUS_PER_INCH), Some(emus), "{text}");
        }
    }

    #[test]
    fn refuses_what_is_no_universal_measure() {
        for text in [
            "12", "12.5", "pt", "12px", "12 pt", " 12pt", "12pt ", "1.xpt", "wide",
        ] {
            assert_eq!(universal_measure(text, TWIPS_PER_INCH), None, "{text}");
        }
        let too_long = format!("{}in", i64::MAX / 1_000);
        assert_eq!(universal_measure(&too_long, EMUS_PER_INCH), None);
    }

    #[test]
    fn reads_a_decimal_number_in_thousandths() {
        let cases = [
            ("11905.51", Some(11_905_510)),
            ("1.23456", Some(1_234)),
            ("-6.8", Some(-6_800)),
            ("+5", Some(5_000)),
            ("5.", Some(5_000)),
            ("1.x", None),
            ("", None),
            (" 5", None),
        ];
        for (text, expected) in cases {
            assert_eq!(decimal_thousandths(text), expected, "{text}");
        }
    }
}