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
use serde::{Deserialize, Deserializer, Serializer};
pub trait ToF64 {
fn to_f64(&self) -> f64;
}
impl ToF64 for u8 {
fn to_f64(&self) -> f64 {
*self as f64
}
}
impl ToF64 for u16 {
fn to_f64(&self) -> f64 {
*self as f64
}
}
impl ToF64 for u32 {
fn to_f64(&self) -> f64 {
*self as f64
}
}
impl ToF64 for u64 {
fn to_f64(&self) -> f64 {
*self as f64
}
}
pub fn serialize<T, S>(v: &T, s: S) -> Result<S::Ok, S::Error>
where T: ToF64,
S: Serializer
{
s.serialize_f64(v.to_f64())
}
pub trait FromF64 {
fn from_f64(v: f64) -> Self;
}
impl FromF64 for u8 {
fn from_f64(v: f64) -> u8 {
v as u8
}
}
impl FromF64 for u16 {
fn from_f64(v: f64) -> u16 {
v as u16
}
}
impl FromF64 for u32 {
fn from_f64(v: f64) -> u32 {
v as u32
}
}
impl FromF64 for u64 {
fn from_f64(v: f64) -> u64 {
v as u64
}
}
pub fn deserialize<'de, T, D>(d: D) -> Result<T, D::Error>
where D: Deserializer<'de>,
T: FromF64
{
f64::deserialize(d).map(T::from_f64)
}