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
//! Convert unsigned types to/from `Bson::FloatingPoint`

use serde::{Deserialize, Deserializer, Serializer};

/// Converts primitive unsigned types to `f64`
pub trait ToF64 {
    /// Converts to `f64` value
    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
    }
}

/// Serialize unsigned types to `Bson::FloatingPoint`
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())
}

/// Converts from `f64` value
pub trait FromF64 {
    /// Converts from `f64` value
    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
    }
}

/// Deserialize unsigned types to `Bson::FloatingPoint`
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)
}