-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfixed_point.fe
More file actions
59 lines (47 loc) · 1.78 KB
/
Copy pathfixed_point.fe
File metadata and controls
59 lines (47 loc) · 1.78 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
/// Fixed-point arithmetic with compile-time scale.
///
/// The scale factor is a type parameter, so the compiler rejects
/// mixing values of different scales:
///
/// const WAD: u256 = 1_000_000_000_000_000_000
/// const RAY: u256 = 1_000_000_000_000_000_000_000_000_000
/// let price: FixedPoint<WAD> = FixedPoint<WAD>::from_int(42)
/// let rate: FixedPoint<RAY> = FixedPoint<RAY>::from_int(1)
/// let bad = price + rate // compile error: type mismatch
use core::ops::{Add, Sub}
use core::Copy
pub struct FixedPoint<const SCALE: u256> {
pub raw: u256,
}
impl<const S: u256> Copy for FixedPoint<S> {}
impl<const S: u256> Add for FixedPoint<S> {
const fn add(own self, _ rhs: own FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: self.raw + rhs.raw }
}
}
impl<const S: u256> Sub for FixedPoint<S> {
const fn sub(own self, _ rhs: own FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: self.raw - rhs.raw }
}
}
impl<const S: u256> FixedPoint<S> {
pub const fn from_raw(raw: u256) -> FixedPoint<S> {
FixedPoint<S> { raw }
}
pub const fn one() -> FixedPoint<S> { FixedPoint<S> { raw: S } }
pub const fn from_int(n: u256) -> FixedPoint<S> {
FixedPoint<S> { raw: n * S }
}
pub const fn mul_down(self, rhs: FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: self.raw * rhs.raw / S }
}
pub const fn mul_up(self, rhs: FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: (self.raw * rhs.raw + S - 1) / S }
}
pub const fn div_down(self, rhs: FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: self.raw * S / rhs.raw }
}
pub const fn div_up(self, rhs: FixedPoint<S>) -> FixedPoint<S> {
FixedPoint<S> { raw: (self.raw * S + rhs.raw - 1) / rhs.raw }
}
}