decimal_rs/lib.rs
1// Copyright 2021 CoD Technologies Corp.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! High precision decimal with maximum precision of 38.
16//!
17//! ## Optional features
18//!
19//! ### `serde`
20//!
21//! When this optional dependency is enabled, `Decimal` implements the `serde::Serialize` and
22//! `serde::Deserialize` traits.
23//!
24//! ## Usage
25//!
26//! To build a decimal, use [`Decimal`]:
27//!
28//! ```
29//! use decimal_rs::Decimal;
30//!
31//! let n1: Decimal = "123".parse().unwrap();
32//! let n2: Decimal = "456".parse().unwrap();
33//! let result = n1 + n2;
34//! assert_eq!(result.to_string(), "579");
35//! ```
36//!
37//! To build a decimal from Rust primitive types:
38//!
39//! ```
40//! use decimal_rs::Decimal;
41//!
42//! let n1 = Decimal::from(123_i32);
43//! let n2 = Decimal::from(456_i32);
44//! let result = n1 + n2;
45//! assert_eq!(result, Decimal::from(579_i32));
46//! ```
47//!
48//! Decimal supports high precision arithmetic operations.
49//!
50//! ```
51//! use decimal_rs::Decimal;
52//!
53//! let n1: Decimal = "123456789.987654321".parse().unwrap();
54//! let n2: Decimal = "987654321.123456789".parse().unwrap();
55//! let result = n1 * n2;
56//! assert_eq!(result.to_string(), "121932632103337905.662094193112635269");
57//! ```
58//!
59//! Decimal can be encoded to bytes and decoded from bytes.
60//!
61//! ```
62//! use decimal_rs::Decimal;
63//!
64//! let n1 = "123456789.987654321".parse::<Decimal>().unwrap();
65//! let mut bytes = Vec::new();
66//! n1.encode(&mut bytes).unwrap();
67//! let n2 = Decimal::decode(&bytes);
68//! assert_eq!(n1, n2);
69//! ```
70
71#![cfg_attr(docsrs, feature(doc_cfg))]
72
73mod convert;
74mod decimal;
75mod error;
76mod ops;
77mod parse;
78mod u256;
79
80#[cfg(feature = "serde")]
81mod serde;
82
83pub use crate::decimal::{
84 Decimal, DECIMAL128, DECIMAL64, DECIMAL64_MAX_PRECISION, MAX_BINARY_SIZE, MAX_PRECISION, MAX_SCALE, MIN_SCALE,
85};
86pub use crate::error::{DecimalConvertError, DecimalFormatError, DecimalParseError};