amount.rs (16374B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2024, 2025, 2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 //! Type for the Taler Amount <https://docs.taler.net/core/api-common.html#tsref-type-Amount> 18 19 use std::{ 20 fmt::{Debug, Display}, 21 num::ParseIntError, 22 str::FromStr, 23 }; 24 25 use super::utils::InlineStr; 26 27 /** Number of characters we use to represent currency names */ 28 // We use the same value than the exchange -1 because we use a byte for the len instead of 0 termination 29 pub const CURRENCY_LEN: usize = 11; 30 31 /** Maximum legal value for an amount, based on IEEE double */ 32 pub const MAX_VALUE: u64 = 2 << 52; 33 34 /** The number of digits in a fraction part of an amount */ 35 pub const FRAC_BASE_NB_DIGITS: u8 = 8; 36 37 /** The fraction part of an amount represents which fraction of the value */ 38 pub const FRAC_BASE: u32 = 10u32.pow(FRAC_BASE_NB_DIGITS as u32); 39 40 const CENT_FRACTION: u32 = 10u32.pow((FRAC_BASE_NB_DIGITS - 2) as u32); 41 42 #[derive( 43 Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay, 44 )] 45 /// Inlined ISO 4217 currency string 46 pub struct Currency(InlineStr<CURRENCY_LEN>); 47 48 impl AsRef<str> for Currency { 49 fn as_ref(&self) -> &str { 50 self.0.as_ref() 51 } 52 } 53 54 #[derive(Debug, thiserror::Error)] 55 pub enum CurrencyErrorKind { 56 #[error("contains illegal characters (only A-Z allowed)")] 57 Invalid, 58 #[error("too long (max {CURRENCY_LEN} chars)")] 59 Big, 60 #[error("is empty")] 61 Empty, 62 } 63 64 #[derive(Debug, thiserror::Error)] 65 #[error("currency code name '{currency}' {kind}")] 66 pub struct ParseCurrencyError { 67 currency: String, 68 pub kind: CurrencyErrorKind, 69 } 70 71 impl Currency { 72 pub const TEST: Self = Self::const_parse("TEST"); 73 pub const KUDOS: Self = Self::const_parse("KUDOS"); 74 pub const EUR: Self = Self::const_parse("EUR"); 75 pub const CHF: Self = Self::const_parse("CHF"); 76 pub const HUF: Self = Self::const_parse("HUF"); 77 78 pub const fn const_parse(s: &str) -> Currency { 79 let bytes = s.as_bytes(); 80 let len = bytes.len(); 81 82 if bytes.is_empty() { 83 panic!("empty") 84 } else if len > CURRENCY_LEN { 85 panic!("too big") 86 } 87 let mut i = 0; 88 while i < bytes.len() { 89 if !bytes[i].is_ascii_uppercase() { 90 panic!("invalid") 91 } 92 i += 1; 93 } 94 Self(InlineStr::copy_from_slice(bytes)) 95 } 96 } 97 98 impl FromStr for Currency { 99 type Err = ParseCurrencyError; 100 101 fn from_str(s: &str) -> Result<Self, Self::Err> { 102 let bytes = s.as_bytes(); 103 let len = bytes.len(); 104 if bytes.is_empty() { 105 Err(CurrencyErrorKind::Empty) 106 } else if len > CURRENCY_LEN { 107 Err(CurrencyErrorKind::Big) 108 } else if !bytes.iter().all(|c| c.is_ascii_uppercase()) { 109 Err(CurrencyErrorKind::Invalid) 110 } else { 111 Ok(Self(InlineStr::copy_from_slice(bytes))) 112 } 113 .map_err(|kind| ParseCurrencyError { 114 currency: s.to_owned(), 115 kind, 116 }) 117 } 118 } 119 120 impl Debug for Currency { 121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 122 Debug::fmt(&self.as_ref(), f) 123 } 124 } 125 126 impl Display for Currency { 127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 128 Display::fmt(&self.as_ref(), f) 129 } 130 } 131 132 #[derive(sqlx::Type)] 133 #[sqlx(type_name = "taler_amount")] 134 struct PgTalerAmount { 135 pub val: i64, 136 pub frac: i32, 137 } 138 139 #[derive( 140 Clone, 141 Copy, 142 PartialEq, 143 Eq, 144 PartialOrd, 145 Ord, 146 serde_with::DeserializeFromStr, 147 serde_with::SerializeDisplay, 148 )] 149 pub struct Decimal { 150 /** Integer part */ 151 pub val: u64, 152 /** Factional part, multiple of FRAC_BASE */ 153 pub frac: u32, 154 } 155 156 impl Decimal { 157 pub const fn new(val: u64, frac: u32) -> Self { 158 Self { val, frac } 159 } 160 161 pub const ZERO: Self = Self::new(0, 0); 162 pub const MAX: Self = Self::new(MAX_VALUE, FRAC_BASE - 1); 163 164 const fn normalize(mut self) -> Option<Self> { 165 let Some(val) = self.val.checked_add((self.frac / FRAC_BASE) as u64) else { 166 return None; 167 }; 168 self.val = val; 169 self.frac %= FRAC_BASE; 170 if self.val > MAX_VALUE { 171 return None; 172 } 173 Some(self) 174 } 175 176 pub fn try_add(mut self, rhs: &Self) -> Option<Self> { 177 self.val = self.val.checked_add(rhs.val)?; 178 self.frac = self 179 .frac 180 .checked_add(rhs.frac) 181 .expect("amount fraction overflow should never happen with normalized amounts"); 182 self.normalize() 183 } 184 185 pub fn try_sub(mut self, rhs: &Self) -> Option<Self> { 186 if rhs.frac > self.frac { 187 self.val = self.val.checked_sub(1)?; 188 self.frac += FRAC_BASE; 189 } 190 self.val = self.val.checked_sub(rhs.val)?; 191 self.frac = self.frac.checked_sub(rhs.frac)?; 192 self.normalize() 193 } 194 195 pub const fn to_amount(self, currency: &Currency) -> Amount { 196 Amount::new_decimal(currency, self) 197 } 198 } 199 200 #[derive(Debug, thiserror::Error)] 201 pub enum DecimalErrKind { 202 #[error("value overflow (must be <= {MAX_VALUE})")] 203 Overflow, 204 #[error("invalid value ({0})")] 205 InvalidValue(ParseIntError), 206 #[error("invalid fraction ({0})")] 207 InvalidFraction(ParseIntError), 208 #[error("fraction overflow (max {FRAC_BASE_NB_DIGITS} digits)")] 209 FractionOverflow, 210 } 211 212 #[derive(Debug, thiserror::Error)] 213 #[error("decimal '{decimal}' {kind}")] 214 pub struct ParseDecimalErr { 215 decimal: String, 216 pub kind: DecimalErrKind, 217 } 218 219 impl FromStr for Decimal { 220 type Err = ParseDecimalErr; 221 222 fn from_str(s: &str) -> Result<Self, Self::Err> { 223 let (value, fraction) = s.split_once('.').unwrap_or((s, "")); 224 225 // TODO use try block when stable 226 (|| { 227 let value: u64 = value.parse().map_err(DecimalErrKind::InvalidValue)?; 228 if value > MAX_VALUE { 229 return Err(DecimalErrKind::Overflow); 230 } 231 232 if fraction.len() > FRAC_BASE_NB_DIGITS as usize { 233 return Err(DecimalErrKind::FractionOverflow); 234 } 235 let fraction: u32 = if fraction.is_empty() { 236 0 237 } else { 238 fraction 239 .parse::<u32>() 240 .map_err(DecimalErrKind::InvalidFraction)? 241 * 10u32.pow(FRAC_BASE_NB_DIGITS as u32 - fraction.len() as u32) 242 }; 243 Ok(Self { 244 val: value, 245 frac: fraction, 246 }) 247 })() 248 .map_err(|kind| ParseDecimalErr { 249 decimal: s.to_owned(), 250 kind, 251 }) 252 } 253 } 254 255 impl Display for Decimal { 256 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 257 if self.frac == 0 { 258 f.write_fmt(format_args!("{}", self.val)) 259 } else { 260 let num = format!("{:08}", self.frac); 261 f.write_fmt(format_args!("{}.{}", self.val, num.trim_end_matches('0'))) 262 } 263 } 264 } 265 266 impl Debug for Decimal { 267 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 268 Display::fmt(&self, f) 269 } 270 } 271 272 impl sqlx::Type<sqlx::Postgres> for Decimal { 273 fn type_info() -> sqlx::postgres::PgTypeInfo { 274 PgTalerAmount::type_info() 275 } 276 } 277 278 impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Decimal { 279 fn encode_by_ref( 280 &self, 281 buf: &mut sqlx::postgres::PgArgumentBuffer, 282 ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { 283 PgTalerAmount { 284 val: self.val as i64, 285 frac: self.frac as i32, 286 } 287 .encode_by_ref(buf) 288 } 289 } 290 291 impl<'r> sqlx::Decode<'r, sqlx::Postgres> for Decimal { 292 fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> { 293 let pg = PgTalerAmount::decode(value)?; 294 Ok(Self { 295 val: pg.val as u64, 296 frac: pg.frac as u32, 297 }) 298 } 299 } 300 301 #[track_caller] 302 pub fn decimal(decimal: impl AsRef<str>) -> Decimal { 303 decimal.as_ref().parse().expect("Invalid decimal constant") 304 } 305 306 /// <https://docs.taler.net/core/api-common.html#tsref-type-Amount> 307 #[derive( 308 Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay, 309 )] 310 pub struct Amount { 311 pub currency: Currency, 312 pub val: u64, 313 pub frac: u32, 314 } 315 316 impl Amount { 317 pub const fn new_decimal(currency: &Currency, decimal: Decimal) -> Self { 318 Self { 319 currency: *currency, 320 val: decimal.val, 321 frac: decimal.frac, 322 } 323 } 324 325 pub const fn new(currency: &Currency, val: u64, frac: u32) -> Self { 326 Self::new_decimal(currency, Decimal { val, frac }) 327 } 328 329 pub const fn max(currency: &Currency) -> Self { 330 Self::new_decimal(currency, Decimal::MAX) 331 } 332 333 pub const fn zero(currency: &Currency) -> Self { 334 Self::new_decimal(currency, Decimal::ZERO) 335 } 336 337 pub fn is_zero(&self) -> bool { 338 self.decimal() == Decimal::ZERO 339 } 340 341 /* Check is amount has fractional amount < 0.01 */ 342 pub const fn is_sub_cent(&self) -> bool { 343 !self.frac.is_multiple_of(CENT_FRACTION) 344 } 345 346 pub const fn decimal(&self) -> Decimal { 347 Decimal { 348 val: self.val, 349 frac: self.frac, 350 } 351 } 352 353 pub fn normalize(self) -> Option<Self> { 354 let decimal = self.decimal().normalize()?; 355 Some((self.currency, decimal).into()) 356 } 357 358 pub fn try_add(self, rhs: &Self) -> Option<Self> { 359 assert_eq!(self.currency, rhs.currency); 360 let decimal = self.decimal().try_add(&rhs.decimal())?.normalize()?; 361 Some((self.currency, decimal).into()) 362 } 363 364 pub fn try_sub(self, rhs: &Self) -> Option<Self> { 365 assert_eq!(self.currency, rhs.currency); 366 let decimal = self.decimal().try_sub(&rhs.decimal())?.normalize()?; 367 Some((self.currency, decimal).into()) 368 } 369 } 370 371 impl From<(Currency, Decimal)> for Amount { 372 fn from((currency, decimal): (Currency, Decimal)) -> Self { 373 Self::new_decimal(¤cy, decimal) 374 } 375 } 376 377 #[track_caller] 378 pub fn amount(amount: impl AsRef<str>) -> Amount { 379 amount.as_ref().parse().expect("Invalid amount constant") 380 } 381 382 #[derive(Debug, thiserror::Error)] 383 pub enum AmountErrKind { 384 #[error("invalid format")] 385 Format, 386 #[error("currency {0}")] 387 Currency(#[from] CurrencyErrorKind), 388 #[error(transparent)] 389 Decimal(#[from] DecimalErrKind), 390 } 391 392 #[derive(Debug, thiserror::Error)] 393 #[error("amount '{amount}' {kind}")] 394 pub struct ParseAmountErr { 395 amount: String, 396 pub kind: AmountErrKind, 397 } 398 399 impl FromStr for Amount { 400 type Err = ParseAmountErr; 401 402 fn from_str(s: &str) -> Result<Self, Self::Err> { 403 // TODO use try block when stable 404 (|| { 405 let (currency, amount) = s.trim().split_once(':').ok_or(AmountErrKind::Format)?; 406 let currency = currency.parse().map_err(|e: ParseCurrencyError| e.kind)?; 407 let decimal = amount.parse().map_err(|e: ParseDecimalErr| e.kind)?; 408 Ok((currency, decimal).into()) 409 })() 410 .map_err(|kind| ParseAmountErr { 411 amount: s.to_owned(), 412 kind, 413 }) 414 } 415 } 416 417 impl Display for Amount { 418 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 419 f.write_fmt(format_args!("{}:{}", self.currency, self.decimal())) 420 } 421 } 422 423 impl Debug for Amount { 424 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 425 Display::fmt(&self, f) 426 } 427 } 428 429 impl sqlx::Type<sqlx::Postgres> for Amount { 430 fn type_info() -> sqlx::postgres::PgTypeInfo { 431 PgTalerAmount::type_info() 432 } 433 } 434 435 impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Amount { 436 fn encode_by_ref( 437 &self, 438 buf: &mut sqlx::postgres::PgArgumentBuffer, 439 ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> { 440 self.decimal().encode_by_ref(buf) 441 } 442 } 443 444 #[test] 445 fn test_amount_parse() { 446 const TALER_AMOUNT_FRAC_BASE: u32 = 100000000; 447 // https://git.taler.net/exchange.git/tree/src/util/test_amount.c 448 449 const INVALID_AMOUNTS: [&str; 6] = [ 450 "EUR:4a", // non-numeric, 451 "EUR:4.4a", // non-numeric 452 "EUR:4.a4", // non-numeric 453 ":4.a4", // no currency 454 "EUR:4.123456789", // precision to high 455 "EUR:1234567890123456789012345678901234567890123456789012345678901234567890", // value to big 456 ]; 457 458 for str in INVALID_AMOUNTS { 459 let amount = Amount::from_str(str); 460 assert!(amount.is_err(), "invalid {} got {:?}", str, &amount); 461 } 462 463 let eur: Currency = Currency::EUR; 464 let local: Currency = Currency::CHF; 465 let valid_amounts: Vec<(&str, &str, Amount)> = vec![ 466 ("EUR:4", "EUR:4", Amount::new(&eur, 4, 0)), // without fraction 467 ( 468 "EUR:0.02", 469 "EUR:0.02", 470 Amount::new(&eur, 0, TALER_AMOUNT_FRAC_BASE / 100 * 2), 471 ), // leading zero fraction 472 ( 473 " EUR:4.12", 474 "EUR:4.12", 475 Amount::new(&eur, 4, TALER_AMOUNT_FRAC_BASE / 100 * 12), 476 ), // leading space and fraction 477 ( 478 " CHF:4444.1000", 479 "CHF:4444.1", 480 Amount::new(&local, 4444, TALER_AMOUNT_FRAC_BASE / 10), 481 ), // local currency 482 ]; 483 for (raw, expected, goal) in valid_amounts { 484 let amount = Amount::from_str(raw); 485 assert!(amount.is_ok(), "Valid {} got {:?}", raw, amount); 486 assert_eq!( 487 *amount.as_ref().unwrap(), 488 goal, 489 "Expected {:?} got {:?} for {}", 490 goal, 491 amount, 492 raw 493 ); 494 let amount = amount.unwrap(); 495 let str = amount.to_string(); 496 assert_eq!(str, expected); 497 assert_eq!(amount, Amount::from_str(&str).unwrap(), "{str}"); 498 } 499 } 500 501 #[test] 502 fn test_amount_add() { 503 let eur: Currency = Currency::EUR; 504 assert_eq!( 505 Amount::max(&eur).try_add(&Amount::zero(&eur)), 506 Some(Amount::max(&eur)) 507 ); 508 assert_eq!( 509 Amount::zero(&eur).try_add(&Amount::zero(&eur)), 510 Some(Amount::zero(&eur)) 511 ); 512 assert_eq!( 513 amount("EUR:6.41").try_add(&amount("EUR:4.69")), 514 Some(amount("EUR:11.1")) 515 ); 516 assert_eq!( 517 amount(format!("EUR:{MAX_VALUE}")).try_add(&amount("EUR:0.99999999")), 518 Some(Amount::max(&eur)) 519 ); 520 521 assert_eq!( 522 amount(format!("EUR:{}", MAX_VALUE - 5)).try_add(&amount("EUR:6")), 523 None 524 ); 525 assert_eq!( 526 Amount::new(&eur, u64::MAX, 0).try_add(&amount("EUR:1")), 527 None 528 ); 529 assert_eq!( 530 amount(format!("EUR:{}.{}", MAX_VALUE - 5, FRAC_BASE - 1)) 531 .try_add(&amount("EUR:5.00000002")), 532 None 533 ); 534 } 535 536 #[test] 537 fn test_amount_normalize() { 538 let eur: Currency = "EUR".parse().unwrap(); 539 assert_eq!( 540 Amount::new(&eur, 4, 2 * FRAC_BASE).normalize(), 541 Some(amount("EUR:6")) 542 ); 543 assert_eq!( 544 Amount::new(&eur, 4, 2 * FRAC_BASE + 1).normalize(), 545 Some(amount("EUR:6.00000001")) 546 ); 547 assert_eq!( 548 Amount::new(&eur, MAX_VALUE, FRAC_BASE - 1).normalize(), 549 Some(Amount::new(&eur, MAX_VALUE, FRAC_BASE - 1)) 550 ); 551 assert_eq!(Amount::new(&eur, u64::MAX, FRAC_BASE).normalize(), None); 552 assert_eq!(Amount::new(&eur, MAX_VALUE, FRAC_BASE).normalize(), None); 553 554 for amount in [Amount::max(&eur), Amount::zero(&eur)] { 555 assert_eq!(amount.normalize(), Some(amount)) 556 } 557 }