https://github.com/kellpossible/commodity
A library for representing commodities/currencies in Rust
https://github.com/kellpossible/commodity
Last synced: about 1 year ago
JSON representation
A library for representing commodities/currencies in Rust
- Host: GitHub
- URL: https://github.com/kellpossible/commodity
- Owner: kellpossible
- License: other
- Created: 2020-03-01T21:59:21.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-06-17T18:57:32.000Z (almost 6 years ago)
- Last Synced: 2025-03-26T23:04:13.094Z (about 1 year ago)
- Language: Rust
- Homepage:
- Size: 69.3 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Commodity [](https://crates.io/crates/commodity) [](https://docs.rs/commodity/) [](https://github.com/kellpossible/commodity/blob/master/LICENSE.txt) [](https://github.com/kellpossible/commodity/actions?query=workflow%3ARust)
A library for representing commodities/currencies, and exchange rates/conversions between them in Rust. Values are backed by the [rust_decimal](https://crates.io/crates/rust_decimal) library.
**[Changelog](./CHANGELOG.md)**
## Optional Features
The following features can be enabled to provide extra functionality:
+ `serde-support`
+ Enables support for serialization/de-serialization via `serde`
## Example
```rust
use commodity::{Commodity, CommodityType, CommodityTypeID};
use rust_decimal::Decimal;
use std::str::FromStr;
// Create a commodity type from a currency's iso4317 three character code.
// The CommodityType stores information associated with that currency,
// such as the full name ("United States dollar" for this one).
let usd = CommodityType::from_currency_alpha3("USD").unwrap();
// Create a commodity with a value of "2.02 USD"
let commodity1 = Commodity::new(Decimal::from_str("2.02").unwrap(), &usd);
// Create commodities using the `from_str` method
let commodity2 = Commodity::from_str("24.00 USD").unwrap();
// Create commodity using a CommodityTypeID
let nzd_code = CommodityTypeID::from_str("NZD").unwrap();
let commodity3 = Commodity::new(Decimal::from_str("24.00").unwrap(), nzd_code);
// Add two compatible (same currency) commodities, the result has
// the same currency (in this case, "USD").
let commodity4 = commodity1.add(&commodity2).unwrap();
// Try to subtract two incompatible commodities
let result = commodity3.sub(&commodity2);
assert!(result.is_err());
```