lib

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

amount.rs (9414B)


      1 use radroots_domain::{AmountError, Decimal, PositiveDecimal};
      2 use std::{
      3     collections::hash_map::DefaultHasher,
      4     hash::{Hash, Hasher},
      5 };
      6 
      7 fn decimal(input: &str) -> Decimal {
      8     input.parse().unwrap()
      9 }
     10 
     11 #[test]
     12 fn canonical_hand_vectors_round_trip_without_float_conversion() {
     13     for (text, coefficient, scale) in [
     14         ("0", 0, 0),
     15         ("1", 1, 0),
     16         ("0.000001", 1, 6),
     17         ("999999999999", 999_999_999_999, 0),
     18         ("999999.999999", 999_999_999_999, 6),
     19         ("12.345", 12_345, 3),
     20         ("0.01", 1, 2),
     21     ] {
     22         let value = decimal(text);
     23         assert_eq!(value.coefficient(), coefficient, "{text}");
     24         assert_eq!(value.scale(), scale, "{text}");
     25         assert_eq!(value.to_string(), text);
     26         assert_eq!(Decimal::from_parts(coefficient, scale).unwrap(), value);
     27     }
     28     assert_eq!(Decimal::MAX, decimal("999999999999"));
     29     assert_eq!(Decimal::ONE, decimal("1"));
     30 }
     31 
     32 #[test]
     33 fn construction_normalizes_fractional_zeros_and_zero() {
     34     for scale in 0..=Decimal::MAX_SCALE {
     35         assert_eq!(Decimal::from_parts(0, scale).unwrap(), Decimal::ZERO);
     36     }
     37     assert_eq!(Decimal::from_parts(123_000, 4).unwrap(), decimal("12.3"));
     38     assert_eq!(Decimal::from_parts(100_000, 5).unwrap(), Decimal::ONE);
     39     assert_eq!(Decimal::from_parts(120, 0).unwrap().coefficient(), 120);
     40 }
     41 
     42 #[test]
     43 fn constructor_checks_both_input_bounds_before_normalization() {
     44     assert_eq!(
     45         Decimal::from_parts(1_000_000_000_000, 1),
     46         Err(AmountError::CoefficientOutOfRange)
     47     );
     48     assert_eq!(
     49         Decimal::from_parts(u64::MAX, 0),
     50         Err(AmountError::CoefficientOutOfRange)
     51     );
     52     assert_eq!(Decimal::from_parts(0, 7), Err(AmountError::ScaleOutOfRange));
     53     assert_eq!(
     54         Decimal::from_parts(1, u8::MAX),
     55         Err(AmountError::ScaleOutOfRange)
     56     );
     57 }
     58 
     59 #[test]
     60 fn strings_require_canonical_unsigned_ascii_spelling() {
     61     for input in [
     62         "", "-0", "-1", "+1", ".1", "1.", "1..2", "1e2", "1E2", " 1", "1 ", "1\n", "1\t", "1,000",
     63         "1_000", "1", "١", "NaN", "Infinity",
     64     ] {
     65         assert!(input.parse::<Decimal>().is_err(), "{input:?}");
     66     }
     67     for input in ["00", "01", "00.1", "0.0", "1.0", "1.2300", "0.000000"] {
     68         assert_eq!(
     69             input.parse::<Decimal>(),
     70             Err(AmountError::NonCanonical),
     71             "{input}"
     72         );
     73     }
     74 }
     75 
     76 #[test]
     77 fn combined_coefficient_and_scale_are_semantic_admission_bounds() {
     78     // These fit the syntax's integer/fraction widths but exceed the combined bound.
     79     for input in ["999999999999.1", "9999999.999999", "1000000000000"] {
     80         assert_eq!(
     81             input.parse::<Decimal>(),
     82             Err(AmountError::CoefficientOutOfRange),
     83             "{input}"
     84         );
     85     }
     86     assert_eq!(
     87         "0.0000001".parse::<Decimal>(),
     88         Err(AmountError::ScaleOutOfRange)
     89     );
     90 }
     91 
     92 #[test]
     93 fn overlong_inputs_fail_with_constant_redacted_diagnostics() {
     94     let input = "sensitive_fixture_".repeat(4096);
     95     let error = input.parse::<Decimal>().unwrap_err();
     96     assert_eq!(error, AmountError::InvalidFormat);
     97     assert_eq!(error.to_string(), "invalid decimal format");
     98     assert!(!format!("{error:?}").contains("sensitive_fixture"));
     99     assert_eq!(
    100         "9".repeat(Decimal::MAX_ENCODED_LEN + 1).parse::<Decimal>(),
    101         Err(AmountError::InvalidFormat)
    102     );
    103 }
    104 
    105 #[test]
    106 fn positivity_cannot_be_bypassed_by_construction_or_parsing() {
    107     assert_eq!(
    108         PositiveDecimal::new(Decimal::ZERO),
    109         Err(AmountError::MustBePositive)
    110     );
    111     assert_eq!(
    112         PositiveDecimal::try_from(Decimal::ZERO),
    113         Err(AmountError::MustBePositive)
    114     );
    115     assert_eq!(
    116         "0".parse::<PositiveDecimal>(),
    117         Err(AmountError::MustBePositive)
    118     );
    119     assert!("-1".parse::<PositiveDecimal>().is_err());
    120     for text in ["0.000001", "1", "999999999999"] {
    121         let positive: PositiveDecimal = text.parse().unwrap();
    122         assert_eq!(positive.amount(), decimal(text));
    123         assert_eq!(Decimal::from(positive), decimal(text));
    124         assert_eq!(positive.to_string(), text);
    125     }
    126 }
    127 
    128 #[test]
    129 fn ordering_is_numeric_across_scales_and_hashing_uses_canonical_parts() {
    130     let ascending = [
    131         "0",
    132         "0.000001",
    133         "0.1",
    134         "0.99",
    135         "1",
    136         "1.01",
    137         "2",
    138         "10",
    139         "999999999999",
    140     ];
    141     for pair in ascending.windows(2) {
    142         assert!(decimal(pair[0]) < decimal(pair[1]));
    143         assert!(decimal(pair[1]) > decimal(pair[0]));
    144     }
    145     let canonical = decimal("1.23");
    146     let normalized = Decimal::from_parts(123_000, 5).unwrap();
    147     assert_eq!(canonical, normalized);
    148     assert_eq!(
    149         canonical.partial_cmp(&normalized),
    150         Some(core::cmp::Ordering::Equal)
    151     );
    152     let hash = |v: Decimal| {
    153         let mut h = DefaultHasher::new();
    154         v.hash(&mut h);
    155         h.finish()
    156     };
    157     assert_eq!(hash(canonical), hash(normalized));
    158     assert!("0.1".parse::<PositiveDecimal>().unwrap() < "1".parse().unwrap());
    159 }
    160 
    161 #[test]
    162 fn addition_and_subtraction_preserve_exact_results_across_scales() {
    163     for (left, right, sum) in [
    164         ("0.1", "0.2", "0.3"),
    165         ("1", "0.000001", "1.000001"),
    166         ("999999999998", "1", "999999999999"),
    167         ("0.999999", "0.000001", "1"),
    168         ("50000000000", "50000000000", "100000000000"),
    169         ("0", "1.23", "1.23"),
    170     ] {
    171         let (left, right, sum) = (decimal(left), decimal(right), decimal(sum));
    172         assert_eq!(left.checked_add(right).unwrap(), sum);
    173         assert_eq!(right.checked_add(left).unwrap(), sum);
    174         assert_eq!(sum.checked_sub(left).unwrap(), right);
    175         assert_eq!(sum.checked_sub(right).unwrap(), left);
    176     }
    177     assert_eq!(Decimal::MAX.checked_sub(Decimal::MAX), Ok(Decimal::ZERO));
    178 }
    179 
    180 #[test]
    181 fn arithmetic_rejects_negative_or_unrepresentable_results_without_rounding() {
    182     assert_eq!(
    183         Decimal::ZERO.checked_sub(Decimal::ONE),
    184         Err(AmountError::NegativeResult)
    185     );
    186     assert_eq!(
    187         Decimal::MAX.checked_add(Decimal::ONE),
    188         Err(AmountError::CoefficientOutOfRange)
    189     );
    190     assert_eq!(
    191         Decimal::MAX.checked_add(decimal("0.000001")),
    192         Err(AmountError::CoefficientOutOfRange)
    193     );
    194     assert_eq!(
    195         Decimal::MAX.checked_sub(decimal("0.000001")),
    196         Err(AmountError::CoefficientOutOfRange)
    197     );
    198     assert_eq!(
    199         decimal("999999999998").checked_sub(Decimal::MAX),
    200         Err(AmountError::NegativeResult)
    201     );
    202 }
    203 
    204 #[test]
    205 fn bounded_small_grid_matches_independent_integer_micro_units() {
    206     // Independent integer oracle in millionths; no production parsing/arithmetic helpers.
    207     for left in 0..=20_u64 {
    208         for right in 0..=20_u64 {
    209             for scale in 0..=6_u8 {
    210                 let a = Decimal::from_parts(left, scale).unwrap();
    211                 let b = Decimal::from_parts(right, 6 - scale).unwrap();
    212                 let expected =
    213                     left * 10_u64.pow(u32::from(6 - scale)) + right * 10_u64.pow(u32::from(scale));
    214                 let sum = a.checked_add(b).unwrap();
    215                 assert_eq!(
    216                     sum.coefficient() * 10_u64.pow(u32::from(6 - sum.scale())),
    217                     expected
    218                 );
    219                 assert_eq!(sum.checked_sub(a).unwrap(), b);
    220             }
    221         }
    222     }
    223 }
    224 
    225 #[test]
    226 fn all_error_messages_are_static_bounded_and_distinct() {
    227     let errors = [
    228         AmountError::InvalidFormat,
    229         AmountError::NonCanonical,
    230         AmountError::CoefficientOutOfRange,
    231         AmountError::ScaleOutOfRange,
    232         AmountError::MustBePositive,
    233         AmountError::NegativeResult,
    234     ];
    235     let messages = errors.map(|e| e.to_string());
    236     for (i, message) in messages.iter().enumerate() {
    237         assert!(!message.is_empty() && message.len() <= 64);
    238         assert!(!messages[..i].contains(message));
    239     }
    240 }
    241 
    242 #[cfg(feature = "serde")]
    243 mod json {
    244     use super::*;
    245 
    246     #[test]
    247     fn decimal_and_positive_values_round_trip_only_as_canonical_strings() {
    248         for text in ["0", "0.000001", "999999999999", "999999.999999"] {
    249             let value = decimal(text);
    250             let encoded = serde_json::to_string(&value).unwrap();
    251             assert_eq!(encoded, format!("\"{text}\""));
    252             assert_eq!(serde_json::from_str::<Decimal>(&encoded).unwrap(), value);
    253             if !value.is_zero() {
    254                 let positive = PositiveDecimal::new(value).unwrap();
    255                 assert_eq!(serde_json::to_string(&positive).unwrap(), encoded);
    256                 assert_eq!(
    257                     serde_json::from_str::<PositiveDecimal>(&encoded).unwrap(),
    258                     positive
    259                 );
    260             }
    261         }
    262     }
    263 
    264     #[test]
    265     fn numbers_objects_and_noncanonical_values_cannot_bypass_admission() {
    266         for input in [
    267             "1",
    268             "1.5",
    269             "null",
    270             "true",
    271             "[]",
    272             "{}",
    273             "{\"coefficient\":1,\"scale\":0}",
    274             "\"-0\"",
    275             "\"01\"",
    276             "\"1.0\"",
    277             "\"1e2\"",
    278             "\"999999999999.1\"",
    279             "\"0.0000001\"",
    280         ] {
    281             assert!(serde_json::from_str::<Decimal>(input).is_err(), "{input}");
    282             assert!(
    283                 serde_json::from_str::<PositiveDecimal>(input).is_err(),
    284                 "{input}"
    285             );
    286         }
    287         assert!(serde_json::from_str::<PositiveDecimal>("\"0\"").is_err());
    288     }
    289 }