Skip to main content

renox_core/
quantity.rs

1//! Exact decimal quantities (kilograms, metres, pieces) with the scale in
2//! the type.
3//!
4//! [`Quantity<SCALE>`](Quantity) is a `Copy` newtype over an `i64` holding
5//! the value in units of 10^-`SCALE`: `Quantity<3>` counts thousandths.
6//! There are no floats. Like [`Money`](crate::money::Money), anything that
7//! can lose digits takes an explicit [`Rounding`]; there is no default.
8//! A quantity carries no unit: keep the unit in its own field.
9//!
10//! ```
11//! use renox::money::Rounding;
12//! use renox::quantity::Quantity;
13//!
14//! let q = Quantity::<3>::parse("2.5", Rounding::HalfEven).unwrap();
15//! assert_eq!(q.raw(), 2500);
16//! assert_eq!(q.to_string(), "2.500");
17//! assert_eq!(Quantity::<3>::parse("0.0005", Rounding::HalfUp).unwrap().to_string(), "0.001");
18//! assert!(Quantity::<3>::parse_exact("0.0005").is_err());
19//! ```
20
21use std::collections::BTreeMap;
22use std::fmt;
23
24use crate::money::{Rounding, div_round};
25
26/// Why a quantity calculation or parse failed.
27///
28/// ```
29/// use renox::quantity::{Quantity, QuantityError};
30///
31/// assert_eq!(Quantity::<3>::parse_exact("0.0005").unwrap_err(), QuantityError::Inexact);
32/// assert!(matches!(Quantity::<3>::parse_exact("abc"), Err(QuantityError::Invalid(_))));
33/// ```
34#[derive(Debug, Clone, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum QuantityError {
37    /// The text is not a decimal number (or a factor).
38    Invalid(String),
39    /// The result does not fit in an `i64` of scaled units.
40    Overflow,
41    /// Digits would be lost and no rounding was allowed.
42    Inexact,
43    /// A unit code that is not in the unit table.
44    UnknownUnit(String),
45    /// A denominator of zero.
46    DivisionByZero,
47    /// A unit table that cannot be built (the reason is in the text).
48    InvalidUnits(String),
49    /// A conversion between units of different bases (kg to m).
50    IncompatibleUnits {
51        /// The unit converted from.
52        from: String,
53        /// The unit converted to.
54        to: String,
55    },
56}
57
58impl fmt::Display for QuantityError {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            QuantityError::Invalid(t) => write!(f, "`{t}` is not a valid quantity"),
62            QuantityError::Overflow => f.write_str("the quantity is too large"),
63            QuantityError::Inexact => f.write_str("the quantity has more decimals than allowed"),
64            QuantityError::UnknownUnit(u) => write!(f, "`{u}` is not a known unit"),
65            QuantityError::DivisionByZero => f.write_str("the denominator is zero"),
66            QuantityError::InvalidUnits(why) => write!(f, "invalid unit table: {why}"),
67            QuantityError::IncompatibleUnits { from, to } => {
68                write!(f, "`{from}` cannot be converted to `{to}`: different bases")
69            }
70        }
71    }
72}
73
74impl std::error::Error for QuantityError {}
75
76/// Splits `[+-]digits[.digits]` into sign, whole and fraction digits.
77/// No exponent, no separators, no empty parts.
78fn split_decimal(text: &str) -> Option<(bool, &str, &str)> {
79    let t = text.trim();
80    let (negative, t) = match t.strip_prefix('-') {
81        Some(rest) => (true, rest),
82        None => (false, t.strip_prefix('+').unwrap_or(t)),
83    };
84    let (whole, fraction) = t.split_once('.').unwrap_or((t, ""));
85    let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
86    if whole.is_empty() || !digits(whole) || !digits(fraction) || t.ends_with('.') {
87        return None;
88    }
89    Some((negative, whole, fraction))
90}
91
92/// Whether `text` reads as a decimal that fits an `i64` at `scale` digits with
93/// nothing rounded (digits beyond the scale must all be zero). For the
94/// validation rule, where the scale is only known at run time.
95pub(crate) fn fits_scale(text: &str, scale: u32) -> bool {
96    let Some((_, whole, fraction)) = split_decimal(text) else {
97        return false;
98    };
99    let scale = scale.min(9) as usize;
100    let (kept, rest) = fraction.split_at(fraction.len().min(scale));
101    rest.bytes().all(|b| b == b'0') && format!("{whole}{kept:0<scale$}").parse::<i64>().is_ok()
102}
103
104/// The value of `text` in billionths (nine decimals), for comparing a typed
105/// quantity with a limit; digits past the ninth are cut. `None` when `text`
106/// is not a plain decimal or does not fit.
107pub(crate) fn nano(text: &str) -> Option<i128> {
108    let (negative, whole, fraction) = split_decimal(text)?;
109    let kept = &fraction[..fraction.len().min(9)];
110    let value: i128 = format!("{whole}{kept:0<9}").parse().ok()?;
111    Some(if negative { -value } else { value })
112}
113
114/// A decimal quantity stored as an `i64` count of 10^-`SCALE` units.
115/// `SCALE` is at most 9, checked at compile time. Adding and subtracting
116/// return a `Result`; there are no panicking operators.
117///
118/// ```
119/// use renox::money::Rounding;
120/// use renox::quantity::Quantity;
121///
122/// let a = Quantity::<3>::parse_exact("1.250").unwrap();
123/// let b = Quantity::<3>::parse_exact("0.750").unwrap();
124/// assert_eq!(a.checked_add(b).unwrap().to_string(), "2.000");
125/// assert_eq!(a.mul_decimal("1.15", Rounding::HalfUp).unwrap().to_string(), "1.438");
126/// assert!(b < a);
127/// ```
128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
129pub struct Quantity<const SCALE: u32>(i64);
130
131impl<const SCALE: u32> Quantity<SCALE> {
132    /// Compile-time check that the scale fits an `i64` (at most 9).
133    const VALID: () = assert!(SCALE <= 9, "Quantity SCALE must be 0..=9");
134
135    /// The zero quantity.
136    pub const ZERO: Self = Quantity(0);
137
138    /// The quantity of `raw` units of 10^-`SCALE` (`2500` is 2.500 for
139    /// `Quantity<3>`).
140    ///
141    /// ```
142    /// use renox::quantity::Quantity;
143    ///
144    /// assert_eq!(Quantity::<3>::from_raw(2500).to_string(), "2.500");
145    /// ```
146    pub const fn from_raw(raw: i64) -> Self {
147        let () = Self::VALID;
148        Quantity(raw)
149    }
150
151    /// The value in units of 10^-`SCALE`.
152    ///
153    /// ```
154    /// use renox::quantity::Quantity;
155    ///
156    /// assert_eq!(Quantity::<2>::from_raw(-150).raw(), -150);
157    /// ```
158    pub const fn raw(self) -> i64 {
159        self.0
160    }
161
162    /// Reads a decimal such as `"2.5"` or `"-0.125"` with `.` as the
163    /// decimal point. Digits beyond the scale are rounded with `rounding`
164    /// (`Down` is toward zero, `Up` away from zero). Empty text, signs
165    /// other than a leading `-` or `+`, exponents and separators are
166    /// `Invalid`; a value that does not fit is `Overflow`.
167    ///
168    /// ```
169    /// use renox::money::Rounding;
170    /// use renox::quantity::Quantity;
171    ///
172    /// let q = |t, r| Quantity::<3>::parse(t, r).unwrap().to_string();
173    /// assert_eq!(q("2.5", Rounding::HalfEven), "2.500");
174    /// assert_eq!(q("0.0005", Rounding::HalfUp), "0.001");
175    /// assert_eq!(q("0.0005", Rounding::HalfEven), "0.000");
176    /// assert_eq!(q("-0.0005", Rounding::Up), "-0.001");
177    /// assert_eq!(q("0.0009", Rounding::Down), "0.000");
178    /// assert!(Quantity::<3>::parse("1e3", Rounding::Down).is_err());
179    /// ```
180    pub fn parse(text: &str, rounding: Rounding) -> Result<Self, QuantityError> {
181        let () = Self::VALID;
182        let (negative, whole, fraction) =
183            split_decimal(text).ok_or_else(|| QuantityError::Invalid(text.to_string()))?;
184        let scale = SCALE as usize;
185        let (kept, rest) = if fraction.len() > scale {
186            fraction.split_at(scale)
187        } else {
188            (fraction, "")
189        };
190        let padded = format!("{whole}{kept:0<scale$}");
191        let mut magnitude: i128 = padded.parse().map_err(|_| QuantityError::Overflow)?;
192        if rest.bytes().any(|b| b != b'0') {
193            let first = rest.as_bytes()[0];
194            let beyond = rest[1..].bytes().any(|b| b != b'0');
195            let round_away = match rounding {
196                Rounding::Down => false,
197                Rounding::Up => true,
198                Rounding::HalfUp | Rounding::HalfEven => {
199                    if first > b'5' || (first == b'5' && beyond) {
200                        true
201                    } else if first == b'5' {
202                        rounding == Rounding::HalfUp || magnitude % 2 != 0
203                    } else {
204                        false
205                    }
206                }
207            };
208            if round_away {
209                magnitude += 1;
210            }
211        }
212        let signed = if negative { -magnitude } else { magnitude };
213        i64::try_from(signed)
214            .map(Quantity)
215            .map_err(|_| QuantityError::Overflow)
216    }
217
218    /// Reads a decimal and fails with `Inexact` if digits beyond the scale
219    /// are not all zero; nothing is rounded.
220    ///
221    /// ```
222    /// use renox::quantity::{Quantity, QuantityError};
223    ///
224    /// assert_eq!(Quantity::<3>::parse_exact("12.50").unwrap().raw(), 12_500);
225    /// assert_eq!(Quantity::<3>::parse_exact("1.2000").unwrap().raw(), 1_200);
226    /// assert_eq!(Quantity::<3>::parse_exact("1.0001").unwrap_err(), QuantityError::Inexact);
227    /// ```
228    pub fn parse_exact(text: &str) -> Result<Self, QuantityError> {
229        let down = Self::parse(text, Rounding::Down)?;
230        let up = Self::parse(text, Rounding::Up)?;
231        if down == up {
232            Ok(down)
233        } else {
234            Err(QuantityError::Inexact)
235        }
236    }
237
238    /// Like [`Quantity::parse`] with `HalfEven` (banker's rounding). It is
239    /// a convenience, not a default: `parse` always asks for a rounding.
240    ///
241    /// ```
242    /// use renox::quantity::Quantity;
243    ///
244    /// assert_eq!(Quantity::<0>::parse_half_even("2.5").unwrap().raw(), 2);
245    /// assert_eq!(Quantity::<0>::parse_half_even("3.5").unwrap().raw(), 4);
246    /// ```
247    pub fn parse_half_even(text: &str) -> Result<Self, QuantityError> {
248        Self::parse(text, Rounding::HalfEven)
249    }
250
251    /// The sum, or `Overflow` past the `i64` limits.
252    ///
253    /// ```
254    /// use renox::quantity::Quantity;
255    ///
256    /// let one = Quantity::<3>::from_raw(1000);
257    /// assert_eq!(one.checked_add(one).unwrap().raw(), 2000);
258    /// assert!(Quantity::<3>::from_raw(i64::MAX).checked_add(one).is_err());
259    /// ```
260    pub fn checked_add(self, other: Self) -> Result<Self, QuantityError> {
261        self.0
262            .checked_add(other.0)
263            .map(Quantity)
264            .ok_or(QuantityError::Overflow)
265    }
266
267    /// The difference, or `Overflow` past the `i64` limits.
268    ///
269    /// ```
270    /// use renox::quantity::Quantity;
271    ///
272    /// let one = Quantity::<3>::from_raw(1000);
273    /// assert_eq!(one.checked_sub(Quantity::from_raw(1500)).unwrap().raw(), -500);
274    /// ```
275    pub fn checked_sub(self, other: Self) -> Result<Self, QuantityError> {
276        self.0
277            .checked_sub(other.0)
278            .map(Quantity)
279            .ok_or(QuantityError::Overflow)
280    }
281
282    /// The negated quantity, or `Overflow` for the smallest `i64`.
283    ///
284    /// ```
285    /// use renox::quantity::Quantity;
286    ///
287    /// assert_eq!(Quantity::<3>::from_raw(5).checked_neg().unwrap().raw(), -5);
288    /// assert!(Quantity::<3>::from_raw(i64::MIN).checked_neg().is_err());
289    /// ```
290    pub fn checked_neg(self) -> Result<Self, QuantityError> {
291        self.0
292            .checked_neg()
293            .map(Quantity)
294            .ok_or(QuantityError::Overflow)
295    }
296
297    /// The quantity times `num / den`, rounded to the scale with
298    /// `rounding`. A zero `den` is `DivisionByZero`.
299    ///
300    /// ```
301    /// use renox::money::Rounding;
302    /// use renox::quantity::Quantity;
303    ///
304    /// let q = Quantity::<3>::from_raw(1000);
305    /// assert_eq!(q.mul_ratio(1, 3, Rounding::Down).unwrap().raw(), 333);
306    /// assert_eq!(q.mul_ratio(1, 3, Rounding::Up).unwrap().raw(), 334);
307    /// ```
308    pub fn mul_ratio(self, num: i64, den: i64, rounding: Rounding) -> Result<Self, QuantityError> {
309        if den == 0 {
310            return Err(QuantityError::DivisionByZero);
311        }
312        let n = self.0 as i128 * num as i128;
313        i64::try_from(div_round(n, den as i128, rounding))
314            .map(Quantity)
315            .map_err(|_| QuantityError::Overflow)
316    }
317
318    /// The quantity times an exact decimal factor such as `"1.15"`,
319    /// rounded with `rounding`. The factor has at most 18 decimals and no
320    /// exponent; anything else is `Invalid`.
321    ///
322    /// ```
323    /// use renox::money::Rounding;
324    /// use renox::quantity::Quantity;
325    ///
326    /// let q = Quantity::<3>::from_raw(2000);
327    /// assert_eq!(q.mul_decimal("1.15", Rounding::HalfUp).unwrap().raw(), 2300);
328    /// assert_eq!(q.mul_decimal("-0.0005", Rounding::HalfUp).unwrap().raw(), -1);
329    /// assert!(q.mul_decimal("1e3", Rounding::HalfUp).is_err());
330    /// ```
331    pub fn mul_decimal(self, factor: &str, rounding: Rounding) -> Result<Self, QuantityError> {
332        let bad = || QuantityError::Invalid(factor.to_string());
333        let (negative, whole, fraction) = split_decimal(factor).ok_or_else(bad)?;
334        if fraction.len() > 18 {
335            return Err(bad());
336        }
337        let magnitude: i128 = format!("{whole}{fraction}")
338            .parse()
339            .map_err(|_| QuantityError::Overflow)?;
340        let num = if negative { -magnitude } else { magnitude };
341        let den = 10i128.pow(fraction.len() as u32);
342        let n = (self.0 as i128)
343            .checked_mul(num)
344            .ok_or(QuantityError::Overflow)?;
345        i64::try_from(div_round(n, den, rounding))
346            .map(Quantity)
347            .map_err(|_| QuantityError::Overflow)
348    }
349
350    /// The same value at another scale. Going to a finer scale is exact
351    /// (or `Overflow`); going coarser rounds with `rounding`.
352    ///
353    /// ```
354    /// use renox::money::Rounding;
355    /// use renox::quantity::Quantity;
356    ///
357    /// let q = Quantity::<3>::from_raw(2505);
358    /// assert_eq!(q.rescale::<2>(Rounding::HalfUp).unwrap().raw(), 251);
359    /// assert_eq!(q.rescale::<2>(Rounding::Down).unwrap().raw(), 250);
360    /// assert_eq!(q.rescale::<4>(Rounding::Down).unwrap().raw(), 25_050);
361    /// ```
362    pub fn rescale<const TO: u32>(self, rounding: Rounding) -> Result<Quantity<TO>, QuantityError> {
363        let () = Quantity::<TO>::VALID;
364        let raw = if TO >= SCALE {
365            (self.0 as i128) * 10i128.pow(TO - SCALE)
366        } else {
367            div_round(self.0 as i128, 10i128.pow(SCALE - TO), rounding)
368        };
369        i64::try_from(raw)
370            .map(Quantity)
371            .map_err(|_| QuantityError::Overflow)
372    }
373}
374
375impl<const SCALE: u32> fmt::Display for Quantity<SCALE> {
376    /// The exact decimal with all `SCALE` digits (`2.500`), `.` as the
377    /// decimal point and no grouping.
378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379        let scale = SCALE as usize;
380        let digits = format!("{:0>width$}", self.0.unsigned_abs(), width = scale + 1);
381        let (whole, fraction) = digits.split_at(digits.len() - scale);
382        let sign = if self.0 < 0 { "-" } else { "" };
383        if scale == 0 {
384            write!(f, "{sign}{whole}")
385        } else {
386            write!(f, "{sign}{whole}.{fraction}")
387        }
388    }
389}
390
391impl<const SCALE: u32> serde::Serialize for Quantity<SCALE> {
392    /// A decimal string such as `"2.500"`, so JSON never loses precision.
393    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
394        serializer.collect_str(self)
395    }
396}
397
398impl<'de, const SCALE: u32> serde::Deserialize<'de> for Quantity<SCALE> {
399    /// Accepts a decimal string, or a JSON number when it is exactly
400    /// representable at the scale (its shortest decimal form is read).
401    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
402        struct V<const S: u32>;
403        impl<const S: u32> serde::de::Visitor<'_> for V<S> {
404            type Value = Quantity<S>;
405
406            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
407                f.write_str("a decimal quantity as a string or an exact number")
408            }
409
410            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
411                Quantity::<S>::parse_exact(v).map_err(E::custom)
412            }
413
414            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Self::Value, E> {
415                Quantity::<S>::parse_exact(&v.to_string()).map_err(E::custom)
416            }
417
418            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Self::Value, E> {
419                Quantity::<S>::parse_exact(&v.to_string()).map_err(E::custom)
420            }
421
422            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Self::Value, E> {
423                if !v.is_finite() {
424                    return Err(E::custom(QuantityError::Invalid(v.to_string())));
425                }
426                Quantity::<S>::parse_exact(&format!("{v}")).map_err(E::custom)
427            }
428        }
429        deserializer.deserialize_any(V::<SCALE>)
430    }
431}
432
433/// How one unit relates to its base: 1 unit = `num / den` of the base.
434#[derive(Debug, Clone, PartialEq, Eq)]
435struct UnitDef {
436    base: String,
437    num: i128,
438    den: i128,
439}
440
441fn gcd(a: i128, b: i128) -> i128 {
442    if b == 0 { a } else { gcd(b, a % b) }
443}
444
445/// Parses a positive exact decimal factor into a reduced fraction.
446fn parse_factor(text: &str) -> Result<(i128, i128), QuantityError> {
447    let bad = || QuantityError::InvalidUnits(format!("`{text}` is not a positive decimal factor"));
448    let (negative, whole, fraction) = split_decimal(text).ok_or_else(bad)?;
449    if negative || fraction.len() > 18 {
450        return Err(bad());
451    }
452    let num: i128 = format!("{whole}{fraction}").parse().map_err(|_| bad())?;
453    if num == 0 {
454        return Err(bad());
455    }
456    let den = 10i128.pow(fraction.len() as u32);
457    let g = gcd(num, den);
458    Ok((num / g, den / g))
459}
460
461/// Builder for a unit conversion table, from strings with exact decimal
462/// factors (never floats). Every unit points at a base unit:
463/// `.unit("g", "kg", "0.001")` says 1 g is 0.001 kg. Units chain only
464/// through the base (one level). [`Units::build`] checks the table and
465/// returns a [`UnitTable`]; conversion takes an explicit [`Rounding`].
466///
467/// ```
468/// use renox::money::Rounding;
469/// use renox::quantity::{Quantity, Units};
470///
471/// let units = Units::new()
472///     .base("kg")
473///     .unit("g", "kg", "0.001")
474///     .unit("t", "kg", "1000")
475///     .build()
476///     .unwrap();
477/// let kg = Quantity::<3>::parse_exact("2.5").unwrap();
478/// let g = units.convert(kg, "kg", "g", Rounding::HalfUp).unwrap();
479/// assert_eq!(g.to_string(), "2500.000");
480/// let grams = Quantity::<3>::parse_exact("1500").unwrap();
481/// let back = units.convert(grams, "g", "kg", Rounding::HalfUp).unwrap();
482/// assert_eq!(back.to_string(), "1.500");
483/// ```
484#[derive(Debug, Clone, Default)]
485pub struct Units {
486    /// Declarations in order: (code, base code or `None` for a base, factor text).
487    declared: Vec<(String, Option<String>, String)>,
488}
489
490/// A checked unit table, ready to convert. Built with [`Units::build`];
491/// plain data, `Clone` and `Debug`.
492#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct UnitTable {
494    defs: BTreeMap<String, UnitDef>,
495}
496
497impl Units {
498    /// An empty table.
499    pub fn new() -> Self {
500        Units::default()
501    }
502
503    /// Declares a base unit (`"kg"`), the unit others are expressed in.
504    pub fn base(mut self, code: &str) -> Self {
505        self.declared.push((code.to_string(), None, String::new()));
506        self
507    }
508
509    /// Declares `code` as `factor` units of the base `base`: 1 `code` =
510    /// `factor` `base`. The factor is an exact positive decimal.
511    pub fn unit(mut self, code: &str, base: &str, factor: &str) -> Self {
512        self.declared
513            .push((code.to_string(), Some(base.to_string()), factor.to_string()));
514        self
515    }
516
517    /// Checks the table and returns it ready to convert. It fails with
518    /// `InvalidUnits` on an empty or duplicate code, a factor that is
519    /// zero, negative or malformed, and a unit whose base is missing or
520    /// is not itself a base. Declaration order does not matter.
521    ///
522    /// ```
523    /// use renox::quantity::Units;
524    ///
525    /// assert!(Units::new().base("kg").unit("g", "kg", "0.001").build().is_ok());
526    /// assert!(Units::new().base("kg").unit("g", "kg", "0").build().is_err());
527    /// let chained = Units::new().base("kg").unit("g", "kg", "0.001").unit("mg", "g", "0.001");
528    /// assert!(chained.build().is_err());
529    /// ```
530    pub fn build(self) -> Result<UnitTable, QuantityError> {
531        let fail = |why: String| Err(QuantityError::InvalidUnits(why));
532        let mut defs: BTreeMap<String, UnitDef> = BTreeMap::new();
533        for (code, base, factor) in &self.declared {
534            if code.trim().is_empty() {
535                return fail("a unit code is empty".into());
536            }
537            if defs.contains_key(code) {
538                return fail(format!("`{code}` is declared twice"));
539            }
540            let def = match base {
541                None => UnitDef {
542                    base: code.clone(),
543                    num: 1,
544                    den: 1,
545                },
546                Some(base) => {
547                    let (num, den) = parse_factor(factor)?;
548                    UnitDef {
549                        base: base.clone(),
550                        num,
551                        den,
552                    }
553                }
554            };
555            defs.insert(code.clone(), def);
556        }
557        for (code, def) in &defs {
558            match defs.get(&def.base) {
559                None => return fail(format!("`{code}` points at unknown base `{}`", def.base)),
560                Some(target) if target.base != def.base => {
561                    return fail(format!(
562                        "`{code}` points at `{}`, which is not a base",
563                        def.base
564                    ));
565                }
566                Some(_) => {}
567            }
568        }
569        Ok(UnitTable { defs })
570    }
571}
572
573impl UnitTable {
574    /// Whether `code` is a unit of this table.
575    ///
576    /// ```
577    /// use renox::quantity::Units;
578    ///
579    /// let t = Units::new().base("kg").unit("g", "kg", "0.001").build().unwrap();
580    /// assert!(t.contains("g"));
581    /// assert!(!t.contains("lb"));
582    /// ```
583    pub fn contains(&self, code: &str) -> bool {
584        self.defs.contains_key(code)
585    }
586
587    /// Converts `q` from unit `from` to unit `to` at the same scale,
588    /// rounding with `rounding` when digits are lost. An unknown unit is
589    /// `UnknownUnit`, units of different bases are `IncompatibleUnits`,
590    /// a result that does not fit is `Overflow`.
591    ///
592    /// ```
593    /// use renox::money::Rounding;
594    /// use renox::quantity::{Quantity, QuantityError, Units};
595    ///
596    /// let t = Units::new()
597    ///     .base("kg")
598    ///     .unit("g", "kg", "0.001")
599    ///     .base("m")
600    ///     .build()
601    ///     .unwrap();
602    /// let q = Quantity::<3>::from_raw(1);
603    /// assert_eq!(t.convert(q, "g", "kg", Rounding::Down).unwrap().raw(), 0);
604    /// assert_eq!(t.convert(q, "g", "kg", Rounding::Up).unwrap().raw(), 1);
605    /// assert!(matches!(
606    ///     t.convert(q, "kg", "m", Rounding::Up),
607    ///     Err(QuantityError::IncompatibleUnits { .. })
608    /// ));
609    /// assert!(matches!(
610    ///     t.convert(q, "kg", "lb", Rounding::Up),
611    ///     Err(QuantityError::UnknownUnit(_))
612    /// ));
613    /// ```
614    pub fn convert<const SCALE: u32>(
615        &self,
616        q: Quantity<SCALE>,
617        from: &str,
618        to: &str,
619        rounding: Rounding,
620    ) -> Result<Quantity<SCALE>, QuantityError> {
621        let unknown = |c: &str| QuantityError::UnknownUnit(c.to_string());
622        let f = self.defs.get(from).ok_or_else(|| unknown(from))?;
623        let t = self.defs.get(to).ok_or_else(|| unknown(to))?;
624        if f.base != t.base {
625            return Err(QuantityError::IncompatibleUnits {
626                from: from.to_string(),
627                to: to.to_string(),
628            });
629        }
630        // value * (f.num / f.den) / (t.num / t.den)
631        let num = (q.raw() as i128)
632            .checked_mul(f.num)
633            .and_then(|n| n.checked_mul(t.den))
634            .ok_or(QuantityError::Overflow)?;
635        let den = f.den.checked_mul(t.num).ok_or(QuantityError::Overflow)?;
636        i64::try_from(div_round(num, den, rounding))
637            .map(Quantity::from_raw)
638            .map_err(|_| QuantityError::Overflow)
639    }
640}