use std::collections::BTreeMap;
use std::fmt;
use crate::money::{Rounding, div_round};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum QuantityError {
Invalid(String),
Overflow,
Inexact,
UnknownUnit(String),
DivisionByZero,
InvalidUnits(String),
IncompatibleUnits {
from: String,
to: String,
},
}
impl fmt::Display for QuantityError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
QuantityError::Invalid(t) => write!(f, "`{t}` is not a valid quantity"),
QuantityError::Overflow => f.write_str("the quantity is too large"),
QuantityError::Inexact => f.write_str("the quantity has more decimals than allowed"),
QuantityError::UnknownUnit(u) => write!(f, "`{u}` is not a known unit"),
QuantityError::DivisionByZero => f.write_str("the denominator is zero"),
QuantityError::InvalidUnits(why) => write!(f, "invalid unit table: {why}"),
QuantityError::IncompatibleUnits { from, to } => {
write!(f, "`{from}` cannot be converted to `{to}`: different bases")
}
}
}
}
impl std::error::Error for QuantityError {}
fn split_decimal(text: &str) -> Option<(bool, &str, &str)> {
let t = text.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
let (whole, fraction) = t.split_once('.').unwrap_or((t, ""));
let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
if whole.is_empty() || !digits(whole) || !digits(fraction) || t.ends_with('.') {
return None;
}
Some((negative, whole, fraction))
}
pub(crate) fn fits_scale(text: &str, scale: u32) -> bool {
let Some((_, whole, fraction)) = split_decimal(text) else {
return false;
};
let scale = scale.min(9) as usize;
let (kept, rest) = fraction.split_at(fraction.len().min(scale));
rest.bytes().all(|b| b == b'0') && format!("{whole}{kept:0<scale$}").parse::<i64>().is_ok()
}
pub(crate) fn nano(text: &str) -> Option<i128> {
let (negative, whole, fraction) = split_decimal(text)?;
let kept = &fraction[..fraction.len().min(9)];
let value: i128 = format!("{whole}{kept:0<9}").parse().ok()?;
Some(if negative { -value } else { value })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Quantity<const SCALE: u32>(i64);
impl<const SCALE: u32> Quantity<SCALE> {
const VALID: () = assert!(SCALE <= 9, "Quantity SCALE must be 0..=9");
pub const ZERO: Self = Quantity(0);
pub const fn from_raw(raw: i64) -> Self {
let () = Self::VALID;
Quantity(raw)
}
pub const fn raw(self) -> i64 {
self.0
}
pub fn parse(text: &str, rounding: Rounding) -> Result<Self, QuantityError> {
let () = Self::VALID;
let (negative, whole, fraction) =
split_decimal(text).ok_or_else(|| QuantityError::Invalid(text.to_string()))?;
let scale = SCALE as usize;
let (kept, rest) = if fraction.len() > scale {
fraction.split_at(scale)
} else {
(fraction, "")
};
let padded = format!("{whole}{kept:0<scale$}");
let mut magnitude: i128 = padded.parse().map_err(|_| QuantityError::Overflow)?;
if rest.bytes().any(|b| b != b'0') {
let first = rest.as_bytes()[0];
let beyond = rest[1..].bytes().any(|b| b != b'0');
let round_away = match rounding {
Rounding::Down => false,
Rounding::Up => true,
Rounding::HalfUp | Rounding::HalfEven => {
if first > b'5' || (first == b'5' && beyond) {
true
} else if first == b'5' {
rounding == Rounding::HalfUp || magnitude % 2 != 0
} else {
false
}
}
};
if round_away {
magnitude += 1;
}
}
let signed = if negative { -magnitude } else { magnitude };
i64::try_from(signed)
.map(Quantity)
.map_err(|_| QuantityError::Overflow)
}
pub fn parse_exact(text: &str) -> Result<Self, QuantityError> {
let down = Self::parse(text, Rounding::Down)?;
let up = Self::parse(text, Rounding::Up)?;
if down == up {
Ok(down)
} else {
Err(QuantityError::Inexact)
}
}
pub fn parse_half_even(text: &str) -> Result<Self, QuantityError> {
Self::parse(text, Rounding::HalfEven)
}
pub fn checked_add(self, other: Self) -> Result<Self, QuantityError> {
self.0
.checked_add(other.0)
.map(Quantity)
.ok_or(QuantityError::Overflow)
}
pub fn checked_sub(self, other: Self) -> Result<Self, QuantityError> {
self.0
.checked_sub(other.0)
.map(Quantity)
.ok_or(QuantityError::Overflow)
}
pub fn checked_neg(self) -> Result<Self, QuantityError> {
self.0
.checked_neg()
.map(Quantity)
.ok_or(QuantityError::Overflow)
}
pub fn mul_ratio(self, num: i64, den: i64, rounding: Rounding) -> Result<Self, QuantityError> {
if den == 0 {
return Err(QuantityError::DivisionByZero);
}
let n = self.0 as i128 * num as i128;
i64::try_from(div_round(n, den as i128, rounding))
.map(Quantity)
.map_err(|_| QuantityError::Overflow)
}
pub fn mul_decimal(self, factor: &str, rounding: Rounding) -> Result<Self, QuantityError> {
let bad = || QuantityError::Invalid(factor.to_string());
let (negative, whole, fraction) = split_decimal(factor).ok_or_else(bad)?;
if fraction.len() > 18 {
return Err(bad());
}
let magnitude: i128 = format!("{whole}{fraction}")
.parse()
.map_err(|_| QuantityError::Overflow)?;
let num = if negative { -magnitude } else { magnitude };
let den = 10i128.pow(fraction.len() as u32);
let n = (self.0 as i128)
.checked_mul(num)
.ok_or(QuantityError::Overflow)?;
i64::try_from(div_round(n, den, rounding))
.map(Quantity)
.map_err(|_| QuantityError::Overflow)
}
pub fn rescale<const TO: u32>(self, rounding: Rounding) -> Result<Quantity<TO>, QuantityError> {
let () = Quantity::<TO>::VALID;
let raw = if TO >= SCALE {
(self.0 as i128) * 10i128.pow(TO - SCALE)
} else {
div_round(self.0 as i128, 10i128.pow(SCALE - TO), rounding)
};
i64::try_from(raw)
.map(Quantity)
.map_err(|_| QuantityError::Overflow)
}
}
impl<const SCALE: u32> fmt::Display for Quantity<SCALE> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let scale = SCALE as usize;
let digits = format!("{:0>width$}", self.0.unsigned_abs(), width = scale + 1);
let (whole, fraction) = digits.split_at(digits.len() - scale);
let sign = if self.0 < 0 { "-" } else { "" };
if scale == 0 {
write!(f, "{sign}{whole}")
} else {
write!(f, "{sign}{whole}.{fraction}")
}
}
}
impl<const SCALE: u32> serde::Serialize for Quantity<SCALE> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de, const SCALE: u32> serde::Deserialize<'de> for Quantity<SCALE> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V<const S: u32>;
impl<const S: u32> serde::de::Visitor<'_> for V<S> {
type Value = Quantity<S>;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a decimal quantity as a string or an exact number")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
Quantity::<S>::parse_exact(v).map_err(E::custom)
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Self::Value, E> {
Quantity::<S>::parse_exact(&v.to_string()).map_err(E::custom)
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Self::Value, E> {
Quantity::<S>::parse_exact(&v.to_string()).map_err(E::custom)
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Self::Value, E> {
if !v.is_finite() {
return Err(E::custom(QuantityError::Invalid(v.to_string())));
}
Quantity::<S>::parse_exact(&format!("{v}")).map_err(E::custom)
}
}
deserializer.deserialize_any(V::<SCALE>)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct UnitDef {
base: String,
num: i128,
den: i128,
}
fn gcd(a: i128, b: i128) -> i128 {
if b == 0 { a } else { gcd(b, a % b) }
}
fn parse_factor(text: &str) -> Result<(i128, i128), QuantityError> {
let bad = || QuantityError::InvalidUnits(format!("`{text}` is not a positive decimal factor"));
let (negative, whole, fraction) = split_decimal(text).ok_or_else(bad)?;
if negative || fraction.len() > 18 {
return Err(bad());
}
let num: i128 = format!("{whole}{fraction}").parse().map_err(|_| bad())?;
if num == 0 {
return Err(bad());
}
let den = 10i128.pow(fraction.len() as u32);
let g = gcd(num, den);
Ok((num / g, den / g))
}
#[derive(Debug, Clone, Default)]
pub struct Units {
declared: Vec<(String, Option<String>, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitTable {
defs: BTreeMap<String, UnitDef>,
}
impl Units {
pub fn new() -> Self {
Units::default()
}
pub fn base(mut self, code: &str) -> Self {
self.declared.push((code.to_string(), None, String::new()));
self
}
pub fn unit(mut self, code: &str, base: &str, factor: &str) -> Self {
self.declared
.push((code.to_string(), Some(base.to_string()), factor.to_string()));
self
}
pub fn build(self) -> Result<UnitTable, QuantityError> {
let fail = |why: String| Err(QuantityError::InvalidUnits(why));
let mut defs: BTreeMap<String, UnitDef> = BTreeMap::new();
for (code, base, factor) in &self.declared {
if code.trim().is_empty() {
return fail("a unit code is empty".into());
}
if defs.contains_key(code) {
return fail(format!("`{code}` is declared twice"));
}
let def = match base {
None => UnitDef {
base: code.clone(),
num: 1,
den: 1,
},
Some(base) => {
let (num, den) = parse_factor(factor)?;
UnitDef {
base: base.clone(),
num,
den,
}
}
};
defs.insert(code.clone(), def);
}
for (code, def) in &defs {
match defs.get(&def.base) {
None => return fail(format!("`{code}` points at unknown base `{}`", def.base)),
Some(target) if target.base != def.base => {
return fail(format!(
"`{code}` points at `{}`, which is not a base",
def.base
));
}
Some(_) => {}
}
}
Ok(UnitTable { defs })
}
}
impl UnitTable {
pub fn contains(&self, code: &str) -> bool {
self.defs.contains_key(code)
}
pub fn convert<const SCALE: u32>(
&self,
q: Quantity<SCALE>,
from: &str,
to: &str,
rounding: Rounding,
) -> Result<Quantity<SCALE>, QuantityError> {
let unknown = |c: &str| QuantityError::UnknownUnit(c.to_string());
let f = self.defs.get(from).ok_or_else(|| unknown(from))?;
let t = self.defs.get(to).ok_or_else(|| unknown(to))?;
if f.base != t.base {
return Err(QuantityError::IncompatibleUnits {
from: from.to_string(),
to: to.to_string(),
});
}
let num = (q.raw() as i128)
.checked_mul(f.num)
.and_then(|n| n.checked_mul(t.den))
.ok_or(QuantityError::Overflow)?;
let den = f.den.checked_mul(t.num).ok_or(QuantityError::Overflow)?;
i64::try_from(div_round(num, den, rounding))
.map(Quantity::from_raw)
.map_err(|_| QuantityError::Overflow)
}
}