commodity/lib.rs
1//! A library with primatives representing commodities/money.
2//!
3//! # Optional Features
4//!
5//! The commodity package has the following optional cargo features:
6//!
7//! + `serde-support`
8//! + Disabled by default
9//! + Enables support for serialization/de-serialization via `serde`
10//!
11//! # Usage
12//!
13//! This library revolves around the [Commodity](Commodity) struct,
14//! which stores a value using
15//! [rust_decimal::Decimal](rust_decimal::Decimal), and a
16//! [CommodityTypeID](CommodityTypeID) which denotes the type of commodity.
17//! Commodities with different currencies cannot interact with
18//! mathematical operations such as `add`, `sub`, etc, this is checked
19//! at runtime.
20//!
21//! [CommodityTypeID](CommodityTypeID) designed to be used directly when
22//! when working with commodities, it is backed by a small fixed size
23//! array which supports the [Copy](std::marker::Copy) trait,
24//! hopefully making it easier fast, lock-free concurrent code that
25//! deals with commodities.
26//!
27//! [CommodityType](CommodityType) is designed to store useful user-facing
28//! information about the currency being referenced by the
29//! [CommodityTypeID](CommodityTypeID), such as its full name/description.
30//!
31//! ```
32//! use commodity::{Commodity, CommodityType, CommodityTypeID};
33//! use rust_decimal::Decimal;
34//! use std::str::FromStr;
35//!
36//! // Create a currency from its iso4317 three character code.
37//! // The currency stores information associated with the currency,
38//! // such as the full name ("United States dollar" for this one).
39//! let usd = CommodityType::from_currency_alpha3("USD").unwrap();
40//!
41//! // Create a commodity with a value of "2.02 USD"
42//! let commodity1 = Commodity::new(Decimal::from_str("2.02").unwrap(), &usd);
43//!
44//! // Create commodities using the `from_str` method
45//! let commodity2 = Commodity::from_str("24.00 USD").unwrap();
46//!
47//! // Create commodity using a CommodityTypeID
48//! let nzd_code = CommodityTypeID::from_str("NZD").unwrap();
49//! let commodity3 = Commodity::new(Decimal::from_str("24.00").unwrap(), nzd_code);
50//!
51//! // Add two compatible (same currency) commodities, the result has
52//! // the same currency (in this case, "USD").
53//! let commodity4 = commodity1.add(&commodity2).unwrap();
54//!
55//! // Try to subtract two incompatible commodities
56//! let result = commodity3.sub(&commodity2);
57//! assert!(result.is_err());
58//! ```
59
60extern crate arrayvec;
61extern crate chrono;
62#[cfg(feature = "iso4217")]
63extern crate iso4217;
64extern crate rust_decimal;
65
66#[cfg(feature = "serde-support")]
67extern crate serde;
68
69#[cfg(test)]
70#[cfg(feature = "serde-support")]
71extern crate serde_json;
72
73mod commodity;
74pub mod exchange_rate;
75
76pub use crate::commodity::*;
77
78#[cfg(doctest)]
79#[macro_use]
80extern crate doc_comment;
81
82#[cfg(doctest)]
83doctest!("../README.md");