forked from solana-labs/solana-program-library
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathdecimal.rs
More file actions
217 lines (189 loc) · 5.96 KB
/
decimal.rs
File metadata and controls
217 lines (189 loc) · 5.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Math for preserving precision of token amounts which are limited
//! by the SPL Token program to be at most u64::MAX.
//!
//! Decimals are internally scaled by a WAD (10^18) to preserve
//! precision up to 18 decimal places. Decimals are sized to support
//! both serialization and precise math for the full range of
//! unsigned 64-bit integers. The underlying representation is a
//! u192 rather than u256 to reduce compute cost while losing
//! support for arithmetic operations at the high end of u64 range.
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::ptr_offset_with_cast)]
#![allow(clippy::manual_range_contains)]
use crate::{
error::LendingError,
math::{common::*, Rate},
};
use solana_program::program_error::ProgramError;
use std::{convert::TryFrom, fmt};
use uint::construct_uint;
// U192 with 192 bits consisting of 3 x 64-bit words
construct_uint! {
#[derive(Serialize)]
pub struct U192(3);
}
/// Large decimal values, precise to 18 digits
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Eq, Ord, Serialize)]
pub struct Decimal(pub U192);
impl Decimal {
/// One
pub fn one() -> Self {
Self(Self::wad())
}
/// Zero
pub fn zero() -> Self {
Self(U192::zero())
}
// OPTIMIZE: use const slice when fixed in BPF toolchain
fn wad() -> U192 {
U192::from(WAD)
}
// OPTIMIZE: use const slice when fixed in BPF toolchain
fn half_wad() -> U192 {
U192::from(HALF_WAD)
}
/// Create scaled decimal from percent value
pub fn from_percent(percent: u8) -> Self {
Self(U192::from(percent as u64 * PERCENT_SCALER))
}
/// Return raw scaled value if it fits within u128
#[allow(clippy::wrong_self_convention)]
pub fn to_scaled_val(&self) -> Result<u128, ProgramError> {
Ok(u128::try_from(self.0).map_err(|_| LendingError::MathOverflow)?)
}
/// Create decimal from scaled value
pub fn from_scaled_val(scaled_val: u128) -> Self {
Self(U192::from(scaled_val))
}
/// Round scaled decimal to u64
pub fn try_round_u64(&self) -> Result<u64, ProgramError> {
let rounded_val = Self::half_wad()
.checked_add(self.0)
.ok_or(LendingError::MathOverflow)?
.checked_div(Self::wad())
.ok_or(LendingError::MathOverflow)?;
Ok(u64::try_from(rounded_val).map_err(|_| LendingError::MathOverflow)?)
}
/// Ceiling scaled decimal to u64
pub fn try_ceil_u64(&self) -> Result<u64, ProgramError> {
let ceil_val = Self::wad()
.checked_sub(U192::from(1u64))
.ok_or(LendingError::MathOverflow)?
.checked_add(self.0)
.ok_or(LendingError::MathOverflow)?
.checked_div(Self::wad())
.ok_or(LendingError::MathOverflow)?;
Ok(u64::try_from(ceil_val).map_err(|_| LendingError::MathOverflow)?)
}
/// Floor scaled decimal to u64
pub fn try_floor_u64(&self) -> Result<u64, ProgramError> {
let ceil_val = self
.0
.checked_div(Self::wad())
.ok_or(LendingError::MathOverflow)?;
Ok(u64::try_from(ceil_val).map_err(|_| LendingError::MathOverflow)?)
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut scaled_val = self.0.to_string();
if scaled_val.len() <= SCALE {
scaled_val.insert_str(0, &vec!["0"; SCALE - scaled_val.len()].join(""));
scaled_val.insert_str(0, "0.");
} else {
scaled_val.insert(scaled_val.len() - SCALE, '.');
}
f.write_str(&scaled_val)
}
}
impl From<u64> for Decimal {
fn from(val: u64) -> Self {
Self(Self::wad() * U192::from(val))
}
}
impl From<u128> for Decimal {
fn from(val: u128) -> Self {
Self(Self::wad() * U192::from(val))
}
}
impl From<Rate> for Decimal {
fn from(val: Rate) -> Self {
Self(U192::from(val.to_scaled_val()))
}
}
impl TryAdd for Decimal {
fn try_add(self, rhs: Self) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_add(rhs.0)
.ok_or(LendingError::MathOverflow)?,
))
}
}
impl TrySub for Decimal {
fn try_sub(self, rhs: Self) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_sub(rhs.0)
.ok_or(LendingError::MathOverflow)?,
))
}
}
impl TryDiv<u64> for Decimal {
fn try_div(self, rhs: u64) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_div(U192::from(rhs))
.ok_or(LendingError::MathOverflow)?,
))
}
}
impl TryDiv<Rate> for Decimal {
fn try_div(self, rhs: Rate) -> Result<Self, ProgramError> {
self.try_div(Self::from(rhs))
}
}
impl TryDiv<Decimal> for Decimal {
fn try_div(self, rhs: Self) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_mul(Self::wad())
.ok_or(LendingError::MathOverflow)?
.checked_div(rhs.0)
.ok_or(LendingError::MathOverflow)?,
))
}
}
impl TryMul<u64> for Decimal {
fn try_mul(self, rhs: u64) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_mul(U192::from(rhs))
.ok_or(LendingError::MathOverflow)?,
))
}
}
impl TryMul<Rate> for Decimal {
fn try_mul(self, rhs: Rate) -> Result<Self, ProgramError> {
self.try_mul(Self::from(rhs))
}
}
impl TryMul<Decimal> for Decimal {
fn try_mul(self, rhs: Self) -> Result<Self, ProgramError> {
Ok(Self(
self.0
.checked_mul(rhs.0)
.ok_or(LendingError::MathOverflow)?
.checked_div(Self::wad())
.ok_or(LendingError::MathOverflow)?,
))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_scaler() {
assert_eq!(U192::exp10(SCALE), Decimal::wad());
}
}