lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

quantity.rs (7229B)


      1 use radroots_domain::listing::MeasurementUnit::{self, Each, Gram, Kilogram, Litre, Millilitre};
      2 use radroots_domain::{AmountError, ContentMeasure, Decimal, Quantity, QuantityError};
      3 use std::error::Error;
      4 
      5 fn quantity(amount: &str, unit: MeasurementUnit) -> Quantity {
      6     Quantity::new(amount.parse().unwrap(), unit).unwrap()
      7 }
      8 
      9 #[test]
     10 fn explicit_si_conversions_match_independent_canonical_examples_in_both_dimensions() {
     11     for (source, target) in [(Gram, Kilogram), (Millilitre, Litre)] {
     12         for (small, large) in [
     13             ("0", "0"),
     14             ("1", "0.001"),
     15             ("1000", "1"),
     16             ("1250", "1.25"),
     17             ("0.001", "0.000001"),
     18             ("999999999999", "999999999.999"),
     19         ] {
     20             let small = quantity(small, source);
     21             let large = quantity(large, target);
     22             assert_eq!(small.convert(target).unwrap(), large);
     23             assert_eq!(large.convert(source).unwrap(), small);
     24             assert_eq!(small.convert(source).unwrap(), small);
     25             assert_eq!(large.convert(target).unwrap(), large);
     26         }
     27     }
     28     assert_eq!(
     29         quantity("0.000001", Kilogram).convert(Gram).unwrap(),
     30         quantity("0.001", Gram)
     31     );
     32     assert_eq!(
     33         quantity("0.000001", Litre).convert(Millilitre).unwrap(),
     34         quantity("0.001", Millilitre)
     35     );
     36 }
     37 
     38 #[test]
     39 fn exact_conversions_refuse_rounding_and_normalized_amount_overflow() {
     40     for (source, target) in [(Gram, Kilogram), (Millilitre, Litre)] {
     41         for amount in ["0.000001", "0.00001", "0.0001", "1.000001"] {
     42             assert_eq!(
     43                 quantity(amount, source).convert(target),
     44                 Err(QuantityError::PrecisionLoss)
     45             );
     46         }
     47         assert_eq!(
     48             quantity("999999999999", target).convert(source),
     49             Err(QuantityError::Amount(AmountError::CoefficientOutOfRange))
     50         );
     51         // The exact largest output remains representable after conversion.
     52         assert_eq!(
     53             quantity("999999999.999", target)
     54                 .convert(source)
     55                 .unwrap()
     56                 .amount(),
     57             Decimal::MAX
     58         );
     59     }
     60 }
     61 
     62 #[test]
     63 fn every_unit_pair_preserves_explicit_dimensions_even_for_zero() {
     64     let units = [Gram, Kilogram, Millilitre, Litre, Each];
     65     for source in units {
     66         for target in units {
     67             let compatible = source == target
     68                 || matches!(
     69                     (source, target),
     70                     (Gram, Kilogram) | (Kilogram, Gram) | (Millilitre, Litre) | (Litre, Millilitre)
     71                 );
     72             for amount in ["0", "1"] {
     73                 let result = quantity(amount, source).convert(target);
     74                 if compatible {
     75                     let converted = result.unwrap();
     76                     assert_eq!(converted.unit(), target);
     77                     assert_eq!(converted.convert(source).unwrap(), quantity(amount, source));
     78                 } else {
     79                     assert_eq!(result, Err(QuantityError::IncompatibleDimension));
     80                 }
     81             }
     82         }
     83     }
     84 }
     85 
     86 #[test]
     87 fn each_counts_use_semantic_normalization_but_cannot_be_fractional() {
     88     for amount in ["0", "1", "999999999999"] {
     89         let value = quantity(amount, Each);
     90         assert_eq!(value.amount().to_string(), amount);
     91         assert_eq!(value.unit(), Each);
     92     }
     93     assert_eq!(
     94         Quantity::new(Decimal::from_parts(10, 1).unwrap(), Each).unwrap(),
     95         quantity("1", Each)
     96     );
     97     for amount in ["0.000001", "0.5", "1.5"] {
     98         assert_eq!(
     99             Quantity::new(amount.parse().unwrap(), Each),
    100             Err(QuantityError::FractionalCount)
    101         );
    102         for unit in [Gram, Kilogram, Millilitre, Litre] {
    103             assert!(Quantity::new(amount.parse().unwrap(), unit).is_ok());
    104         }
    105     }
    106 }
    107 
    108 #[test]
    109 fn arithmetic_requires_matching_units_and_keeps_decimal_bounds_exact() {
    110     let one = quantity("1", Kilogram);
    111     let quarter = quantity("250", Gram);
    112     assert_eq!(one.checked_add(quarter), Err(QuantityError::UnitMismatch));
    113     assert_eq!(one.checked_sub(quarter), Err(QuantityError::UnitMismatch));
    114     let quarter = quarter.convert(Kilogram).unwrap();
    115     assert_eq!(
    116         one.checked_add(quarter).unwrap(),
    117         quantity("1.25", Kilogram)
    118     );
    119     assert_eq!(
    120         one.checked_sub(quarter).unwrap(),
    121         quantity("0.75", Kilogram)
    122     );
    123     assert_eq!(one.checked_sub(one).unwrap(), quantity("0", Kilogram));
    124     assert_eq!(
    125         quarter.checked_sub(one),
    126         Err(QuantityError::Amount(AmountError::NegativeResult))
    127     );
    128     assert_eq!(
    129         quantity("999999999999", Each).checked_add(quantity("1", Each)),
    130         Err(QuantityError::Amount(AmountError::CoefficientOutOfRange))
    131     );
    132 }
    133 
    134 #[test]
    135 fn fixed_estimated_and_unspecified_contents_never_collapse_into_one_claim() {
    136     let amount = quantity("1.25", Kilogram);
    137     let fixed = ContentMeasure::Fixed { quantity: amount };
    138     let estimated = ContentMeasure::Estimated { quantity: amount };
    139     assert_ne!(fixed, estimated);
    140     assert_eq!(fixed.fixed_quantity(), Some(amount));
    141     assert_eq!(estimated.fixed_quantity(), None);
    142     assert_eq!(ContentMeasure::Unspecified.fixed_quantity(), None);
    143     let explicit_zero = ContentMeasure::Fixed {
    144         quantity: quantity("0", Gram),
    145     };
    146     assert_ne!(explicit_zero, ContentMeasure::Unspecified);
    147 }
    148 
    149 #[test]
    150 fn diagnostics_redact_physical_values_and_preserve_typed_fixed_failures() {
    151     let value = quantity("928174615", Kilogram);
    152     for debug in [
    153         format!("{value:?}"),
    154         format!("{:?}", ContentMeasure::Fixed { quantity: value }),
    155         format!("{:?}", ContentMeasure::Estimated { quantity: value }),
    156     ] {
    157         assert!(!debug.contains("928174615"));
    158         assert!(!debug.contains("Kilogram"));
    159     }
    160     for error in [
    161         QuantityError::FractionalCount,
    162         QuantityError::UnitMismatch,
    163         QuantityError::IncompatibleDimension,
    164         QuantityError::PrecisionLoss,
    165         QuantityError::ArithmeticOutOfRange,
    166         AmountError::CoefficientOutOfRange.into(),
    167     ] {
    168         assert!(!error.to_string().is_empty());
    169         assert!(!error.to_string().contains("928174615"));
    170     }
    171     assert!(QuantityError::PrecisionLoss.source().is_none());
    172     assert!(
    173         QuantityError::Amount(AmountError::NegativeResult)
    174             .source()
    175             .is_some()
    176     );
    177 }
    178 
    179 #[cfg(feature = "serde")]
    180 #[test]
    181 fn serialization_preserves_exact_strings_units_and_explicit_content_alternatives() {
    182     let value = quantity("0.000001", Kilogram);
    183     assert_eq!(
    184         serde_json::to_value(value).unwrap(),
    185         serde_json::json!({"amount":"0.000001","unit":"kg"})
    186     );
    187     assert_eq!(
    188         serde_json::to_value(ContentMeasure::Fixed { quantity: value }).unwrap(),
    189         serde_json::json!({"type":"fixed","quantity":{"amount":"0.000001","unit":"kg"}})
    190     );
    191     assert_eq!(
    192         serde_json::to_value(ContentMeasure::Estimated { quantity: value }).unwrap(),
    193         serde_json::json!({"type":"estimated","quantity":{"amount":"0.000001","unit":"kg"}})
    194     );
    195     assert_eq!(
    196         serde_json::to_value(ContentMeasure::Unspecified).unwrap(),
    197         serde_json::json!({"type":"unspecified"})
    198     );
    199 }