use core::fmt;
use core::hash::{Hash, Hasher};
use crate::numeric::{Decimal, Rational, RoundingMode};
#[derive(Clone, Copy, Debug)]
pub struct Currency {
pub code: &'static str,
pub scale: u32,
}
impl PartialEq for Currency {
fn eq(&self, other: &Self) -> bool {
self.code == other.code
}
}
impl Eq for Currency {}
impl Hash for Currency {
fn hash<H: Hasher>(&self, state: &mut H) {
self.code.hash(state);
}
}
pub mod currency {
use super::Currency;
pub fn by_code(code: &str) -> Option<Currency> {
let c = code.trim().to_ascii_uppercase();
let cur = |code, scale| Currency { code, scale };
Some(match c.as_str() {
"USD" => cur("USD", 2),
"EUR" => cur("EUR", 2),
"GBP" => cur("GBP", 2),
"CHF" => cur("CHF", 2),
"CAD" => cur("CAD", 2),
"AUD" => cur("AUD", 2),
"NZD" => cur("NZD", 2),
"SGD" => cur("SGD", 2),
"HKD" => cur("HKD", 2),
"CNY" => cur("CNY", 2),
"INR" => cur("INR", 2),
"BRL" => cur("BRL", 2),
"MXN" => cur("MXN", 2),
"ZAR" => cur("ZAR", 2),
"SEK" => cur("SEK", 2),
"NOK" => cur("NOK", 2),
"DKK" => cur("DKK", 2),
"RUB" => cur("RUB", 2),
"TRY" => cur("TRY", 2),
"PLN" => cur("PLN", 2),
"JPY" => cur("JPY", 0),
"KRW" => cur("KRW", 0),
"ISK" => cur("ISK", 0),
"VND" => cur("VND", 0),
"CLP" => cur("CLP", 0),
"BHD" => cur("BHD", 3),
"KWD" => cur("KWD", 3),
"OMR" => cur("OMR", 3),
"JOD" => cur("JOD", 3),
"TND" => cur("TND", 3),
_ => return None,
})
}
}
#[derive(Clone, Debug)]
pub struct Money {
pub amount: Decimal,
pub currency: Currency,
}
impl Money {
pub fn of(amount: Decimal, currency: Currency) -> Money {
Money { amount: amount.rescale(currency.scale, RoundingMode::HalfEven), currency }
}
pub fn add(&self, other: &Money) -> Option<Money> {
if self.currency != other.currency {
return None;
}
Some(Money { amount: self.amount.add(&other.amount), currency: self.currency })
}
pub fn sub(&self, other: &Money) -> Option<Money> {
if self.currency != other.currency {
return None;
}
Some(Money { amount: self.amount.sub(&other.amount), currency: self.currency })
}
pub fn scale_int(&self, k: i64) -> Money {
Money::of(self.amount.mul(&Decimal::from_i64(k)), self.currency)
}
pub fn ratio(&self, other: &Money) -> Option<Rational> {
if self.currency != other.currency {
return None;
}
self.amount.to_rational().div(&other.amount.to_rational())
}
}
impl PartialEq for Money {
fn eq(&self, other: &Self) -> bool {
self.currency == other.currency && self.amount.to_rational() == other.amount.to_rational()
}
}
impl Eq for Money {}
impl Hash for Money {
fn hash<H: Hasher>(&self, state: &mut H) {
self.currency.hash(state);
self.amount.to_rational().hash(state);
}
}
impl fmt::Display for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.amount, self.currency.code)
}
}
#[derive(Clone, Debug, Default)]
pub struct RateTable {
rates: std::collections::HashMap<String, Rational>,
}
impl RateTable {
pub fn new() -> Self {
RateTable { rates: std::collections::HashMap::new() }
}
pub fn set(&mut self, code: &str, rate: Rational) {
self.rates.insert(code.trim().to_ascii_uppercase(), rate);
}
pub fn rate(&self, code: &str) -> Option<&Rational> {
self.rates.get(&code.trim().to_ascii_uppercase())
}
pub fn convert(&self, m: &Money, to: Currency) -> Option<Money> {
let from_rate = self.rate(m.currency.code)?;
let to_rate = self.rate(to.code)?;
let value_in_reference = m.amount.to_rational().mul(from_rate);
let amount_in_to = value_in_reference.div(to_rate)?;
Some(Money::of(Decimal::from_rational(&amount_in_to, to.scale, RoundingMode::HalfEven), to))
}
}
thread_local! {
static AMBIENT_RATES: std::cell::RefCell<Option<RateTable>> =
const { std::cell::RefCell::new(None) };
}
pub fn set_ambient_rates(table: RateTable) {
AMBIENT_RATES.with(|r| *r.borrow_mut() = Some(table));
}
pub fn set_ambient_rate(code: &str, rate: Rational) {
AMBIENT_RATES.with(|r| r.borrow_mut().get_or_insert_with(RateTable::new).set(code, rate));
}
pub fn clear_ambient_rates() {
AMBIENT_RATES.with(|r| *r.borrow_mut() = None);
}
pub fn has_ambient_rates() -> bool {
AMBIENT_RATES.with(|r| r.borrow().is_some())
}
pub fn ambient_convert(m: &Money, to: Currency) -> Option<Money> {
AMBIENT_RATES.with(|r| r.borrow().as_ref().and_then(|t| t.convert(m, to)))
}
#[cfg(test)]
mod tests {
use super::*;
fn money(s: &str, code: &str) -> Money {
Money::of(Decimal::parse(s).unwrap(), currency::by_code(code).unwrap())
}
#[test]
fn currency_catalog_resolves_codes_with_their_iso_scales() {
assert_eq!(currency::by_code("USD").unwrap().scale, 2);
assert_eq!(currency::by_code("usd").unwrap().scale, 2); assert_eq!(currency::by_code("JPY").unwrap().scale, 0); assert_eq!(currency::by_code("BHD").unwrap().scale, 3); assert_eq!(currency::by_code("KWD").unwrap().scale, 3);
assert_eq!(currency::by_code("XYZ"), None);
}
#[test]
fn money_quantises_to_the_currency_minor_unit() {
assert_eq!(money("19.99", "USD").to_string(), "19.99 USD");
assert_eq!(money("5", "USD").to_string(), "5.00 USD"); assert_eq!(money("100", "JPY").to_string(), "100 JPY"); assert_eq!(money("1.5", "BHD").to_string(), "1.500 BHD"); assert_eq!(money("19.999", "USD").to_string(), "20.00 USD");
assert_eq!(money("2.345", "USD").to_string(), "2.34 USD"); }
#[test]
fn same_currency_add_sub_are_exact_and_keep_the_currency() {
assert_eq!(money("0.10", "USD").add(&money("0.20", "USD")).unwrap().to_string(), "0.30 USD");
assert_eq!(money("19.99", "USD").add(&money("5.00", "USD")).unwrap().to_string(), "24.99 USD");
assert_eq!(money("24.99", "USD").sub(&money("5.00", "USD")).unwrap().to_string(), "19.99 USD");
assert_eq!(money("100", "JPY").add(&money("50", "JPY")).unwrap().to_string(), "150 JPY");
}
#[test]
fn cross_currency_arithmetic_is_forbidden() {
assert_eq!(money("5.00", "USD").add(&money("1.00", "EUR")), None);
assert_eq!(money("5.00", "USD").sub(&money("1.00", "EUR")), None);
assert_eq!(money("5.00", "USD").ratio(&money("1.00", "EUR")), None);
}
#[test]
fn scaling_and_ratio() {
assert_eq!(money("19.99", "USD").scale_int(3).to_string(), "59.97 USD");
assert_eq!(money("30.00", "USD").ratio(&money("10.00", "USD")).unwrap(), Rational::from_i64(3));
assert_eq!(money("1.00", "USD").ratio(&money("0.00", "USD")), None); }
#[test]
fn universal_money_amount_converts_exactly_via_a_rate_table() {
let mut rates = RateTable::new();
rates.set("USD", Rational::from_i64(1));
rates.set("EUR", Rational::from_ratio_i64(11, 10).unwrap());
rates.set("GBP", Rational::from_ratio_i64(5, 4).unwrap());
let usd = currency::by_code("USD").unwrap();
let eur = currency::by_code("EUR").unwrap();
let gbp = currency::by_code("GBP").unwrap();
assert_eq!(rates.convert(&money("10.00", "EUR"), usd).unwrap().to_string(), "11.00 USD");
assert_eq!(rates.convert(&money("11.00", "USD"), eur).unwrap().to_string(), "10.00 EUR");
assert_eq!(rates.convert(&money("42.00", "USD"), usd).unwrap().to_string(), "42.00 USD");
assert_eq!(rates.convert(&money("10.00", "GBP"), eur).unwrap().to_string(), "11.36 EUR");
assert_eq!(rates.convert(&money("1.00", "USD"), currency::by_code("JPY").unwrap()), None);
}
#[test]
fn value_equality() {
assert_eq!(money("5", "USD"), money("5.00", "USD")); assert_ne!(money("5.00", "USD"), money("5.00", "EUR")); assert_ne!(money("5.00", "USD"), money("6.00", "USD"));
}
}