money.rs (9450B)
1 use crate::{Currency, CurrencyError}; 2 use core::{fmt, str::FromStr}; 3 4 /// Exact bounded nonnegative minor amount; JSON uses a canonical integer string. 5 #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] 6 pub struct MinorAmount(u64); 7 8 /// Validated money with one supported currency and its fixed registry exponent. 9 #[derive(Clone, Copy, Eq, PartialEq, Hash)] 10 pub struct Money { 11 currency: Currency, 12 minor: MinorAmount, 13 } 14 15 /// Input-free monetary admission or checked-arithmetic failure. 16 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 17 #[non_exhaustive] 18 pub enum MoneyError { 19 /// The input is not an unsigned ASCII integer string. 20 InvalidMinorFormat, 21 /// A leading zero makes the spelling noncanonical. 22 NonCanonicalMinor, 23 /// The supported fifteen-digit minor amount bound is exceeded. 24 MinorOutOfRange, 25 /// The supplied exponent exceeds the supported range 0-4. 26 InvalidExponent, 27 /// The supplied exponent disagrees with the supported currency registry. 28 ExponentMismatch, 29 /// Arithmetic operands have different currencies. 30 CurrencyMismatch, 31 /// Subtraction would produce a negative monetary value. 32 NegativeResult, 33 /// The currency could not be admitted. 34 Currency(CurrencyError), 35 } 36 37 impl MinorAmount { 38 /// Largest supported exact minor amount. 39 pub const MAX_VALUE: u64 = 999_999_999_999_999; 40 /// Explicit valid zero; it does not imply a price mode or currency. 41 pub const ZERO: Self = Self(0); 42 /// Largest supported validated amount. 43 pub const MAX: Self = Self(Self::MAX_VALUE); 44 45 /// Checks the exact minor-unit bound without a floating conversion. 46 pub const fn new(value: u64) -> Result<Self, MoneyError> { 47 if value > Self::MAX_VALUE { 48 Err(MoneyError::MinorOutOfRange) 49 } else { 50 Ok(Self(value)) 51 } 52 } 53 54 /// Returns the exact bounded integer representation. 55 pub const fn get(self) -> u64 { 56 self.0 57 } 58 } 59 60 impl TryFrom<u64> for MinorAmount { 61 type Error = MoneyError; 62 fn try_from(value: u64) -> Result<Self, Self::Error> { 63 Self::new(value) 64 } 65 } 66 67 impl FromStr for MinorAmount { 68 type Err = MoneyError; 69 fn from_str(value: &str) -> Result<Self, Self::Err> { 70 if value.is_empty() { 71 return Err(MoneyError::InvalidMinorFormat); 72 } 73 if value.len() > 15 { 74 return Err(MoneyError::MinorOutOfRange); 75 } 76 if !value.bytes().all(|byte| byte.is_ascii_digit()) { 77 return Err(MoneyError::InvalidMinorFormat); 78 } 79 if value.len() > 1 && value.starts_with('0') { 80 return Err(MoneyError::NonCanonicalMinor); 81 } 82 let mut result = 0_u64; 83 for byte in value.bytes() { 84 result = result 85 .checked_mul(10) 86 .and_then(|n| n.checked_add(u64::from(byte - b'0'))) 87 .ok_or(MoneyError::MinorOutOfRange)?; 88 } 89 Self::new(result) 90 } 91 } 92 93 impl fmt::Display for MinorAmount { 94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 95 self.0.fmt(f) 96 } 97 } 98 99 impl fmt::Debug for MinorAmount { 100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 101 f.write_str("MinorAmount(<redacted>)") 102 } 103 } 104 105 impl Money { 106 /// Combines already validated values. Zero is explicit money, not a quote. 107 pub const fn new(currency: Currency, minor: MinorAmount) -> Self { 108 Self { currency, minor } 109 } 110 111 /// Admits wire/FFI parts and checks their explicit registry exponent. 112 pub fn from_parts(currency: &str, minor: &str, exponent: u8) -> Result<Self, MoneyError> { 113 let currency = Currency::from_code(currency)?; 114 let minor = minor.parse()?; 115 Self::from_wire(currency, minor, exponent) 116 } 117 118 fn from_wire(currency: Currency, minor: MinorAmount, exponent: u8) -> Result<Self, MoneyError> { 119 if exponent > 4 { 120 return Err(MoneyError::InvalidExponent); 121 } 122 if exponent != currency.exponent() { 123 return Err(MoneyError::ExponentMismatch); 124 } 125 Ok(Self::new(currency, minor)) 126 } 127 128 /// Returns the validated supported currency. 129 pub const fn currency(self) -> Currency { 130 self.currency 131 } 132 133 /// Returns the exact validated minor amount. 134 pub const fn minor(self) -> MinorAmount { 135 self.minor 136 } 137 138 /// Returns the currency's fixed minor exponent. 139 pub const fn exponent(self) -> u8 { 140 self.currency.exponent() 141 } 142 143 /// Adds in checked signed 128-bit arithmetic, retaining currency and bounds. 144 pub fn checked_add(self, other: Self) -> Result<Self, MoneyError> { 145 if self.currency != other.currency { 146 return Err(MoneyError::CurrencyMismatch); 147 } 148 let result = i128::from(self.minor.get()) 149 .checked_add(i128::from(other.minor.get())) 150 .ok_or(MoneyError::MinorOutOfRange)?; 151 self.with_result(result) 152 } 153 154 /// Subtracts exactly; different currencies and negative values are errors. 155 pub fn checked_sub(self, other: Self) -> Result<Self, MoneyError> { 156 if self.currency != other.currency { 157 return Err(MoneyError::CurrencyMismatch); 158 } 159 let result = i128::from(self.minor.get()) 160 .checked_sub(i128::from(other.minor.get())) 161 .filter(|result| *result >= 0) 162 .ok_or(MoneyError::NegativeResult)?; 163 self.with_result(result) 164 } 165 166 fn with_result(self, value: i128) -> Result<Self, MoneyError> { 167 let value = u64::try_from(value).map_err(|_| MoneyError::MinorOutOfRange)?; 168 Ok(Self::new(self.currency, MinorAmount::new(value)?)) 169 } 170 } 171 172 impl From<CurrencyError> for MoneyError { 173 fn from(value: CurrencyError) -> Self { 174 Self::Currency(value) 175 } 176 } 177 178 impl fmt::Debug for Money { 179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 180 f.write_str("Money(<redacted>)") 181 } 182 } 183 184 impl fmt::Display for MoneyError { 185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 186 f.write_str(match self { 187 Self::InvalidMinorFormat => "invalid minor amount format", 188 Self::NonCanonicalMinor => "noncanonical minor amount", 189 Self::MinorOutOfRange => "minor amount exceeds supported bound", 190 Self::InvalidExponent => "invalid currency exponent", 191 Self::ExponentMismatch => "currency exponent mismatch", 192 Self::CurrencyMismatch => "currency mismatch", 193 Self::NegativeResult => "monetary subtraction would be negative", 194 Self::Currency(error) => return error.fmt(f), 195 }) 196 } 197 } 198 199 impl core::error::Error for MoneyError { 200 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { 201 match self { 202 Self::Currency(error) => Some(error), 203 _ => None, 204 } 205 } 206 } 207 208 #[cfg(feature = "serde")] 209 mod serde_impl { 210 use super::{MinorAmount, Money}; 211 use crate::Currency; 212 use core::fmt; 213 use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser::SerializeStruct}; 214 215 impl Serialize for MinorAmount { 216 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { 217 serializer.collect_str(self) 218 } 219 } 220 221 impl<'de> Deserialize<'de> for MinorAmount { 222 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 223 struct Visitor; 224 impl de::Visitor<'_> for Visitor { 225 type Value = MinorAmount; 226 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 227 f.write_str("a bounded canonical minor amount string") 228 } 229 fn visit_str<E: de::Error>(self, value: &str) -> Result<MinorAmount, E> { 230 value.parse().map_err(E::custom) 231 } 232 } 233 deserializer.deserialize_str(Visitor) 234 } 235 } 236 237 impl Serialize for Money { 238 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { 239 let mut state = serializer.serialize_struct("Money", 3)?; 240 state.serialize_field("currency", &self.currency())?; 241 state.serialize_field("minor", &self.minor())?; 242 state.serialize_field("exponent", &self.exponent())?; 243 state.end() 244 } 245 } 246 247 impl<'de> Deserialize<'de> for Money { 248 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 249 #[derive(Deserialize)] 250 #[serde(deny_unknown_fields)] 251 struct Wire { 252 currency: Currency, 253 minor: MinorAmount, 254 exponent: u8, 255 } 256 struct Visitor; 257 impl<'de> de::Visitor<'de> for Visitor { 258 type Value = Money; 259 260 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 261 f.write_str("a money object with currency, minor and exponent") 262 } 263 264 fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<Money, A::Error> { 265 let wire = Wire::deserialize(de::value::MapAccessDeserializer::new(map))?; 266 Money::from_wire(wire.currency, wire.minor, wire.exponent) 267 .map_err(de::Error::custom) 268 } 269 } 270 deserializer.deserialize_map(Visitor) 271 } 272 } 273 }