1use std::fmt;
8use std::ops::{Add, Mul, Sub};
9use std::str::FromStr;
10
11pub use rust_decimal::Decimal;
12use serde::{Deserialize, Serialize};
13
14use crate::ExchangeError;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Rounding {
19 Down,
21 Up,
23 Nearest,
25}
26
27pub fn round_to(value: Decimal, increment: Decimal, mode: Rounding) -> Decimal {
29 if increment <= Decimal::ZERO {
30 return value;
31 }
32 let n = value / increment;
33 let n = match mode {
34 Rounding::Down => n.floor(),
35 Rounding::Up => n.ceil(),
36 Rounding::Nearest => n.round_dp_with_strategy(0, rust_decimal::RoundingStrategy::MidpointAwayFromZero),
37 };
38 (n * increment).normalize()
39}
40
41pub fn is_multiple(value: Decimal, increment: Decimal) -> bool {
43 increment <= Decimal::ZERO || (value % increment).is_zero()
44}
45
46macro_rules! decimal_newtype {
47 ($(#[$m:meta])* $name:ident) => {
48 $(#[$m])*
49 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
50 #[serde(transparent)]
51 pub struct $name(pub Decimal);
52
53 impl $name {
54 pub const ZERO: Self = Self(Decimal::ZERO);
55
56 pub fn new(value: Decimal) -> Self {
57 Self(value)
58 }
59
60 pub fn parse(s: &str) -> Result<Self, ExchangeError> {
62 Decimal::from_str_exact(s.trim()).map(Self).map_err(|e| ExchangeError::invalid(format!("{s:?}: {e}")))
63 }
64
65 pub fn value(self) -> Decimal {
66 self.0
67 }
68
69 pub fn is_zero(self) -> bool {
70 self.0.is_zero()
71 }
72
73 pub fn is_positive(self) -> bool {
74 self.0 > Decimal::ZERO
75 }
76
77 pub fn round_to(self, increment: Decimal, mode: Rounding) -> Self {
79 Self(round_to(self.0, increment, mode))
80 }
81
82 pub fn min(self, other: Self) -> Self {
83 if other < self { other } else { self }
84 }
85 }
86
87 impl fmt::Display for $name {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 fmt::Display::fmt(&self.0.normalize(), f)
90 }
91 }
92
93 impl FromStr for $name {
94 type Err = ExchangeError;
95 fn from_str(s: &str) -> Result<Self, ExchangeError> {
96 Self::parse(s)
97 }
98 }
99
100 impl From<Decimal> for $name {
101 fn from(d: Decimal) -> Self {
102 Self(d)
103 }
104 }
105
106 impl Add for $name {
107 type Output = Self;
108 fn add(self, o: Self) -> Self {
109 Self(self.0 + o.0)
110 }
111 }
112
113 impl Sub for $name {
114 type Output = Self;
115 fn sub(self, o: Self) -> Self {
116 Self(self.0 - o.0)
117 }
118 }
119 };
120}
121
122decimal_newtype!(
123 Price
125);
126decimal_newtype!(
127 Qty
129);
130
131impl Mul<Qty> for Price {
132 type Output = Decimal;
133 fn mul(self, q: Qty) -> Decimal {
134 self.0 * q.0
135 }
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 fn d(s: &str) -> Decimal {
143 Decimal::from_str_exact(s).unwrap()
144 }
145
146 #[test]
147 fn exact_parsing_rounding_and_strings() {
148 let p = Price::parse("64250.105").unwrap();
149 assert_eq!(p.round_to(d("0.01"), Rounding::Down), Price::parse("64250.10").unwrap());
150 assert_eq!(p.round_to(d("0.01"), Rounding::Up).to_string(), "64250.11");
151 assert_eq!(p.round_to(d("0.01"), Rounding::Nearest).to_string(), "64250.11");
152 assert_eq!(Qty::parse("0.000123456").unwrap().round_to(d("0.00001"), Rounding::Down).to_string(), "0.00012");
153 assert!(Price::parse("abc").is_err());
154 assert!(is_multiple(d("0.30"), d("0.1")) && !is_multiple(d("0.35"), d("0.1")) && is_multiple(d("7"), Decimal::ZERO));
155 assert_eq!(Price::parse("0.1").unwrap() + Price::parse("0.2").unwrap(), Price::parse("0.3").unwrap());
157 assert_eq!(Price::parse("2.5").unwrap() * Qty::parse("4").unwrap(), d("10"));
158 let json = serde_json::to_string(&Price::parse("64250.10").unwrap()).unwrap();
159 assert_eq!(json, "\"64250.10\"");
160 assert_eq!(serde_json::from_str::<Qty>("\"0.5\"").unwrap(), Qty::parse("0.5").unwrap());
161 }
162}