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
pub trait ToNumberRepresentation: Sized {
    type Err;
    fn to_number_representation(self) -> Result<Vec<u8>, Self::Err>;
}

pub enum IntegerRepresentor {}
pub enum FloatRepresentor {}

pub trait Representor<N> {
    type Err;
    fn represent(n: N) -> Result<Vec<u8>, Self::Err>;
}
impl<N: itoa::Integer> Representor<N> for IntegerRepresentor {
    type Err = crate::Error;
    fn represent(n: N) -> Result<Vec<u8>, Self::Err> {
        let mut buffer = itoa::Buffer::new();
        let represented = buffer.format(n);
        Ok(represented.as_bytes().to_vec())
    }
}
impl<N: ryu::Float> Representor<N> for FloatRepresentor {
    type Err = crate::Error;
    fn represent(n: N) -> Result<Vec<u8>, Self::Err> {
        let mut buffer = ryu::Buffer::new();
        let represented = buffer.format(n);
        Ok(represented.as_bytes().to_vec())
    }
}

pub trait Represent: Sized {
    type Representor: Representor<Self>;
    fn represent(self) -> Result<Vec<u8>, <Self::Representor as Representor<Self>>::Err> {
        Self::Representor::represent(self)
    }
}

impl<T: Represent> ToNumberRepresentation for T {
    type Err = <T::Representor as Representor<T>>::Err;
    fn to_number_representation(self) -> Result<Vec<u8>, Self::Err> {
        self.represent()
    }
}

impl Represent for u8 {
    type Representor = IntegerRepresentor;
}
impl Represent for u16 {
    type Representor = IntegerRepresentor;
}
impl Represent for u32 {
    type Representor = IntegerRepresentor;
}
impl Represent for u64 {
    type Representor = IntegerRepresentor;
}
impl Represent for u128 {
    type Representor = IntegerRepresentor;
}
impl Represent for i8 {
    type Representor = IntegerRepresentor;
}
impl Represent for i16 {
    type Representor = IntegerRepresentor;
}
impl Represent for i32 {
    type Representor = IntegerRepresentor;
}
impl Represent for i64 {
    type Representor = IntegerRepresentor;
}
impl Represent for i128 {
    type Representor = IntegerRepresentor;
}
impl Represent for f32 {
    type Representor = FloatRepresentor;
}
impl Represent for f64 {
    type Representor = FloatRepresentor;
}