use serde::{Deserialize, Serialize};
const ZERO_EXPONENT: &[&str] = &[
"BIF", "CLP", "DJF", "GNF", "ISK", "JPY", "KMF", "KRW", "PYG", "RWF", "UGX", "UYI", "VND",
"VUV", "XAF", "XOF", "XPF",
];
const THREE_EXPONENT: &[&str] = &["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"];
const TWO_EXPONENT: &[&str] = &[
"AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT",
"BGN", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHF",
"CNY", "COP", "CRC", "CUP", "CVE", "CZK", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR",
"FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG",
"HUF", "IDR", "ILS", "INR", "IRR", "JMD", "KES", "KGS", "KHR", "KPW", "KYD", "KZT", "LAK",
"LBP", "LKR", "LRD", "LSL", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR",
"MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "PAB", "PEN",
"PGK", "PHP", "PKR", "PLN", "QAR", "RON", "RSD", "RUB", "SAR", "SBD", "SCR", "SDG", "SEK",
"SGD", "SHP", "SLE", "SOS", "SRD", "SSP", "STN", "SVC", "SYP", "SZL", "THB", "TJS", "TMT",
"TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "USD", "UZS", "VES", "WST", "XCD", "XCG", "YER",
"ZAR", "ZMW", "ZWG", "ZWL",
];
#[must_use]
pub fn currency_exponent(currency: &str) -> Option<u32> {
let code = currency.trim();
if code.len() != 3 {
return None;
}
let upper = code.to_ascii_uppercase();
let matches = |set: &[&str]| set.iter().any(|c| *c == upper);
if matches(ZERO_EXPONENT) {
Some(0)
} else if matches(THREE_EXPONENT) {
Some(3)
} else if matches(TWO_EXPONENT) {
Some(2)
} else {
None
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Money {
pub amount: i64,
pub currency: String,
}
impl Money {
pub fn new(amount: i64, currency: impl Into<String>) -> Self {
Self {
amount,
currency: currency.into(),
}
}
#[must_use]
pub fn exponent(&self) -> Option<u32> {
currency_exponent(&self.currency)
}
#[must_use]
pub fn to_major_string(&self) -> Option<String> {
let exponent = self.exponent()?;
if exponent == 0 {
return Some(self.amount.to_string());
}
let sign = if self.amount < 0 { "-" } else { "" };
let magnitude = self.amount.unsigned_abs();
let divisor = 10_u64.pow(exponent);
let whole = magnitude / divisor;
let fraction = magnitude % divisor;
Some(format!(
"{sign}{whole}.{fraction:0width$}",
width = exponent as usize
))
}
#[must_use]
pub fn checked_add(&self, other: &Self) -> Option<Self> {
if !self.currency.eq_ignore_ascii_case(&other.currency) {
return None;
}
Some(Self {
amount: self.amount.checked_add(other.amount)?,
currency: self.currency.clone(),
})
}
}
impl std::fmt::Display for Money {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.to_major_string() {
Some(major) => write!(f, "{major} {}", self.currency),
None => write!(f, "{} (minor units) {}", self.amount, self.currency),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exponent_is_looked_up_not_defaulted() {
assert_eq!(currency_exponent("USD"), Some(2));
assert_eq!(currency_exponent("JPY"), Some(0));
assert_eq!(currency_exponent("KWD"), Some(3));
assert_eq!(currency_exponent("XYZ"), None);
assert_eq!(currency_exponent(""), None);
assert_eq!(currency_exponent("EURO"), None);
}
#[test]
fn a_renamed_currency_and_its_predecessor_both_resolve() {
assert_eq!(currency_exponent("ANG"), Some(2)); assert_eq!(currency_exponent("XCG"), Some(2));
assert_eq!(currency_exponent("ZWL"), Some(2)); assert_eq!(currency_exponent("ZWG"), Some(2));
}
#[test]
fn exponent_lookup_is_case_and_space_insensitive() {
assert_eq!(currency_exponent("jpy"), Some(0));
assert_eq!(currency_exponent(" eur "), Some(2));
}
#[test]
fn major_string_places_the_point_per_currency() {
assert_eq!(
Money::new(1999, "EUR").to_major_string().as_deref(),
Some("19.99")
);
assert_eq!(
Money::new(1999, "JPY").to_major_string().as_deref(),
Some("1999")
);
assert_eq!(
Money::new(1999, "KWD").to_major_string().as_deref(),
Some("1.999")
);
}
#[test]
fn major_string_pads_the_fraction() {
assert_eq!(
Money::new(5, "USD").to_major_string().as_deref(),
Some("0.05")
);
assert_eq!(
Money::new(50, "USD").to_major_string().as_deref(),
Some("0.50")
);
}
#[test]
fn major_string_keeps_the_sign_on_negatives() {
assert_eq!(
Money::new(-500, "USD").to_major_string().as_deref(),
Some("-5.00")
);
assert_eq!(
Money::new(-5, "USD").to_major_string().as_deref(),
Some("-0.05")
);
}
#[test]
fn major_string_survives_i64_min() {
assert!(Money::new(i64::MIN, "USD").to_major_string().is_some());
}
#[test]
fn major_string_is_none_for_an_unknown_currency() {
assert_eq!(Money::new(1999, "XYZ").to_major_string(), None);
}
#[test]
fn add_refuses_to_mix_currencies() {
let eur = Money::new(100, "EUR");
let usd = Money::new(100, "USD");
assert_eq!(eur.checked_add(&usd), None);
assert_eq!(
eur.checked_add(&Money::new(23, "eur")),
Some(Money::new(123, "EUR"))
);
}
#[test]
fn add_refuses_to_overflow() {
let big = Money::new(i64::MAX, "USD");
assert_eq!(big.checked_add(&Money::new(1, "USD")), None);
}
#[test]
fn display_never_prints_a_guessed_decimal_point() {
assert_eq!(Money::new(1999, "EUR").to_string(), "19.99 EUR");
assert_eq!(
Money::new(1999, "XYZ").to_string(),
"1999 (minor units) XYZ"
);
}
}