use std::fmt;
use std::str::FromStr;
const TABLE: &[(&str, &str, u32)] = &[
("AED", "AED", 2),
("AUD", "A$", 2),
("BHD", "BHD", 3),
("BRL", "R$", 2),
("CAD", "CA$", 2),
("CHF", "CHF", 2),
("CLP", "CLP", 0),
("CNY", "CNÂ¥", 2),
("COP", "COP", 2),
("CZK", "CZK", 2),
("DKK", "DKK", 2),
("EGP", "EGP", 2),
("EUR", "€", 2),
("GBP", "£", 2),
("HKD", "HK$", 2),
("HUF", "HUF", 2),
("IDR", "Rp", 0),
("ILS", "₪", 2),
("INR", "₹", 2),
("IQD", "IQD", 3),
("JOD", "JOD", 3),
("JPY", "Â¥", 0),
("KRW", "â‚©", 0),
("KWD", "KWD", 3),
("LYD", "LYD", 3),
("MAD", "MAD", 2),
("MXN", "MX$", 2),
("MYR", "RM", 2),
("NGN", "₦", 2),
("NOK", "NOK", 2),
("NZD", "NZ$", 2),
("OMR", "OMR", 3),
("PHP", "₱", 2),
("PKR", "PKR", 2),
("PLN", "PLN", 2),
("QAR", "QAR", 2),
("RON", "RON", 2),
("RUB", "RUB", 2),
("SAR", "SAR", 2),
("SEK", "SEK", 2),
("SGD", "S$", 2),
("THB", "฿", 2),
("TND", "TND", 3),
("TRY", "₺", 2),
("TWD", "NT$", 2),
("UGX", "UGX", 0),
("USD", "$", 2),
("VND", "â‚«", 0),
("ZAR", "R", 2),
];
fn row(code: &str) -> Option<&'static (&'static str, &'static str, u32)> {
TABLE.iter().find(|r| r.0 == code)
}
pub(crate) fn info(code: &str) -> (&str, u32) {
match row(code) {
Some(&(_, symbol, digits)) => (symbol, digits),
None => (code, 2),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Currency([u8; 3]);
macro_rules! currency_consts {
($($(#[$m:meta])* $name:ident),+ $(,)?) => {
impl Currency {
$(
$(#[$m])*
pub const $name: Currency = Currency::from_literal(stringify!($name));
)+
}
};
}
currency_consts! {
AED,
AUD,
BHD,
CAD,
CHF,
CNY,
EUR,
GBP,
IDR,
INR,
JPY,
KRW,
KWD,
OMR,
SAR,
SGD,
USD,
}
impl Currency {
const fn from_literal(code: &str) -> Currency {
let b = code.as_bytes();
Currency([b[0], b[1], b[2]])
}
pub fn parse(code: &str) -> Result<Currency, CurrencyError> {
let upper = code.trim().to_ascii_uppercase();
match row(&upper) {
Some(r) => Ok(Currency::from_literal(r.0)),
None => Err(CurrencyError {
code: code.trim().to_string(),
}),
}
}
pub fn code(&self) -> &'static str {
TABLE
.iter()
.find(|r| r.0.as_bytes() == self.0)
.expect("a Currency is always in the table")
.0
}
pub fn symbol(&self) -> &'static str {
self.entry().1
}
pub fn decimals(&self) -> u32 {
self.entry().2
}
fn entry(&self) -> &'static (&'static str, &'static str, u32) {
TABLE
.iter()
.find(|r| r.0.as_bytes() == self.0)
.expect("a Currency is always in the table")
}
}
impl fmt::Display for Currency {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.code())
}
}
impl FromStr for Currency {
type Err = CurrencyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Currency::parse(s)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurrencyError {
code: String,
}
impl fmt::Display for CurrencyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`{}` is not a known ISO 4217 currency code", self.code)
}
}
impl std::error::Error for CurrencyError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Rounding {
HalfUp,
HalfEven,
Down,
Up,
}
impl Rounding {
pub fn as_str(&self) -> &'static str {
match self {
Rounding::HalfUp => "half_up",
Rounding::HalfEven => "half_even",
Rounding::Down => "down",
Rounding::Up => "up",
}
}
}
impl fmt::Display for Rounding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl serde::Serialize for Currency {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.code())
}
}
impl<'de> serde::Deserialize<'de> for Currency {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let text = <String as serde::Deserialize>::deserialize(d)?;
Currency::parse(&text).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MoneyError {
CurrencyMismatch {
left: Currency,
right: Currency,
},
Overflow,
DivisionByZero,
NoParts,
InvalidRate(String),
InvalidAmount(String),
TooManyDecimals {
currency: Currency,
allowed: u32,
},
}
impl fmt::Display for MoneyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MoneyError::CurrencyMismatch { left, right } => {
write!(f, "cannot combine {left} and {right} amounts")
}
MoneyError::Overflow => f.write_str("the amount is too large"),
MoneyError::DivisionByZero => f.write_str("the denominator is zero"),
MoneyError::NoParts => f.write_str("there is nothing to split between"),
MoneyError::InvalidRate(r) => write!(f, "`{r}` is not a valid exchange rate"),
MoneyError::InvalidAmount(a) => write!(f, "`{a}` is not a valid amount"),
MoneyError::TooManyDecimals { currency, allowed } => {
write!(f, "{currency} amounts have at most {allowed} decimals")
}
}
}
}
impl std::error::Error for MoneyError {}
pub(crate) fn div_round(num: i128, den: i128, rounding: Rounding) -> i128 {
let (num, den) = if den < 0 { (-num, -den) } else { (num, den) };
let q = num / den;
let rem = num % den;
if rem == 0 {
return q;
}
let away = if num < 0 { q - 1 } else { q + 1 };
match rounding {
Rounding::Down => q,
Rounding::Up => away,
Rounding::HalfUp | Rounding::HalfEven => {
let r = rem.abs();
let other = den - r;
if r > other {
away
} else if r < other {
q
} else if rounding == Rounding::HalfUp || q % 2 != 0 {
away
} else {
q
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rate {
num: i64,
den: i64,
}
impl Rate {
pub fn new(num: i64, den: i64) -> Result<Rate, MoneyError> {
if num <= 0 || den <= 0 {
return Err(MoneyError::InvalidRate(format!("{num}/{den}")));
}
Ok(Rate { num, den })
}
pub fn parse(text: &str) -> Result<Rate, MoneyError> {
let bad = || MoneyError::InvalidRate(text.to_string());
let t = text.trim();
let (whole, fraction) = t.split_once('.').unwrap_or((t, ""));
let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
if whole.is_empty() || !digits(whole) || !digits(fraction) || fraction.len() > 18 {
return Err(bad());
}
if t.ends_with('.') {
return Err(bad());
}
let num: i64 = format!("{whole}{fraction}").parse().map_err(|_| bad())?;
let den = 10i64.pow(fraction.len() as u32);
Rate::new(num, den).map_err(|_| bad())
}
}
pub trait IntoRate {
fn into_rate(self) -> Result<Rate, MoneyError>;
}
impl IntoRate for Rate {
fn into_rate(self) -> Result<Rate, MoneyError> {
Ok(self)
}
}
impl IntoRate for &str {
fn into_rate(self) -> Result<Rate, MoneyError> {
Rate::parse(self)
}
}
impl IntoRate for (i64, i64) {
fn into_rate(self) -> Result<Rate, MoneyError> {
Rate::new(self.0, self.1)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Money {
pub minor: i64,
pub currency: Currency,
}
macro_rules! money_ctors {
($($(#[$m:meta])* $name:ident => $cur:ident),+ $(,)?) => {
impl Money {
$(
$(#[$m])*
pub const fn $name(minor: i64) -> Money {
Money { minor, currency: Currency::$cur }
}
)+
}
};
}
money_ctors! {
usd => USD,
eur => EUR,
aed => AED,
jpy => JPY,
bhd => BHD,
kwd => KWD,
}
impl Money {
pub const fn new(minor: i64, currency: Currency) -> Money {
Money { minor, currency }
}
pub const fn is_zero(&self) -> bool {
self.minor == 0
}
pub const fn is_negative(&self) -> bool {
self.minor < 0
}
fn same_currency(&self, other: &Money) -> Result<(), MoneyError> {
if self.currency == other.currency {
Ok(())
} else {
Err(MoneyError::CurrencyMismatch {
left: self.currency,
right: other.currency,
})
}
}
pub fn checked_add(self, other: Money) -> Result<Money, MoneyError> {
self.same_currency(&other)?;
let minor = self
.minor
.checked_add(other.minor)
.ok_or(MoneyError::Overflow)?;
Ok(Money::new(minor, self.currency))
}
pub fn checked_sub(self, other: Money) -> Result<Money, MoneyError> {
self.same_currency(&other)?;
let minor = self
.minor
.checked_sub(other.minor)
.ok_or(MoneyError::Overflow)?;
Ok(Money::new(minor, self.currency))
}
pub fn allocate(self, parts: usize) -> Result<Vec<Money>, MoneyError> {
if parts == 0 {
return Err(MoneyError::NoParts);
}
self.allocate_by(&vec![1; parts])
}
pub fn allocate_by(self, weights: &[i64]) -> Result<Vec<Money>, MoneyError> {
let total: i128 = weights.iter().map(|w| *w as i128).sum();
if weights.is_empty() || total == 0 {
return Err(MoneyError::NoParts);
}
let mut shares: Vec<i128> = weights
.iter()
.map(|w| self.minor as i128 * *w as i128 / total)
.collect();
let left = self.minor as i128 - shares.iter().sum::<i128>();
let step = left.signum();
let mut to_give = left.abs();
for (share, weight) in shares.iter_mut().zip(weights) {
if to_give == 0 {
break;
}
if *weight != 0 {
*share += step;
to_give -= 1;
}
}
shares
.into_iter()
.map(|s| {
i64::try_from(s)
.map(|minor| Money::new(minor, self.currency))
.map_err(|_| MoneyError::Overflow)
})
.collect()
}
pub fn mul_ratio(self, num: i64, den: i64, rounding: Rounding) -> Result<Money, MoneyError> {
if den == 0 {
return Err(MoneyError::DivisionByZero);
}
let n = self.minor as i128 * num as i128;
let minor =
i64::try_from(div_round(n, den as i128, rounding)).map_err(|_| MoneyError::Overflow)?;
Ok(Money::new(minor, self.currency))
}
pub fn percent(self, basis_points: i64, rounding: Rounding) -> Result<Money, MoneyError> {
self.mul_ratio(basis_points, 10_000, rounding)
}
pub fn convert(
self,
rate: impl IntoRate,
to: Currency,
rounding: Rounding,
) -> Result<Money, MoneyError> {
let rate = rate.into_rate()?;
let mut num = self.minor as i128 * rate.num as i128;
let mut den = rate.den as i128;
let from_digits = self.currency.decimals();
let to_digits = to.decimals();
if to_digits >= from_digits {
num = num
.checked_mul(10i128.pow(to_digits - from_digits))
.ok_or(MoneyError::Overflow)?;
} else {
den *= 10i128.pow(from_digits - to_digits);
}
let minor =
i64::try_from(div_round(num, den, rounding)).map_err(|_| MoneyError::Overflow)?;
Ok(Money::new(minor, to))
}
pub fn format(&self, locale: &str) -> String {
let (thousands, decimal) = crate::view_filters::separators(locale);
let decimals = self.currency.decimals() as usize;
let digits = format!(
"{:0>width$}",
self.minor.unsigned_abs(),
width = decimals + 1
);
let (whole, fraction) = digits.split_at(digits.len() - decimals);
let mut grouped = String::new();
for (i, digit) in whole.chars().enumerate() {
if i > 0 && (whole.len() - i) % 3 == 0 {
grouped.push_str(thousands);
}
grouped.push(digit);
}
if decimals > 0 {
grouped.push_str(decimal);
grouped.push_str(fraction);
}
let sign = if self.minor < 0 { "-" } else { "" };
let symbol = self.currency.symbol();
let space = if symbol.ends_with(|c: char| c.is_ascii_alphabetic()) {
" "
} else {
""
};
format!("{sign}{symbol}{space}{grouped}")
}
pub fn parse(text: &str, currency: Currency) -> Result<Money, MoneyError> {
let bad = || MoneyError::InvalidAmount(text.to_string());
let t = text.trim();
let (negative, t) = match t.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, t.strip_prefix('+').unwrap_or(t)),
};
let (whole, fraction) = t.split_once('.').unwrap_or((t, ""));
let digits = |s: &str| s.bytes().all(|b| b.is_ascii_digit());
if whole.is_empty() || !digits(whole) || !digits(fraction) || t.ends_with('.') {
return Err(bad());
}
let allowed = currency.decimals();
if fraction.len() > allowed as usize {
return Err(MoneyError::TooManyDecimals { currency, allowed });
}
let padded = format!("{whole}{fraction:0<width$}", width = allowed as usize);
let magnitude: i128 = padded.parse().map_err(|_| MoneyError::Overflow)?;
let signed = if negative { -magnitude } else { magnitude };
let minor = i64::try_from(signed).map_err(|_| MoneyError::Overflow)?;
Ok(Money::new(minor, currency))
}
pub fn parse_locale(text: &str, currency: Currency, locale: &str) -> Result<Money, MoneyError> {
let (thousands, decimal) = crate::view_filters::separators(locale);
let plain = text
.replace(thousands, "")
.replace(' ', "")
.replace(decimal, ".");
Money::parse(&plain, currency).map_err(|e| match e {
MoneyError::InvalidAmount(_) => MoneyError::InvalidAmount(text.to_string()),
other => other,
})
}
}
impl fmt::Display for Money {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.format("en"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constants_match_the_table() {
for (c, code, digits) in [
(Currency::AED, "AED", 2),
(Currency::BHD, "BHD", 3),
(Currency::JPY, "JPY", 0),
(Currency::KWD, "KWD", 3),
(Currency::USD, "USD", 2),
(Currency::IDR, "IDR", 0),
(Currency::EUR, "EUR", 2),
] {
assert_eq!(c.code(), code);
assert_eq!(c.decimals(), digits);
assert_eq!(Currency::parse(code).unwrap(), c);
}
}
#[test]
fn every_row_round_trips() {
for &(code, symbol, digits) in TABLE {
let c = Currency::parse(&code.to_lowercase()).unwrap();
assert_eq!((c.code(), c.symbol(), c.decimals()), (code, symbol, digits));
}
}
#[test]
fn rejects_bad_codes() {
for bad in ["", "XX", "ABCD", "123", "U$D", "XYZ"] {
assert!(Currency::parse(bad).is_err(), "{bad}");
}
}
#[test]
fn old_functions_agree_with_the_table() {
for &(code, _, digits) in TABLE {
assert_eq!(crate::currency_decimals(code), digits);
}
assert_eq!(crate::currency_decimals("ZZZ"), 2);
}
}