pub const UNITY: i64 = 65536;
pub const MAX_DIMEN: i64 = 0x3FFF_FFFF;
pub fn unit_ratio(unit: &str) -> Option<(i64, i64)> {
Some(match unit {
"pt" => (1, 1),
"in" => (7227, 100),
"pc" => (12, 1),
"cm" => (7227, 254),
"mm" => (7227, 2540),
"bp" => (7227, 7200),
"dd" => (1238, 1157),
"cc" => (14856, 1157),
"sp" => (0, 0),
_ => return None,
})
}
pub fn round_decimals(digits: &str) -> i64 {
let mut f = 0i64;
for digit in digits.bytes().rev().take(17) {
f = (f + i64::from(digit.wrapping_sub(b'0')) * 0x2_0000) / 10;
}
(f + 1) / 2
}
pub fn to_scaled(int: i64, frac: i64, unit: &str) -> Option<i64> {
let (num, den) = unit_ratio(unit)?;
if unit == "sp" {
return Some(int);
}
let sp = int * UNITY + frac;
Some(sp.saturating_mul(num) / den)
}
pub fn print_scaled(mut s: i64) -> String {
let mut out = String::new();
if s < 0 {
out.push('-');
s = -s;
}
out.push_str(&(s / UNITY).to_string());
out.push('.');
s = 10 * (s % UNITY) + 5;
let mut delta = 10i64;
loop {
if delta > UNITY {
s += 0x8000 - 50000;
}
out.push(char::from_digit((s / UNITY) as u32, 10).unwrap_or('0'));
s = 10 * (s % UNITY);
delta *= 10;
if s <= delta {
break;
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn units_reach_the_scaled_points_tex_computes() {
for (unit, want) in [
("pt", "1.0"),
("in", "72.26999"),
("cm", "28.45274"),
("mm", "2.84526"),
("bp", "1.00374"),
("pc", "12.0"),
("dd", "1.07"),
("cc", "12.8401"),
] {
let sp = to_scaled(1, 0, unit).expect("a known unit");
assert_eq!(print_scaled(sp), want, "1{unit}");
}
}
#[test]
fn a_scaled_point_is_the_smallest_step() {
assert_eq!(print_scaled(to_scaled(1, 0, "sp").expect("sp")), "0.00002");
assert_eq!(print_scaled(UNITY), "1.0");
}
#[test]
fn fractions_and_signs_print_as_tex_prints_them() {
assert_eq!(
print_scaled(to_scaled(0, UNITY / 2, "pt").expect("pt")),
"0.5"
);
assert_eq!(print_scaled(-(3 * UNITY + UNITY / 4)), "-3.25");
}
}