//! Money: whole haléře in an `i64`. Outflows are negative, as on a statement. Every operation is checked. use serde::{Deserialize, Serialize}; use std::fmt; /// An amount in haléře (1 CZK = 100 haléřů). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct Haler(pub i64); #[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] pub enum MoneyError { #[error("the amount is too large")] Overflow, #[error("there is nobody to split between")] NoWeight, #[error("not an amount in CZK")] NotAnAmount, } impl Haler { pub const ZERO: Haler = Haler(0); pub fn checked_add(self, other: Haler) -> Result { self.0.checked_add(other.0).map(Haler).ok_or(MoneyError::Overflow) } pub fn checked_sub(self, other: Haler) -> Result { self.0.checked_sub(other.0).map(Haler).ok_or(MoneyError::Overflow) } pub fn checked_neg(self) -> Result { self.0.checked_neg().map(Haler).ok_or(MoneyError::Overflow) } pub fn is_outflow(self) -> bool { self.0 < 0 } /// The sum, or `Overflow`. Integer addition is associative, so the order never matters. pub fn sum>(items: I) -> Result { items.into_iter().try_fold(Haler::ZERO, Haler::checked_add) } /// `-1 234,50`: a space between thousands, a decimal comma, always two decimals, no currency. pub fn to_czk(self) -> String { let neg = self.0 < 0; let abs = self.0.unsigned_abs(); let whole = (abs / 100).to_string(); let mut grouped = String::with_capacity(whole.len() + whole.len() / 3); for (i, c) in whole.chars().enumerate() { if i > 0 && (whole.len() - i) % 3 == 0 { grouped.push(' '); } grouped.push(c); } format!("{}{},{:02}", if neg { "-" } else { "" }, grouped, abs % 100) } /// The inverse of [`Haler::to_czk`], also taking a plain `1234`, `1234,5` or `1234.50` as typed by hand. /// Strict: one optional leading minus, ASCII digits, spaces only between groups of three, at most two /// decimals after one `,` or `.`. pub fn parse_czk(text: &str) -> Result { let t = text.trim(); let (neg, t) = match t.strip_prefix('-') { Some(rest) => (true, rest), None => (false, t), }; let (int, frac) = match t.find([',', '.']) { Some(i) => (&t[..i], Some(&t[i + 1..])), None => (t, None), }; let groups: Vec<&str> = int.split(' ').collect(); if groups.iter().any(|g| g.is_empty() || !g.bytes().all(|b| b.is_ascii_digit())) || groups.iter().skip(1).any(|g| g.len() != 3) || (groups.len() > 1 && groups[0].len() > 3) { return Err(MoneyError::NotAnAmount); } let digits: String = groups.concat(); let cents = match frac { None => 0, Some(f) if (1..=2).contains(&f.len()) && f.bytes().all(|b| b.is_ascii_digit()) => { let v: i64 = f.parse().map_err(|_| MoneyError::NotAnAmount)?; if f.len() == 1 { v * 10 } else { v } } Some(_) => return Err(MoneyError::NotAnAmount), }; let whole: i64 = digits.parse().map_err(|_| MoneyError::Overflow)?; let abs = whole.checked_mul(100).and_then(|w| w.checked_add(cents)).ok_or(MoneyError::Overflow)?; Ok(Haler(if neg { -abs } else { abs })) } } impl fmt::Display for Haler { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} Kč", self.to_czk()) } } /// Splits `total` by `weights` so that the shares always sum to `total` exactly. /// /// Largest remainder: each share is `floor(|total|·w/Σw)`; the haléře left over go one each to the largest /// remainders, ties to the lower index. A negative total is split as its absolute value, then mirrored. pub fn split(total: Haler, weights: &[u64]) -> Result, MoneyError> { let sum_w: u128 = weights.iter().map(|w| *w as u128).sum(); if sum_w == 0 { return Err(MoneyError::NoWeight); } let abs = total.0.unsigned_abs() as u128; let mut shares: Vec = Vec::with_capacity(weights.len()); let mut rems: Vec<(u128, usize)> = Vec::with_capacity(weights.len()); for (i, w) in weights.iter().enumerate() { let num = abs * (*w as u128); shares.push(num / sum_w); rems.push((num % sum_w, i)); } let given: u128 = shares.iter().sum(); let mut left = abs - given; // < weights.len() // Largest remainder first; equal remainders by index. rems.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); for (rem, i) in rems { if left == 0 { break; } if rem == 0 && weights[i] == 0 { continue; } shares[i] += 1; left -= 1; } shares .into_iter() .map(|s| { let s = i64::try_from(s).map_err(|_| MoneyError::Overflow)?; Ok(Haler(if total.0 < 0 { -s } else { s })) }) .collect() }