use super::{syntax, units::Units};
use crate::{Context, Error, Outcome, number, re};
use std::collections::BTreeMap;
mod exact;
mod functions;
pub(super) use functions::{arguments as function_arguments, has_function};
type Dimensions = BTreeMap<String, i8>;
#[derive(Clone)]
struct Value {
base: f64,
exact: Option<exact::Exact>,
dimensions: Dimensions,
preferred: Option<DisplayUnit>,
affine_temperature: bool,
}
#[derive(Clone)]
struct DisplayUnit {
name: String,
scale: f64,
dimensions: Dimensions,
currency: bool,
offset: f64,
}
fn checked_number(value: f64, nonzero: bool) -> Result<f64, Error> {
if !value.is_finite() {
Err(Error("numeric_overflow".into()))
} else if value == 0.0 && nonzero {
Err(Error("numeric_underflow".into()))
} else {
Ok(value)
}
}
fn literal_number(input: &str) -> Result<f64, Error> {
let value = input
.replace(',', "")
.parse::<f64>()
.map_err(|_| Error("invalid_expression".into()))?;
let mantissa = input.split(['e', 'E']).next().unwrap();
checked_number(value, mantissa.bytes().any(|b| (b'1'..=b'9').contains(&b)))
}
fn named(name: &str, context: &Context) -> Option<DisplayUnit> {
let lower = name.trim().to_ascii_lowercase();
if matches!(lower.as_str(), "cent" | "cents") {
let mut unit = named("AUD", context)?;
unit.name = "cents".into();
unit.scale /= 100.0;
unit.currency = false;
return Some(unit);
}
let (name, currency) = match lower.as_str() {
"dollar" | "dollars" | "aud" => ("AUD", true),
"usd" => ("USD", true),
"eur" => ("EUR", true),
"gbp" => ("GBP", true),
"jpy" => ("JPY", true),
"word" | "words" => ("words", false),
"page" | "pages" => ("pages", false),
"bottle" | "bottles" => ("bottles", false),
"item" | "items" => ("items", false),
"batch" | "batches" => ("batches", false),
"beat" | "beats" => ("beats", false),
"crate" | "crates" => ("crates", false),
"chapter" | "chapters" => ("chapters", false),
"label" | "labels" => ("labels", false),
"order" | "orders" => ("orders", false),
"part" | "parts" => ("parts", false),
"box" | "boxes" => ("boxes", false),
"unit" | "units" => ("units", false),
"point" | "points" => ("points", false),
"coffee" | "coffees" => ("coffees", false),
"request" | "requests" => ("requests", false),
"worker" | "workers" => ("workers", false),
"job" | "jobs" => ("jobs", false),
"muffin" | "muffins" => ("muffins", false),
"drink" | "drinks" => ("drinks", false),
"event" | "events" => ("events", false),
"widget" | "widgets" => ("widgets", false),
"apple" | "apples" => ("apples", false),
"particle" | "particles" => ("particles", false),
"person" | "people" => ("people", false),
_ => (super::finance::currency(name)?, true),
};
let (dimension, scale) = if currency {
context
.rates
.get(name)
.filter(|r| r.is_finite() && **r > 0.0)
.map(|rate| ("money".into(), 1.0 / rate))
.unwrap_or_else(|| (format!("money:{name}"), 1.0))
} else {
(format!("count:{name}"), 1.0)
};
Some(DisplayUnit {
name: name.into(),
scale,
dimensions: BTreeMap::from([(dimension, 1)]),
currency,
offset: 0.0,
})
}
pub(super) fn recognizes(name: &str) -> bool {
named(name, &Context::default()).is_some()
}
pub(super) fn extended_count(name: &str) -> bool {
matches!(
name.trim().to_ascii_lowercase().as_str(),
"piece" | "pieces"
)
}
pub(super) fn validate_rate(
input: &str,
duration: &str,
units: &Units,
context: &Context,
) -> Result<(), Error> {
let mut parser = Parser {
units,
context,
seen: vec![],
standard: false,
};
let rate = parser.expression(input, 0)?;
let duration = parser.expression(duration, 0)?;
if duration.dimensions.iter().any(|(dimension, power)| {
*power > 0 && rate.dimensions.get(dimension).is_some_and(|p| *p < 0)
}) || denominator_matches(input, &duration.dimensions, &mut parser, 0)
{
Ok(())
} else {
Err(Error("invalid_rate".into()))
}
}
fn denominator_matches(
input: &str,
dimensions: &Dimensions,
parser: &mut Parser<'_>,
depth: usize,
) -> bool {
if depth > 64 {
return false;
}
let input = syntax::ungroup(input);
let Some(operators) = super::arithmetic::operators(input) else {
return false;
};
let Some(&(index, operator)) = operators.last() else {
return false;
};
let (left, right) = (&input[..index], &input[index + 1..]);
(operator == '/'
&& parser.expression(right, 0).is_ok_and(|denominator| {
dimensions.iter().any(|(dimension, power)| {
*power > 0
&& denominator
.dimensions
.get(dimension)
.is_some_and(|p| *p > 0)
})
}))
|| denominator_matches(left, dimensions, parser, depth + 1)
|| denominator_matches(right, dimensions, parser, depth + 1)
}
fn physical(unit: &super::units::Unit) -> Dimensions {
unit.dimension
.iter()
.enumerate()
.filter(|(_, p)| **p != 0)
.map(|(i, p)| (format!("physical:{i}"), *p))
.collect()
}
struct Parser<'a> {
units: &'a Units,
context: &'a Context,
seen: Vec<DisplayUnit>,
standard: bool,
}
impl Parser<'_> {
fn exact_unit(&self, spelling: &str) -> Option<exact::Exact> {
let spelling = spelling.trim();
if let Some(unit) = named(spelling, self.context) {
let scale = if unit.currency {
let rate = self.context.rates.get(&unit.name).copied();
rate.map_or_else(
|| exact::decimal("1"),
|rate| {
(rate.is_finite() && rate > 0.0)
.then(|| exact::decimal(&rate.to_string()))
.flatten()
.map(|rate| num_rational::BigRational::from_integer(1.into()) / rate)
},
)?
} else {
(unit.scale == 1.0).then(|| num_rational::BigRational::from_integer(1.into()))?
};
return exact::bounded(scale, unit.currency.then_some(unit.name));
}
if let Some(factors) =
super::compound_units::factors(spelling, |leaf| self.leaf_unit(leaf).is_some())
&& !(factors.len() == 1 && factors[0].0 == spelling && factors[0].1 == 1)
{
let mut result =
exact::bounded(num_rational::BigRational::from_integer(1.into()), None)?;
for (leaf, exponent) in factors {
let factor = self.exact_unit(&leaf)?;
for _ in 0..exponent.unsigned_abs() {
result = if exponent > 0 {
exact::combine(Some(result), Some(factor.clone()), '*')?
} else {
exact::combine(Some(result), Some(factor.clone()), '/')?
};
}
}
return Some(result);
}
let unit = self.units.unit(spelling)?;
exact::bounded(exact::linear_si_scale(&unit)?, None)
}
fn unit(&self, name: &str) -> Option<DisplayUnit> {
self.resolve_unit(name, false)
}
fn resolve_unit(&self, name: &str, prefer_physical: bool) -> Option<DisplayUnit> {
let name = name.trim();
if !self.standard {
let resolve_leaf = |name: &str| {
if prefer_physical {
self.physical_unit(name)
.or_else(|| named(name, self.context))
.or_else(|| self.extended_count(name))
} else {
self.leaf_unit(name)
}
};
if let Some(unit) = resolve_leaf(name) {
return Some(unit);
}
let factors =
super::compound_units::factors(name, |name| resolve_leaf(name).is_some())?;
let mut unit = DisplayUnit {
name: name.into(),
scale: 1.0,
dimensions: Dimensions::new(),
currency: false,
offset: 0.0,
};
for (leaf, exponent) in factors {
let leaf = resolve_leaf(&leaf)?;
if leaf.offset != 0.0 {
return None;
}
unit.scale *= leaf.scale.powi(i32::from(exponent));
for (dimension, power) in leaf.dimensions {
let current = unit.dimensions.entry(dimension).or_default();
*current = current.checked_add(power.checked_mul(exponent)?)?;
}
}
if !unit.scale.is_finite() || unit.scale <= 0.0 {
return None;
}
unit.dimensions.retain(|_, p| *p != 0);
return Some(unit);
}
if name.contains('/') {
let mut parts = name.split('/');
let mut result = self.unit(parts.next()?)?;
if result.offset != 0.0 {
return None;
}
for part in parts {
let denominator = self.unit(part)?;
if denominator.offset != 0.0 {
return None;
}
result.scale /= denominator.scale;
for (dimension, power) in denominator.dimensions {
let exponent = result.dimensions.entry(dimension).or_default();
*exponent = exponent.checked_sub(power)?;
}
}
result.dimensions.retain(|_, exponent| *exponent != 0);
result.name = name.into();
result.currency = false;
return Some(result);
}
named(name, self.context).or_else(|| {
self.units.unit(name).map(|unit| DisplayUnit {
dimensions: physical(&unit),
name: unit.symbol,
scale: unit.scale,
currency: false,
offset: unit.offset,
})
})
}
fn leaf_unit(&self, name: &str) -> Option<DisplayUnit> {
named(name, self.context)
.or_else(|| self.extended_count(name))
.or_else(|| self.physical_unit(name))
}
fn extended_count(&self, name: &str) -> Option<DisplayUnit> {
if self.standard || !extended_count(name) {
return None;
}
Some(DisplayUnit {
name: "pieces".into(),
scale: 1.0,
dimensions: BTreeMap::from([("count:pieces".into(), 1)]),
currency: false,
offset: 0.0,
})
}
fn physical_unit(&self, name: &str) -> Option<DisplayUnit> {
if name.contains('/')
&& !self.units.units.iter().any(|u| {
u.aliases
.split('|')
.any(|alias| alias.eq_ignore_ascii_case(name))
})
{
return None;
}
let unit = self
.units
.units
.iter()
.find(|u| u.symbol == name || u.aliases.split('|').any(|alias| alias == name))
.cloned()
.or_else(|| {
name.contains('μ')
.then(|| self.units.unit(&name.replace('μ', "µ")))
.flatten()
})
.or_else(|| self.units.unit(name))
.or_else(|| {
self.units
.units
.iter()
.find(|u| u.symbol.eq_ignore_ascii_case(name))
.cloned()
})?;
if unit.offset != 0.0 && unit.dimension != [0, 0, 0, 1, 0, 0, 0, 0] {
return None;
}
Some(DisplayUnit {
dimensions: physical(&unit),
name: unit.symbol,
scale: unit.scale,
currency: false,
offset: unit.offset,
})
}
fn quantity(
&mut self,
amount: f64,
exact_amount: Option<exact::Exact>,
mut unit: DisplayUnit,
spelling: &str,
) -> Result<Value, Error> {
if let Some(physical_unit) = self.units.unit(spelling)
&& physical(&physical_unit) == unit.dimensions
&& physical_unit.scale == unit.scale
&& physical_unit.offset == unit.offset
{
unit.name = physical_unit.symbol;
}
let value = Value {
base: checked_number(amount * unit.scale, amount != 0.0)? + unit.offset,
exact: if !self.standard && unit.offset == 0.0 {
exact::combine(exact_amount, self.exact_unit(spelling), '*')
} else {
None
},
dimensions: unit.dimensions.clone(),
affine_temperature: unit.offset != 0.0,
preferred: Some(unit.clone()),
};
if !value.base.is_finite() {
return Err(Error("numeric_overflow".into()));
}
if let Some(factors) =
super::compound_units::factors(spelling, |leaf| self.leaf_unit(leaf).is_some())
{
for (leaf, _) in factors {
if let Some(leaf) = self.leaf_unit(&leaf) {
self.seen.push(leaf);
}
}
}
self.seen.push(unit);
Ok(value)
}
fn expression(&mut self, input: &str, depth: usize) -> Result<Value, Error> {
let error = || Error("invalid_expression".into());
if depth > 64 {
return Err(error());
}
let s = syntax::ungroup(input);
if let Some((source, target)) = syntax::split_last(s, syntax::CONVERSIONS)
&& let Some(unit) = self.unit(target)
{
let mut value = self.expression(source, depth + 1)?;
let mut unit = unit;
if !self.standard && value.dimensions != unit.dimensions {
if let Some(physical_unit) = self.resolve_unit(target, true)
&& physical_unit.dimensions == value.dimensions
{
unit = physical_unit;
} else if value
.dimensions
.keys()
.any(|dimension| dimension.starts_with("money"))
&& let Some(c) =
re!(r"^([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$")
.captures(source)
&& let Some(physical_unit) = self.resolve_unit(&c[2], true)
&& physical_unit.dimensions == unit.dimensions
{
value.base = c[1].replace(',', "").parse::<f64>().map_err(|_| error())?
* physical_unit.scale
+ physical_unit.offset;
value.exact = None;
value.dimensions = unit.dimensions.clone();
}
}
if value.dimensions != unit.dimensions {
return Err(Error("incompatible_units".into()));
}
value.affine_temperature = unit.offset != 0.0;
if value.affine_temperature {
value.exact = None;
}
value.preferred = Some(unit);
return Ok(value);
}
if !self.standard {
if let Some(product) = syntax::group_products(s, |_| true)? {
return self.expression(&product, depth + 1);
}
if super::calendar::date(s, self.context).is_some() {
return Err(Error("invalid_expression".into()));
}
if let Some(c) =
re!(r"^([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$").captures(s)
&& c[2].trim() != "1"
&& let Some(unit) = self.unit(&c[2])
{
let amount = literal_number(&c[1])?;
let exact_amount =
exact::decimal(&c[1]).and_then(|amount| exact::bounded(amount, None));
return self.quantity(amount, exact_amount, unit, &c[2]);
}
if let Some(groups) = syntax::groups(s)
&& let Some(group) = groups.first()
&& let Some(unit) = self.unit(s[group.end + 1..].trim())
{
let prefix = &s[..group.start - 1];
if prefix.is_empty()
|| prefix.chars().all(|c| c.is_ascii_alphabetic())
&& has_function(&s[..group.start])
{
let coefficient = self.expression(&s[..group.end + 1], depth + 1)?;
if !coefficient.dimensions.is_empty() {
return Err(Error("incompatible_units".into()));
}
return self.quantity(
coefficient.base,
coefficient.exact,
unit,
s[group.end + 1..].trim(),
);
}
}
}
let operators = super::arithmetic::operators(s).ok_or_else(error)?;
for level in ["+-", "*/", "^"] {
if let Some(&(i, op)) = operators
.iter()
.filter(|(_, op)| level.contains(*op))
.reduce(|previous, current| if level == "^" { previous } else { current })
{
let mut a = self.expression(&s[..i], depth + 1)?;
let mut b = self.expression(&s[i + 1..], depth + 1)?;
if a.affine_temperature || b.affine_temperature {
return Err(Error(
if matches!(op, '+' | '-') && a.dimensions != b.dimensions {
"incompatible_units"
} else {
"affine_unit_in_rate"
}
.into(),
));
}
let exact = if self.standard || op == '^' {
None
} else {
exact::combine(a.exact.take(), b.exact.take(), op)
};
match op {
'+' | '-' => {
if self.standard
&& b.dimensions.is_empty()
&& let Some(unit) = self
.seen
.iter()
.find(|u| u.currency && u.dimensions == a.dimensions)
{
b.base *= unit.scale;
b.dimensions = a.dimensions.clone();
}
if a.dimensions != b.dimensions {
return Err(Error("incompatible_units".into()));
}
a.base += if op == '+' { b.base } else { -b.base };
}
'*' | '/' => {
if op == '/' && b.base == 0.0 {
return Err(Error("division_by_zero".into()));
}
let nonzero = a.base != 0.0 && b.base != 0.0;
a.base = if op == '*' {
a.base * b.base
} else {
a.base / b.base
};
if !self.standard {
a.base = checked_number(a.base, nonzero)?;
}
let scalar = b.dimensions.is_empty();
for (key, power) in b.dimensions {
let value = a.dimensions.entry(key).or_default();
*value = if op == '*' {
value.checked_add(power)
} else {
value.checked_sub(power)
}
.ok_or_else(error)?;
}
a.dimensions.retain(|_, p| *p != 0);
if !scalar {
a.preferred = None;
}
}
'^' => {
if !b.dimensions.is_empty()
|| (!a.dimensions.is_empty()
&& (b.base.fract() != 0.0 || b.base.abs() > 16.0))
{
return Err(error());
}
let nonzero = a.base != 0.0;
a.base = a.base.powf(b.base);
if !self.standard {
a.base = checked_number(a.base, nonzero)?;
}
for power in a.dimensions.values_mut() {
*power = power.checked_mul(b.base as i8).ok_or_else(error)?;
}
a.dimensions.retain(|_, p| *p != 0);
a.preferred = None;
}
_ => unreachable!(),
}
if !a.base.is_finite() {
return Err(Error("numeric_overflow".into()));
}
a.exact = exact;
return Ok(a);
}
}
if !self.standard
&& let Some(result) = self.function(s, depth)
{
return result;
}
if let Some(inner) = s.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
return self.expression(inner, depth + 1);
}
if let Some((amount, code)) = super::finance::amount(s)
&& !code.is_empty()
&& let Some(unit) = named(code, self.context)
{
let value = Value {
base: amount * unit.scale,
exact: if self.standard {
None
} else {
re!(r"(?i)([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?)")
.captures(s)
.and_then(|c| exact::decimal(&c[1]))
.and_then(|amount| exact::bounded(amount, None))
.and_then(|amount| exact::combine(Some(amount), self.exact_unit(code), '*'))
},
dimensions: unit.dimensions.clone(),
preferred: (!self.standard).then(|| unit.clone()),
affine_temperature: false,
};
self.seen.push(unit);
return Ok(value);
}
if let Some(c) = re!(r"^([+-]?[\d.,]+)\s*([a-zA-Z]+)$").captures(s)
&& let Some(unit) = named(&c[2], self.context)
{
let base = c[1].replace(',', "").parse::<f64>().map_err(|_| error())? * unit.scale;
let dimensions = if self.standard && !unit.currency && unit.name != "cents" {
Dimensions::new()
} else {
unit.dimensions.clone()
};
let preferred = (!self.standard).then(|| unit.clone());
if !dimensions.is_empty() {
self.seen.push(unit);
}
return Ok(Value {
base,
exact: if self.standard {
None
} else {
exact::decimal(&c[1])
.and_then(|amount| exact::bounded(amount, None))
.and_then(|amount| {
exact::combine(Some(amount), self.exact_unit(&c[2]), '*')
})
},
dimensions,
preferred,
affine_temperature: false,
});
}
if let Some(q) = self.units.quantity(s) {
if q.unit.offset != 0.0
&& (self.standard || q.unit.dimension != [0, 0, 0, 1, 0, 0, 0, 0])
{
return Err(Error("affine_unit_in_rate".into()));
}
let dimensions = physical(&q.unit);
let unit = DisplayUnit {
name: q.unit.symbol,
scale: q.unit.scale,
dimensions: dimensions.clone(),
currency: false,
offset: q.unit.offset,
};
let preferred = (!self.standard).then(|| unit.clone());
self.seen.push(unit);
return Ok(Value {
base: q.base,
exact: if self.standard || q.unit.offset != 0.0 {
None
} else {
self.exact_unit(s)
},
affine_temperature: q.unit.offset != 0.0,
dimensions,
preferred,
});
}
if let Some(inner) = s.strip_prefix('-') {
let mut v = self.expression(inner, depth + 1)?;
if v.affine_temperature {
return Err(Error("affine_unit_in_rate".into()));
}
v.base = -v.base;
if let Some(exact) = &mut v.exact {
exact.amount = -exact.amount.clone();
}
return Ok(v);
}
if self.standard
&& let Some(c) = re!(r"^([+-]?[\d.,]+)\s+[a-zA-Z]+$").captures(s)
{
return Ok(Value {
base: c[1].replace(',', "").parse().map_err(|_| error())?,
exact: None,
dimensions: Dimensions::new(),
preferred: None,
affine_temperature: false,
});
}
if let Ok(base) = s.replace(',', "").parse::<f64>() {
let base = if self.standard {
checked_number(base, false)?
} else {
literal_number(s)?
};
return Ok(Value {
base,
exact: if self.standard {
None
} else {
exact::decimal(s).and_then(|amount| exact::bounded(amount, None))
},
dimensions: Dimensions::new(),
preferred: None,
affine_temperature: false,
});
}
super::arithmetic::eval(s)
.map(|base| Value {
base,
exact: None,
dimensions: Dimensions::new(),
preferred: None,
affine_temperature: false,
})
.ok_or_else(error)
}
}
pub(super) fn recognizes_expression(input: &str) -> bool {
input.contains(['$', '€', '£', '¥', '₿']) || re!(r"(?i)\b(?:dollars?|cents?|USD|AUD|EUR|GBP|JPY|BTC|words?|pages?|bottles?|items?|batch|batches|beats?|crates?|chapters?|labels?|orders?|parts?|box|boxes|units?|points?|coffees?|requests?|workers?|jobs?|muffins?|drinks?|events?|widgets?|apples?|particles?|person|people)\b").is_match(input)
}
pub(super) fn recognizes_quantity(input: &str, units: &Units, context: &Context) -> bool {
re!(r"^([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$")
.captures(input)
.is_some_and(|c| {
c[2].trim() != "1"
&& Parser {
units,
context,
seen: vec![],
standard: false,
}
.unit(&c[2])
.is_some()
})
}
pub(super) fn evaluate_any(input: &str, units: &Units, context: &Context) -> Outcome {
evaluate_mode(input, units, context, false)
}
pub(super) fn evaluate_standard(input: &str, units: &Units, context: &Context) -> Outcome {
evaluate_mode(input, units, context, true)
}
fn evaluate_mode(input: &str, units: &Units, context: &Context, standard: bool) -> Outcome {
let mut parser = Parser {
units,
context,
seen: vec![],
standard,
};
let result = (|| {
let value = parser.expression(input, 0)?;
let display = value.preferred.as_ref().or_else(|| {
parser
.seen
.iter()
.find(|u| u.dimensions == value.dimensions)
});
if let Some(unit) = display {
if unit.dimensions != value.dimensions {
return Err(Error("incompatible_units".into()));
}
let n = (value.base - unit.offset) / unit.scale;
Ok(if unit.currency {
let exact_cents = (!standard && n.abs() >= 0.01 && n.abs() < 1e12)
.then_some(value.exact.as_ref())
.flatten()
.filter(|exact| exact.currency.as_deref() == Some(unit.name.as_str()))
.and_then(|exact| {
let scale = parser.exact_unit(&unit.name)?;
exact::ordinary_money(&(&exact.amount / scale.amount), &unit.name)
});
super::money(exact_cents.unwrap_or(n), &unit.name)
} else if let Some((currency, denominator)) = unit.name.split_once('/')
&& unit
.dimensions
.keys()
.any(|dimension| dimension.starts_with("money"))
&& let Some(currency) = named(currency, context).filter(|unit| unit.currency)
{
format!("{}/{denominator}", super::money(n, ¤cy.name))
} else {
format!(
"{} {}",
number(n),
if n.abs() == 1.0 {
singular(&unit.name)
} else {
&unit.name
}
)
})
} else if value.dimensions.is_empty() {
Ok(number(value.base))
} else {
if standard && value.dimensions == BTreeMap::from([("physical:2".into(), -2)]) {
let time = parser
.seen
.iter()
.find(|u| u.dimensions == BTreeMap::from([("physical:2".into(), 1)]))
.ok_or_else(|| Error("invalid_expression".into()))?;
return Ok(format!(
"{} Hz/{}",
number(value.base * time.scale),
singular(&time.name)
));
}
if standard && value.dimensions.get("physical:2") == Some(&-1) {
let time = parser
.seen
.iter()
.find(|u| u.dimensions == BTreeMap::from([("physical:2".into(), 1)]))
.ok_or_else(|| Error("invalid_expression".into()))?;
let money = parser.seen.iter().find(|u| u.currency);
let magnitude = value.base * time.scale / money.map_or(1.0, |u| u.scale);
let numerator =
money.map_or_else(|| number(magnitude), |u| super::money(magnitude, &u.name));
return Ok(format!("{numerator}/{}", singular(&time.name)));
}
let mut scale = 1.0;
let mut numerator = vec![];
let mut denominator = vec![];
for (dimension, power) in &value.dimensions {
let unit = parser
.seen
.iter()
.rev()
.find(|u| u.dimensions.len() == 1 && u.dimensions.get(dimension) == Some(&1))
.ok_or_else(|| Error("unsupported_compound_unit".into()))?;
scale *= unit.scale.powi(i32::from(*power));
let label = if power.unsigned_abs() == 1 {
singular(&unit.name).to_string()
} else {
format!("{}^{}", singular(&unit.name), power.unsigned_abs())
};
if *power > 0 {
numerator.push(label);
} else {
denominator.push(label);
}
}
let top = if numerator.is_empty() {
"1".into()
} else {
numerator.join("·")
};
let symbol = if denominator.is_empty() {
top
} else if denominator.len() == 1 {
format!("{top}/{}", denominator[0])
} else {
format!("{top}/({})", denominator.join("·"))
};
Ok(format!("{} {symbol}", number(value.base / scale)))
}
})();
Some(result)
}
fn singular(name: &str) -> &str {
match name {
"batches" => "batch",
"people" => "person",
"pages" => "page",
"words" => "word",
"bottles" => "bottle",
"items" => "item",
"beats" => "beat",
"crates" => "crate",
"chapters" => "chapter",
"labels" => "label",
"orders" => "order",
"parts" => "part",
"pieces" => "piece",
"boxes" => "box",
"units" => "unit",
"points" => "point",
"coffees" => "coffee",
"requests" => "request",
"workers" => "worker",
"jobs" => "job",
"muffins" => "muffin",
"drinks" => "drink",
"events" => "event",
"widgets" => "widget",
"apples" => "apple",
"particles" => "particle",
"hours" => "hour",
"days" => "day",
"weeks" => "week",
"months" => "month",
s => s,
}
}
pub(super) fn validate_quantity(
input: &str,
units: &Units,
context: &Context,
) -> Result<(), Error> {
let mut parser = Parser {
units,
context,
seen: vec![],
standard: false,
};
let value = parser.expression(input, 0)?;
if value.dimensions.is_empty() {
return Err(Error("invalid_duration".into()));
}
Ok(())
}
pub(super) fn validate_money(input: &str, units: &Units, context: &Context) -> Result<(), Error> {
let value = Parser {
units,
context,
seen: vec![],
standard: false,
}
.expression(input, 0)?;
if value.dimensions.len() != 1
|| !value.dimensions.iter().any(|(dimension, power)| {
*power == 1 && (dimension == "money" || dimension.starts_with("money:"))
})
{
return Err(Error("incompatible_units".into()));
}
Ok(())
}
pub(super) fn quantity_order(
left: &str,
right: &str,
units: &Units,
context: &Context,
) -> Result<std::cmp::Ordering, Error> {
let mut parser = Parser {
units,
context,
seen: vec![],
standard: false,
};
let a = parser.expression(left, 0)?;
let b = parser.expression(right, 0)?;
if a.dimensions != b.dimensions {
return Err(Error("incompatible_units".into()));
}
if !a.base.is_finite() || !b.base.is_finite() {
return Err(Error("numeric_overflow".into()));
}
let roundoff_equal = a.base != 0.0
&& b.base != 0.0
&& a.base.is_sign_negative() == b.base.is_sign_negative()
&& a.base.to_bits().abs_diff(b.base.to_bits()) <= 4;
if a.base == b.base || roundoff_equal {
Ok(std::cmp::Ordering::Equal)
} else {
Ok(a.base.total_cmp(&b.base))
}
}
pub(super) fn quantity_value(
input: &str,
reference: &str,
units: &Units,
context: &Context,
) -> Result<f64, Error> {
let mut parser = Parser {
units,
context,
seen: vec![],
standard: false,
};
let value = parser.expression(input, 0)?;
let reference = parser
.unit(reference)
.ok_or_else(|| Error("incompatible_units".into()))?;
if value.dimensions != reference.dimensions {
return Err(Error("incompatible_units".into()));
}
let coordinate = (value.base - reference.offset) / reference.scale;
if !coordinate.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(coordinate)
}