Skip to main content

logicaffeine_base/
money.rs

1//! Money — an exact monetary amount in a specific currency (UNIVERSAL_TYPES Part V).
2//!
3//! Money rides the exact [`Decimal`] tower, so it **never float-drifts**: `0.10 + 0.20` is exactly
4//! `0.30`, not `0.30000000000000004`. The amount is quantised to the currency's minor unit (USD has
5//! 2 fractional digits, JPY has 0, BHD has 3), with banker's rounding.
6//!
7//! Currency is part of the value, and same-currency arithmetic is the only kind that means anything:
8//! `5 USD + 1 EUR` has no answer, so `add`/`sub` across currencies return `None` — the exact analogue
9//! of the dimensional rule that forbids `meter + gram`. `× ÷` by a plain number scales the amount; a
10//! same-currency `Money ÷ Money` is an exact dimensionless ratio.
11
12use core::fmt;
13use core::hash::{Hash, Hasher};
14
15use crate::numeric::{Decimal, Rational, RoundingMode};
16
17/// An ISO-4217 currency: its three-letter code and its minor-unit `scale` (the number of fractional
18/// digits — `USD`→2, `JPY`→0, `BHD`→3). The code is the identity.
19#[derive(Clone, Copy, Debug)]
20pub struct Currency {
21    pub code: &'static str,
22    pub scale: u32,
23}
24
25impl PartialEq for Currency {
26    fn eq(&self, other: &Self) -> bool {
27        self.code == other.code
28    }
29}
30impl Eq for Currency {}
31impl Hash for Currency {
32    fn hash<H: Hasher>(&self, state: &mut H) {
33        self.code.hash(state);
34    }
35}
36
37/// The currency catalog — resolve an ISO-4217 code (case-insensitive) to its [`Currency`]. A growable
38/// data table, mirroring [`crate::quantity::units::by_name`]; the minor-unit scales follow ISO-4217.
39pub mod currency {
40    use super::Currency;
41
42    /// Look up a currency by its ISO-4217 code (case-insensitive); `None` for an unknown code.
43    pub fn by_code(code: &str) -> Option<Currency> {
44        let c = code.trim().to_ascii_uppercase();
45        let cur = |code, scale| Currency { code, scale };
46        Some(match c.as_str() {
47            "USD" => cur("USD", 2),
48            "EUR" => cur("EUR", 2),
49            "GBP" => cur("GBP", 2),
50            "CHF" => cur("CHF", 2),
51            "CAD" => cur("CAD", 2),
52            "AUD" => cur("AUD", 2),
53            "NZD" => cur("NZD", 2),
54            "SGD" => cur("SGD", 2),
55            "HKD" => cur("HKD", 2),
56            "CNY" => cur("CNY", 2),
57            "INR" => cur("INR", 2),
58            "BRL" => cur("BRL", 2),
59            "MXN" => cur("MXN", 2),
60            "ZAR" => cur("ZAR", 2),
61            "SEK" => cur("SEK", 2),
62            "NOK" => cur("NOK", 2),
63            "DKK" => cur("DKK", 2),
64            "RUB" => cur("RUB", 2),
65            "TRY" => cur("TRY", 2),
66            "PLN" => cur("PLN", 2),
67            // Zero-decimal currencies (no minor unit).
68            "JPY" => cur("JPY", 0),
69            "KRW" => cur("KRW", 0),
70            "ISK" => cur("ISK", 0),
71            "VND" => cur("VND", 0),
72            "CLP" => cur("CLP", 0),
73            // Three-decimal currencies.
74            "BHD" => cur("BHD", 3),
75            "KWD" => cur("KWD", 3),
76            "OMR" => cur("OMR", 3),
77            "JOD" => cur("JOD", 3),
78            "TND" => cur("TND", 3),
79            _ => return None,
80        })
81    }
82}
83
84/// An exact monetary amount, quantised to its currency's minor unit.
85#[derive(Clone, Debug)]
86pub struct Money {
87    /// The amount, exact, at `currency.scale` fractional digits.
88    pub amount: Decimal,
89    pub currency: Currency,
90}
91
92impl Money {
93    /// Build money, quantising the amount to the currency's minor unit with banker's rounding —
94    /// `5 USD` is stored as `5.00`, `19.999 USD` rounds to `20.00`, `100 JPY` stays `100`.
95    pub fn of(amount: Decimal, currency: Currency) -> Money {
96        Money { amount: amount.rescale(currency.scale, RoundingMode::HalfEven), currency }
97    }
98
99    /// Sum of two amounts in the **same** currency; `None` across currencies (no common meaning).
100    pub fn add(&self, other: &Money) -> Option<Money> {
101        if self.currency != other.currency {
102            return None;
103        }
104        Some(Money { amount: self.amount.add(&other.amount), currency: self.currency })
105    }
106
107    /// Difference of two amounts in the **same** currency; `None` across currencies.
108    pub fn sub(&self, other: &Money) -> Option<Money> {
109        if self.currency != other.currency {
110            return None;
111        }
112        Some(Money { amount: self.amount.sub(&other.amount), currency: self.currency })
113    }
114
115    /// Scale an amount by a plain integer (`19.99 USD × 3 = 59.97 USD`), re-quantised to the currency.
116    pub fn scale_int(&self, k: i64) -> Money {
117        Money::of(self.amount.mul(&Decimal::from_i64(k)), self.currency)
118    }
119
120    /// The exact dimensionless ratio of two same-currency amounts (`30 USD ÷ 10 USD = 3`); `None`
121    /// across currencies or when the divisor is zero.
122    pub fn ratio(&self, other: &Money) -> Option<Rational> {
123        if self.currency != other.currency {
124            return None;
125        }
126        self.amount.to_rational().div(&other.amount.to_rational())
127    }
128}
129
130impl PartialEq for Money {
131    /// Value equality: same currency and equal amount (`5 USD == 5.00 USD`, `5 USD ≠ 5 EUR`).
132    fn eq(&self, other: &Self) -> bool {
133        self.currency == other.currency && self.amount.to_rational() == other.amount.to_rational()
134    }
135}
136impl Eq for Money {}
137
138impl Hash for Money {
139    fn hash<H: Hasher>(&self, state: &mut H) {
140        self.currency.hash(state);
141        self.amount.to_rational().hash(state);
142    }
143}
144
145impl fmt::Display for Money {
146    /// `"19.99 USD"` — the amount at the currency's minor-unit scale, then the code.
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        write!(f, "{} {}", self.amount, self.currency.code)
149    }
150}
151
152/// A pluggable exchange-rate table — the substrate of the **Universal Money Amount** (money's UTC).
153/// Each currency code maps to its rate **versus a chosen reference currency**: how many reference
154/// units one unit of the currency is worth, exact on the Rational tower (the reference itself is 1).
155/// The *source* is interchangeable — a literal table, a CRDT-synced table, an API fetch — they all
156/// produce this same value, so with rates in scope money of different currencies shares one
157/// coordinate and cross-currency math becomes meaningful (and exact).
158#[derive(Clone, Debug, Default)]
159pub struct RateTable {
160    rates: std::collections::HashMap<String, Rational>,
161}
162
163impl RateTable {
164    pub fn new() -> Self {
165        RateTable { rates: std::collections::HashMap::new() }
166    }
167
168    /// Record that `1 <code> = rate` reference units (case-insensitive code).
169    pub fn set(&mut self, code: &str, rate: Rational) {
170        self.rates.insert(code.trim().to_ascii_uppercase(), rate);
171    }
172
173    /// The rate of `code` versus the reference, if known.
174    pub fn rate(&self, code: &str) -> Option<&Rational> {
175        self.rates.get(&code.trim().to_ascii_uppercase())
176    }
177
178    /// Convert `m` into `to`, exact via the Rational tower (normalise to the reference, then to the
179    /// target), quantised to `to`'s minor unit. `None` if either currency's rate is missing.
180    pub fn convert(&self, m: &Money, to: Currency) -> Option<Money> {
181        let from_rate = self.rate(m.currency.code)?;
182        let to_rate = self.rate(to.code)?;
183        let value_in_reference = m.amount.to_rational().mul(from_rate);
184        let amount_in_to = value_in_reference.div(to_rate)?;
185        Some(Money::of(Decimal::from_rational(&amount_in_to, to.scale, RoundingMode::HalfEven), to))
186    }
187}
188
189thread_local! {
190    /// The in-scope exchange-rate context for `<money> in <currency>` conversion. Pluggable: a
191    /// program installs it from a literal table, a CRDT-synced table, or an API fetch — they all land
192    /// here. `None` until rates are provided (conversion then errors, rather than guessing).
193    static AMBIENT_RATES: std::cell::RefCell<Option<RateTable>> =
194        const { std::cell::RefCell::new(None) };
195}
196
197/// Install (replace) the ambient rate table.
198pub fn set_ambient_rates(table: RateTable) {
199    AMBIENT_RATES.with(|r| *r.borrow_mut() = Some(table));
200}
201
202/// Add or replace one rate in the ambient table (`1 <code> = rate` reference units), creating the
203/// table if none is in scope yet.
204pub fn set_ambient_rate(code: &str, rate: Rational) {
205    AMBIENT_RATES.with(|r| r.borrow_mut().get_or_insert_with(RateTable::new).set(code, rate));
206}
207
208/// Drop the ambient rate table (back to "no rates in scope").
209pub fn clear_ambient_rates() {
210    AMBIENT_RATES.with(|r| *r.borrow_mut() = None);
211}
212
213/// True if any rate context is in scope.
214pub fn has_ambient_rates() -> bool {
215    AMBIENT_RATES.with(|r| r.borrow().is_some())
216}
217
218/// Convert `m` to `to` using the ambient rate table. `None` if no rates are in scope or a currency's
219/// rate is missing — the caller surfaces a clean error rather than a wrong number.
220pub fn ambient_convert(m: &Money, to: Currency) -> Option<Money> {
221    AMBIENT_RATES.with(|r| r.borrow().as_ref().and_then(|t| t.convert(m, to)))
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    fn money(s: &str, code: &str) -> Money {
229        Money::of(Decimal::parse(s).unwrap(), currency::by_code(code).unwrap())
230    }
231
232    #[test]
233    fn currency_catalog_resolves_codes_with_their_iso_scales() {
234        assert_eq!(currency::by_code("USD").unwrap().scale, 2);
235        assert_eq!(currency::by_code("usd").unwrap().scale, 2); // case-insensitive
236        assert_eq!(currency::by_code("JPY").unwrap().scale, 0); // zero-decimal
237        assert_eq!(currency::by_code("BHD").unwrap().scale, 3); // three-decimal
238        assert_eq!(currency::by_code("KWD").unwrap().scale, 3);
239        assert_eq!(currency::by_code("XYZ"), None);
240    }
241
242    #[test]
243    fn money_quantises_to_the_currency_minor_unit() {
244        assert_eq!(money("19.99", "USD").to_string(), "19.99 USD");
245        assert_eq!(money("5", "USD").to_string(), "5.00 USD"); // padded to 2dp
246        assert_eq!(money("100", "JPY").to_string(), "100 JPY"); // no decimals
247        assert_eq!(money("1.5", "BHD").to_string(), "1.500 BHD"); // 3dp
248        // Banker's rounding to the minor unit.
249        assert_eq!(money("19.999", "USD").to_string(), "20.00 USD");
250        assert_eq!(money("2.345", "USD").to_string(), "2.34 USD"); // HalfEven: 4 is even
251    }
252
253    #[test]
254    fn same_currency_add_sub_are_exact_and_keep_the_currency() {
255        // The "JSON numbers ruin lives" footgun, gone: 0.10 + 0.20 is EXACTLY 0.30.
256        assert_eq!(money("0.10", "USD").add(&money("0.20", "USD")).unwrap().to_string(), "0.30 USD");
257        assert_eq!(money("19.99", "USD").add(&money("5.00", "USD")).unwrap().to_string(), "24.99 USD");
258        assert_eq!(money("24.99", "USD").sub(&money("5.00", "USD")).unwrap().to_string(), "19.99 USD");
259        assert_eq!(money("100", "JPY").add(&money("50", "JPY")).unwrap().to_string(), "150 JPY");
260    }
261
262    #[test]
263    fn cross_currency_arithmetic_is_forbidden() {
264        // A dollar plus a euro has no answer — like meter + gram.
265        assert_eq!(money("5.00", "USD").add(&money("1.00", "EUR")), None);
266        assert_eq!(money("5.00", "USD").sub(&money("1.00", "EUR")), None);
267        assert_eq!(money("5.00", "USD").ratio(&money("1.00", "EUR")), None);
268    }
269
270    #[test]
271    fn scaling_and_ratio() {
272        assert_eq!(money("19.99", "USD").scale_int(3).to_string(), "59.97 USD");
273        assert_eq!(money("30.00", "USD").ratio(&money("10.00", "USD")).unwrap(), Rational::from_i64(3));
274        assert_eq!(money("1.00", "USD").ratio(&money("0.00", "USD")), None); // divide by zero
275    }
276
277    #[test]
278    fn universal_money_amount_converts_exactly_via_a_rate_table() {
279        // Reference = USD. 1 EUR = 1.10 USD, 1 GBP = 1.25 USD.
280        let mut rates = RateTable::new();
281        rates.set("USD", Rational::from_i64(1));
282        rates.set("EUR", Rational::from_ratio_i64(11, 10).unwrap());
283        rates.set("GBP", Rational::from_ratio_i64(5, 4).unwrap());
284        let usd = currency::by_code("USD").unwrap();
285        let eur = currency::by_code("EUR").unwrap();
286        let gbp = currency::by_code("GBP").unwrap();
287
288        // 10 EUR → USD = 11.00 USD; and back to EUR = exactly 10.00 (lossless round-trip).
289        assert_eq!(rates.convert(&money("10.00", "EUR"), usd).unwrap().to_string(), "11.00 USD");
290        assert_eq!(rates.convert(&money("11.00", "USD"), eur).unwrap().to_string(), "10.00 EUR");
291        // Converting to the same currency is the identity.
292        assert_eq!(rates.convert(&money("42.00", "USD"), usd).unwrap().to_string(), "42.00 USD");
293        // Cross-rate via the reference: 10 GBP = 12.50 USD = 12.50/1.10 EUR ≈ 11.36 EUR.
294        assert_eq!(rates.convert(&money("10.00", "GBP"), eur).unwrap().to_string(), "11.36 EUR");
295        // An unknown currency yields None, never a wrong number.
296        assert_eq!(rates.convert(&money("1.00", "USD"), currency::by_code("JPY").unwrap()), None);
297    }
298
299    #[test]
300    fn value_equality() {
301        assert_eq!(money("5", "USD"), money("5.00", "USD")); // value-equal across input forms
302        assert_ne!(money("5.00", "USD"), money("5.00", "EUR")); // currency matters
303        assert_ne!(money("5.00", "USD"), money("6.00", "USD"));
304    }
305}