1pub trait Bytes32: Sized {
5 fn to_bytes32(&self) -> [u8; 32];
7
8 fn to_vec(&self) -> Vec<u8> {
10 self.to_bytes32().to_vec()
11 }
12}
13
14macro_rules! impl_bytes32 {
16 ($($ty:ident),+) => {
17 $(
18 impl Bytes32 for $ty {
19 fn to_bytes32(&self) -> [u8; 32] {
20 let mut bytes = [0u8; 32];
21 let ls_bytes = {
22 self.to_le_bytes()
23 .into_iter()
24 .rev()
25 .skip_while(|b| *b == 0)
26 .collect::<Vec<_>>()
27 .into_iter()
28 .rev()
29 .collect::<Vec<_>>()
30 };
31
32 bytes[(32 - ls_bytes.len())..].copy_from_slice(&ls_bytes);
33 bytes
34 }
35
36 fn to_vec(&self) -> Vec<u8> {
37 self.to_le_bytes().to_vec()
38 }
39 }
40 )+
41 };
42}
43
44impl Bytes32 for Vec<u8> {
45 fn to_bytes32(&self) -> [u8; 32] {
46 let mut bytes = [0u8; 32];
47 bytes[(32 - self.len())..].copy_from_slice(self);
48 bytes
49 }
50
51 fn to_vec(&self) -> Vec<u8> {
52 self.clone()
53 }
54}
55
56impl Bytes32 for [u8; 20] {
57 fn to_bytes32(&self) -> [u8; 32] {
58 let mut bytes = [0u8; 32];
59 bytes[12..].copy_from_slice(self);
60 bytes
61 }
62}
63
64impl Bytes32 for [u8; 32] {
65 fn to_bytes32(&self) -> [u8; 32] {
66 *self
67 }
68
69 fn to_vec(&self) -> Vec<u8> {
70 self.as_ref().into()
71 }
72}
73
74impl Bytes32 for &[u8] {
75 fn to_bytes32(&self) -> [u8; 32] {
76 let mut bytes = [0u8; 32];
77 bytes[(32 - self.len())..].copy_from_slice(self);
78 bytes
79 }
80
81 fn to_vec(&self) -> Vec<u8> {
82 (*self).into()
83 }
84}
85
86impl Bytes32 for () {
87 fn to_bytes32(&self) -> [u8; 32] {
88 [0; 32]
89 }
90
91 fn to_vec(&self) -> Vec<u8> {
92 Default::default()
93 }
94}
95
96impl Bytes32 for &str {
97 fn to_bytes32(&self) -> [u8; 32] {
98 let mut bytes = [0u8; 32];
99 bytes[(32 - self.len())..].copy_from_slice(self.as_bytes());
100 bytes
101 }
102
103 fn to_vec(&self) -> Vec<u8> {
104 self.as_bytes().into()
105 }
106}
107
108impl Bytes32 for bool {
109 fn to_bytes32(&self) -> [u8; 32] {
110 let mut output = [0; 32];
111 if *self {
112 output[31] = 1;
113 }
114
115 output
116 }
117}
118
119impl_bytes32!(i8, u8, i16, u16, i32, u32, usize, i64, u64, i128, u128);