Lines
100 %
Functions
87.5 %
Branches
//! Display and wire renderings of an exact amount.
use num_rational::Rational64;
use crate::parse_amount;
const MIN_SCALE: u32 = 2;
/// Reduced `(num, denom)` with a positive denominator; `None` for a zero one.
fn reduced(num: i64, denom: i64) -> Option<(i128, i128)> {
if denom == 0 {
return None;
}
let sign = if denom < 0 { -1 } else { 1 };
let (num, denom) = (i128::from(num) * sign, i128::from(denom).abs());
let divisor = crate::gcd(num.abs(), denom).max(1);
Some((num / divisor, denom / divisor))
/// Wire token for the nomiscript reader: the reduced `n` for a whole value,
/// else `n/d` with the sign on `n`. `None` for a zero denominator.
pub fn wire_token(num: i64, denom: i64) -> Option<String> {
let (num, denom) = reduced(num, denom)?;
Some(match denom {
1 => num.to_string(),
_ => format!("{num}/{denom}"),
})
/// Wire token of a `Rational64`; a zero-denominator ratio (constructible only
/// unchecked) renders as `n/0`, which the reader rejects instead of misreading.
pub fn wire_rational(value: Rational64) -> String {
let (num, denom) = (*value.numer(), *value.denom());
wire_token(num, denom).unwrap_or_else(|| format!("{num}/{denom}"))
/// Display text of `num/denom`: the exact decimal or fraction, falling back
/// to the wire token (`n/0` for a zero denominator).
pub fn display(num: i64, denom: i64) -> String {
format_amount(i128::from(num), denom)
.or_else(|| wire_token(num, denom))
.unwrap_or_else(|| format!("{num}/{denom}"))
fn strip_factor(mut value: i128, factor: i128) -> (i128, u32) {
let mut count = 0;
while value % factor == 0 {
value /= factor;
count += 1;
(value, count)
fn terminating_scale(denom: i128) -> Option<u32> {
let (rest, twos) = strip_factor(denom, 2);
let (rest, fives) = strip_factor(rest, 5);
(rest == 1).then_some(twos.max(fives))
/// Exact decimal of the reduced `num/denom` (`num >= 0`), with at least two
/// places; `None` when the expansion does not terminate or overflows `i128`.
fn exact_decimal(num: i128, denom: i128) -> Option<String> {
let scale = terminating_scale(denom)?.max(MIN_SCALE);
let unit = 10_i128.checked_pow(scale)?;
let scaled = num.checked_mul(unit)? / denom;
Some(format!(
"{}.{:0width$}",
scaled / unit,
scaled % unit,
width = scale as usize
))
/// Renders `num/denom` so the amount parser reads back the same reduced
/// value: the exact decimal when it terminates and the parser accepts it,
/// otherwise the reduced fraction `a/b`. Never rounds. `None` for a zero
/// denominator or a value the parser cannot hold.
pub fn format_amount(num: i128, denom: i64) -> Option<String> {
let negative = (num < 0) != (denom < 0);
let (num, denom) = (num.abs(), i128::from(denom).abs());
let divisor = crate::gcd(num, denom).max(1);
let (num, denom) = (num / divisor, denom / divisor);
let sign = if negative && num != 0 { "-" } else { "" };
let decimal = exact_decimal(num, denom).map(|d| format!("{sign}{d}"));
let fraction = format!("{sign}{num}/{denom}");
let signed = if sign.is_empty() { num } else { -num };
let expected = (i64::try_from(signed).ok()?, i64::try_from(denom).ok()?);
let reads_back = |text: &str| parse_amount(text) == Ok(expected);
decimal
.filter(|d| reads_back(d))
.or_else(|| Some(fraction).filter(|f| reads_back(f)))