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
//! Utils for bytes conversion.

/// Trait for converting type to bytes32.
pub trait Bytes32: Sized {
    /// Convert type to the lowest significant bytes 32.
    fn to_bytes32(&self) -> [u8; 32];

    /// Convert type to vec of bytes.
    fn to_vec(&self) -> Vec<u8>;
}

/// Implement Bytes32 for types.
macro_rules! impl_bytes32 {
    ($($ty:ident),+) => {
        $(
            impl Bytes32 for $ty {
                fn to_bytes32(&self) -> [u8; 32] {
                    let mut bytes = [0u8; 32];
                    let ls_bytes = {
                        self.to_le_bytes()
                            .into_iter()
                            .rev()
                            .skip_while(|b| *b == 0)
                            .collect::<Vec<_>>()
                            .into_iter()
                            .rev()
                            .collect::<Vec<_>>()
                    };

                    bytes[(32 - ls_bytes.len())..].copy_from_slice(&ls_bytes);
                    bytes
                }

                fn to_vec(&self) -> Vec<u8> {
                    self.to_le_bytes().to_vec()
                }
            }
        )+
    };
}

impl Bytes32 for Vec<u8> {
    fn to_bytes32(&self) -> [u8; 32] {
        let mut bytes = [0u8; 32];
        bytes[(32 - self.len())..].copy_from_slice(self);
        bytes
    }

    fn to_vec(&self) -> Vec<u8> {
        self.clone()
    }
}

impl Bytes32 for [u8; 32] {
    fn to_bytes32(&self) -> [u8; 32] {
        *self
    }

    fn to_vec(&self) -> Vec<u8> {
        self.as_ref().into()
    }
}

impl Bytes32 for &[u8] {
    fn to_bytes32(&self) -> [u8; 32] {
        let mut bytes = [0u8; 32];
        bytes[(32 - self.len())..].copy_from_slice(self);
        bytes
    }

    fn to_vec(&self) -> Vec<u8> {
        (*self).into()
    }
}

impl Bytes32 for () {
    fn to_bytes32(&self) -> [u8; 32] {
        [0; 32]
    }

    fn to_vec(&self) -> Vec<u8> {
        Default::default()
    }
}

impl Bytes32 for &str {
    fn to_bytes32(&self) -> [u8; 32] {
        let mut bytes = [0u8; 32];
        bytes[(32 - self.len())..].copy_from_slice(self.as_bytes());
        bytes
    }

    fn to_vec(&self) -> Vec<u8> {
        self.as_bytes().into()
    }
}

impl_bytes32!(i8, u8, i16, u16, i32, u32, usize, i64, u64, i128, u128);