Cotton code
243 lines · 10.8 KB · RustRaw
//! THE AMOUNT TRANSFORM (contract 1–4, lane T4, 22 Oct 2026): whole minor//! units and a currency code become a typed [`Money`] — its sign, whole//! units, minor part, the currency's minor digits, symbol and code — and//! never a sentence. A transform names no table and no column: any tool's//! amount column reaches it by its value and the code its `currency` column//! holds.//!//! Saying it is the reading edge's job: [`Money::said`] picks a line of the//! `money` line set (`kits/shell/lines/money.json`) by the form a definition//! names (`money` / `money_signed`) and fills it, the database's rows first,//! so a rewording is a row, never a build.//!//! NO DEFAULT CURRENCY: an amount whose row names no currency is its number//! in the code-less line (`bare`), never rupees or dollars by assumption.use std::sync::LazyLock;use iso_currency::Currency;use serde::Serialize;use crate::rules::shell_lines::{self, LineRow, LineSet};/// The line set every amount is said through.pub const LINES: &str = "money";/// Which way an amount points.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum Sign {    Minus,    Zero,    Plus,}/// An amount as a typed form: `units` whole and `minor` of `minor_digits` places/// (12.05 USD is units 12, minor 5, minor_digits 2). `symbol` is the mark the/// `money` set's map gives the currency; `code` the currency code, `None`/// when the row named no currency.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]pub struct Money {    pub sign: Sign,    pub units: u64,    pub minor: u64,    #[serde(rename = "digits")]    pub minor_digits: u8,    pub symbol: Option<String>,    pub code: Option<String>,}/// The form a definition names where an amount is drawn (contract 6):/// `money` says the amount, `money_signed` puts a plus before one above zero.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum MoneyForm {    Money,    MoneySigned,}/// Minor digits when the code is not an ISO 4217 currency, or the row names/// none: the stored value is still minor units, and two places is what ISO/// gives the most currencies — the number's shape, not a currency.const UNKNOWN_DIGITS: u8 = 2;/// The minor digits of `code` by ISO 4217 (yen 0, dinar 3, rupee 2).pub fn digits(code: &str) -> u8 {    Currency::from_code(code.trim().to_ascii_uppercase().as_str())        .and_then(Currency::exponent)        .map_or(UNKNOWN_DIGITS, |places| places as u8)}/// The `money` line set as one database says it, resolved once: the symbol/// map and every line an amount is said in.#[derive(Debug, Clone, PartialEq)]pub struct MoneyWords(LineSet);impl MoneyWords {    /// The kit's words, when no database is at hand.    pub fn shipped() -> &'static MoneyWords {        static WORDS: LazyLock<MoneyWords> = LazyLock::new(|| MoneyWords::of_rows(&[]));        &WORDS    }    /// The words a database says: its `lines` rows first, the kit for the rest.    pub fn of_rows(rows: &[LineRow]) -> MoneyWords {        MoneyWords(LineSet::of_rows(LINES, rows).expect("the kit ships the money set"))    }    /// One line of the set, filled; `None` when the set has no such line.    pub fn say(&self, line: &str, fills: &[(&str, &str)]) -> Option<String> {        self.0.say(line, fills)    }    /// The currency's symbol: the database's `money.symbols.<CODE>` row, else    /// the kit's (CLDR English: USD `$`, CAD `CA$`, GBP `£`). A code the map    /// does not hold, or holds as blank, has none and says its code.    pub fn symbol(&self, code: &str) -> Option<String> {        self.say(&format!("symbols.{code}"), &[]).filter(|symbol| !symbol.trim().is_empty())    }    /// The CLDR locale an amount in `code` is grouped by: the database's    /// `money.grouping.<CODE>` row, else the kit's (INR `en-IN`), else    /// `grouping_default`. Data, never the device's locale.    pub fn grouping(&self, code: Option<&str>) -> String {        code.and_then(|code| self.say(&format!("grouping.{code}"), &[]))            .or_else(|| self.say("grouping_default", &[]))            .filter(|locale| !locale.trim().is_empty())            .unwrap_or_default()    }}/// THE TRANSFORM: `minor` whole minor units in `currency` (an ISO code, any/// case; blank or `None` for none) as a typed [`Money`], its symbol from the/// `money` set's map in `words`. Pure: no table, no/// floating point.pub fn amount(minor: i64, currency: Option<&str>, words: &MoneyWords) -> Money {    let code = currency.map(|code| code.trim().to_ascii_uppercase()).filter(|code| !code.is_empty());    let minor_digits = code.as_deref().map_or(UNKNOWN_DIGITS, digits);    let scale = 10_u64.pow(u32::from(minor_digits));    let magnitude = minor.unsigned_abs();    Money {        sign: match minor.signum() {            -1 => Sign::Minus,            0 => Sign::Zero,            _ => Sign::Plus,        },        units: magnitude / scale,        minor: magnitude % scale,        minor_digits,        symbol: code.as_deref().and_then(|code| words.symbol(code)),        code,    }}impl Money {    /// The number as a person reads it, unsigned: whole units grouped by    /// CLDR as the currency's `grouping` locale groups them, then the minor part through `money.fraction` when there is one    /// (`1,601,625`, `12.05`).    pub fn number(&self, words: &MoneyWords) -> String {        let units = i64::try_from(self.units).unwrap_or(i64::MAX);        let units = shell_lines::number_grouped(units, &words.grouping(self.code.as_deref()));        if self.minor == 0 {            return units;        }        let minor = format!("{:0width$}", self.minor, width = usize::from(self.minor_digits));        words.say("fraction", &[("units", &units), ("minor", &minor)]).unwrap_or(units)    }    /// The amount said in `form` through the database's `money` words: `amount.*` for nought and above, `negative.*`    /// below, `signed.*` above nought in `money_signed`; each by the    /// currency's symbol (`symbol_spaced` when it ends in a letter, CLDR's    /// currency spacing: `SGD 12`, `$12`), else its code, else `bare`.    pub fn said(&self, form: MoneyForm, words: &MoneyWords) -> String {        let group = match (self.sign, form) {            (Sign::Minus, _) => "negative",            (Sign::Plus, MoneyForm::MoneySigned) => "signed",            _ => "amount",        };        let number = self.number(words);        let (mark, fills): (&str, Vec<(&str, &str)>) = match (&self.symbol, &self.code) {            (Some(symbol), _) if symbol.chars().last().is_some_and(char::is_alphabetic) => {                ("symbol_spaced", vec![("symbol", symbol), ("number", &number)])            }            (Some(symbol), _) => ("symbol", vec![("symbol", symbol), ("number", &number)]),            (None, Some(code)) => ("code", vec![("code", code), ("number", &number)]),            (None, None) => ("bare", vec![("number", &number)]),        };        words.say(&format!("{group}.{mark}"), &fills).unwrap_or(number)    }}#[cfg(test)]mod tests {    use super::*;    fn said(minor: i64, currency: &str) -> String {        amount(minor, Some(currency), MoneyWords::shipped()).said(MoneyForm::Money, MoneyWords::shipped())    }    #[test]    fn a_currency_brings_its_own_digits() {        assert_eq!(amount(1_200, Some("jpy"), MoneyWords::shipped()), Money { sign: Sign::Plus, units: 1_200, minor: 0, minor_digits: 0, symbol: Some("¥".into()), code: Some("JPY".into()) });        let dinar = amount(-1_234, Some("BHD"), MoneyWords::shipped());        assert_eq!((dinar.sign, dinar.units, dinar.minor, dinar.minor_digits), (Sign::Minus, 1, 234, 3));        assert_eq!(digits("INR"), 2);    }    #[test]    fn the_symbol_is_the_maps_and_a_code_off_the_map_says_itself() {        assert_eq!(said(160_162_500, "EUR"), "€1,601,625");        assert_eq!(said(160_162_550, "INR"), "₹16,01,625.50");        assert_eq!(said(1_250, "USD"), "$12.50");        assert_eq!(said(1_250, "CAD"), "CA$12.50");        assert_eq!(said(800, "JPY"), "¥800");        assert_eq!(said(1_250, "SGD"), "SGD 12.50");        assert_eq!(said(1_005, "BHD"), "BHD 1.005");        assert_eq!(said(-500, "ZZZ"), "−ZZZ 5");    }    #[test]    fn no_currency_says_the_number_alone() {        let bare = amount(-1_234_500, None, MoneyWords::shipped());        assert_eq!((bare.code.as_deref(), bare.symbol.as_deref()), (None, None));        assert_eq!(bare.said(MoneyForm::Money, MoneyWords::shipped()), "−12,345");        assert_eq!(amount(7, Some("  "), MoneyWords::shipped()).said(MoneyForm::MoneySigned, MoneyWords::shipped()), "+0.07");    }    #[test]    fn signed_marks_a_gain_and_never_nought() {        let eur = |minor| amount(minor, Some("EUR"), MoneyWords::shipped()).said(MoneyForm::MoneySigned, MoneyWords::shipped());        assert_eq!((eur(500), eur(0), eur(-500)), ("+€5".into(), "€0".into(), "−€5".into()));    }    #[test]    /// Grouping follows the amount's currency, by data (the money set's    /// `grouping`): rupees by `en-IN` lakhs and crores, everything else by    /// `en` — never the device's locale.    #[test]    fn rupees_group_in_lakhs_and_crores() {        let words = MoneyWords::shipped();        assert_eq!(amount(10_000_000, Some("INR"), words).said(MoneyForm::Money, words), "₹1,00,000");        assert_eq!(amount(123_456_789, Some("INR"), words).said(MoneyForm::Money, words), "₹12,34,567.89");        assert_eq!(amount(123_456_789, Some("USD"), words).said(MoneyForm::Money, words), "$1,234,567.89");        assert_eq!(amount(123_456_789, None, words).said(MoneyForm::Money, words), "1,234,567.89");    }    /// A line that is a map takes a database row for a key the kit lacks: a    /// currency the kit has no symbol for gets one by a row, not a build.    #[test]    fn a_row_adds_a_key_to_a_map() {        let row = |line: &str, words: &str| LineRow { set: LINES.into(), line: line.into(), words: words.into() };        let words = MoneyWords::of_rows(&[row("symbols.KES", "KSh"), row("grouping.KES", "en-IN"), row("nowhere.KES", "x")]);        assert_eq!(amount(10_000_000, Some("KES"), &words).said(MoneyForm::Money, &words), "KSh 1,00,000");        assert_eq!(words.say("nowhere.KES", &[]), None, "a fixed line the kit lacks stays ignored");    }    fn a_rewording_or_a_preference_is_a_row() {        let row = |line: &str, words: &str| LineRow { set: LINES.into(), line: line.into(), words: words.into() };        let rows = [row("amount.symbol", "{number} {symbol}"), row("fraction", "{units},{minor}"), row("symbols.INR", "Rs"), row("symbols.USD", "")];        let words = MoneyWords::of_rows(&rows);        assert_eq!(amount(1_050, Some("EUR"), &words).said(MoneyForm::Money, &words), "10,50 €");        assert_eq!(amount(1_000, Some("INR"), &words).said(MoneyForm::Money, &words), "Rs 10");        assert_eq!(amount(1_000, Some("USD"), &words).said(MoneyForm::Money, &words), "USD 10");    }}