Skip to main content

payrail_core/
money.rs

1use crate::{CurrencyCode, MinorAmount, PaymentError};
2
3/// Money represented in minor units.
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5pub struct Money {
6    amount: MinorAmount,
7    currency: CurrencyCode,
8}
9
10impl Money {
11    /// Creates money from a minor-unit amount and currency code.
12    ///
13    /// # Errors
14    ///
15    /// Returns an error when either component is invalid.
16    pub fn new_minor(amount: i64, currency: impl AsRef<str>) -> Result<Self, PaymentError> {
17        Ok(Self {
18            amount: MinorAmount::new(amount)?,
19            currency: CurrencyCode::new(currency)?,
20        })
21    }
22
23    /// Returns the amount.
24    #[inline]
25    #[must_use]
26    pub const fn amount(&self) -> MinorAmount {
27        self.amount
28    }
29
30    /// Returns the currency.
31    #[inline]
32    #[must_use]
33    pub const fn currency(&self) -> &CurrencyCode {
34        &self.currency
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn new_minor_builds_money() {
44        let money = Money::new_minor(1_000, "usd").expect("money should be valid");
45
46        assert_eq!(money.amount().value(), 1_000);
47        assert_eq!(money.currency().as_str(), "USD");
48    }
49}