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
pub trait IntoPoints {
fn into_points(self) -> u64;
}
impl IntoPoints for f64 {
#[inline(always)]
fn into_points(self) -> u64 {
points(self)
}
}
impl IntoPoints for f32 {
#[inline(always)]
fn into_points(self) -> u64 {
points(self as f64)
}
}
impl IntoPoints for u64 {
#[inline(always)]
fn into_points(self) -> u64 {
self
}
}
pub trait IntoPrice {
fn into_price(self) -> f64;
}
impl IntoPrice for u64 {
#[inline(always)]
fn into_price(self) -> f64 {
price(self)
}
}
impl IntoPrice for f64 {
fn into_price(self) -> f64 {
self
}
}
impl IntoPrice for f32 {
fn into_price(self) -> f64 {
self as f64
}
}
#[inline(always)]
pub fn points(price: f64) -> u64 {
(price * 1e8).round() as u64
}
#[inline(always)]
pub fn price(points: u64) -> f64 {
points as f64 / 1e8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn price_points() {
assert_eq!(points(1.0), 100000000);
assert_eq!(points(2.55751896), 255751896);
assert_eq!(points(0.00049245), 49245);
assert_eq!(price(49245), 0.00049245);
assert_eq!(points(0.015399360), 1539936);
assert_eq!(price(1539936), 0.01539936);
assert_eq!(points(0.09744111), 9744111);
assert_eq!(price(9744111), 0.09744111);
assert_eq!(points(0.15399360), 15399360);
assert_eq!(price(15399360), 0.15399360);
assert_eq!(points(0.00000354), 354);
assert_eq!(price(354), 0.00000354);
assert_eq!(points(0.20425743), 20425743);
assert_eq!(price(20425743), 0.20425743);
assert_eq!(points(0.03300001), 03300001);
assert_eq!(price(03300001), 0.03300001);
assert_eq!(points(0.00010030), 10030);
assert_eq!(price(10030), 0.00010030);
assert_eq!(points(0.00001104), 1104);
assert_eq!(price(1104), 0.00001104);
assert_eq!(points(0.01497375), 1497375);
assert_eq!(price(1497375), 0.01497375);
}
#[test]
fn points_u64_max() {
let r = points(0.00015370);
let a = points(12e6);
assert!(r * a < ::std::u64::MAX);
}
}