Tahler / currency-rs

A library providing a way to represent currencies in Rust.
http://tahler.github.io/currency-rs/currency/index.html
MIT License
8 stars 4 forks source link

Support currency symbols as strings + bugfix #10

Open Moxinilian opened 5 years ago

Moxinilian commented 5 years ago

This PR fixes #9.

As all methods are now generic over char representations (meaning char, &str, String...), this is not a breaking change! 🎉

Those changes also mean that creating a Currency now requires a second allocation to hold the symbol. This should be negligible next to the parsing process, and hopefully the BigInt allocation. I also got rid of the Option, as an empty string now plays the same role.

I added a couple methods to make the use of currency symbols easier as well. They are all generic, and passing a String to them does not reallocate.

To make the new behavior clearer, here are the tests I added:

let expected = Currency { symbol: "USD".into(), coin: BigInt::from(-12000) };
let actual = Currency::from_str("-USD120").unwrap();
assert_eq!(expected, actual);
let actual = Currency::from_str("USD-120").unwrap();
assert_eq!(expected, actual);
let actual = Currency::from_str("(USD1€20EUR)JPY").unwrap();
assert_eq!(expected, actual);
let actual = Currency::from_str("USD(D120)").unwrap();
assert_eq!(expected, actual);

let expected = Currency { symbol: "".into(), coin: BigInt::from(12000) };
let actual = Currency::from_str("120USD").unwrap();
assert_eq!(expected, actual);
let actual = Currency::from_str("1U2S0D").unwrap();
assert_eq!(expected, actual);

assert_eq!(
    Currency { symbol: "USD".into(), coin: BigInt::from(100010) }.to_string(),
    "USD1,000.10"
);

assert_eq!(
    Currency { symbol: "USD ".into(), coin: BigInt::from(100010) }.to_string(),
    "USD 1,000.10"
);

I also fixed a bug with Display that was displaying $100.00 as $,100.00.