bnr_xfs/
currency.rs

1//! Types and functions for handling currency sets.
2
3use std::fmt;
4
5use crate::impl_xfs_struct;
6
7mod cash_order;
8mod cash_type;
9mod code;
10mod cu_enum;
11mod denomination;
12mod exponent;
13mod mix;
14
15pub use cash_order::*;
16pub use cash_type::*;
17pub use code::*;
18pub use cu_enum::*;
19pub use denomination::*;
20pub use exponent::*;
21pub use mix::*;
22
23/// Represents a currency set used in the CDR.
24#[repr(C)]
25#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Deserialize, serde::Serialize)]
26pub struct Currency {
27    currency_code: CurrencyCode,
28    exponent: Exponent,
29}
30
31impl Currency {
32    /// Creates a new [Currency].
33    pub const fn new() -> Self {
34        Self {
35            currency_code: CurrencyCode::new(),
36            exponent: Exponent::new(),
37        }
38    }
39
40    /// Gets the [CurrencyCode].
41    pub fn currency_code(&self) -> CurrencyCode {
42        self.currency_code
43    }
44
45    /// Gets the [Currency] exponent.
46    ///
47    /// Used to get the real value of a denomination by raising 10 to the exponent, and multiplying
48    /// by the denomination amount.
49    pub fn exponent(&self) -> i32 {
50        self.exponent.inner()
51    }
52
53    /// Converts a standard value to a MDU value.
54    ///
55    /// Example:
56    ///
57    /// ```no_run
58    /// # use bnr_xfs::{Currency, CurrencyCode};
59    /// let value = 10;
60    /// let currency = Currency::from(CurrencyCode::from("USD"));
61    /// assert_eq!(currency.to_mdu_value(value), 1000);
62    /// ```
63    pub fn to_mdu_value(&self, value: u32) -> u32 {
64        (value as f32 * 10f32.powf(self.exponent.inner().abs() as f32)) as u32
65    }
66
67    /// Converts a MDU value to a standard value.
68    ///
69    /// Example:
70    ///
71    /// ```no_run
72    /// # use bnr_xfs::{Currency, CurrencyCode};
73    /// let mdu_value = 1000;
74    /// let currency = Currency::from(CurrencyCode::from("USD"));
75    /// assert_eq!(currency.from_mdu_value(mdu_value), 10);
76    /// ```
77    pub fn from_mdu_value(&self, value: u32) -> u32 {
78        (value as f32 * 10f32.powf(self.exponent.inner() as f32)) as u32
79    }
80}
81
82impl From<CurrencyCode> for Currency {
83    fn from(val: CurrencyCode) -> Self {
84        let exponent: Exponent = val.into();
85
86        Self {
87            currency_code: val,
88            exponent,
89        }
90    }
91}
92
93impl fmt::Display for Currency {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        write!(
96            f,
97            r#""currency": {{"currency_code": "{}", "exponent": {}}}"#,
98            self.currency_code, self.exponent
99        )
100    }
101}
102
103impl_xfs_struct!(Currency, "currency", [currency_code: CurrencyCode, exponent: Exponent]);