currencies_core/
lib.rs

1//! Core functionality for [`currencies`](https://crates.io/crates/currencies) crate, not
2//! including proc macros.
3
4#![cfg_attr(not(feature = "std"), no_std)]
5#![warn(missing_docs)]
6
7pub mod amount;
8pub use amount::{Amount, Backing};
9pub mod currency;
10pub use currency::Currency;
11pub mod u256;
12pub use u256::U256;
13pub mod safety;
14
15#[cfg(feature = "parsing")]
16mod parsing;
17#[cfg(feature = "parsing")]
18pub use parsing::*;
19
20/// Contains impls for [`serde`] integration
21#[cfg(feature = "serde")]
22pub mod serde_integration;
23
24#[cfg(test)]
25extern crate alloc;
26
27#[cfg(test)]
28use alloc::format;
29
30#[test]
31fn show_off_currency_math() {
32    use currency::*;
33
34    let apple_cost = Amount::<USD>::from_raw(3_24);
35    let orange_cost = Amount::<USD>::from_raw(7_97);
36    assert!(apple_cost < orange_cost);
37    assert!(apple_cost + orange_cost > orange_cost);
38    assert_eq!(format!("{}", apple_cost * orange_cost), "$25.82");
39    assert_eq!(format!("{}", apple_cost * 3), "$9.72");
40
41    let mut total = Amount::<DOT>::from_raw(5762244984_10000000004u128.into());
42    total -= Amount::from_raw(1000_0000000000u128.into());
43    total *= Amount::from_raw(2_0000000000u64.into());
44    assert_eq!(format!("{}", total), "115244897682.0000000008 DOT");
45}
46
47#[test]
48fn show_off_checked_math() {
49    use currency::*;
50    use safety::*;
51
52    // When using currency amounts with `Safety = Checked`, the Amount struct has been specially set
53    // up so that only checked math will be allowed, and you can still use the normal
54    // operator-based syntax. Thus currency amounts like this should never panic and are
55    // suitable for use in critical/infallible environments.
56
57    let drink_cost = Amount::<USD, Checked>::from_raw(6_29);
58    let movie_cost = Amount::<USD, Checked>::from_raw(24_99);
59    let Some(outing_cost) = drink_cost + movie_cost else {
60        unimplemented!("compiler forces you to handle this!")
61    };
62    assert_eq!(format!("{}", outing_cost), "$31.28");
63}