lib

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

amount.rs (9624B)


      1 use core::{cmp::Ordering, fmt, str::FromStr};
      2 
      3 /// A validated, canonical, nonnegative decimal with no floating representation.
      4 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
      5 pub struct Decimal {
      6     coefficient: u64,
      7     scale: u8,
      8 }
      9 
     10 /// A validated decimal strictly greater than zero.
     11 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
     12 pub struct PositiveDecimal(Decimal);
     13 
     14 /// A bounded value admission or exact-arithmetic failure; never contains input.
     15 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     16 #[non_exhaustive]
     17 pub enum AmountError {
     18     /// The input is not an unsigned ASCII decimal string.
     19     InvalidFormat,
     20     /// The spelling is not the canonical representation of its value.
     21     NonCanonical,
     22     /// The coefficient exceeds the supported twelve-digit bound.
     23     CoefficientOutOfRange,
     24     /// The scale exceeds six fractional digits.
     25     ScaleOutOfRange,
     26     /// A strictly positive amount was required.
     27     MustBePositive,
     28     /// Subtraction would produce a negative value.
     29     NegativeResult,
     30 }
     31 
     32 impl fmt::Display for AmountError {
     33     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     34         f.write_str(match self {
     35             Self::InvalidFormat => "invalid decimal format",
     36             Self::NonCanonical => "noncanonical decimal representation",
     37             Self::CoefficientOutOfRange => "decimal coefficient exceeds supported bound",
     38             Self::ScaleOutOfRange => "decimal scale exceeds supported bound",
     39             Self::MustBePositive => "decimal must be positive",
     40             Self::NegativeResult => "decimal subtraction would be negative",
     41         })
     42     }
     43 }
     44 
     45 impl core::error::Error for AmountError {}
     46 
     47 impl Decimal {
     48     /// Largest supported canonical coefficient.
     49     pub const MAX_COEFFICIENT: u64 = 999_999_999_999;
     50     /// Largest supported scale.
     51     pub const MAX_SCALE: u8 = 6;
     52     /// Maximum syntax length, checked before examining untrusted string contents.
     53     pub const MAX_ENCODED_LEN: usize = 19;
     54     /// Canonical zero.
     55     pub const ZERO: Self = Self {
     56         coefficient: 0,
     57         scale: 0,
     58     };
     59     /// Canonical one.
     60     pub const ONE: Self = Self {
     61         coefficient: 1,
     62         scale: 0,
     63     };
     64     /// Largest supported value.
     65     pub const MAX: Self = Self {
     66         coefficient: Self::MAX_COEFFICIENT,
     67         scale: 0,
     68     };
     69 
     70     /// Validates bounded input parts, then removes fractional trailing zeros.
     71     ///
     72     /// Both input bounds apply before normalization. Zero always has scale zero.
     73     pub const fn from_parts(coefficient: u64, scale: u8) -> Result<Self, AmountError> {
     74         if scale > Self::MAX_SCALE {
     75             return Err(AmountError::ScaleOutOfRange);
     76         }
     77         if coefficient > Self::MAX_COEFFICIENT {
     78             return Err(AmountError::CoefficientOutOfRange);
     79         }
     80         Ok(Self::normalized(coefficient, scale))
     81     }
     82 
     83     const fn normalized(mut coefficient: u64, mut scale: u8) -> Self {
     84         if coefficient == 0 {
     85             return Self::ZERO;
     86         }
     87         while scale > 0 && coefficient.is_multiple_of(10) {
     88             coefficient /= 10;
     89             scale -= 1;
     90         }
     91         Self { coefficient, scale }
     92     }
     93 
     94     /// The canonical coefficient, without an implicit unit or currency.
     95     pub const fn coefficient(self) -> u64 {
     96         self.coefficient
     97     }
     98     /// The canonical number of fractional decimal digits.
     99     pub const fn scale(self) -> u8 {
    100         self.scale
    101     }
    102     /// Whether this amount is exactly zero.
    103     pub const fn is_zero(self) -> bool {
    104         self.coefficient == 0
    105     }
    106 
    107     // Validated coefficients times at most 10^6 fit in u64, including the
    108     // addition of two such aligned values. These helpers never round.
    109     fn aligned(self, scale: u8) -> u64 {
    110         self.coefficient * 10_u64.pow(u32::from(scale - self.scale))
    111     }
    112 
    113     fn from_result(coefficient: u64, scale: u8) -> Result<Self, AmountError> {
    114         let value = Self::normalized(coefficient, scale);
    115         Self::from_parts(value.coefficient, value.scale)
    116     }
    117 
    118     /// Adds exactly, rejecting a result outside the canonical coefficient bound.
    119     pub fn checked_add(self, rhs: Self) -> Result<Self, AmountError> {
    120         let scale = self.scale.max(rhs.scale);
    121         let coefficient = self
    122             .aligned(scale)
    123             .checked_add(rhs.aligned(scale))
    124             .ok_or(AmountError::CoefficientOutOfRange)?;
    125         Self::from_result(coefficient, scale)
    126     }
    127 
    128     /// Subtracts exactly; negative or unrepresentable results are errors.
    129     pub fn checked_sub(self, rhs: Self) -> Result<Self, AmountError> {
    130         let scale = self.scale.max(rhs.scale);
    131         let coefficient = self
    132             .aligned(scale)
    133             .checked_sub(rhs.aligned(scale))
    134             .ok_or(AmountError::NegativeResult)?;
    135         Self::from_result(coefficient, scale)
    136     }
    137 }
    138 
    139 impl Ord for Decimal {
    140     fn cmp(&self, rhs: &Self) -> Ordering {
    141         let scale = self.scale.max(rhs.scale);
    142         self.aligned(scale).cmp(&rhs.aligned(scale))
    143     }
    144 }
    145 
    146 impl PartialOrd for Decimal {
    147     fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
    148         Some(self.cmp(rhs))
    149     }
    150 }
    151 
    152 impl FromStr for Decimal {
    153     type Err = AmountError;
    154 
    155     fn from_str(input: &str) -> Result<Self, Self::Err> {
    156         if input.is_empty() || input.len() > Self::MAX_ENCODED_LEN {
    157             return Err(AmountError::InvalidFormat);
    158         }
    159         let (whole, fraction) = match input.split_once('.') {
    160             Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction),
    161             Some(_) => return Err(AmountError::InvalidFormat),
    162             None => (input, ""),
    163         };
    164         if whole.is_empty()
    165             || !whole
    166                 .bytes()
    167                 .chain(fraction.bytes())
    168                 .all(|b| b.is_ascii_digit())
    169         {
    170             return Err(AmountError::InvalidFormat);
    171         }
    172         if (whole.len() > 1 && whole.starts_with('0')) || fraction.ends_with('0') {
    173             return Err(AmountError::NonCanonical);
    174         }
    175         if fraction.len() > usize::from(Self::MAX_SCALE) {
    176             return Err(AmountError::ScaleOutOfRange);
    177         }
    178         let mut coefficient = 0_u64;
    179         for digit in whole.bytes().chain(fraction.bytes()) {
    180             coefficient = coefficient
    181                 .checked_mul(10)
    182                 .and_then(|v| v.checked_add(u64::from(digit - b'0')))
    183                 .filter(|v| *v <= Self::MAX_COEFFICIENT)
    184                 .ok_or(AmountError::CoefficientOutOfRange)?;
    185         }
    186         // The length bound above proves conversion fits in u8.
    187         Self::from_parts(coefficient, fraction.len() as u8)
    188     }
    189 }
    190 
    191 impl fmt::Display for Decimal {
    192     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    193         if self.scale == 0 {
    194             return write!(f, "{}", self.coefficient);
    195         }
    196         let divisor = 10_u64.pow(u32::from(self.scale));
    197         write!(
    198             f,
    199             "{}.{:0width$}",
    200             self.coefficient / divisor,
    201             self.coefficient % divisor,
    202             width = usize::from(self.scale)
    203         )
    204     }
    205 }
    206 
    207 impl PositiveDecimal {
    208     /// Requires an already validated nonzero value.
    209     pub const fn new(value: Decimal) -> Result<Self, AmountError> {
    210         if value.is_zero() {
    211             Err(AmountError::MustBePositive)
    212         } else {
    213             Ok(Self(value))
    214         }
    215     }
    216     /// Returns the validated nonnegative representation without losing precision.
    217     pub const fn amount(self) -> Decimal {
    218         self.0
    219     }
    220 }
    221 
    222 impl TryFrom<Decimal> for PositiveDecimal {
    223     type Error = AmountError;
    224     fn try_from(value: Decimal) -> Result<Self, Self::Error> {
    225         Self::new(value)
    226     }
    227 }
    228 
    229 impl From<PositiveDecimal> for Decimal {
    230     fn from(value: PositiveDecimal) -> Self {
    231         value.amount()
    232     }
    233 }
    234 
    235 impl FromStr for PositiveDecimal {
    236     type Err = AmountError;
    237     fn from_str(input: &str) -> Result<Self, Self::Err> {
    238         Self::new(input.parse()?)
    239     }
    240 }
    241 
    242 impl fmt::Display for PositiveDecimal {
    243     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    244         self.0.fmt(f)
    245     }
    246 }
    247 
    248 #[cfg(feature = "serde")]
    249 mod serde_impl {
    250     use super::{Decimal, PositiveDecimal};
    251     use core::fmt;
    252     use serde::{
    253         Deserialize, Deserializer, Serialize, Serializer,
    254         de::{self, Visitor},
    255     };
    256 
    257     impl Serialize for Decimal {
    258         fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    259             serializer.collect_str(self)
    260         }
    261     }
    262 
    263     impl<'de> Deserialize<'de> for Decimal {
    264         fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    265             struct DecimalVisitor;
    266             impl Visitor<'_> for DecimalVisitor {
    267                 type Value = Decimal;
    268                 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    269                     f.write_str("a canonical Radroots decimal string")
    270                 }
    271                 fn visit_str<E: de::Error>(self, value: &str) -> Result<Decimal, E> {
    272                     value.parse().map_err(E::custom)
    273                 }
    274             }
    275             deserializer.deserialize_str(DecimalVisitor)
    276         }
    277     }
    278 
    279     impl Serialize for PositiveDecimal {
    280         fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    281             self.amount().serialize(serializer)
    282         }
    283     }
    284 
    285     impl<'de> Deserialize<'de> for PositiveDecimal {
    286         fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    287             Self::new(Decimal::deserialize(deserializer)?).map_err(de::Error::custom)
    288         }
    289     }
    290 }