Skip to main content

flatland_client_lib/
currency.rs

1//! Client-side currency display from inventory stacks.
2
3const COPPER: &str = "copper_coin";
4const SILVER: &str = "silver_coin";
5const GOLD: &str = "gold_coin";
6const PLATINUM: &str = "platinum_coin";
7
8const COPPER_PER_SILVER: u64 = 100;
9const COPPER_PER_GOLD: u64 = 10_000;
10const COPPER_PER_PLATINUM: u64 = 1_000_000;
11
12pub fn copper_from_counts(counts: &std::collections::HashMap<String, u32>) -> u64 {
13    counts
14        .iter()
15        .map(|(id, qty)| copper_value(id).saturating_mul(*qty as u64))
16        .sum()
17}
18
19fn copper_value(template_id: &str) -> u64 {
20    match template_id {
21        PLATINUM => COPPER_PER_PLATINUM,
22        GOLD => COPPER_PER_GOLD,
23        SILVER => COPPER_PER_SILVER,
24        COPPER => 1,
25        _ => 0,
26    }
27}
28
29pub fn format_copper(amount: u64) -> String {
30    let denoms = [
31        (COPPER_PER_PLATINUM, "pp"),
32        (COPPER_PER_GOLD, "gp"),
33        (COPPER_PER_SILVER, "sp"),
34        (1, "cp"),
35    ];
36    let mut rest = amount;
37    let mut parts = Vec::new();
38    for (unit, label) in denoms {
39        if rest >= unit {
40            let count = rest / unit;
41            rest %= unit;
42            parts.push(format!("{count}{label}"));
43        }
44    }
45    if parts.is_empty() {
46        "0cp".into()
47    } else {
48        parts.join(" ")
49    }
50}
51
52pub fn currency_line(counts: &std::collections::HashMap<String, u32>) -> String {
53    format_copper(copper_from_counts(counts))
54}