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
99
100
101
use core::convert::TryInto;
pub(crate) fn is_default<T: Default + PartialEq>(t: &T) -> bool {
*t == Default::default()
}
pub fn hex_serialize<S, T>(x: &T, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
T: AsRef<[u8]>,
{
s.serialize_str(&hex::encode(x.as_ref()))
}
pub fn hex_deserialize_256<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: From<[u8; 32]>,
{
let s: &str = serde::de::Deserialize::deserialize(deserializer)?;
let mut s = String::from(s);
s.retain(|c| !c.is_whitespace());
let v: [u8; 32] = hex::decode(&s)
.expect("Hex decoding failed!")
.try_into()
.unwrap();
let t = T::from(v);
Ok(t)
}
pub fn hex_deserialize_32<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: From<[u8; 4]>,
{
let s: &str = serde::de::Deserialize::deserialize(deserializer)?;
let mut s = String::from(s);
s.retain(|c| !c.is_whitespace());
let v: [u8; 4] = hex::decode(&s)
.expect("Hex decoding failed!")
.try_into()
.unwrap();
let t = T::from(v);
Ok(t)
}
pub fn block_pad_len(len: usize) -> usize {
16 * ((len + 15) / 16)
}
pub fn block_pad(data: &mut Vec<u8>) {
let size = data.len();
data.resize(block_pad_len(size), 0);
}
pub fn block_padded(data: &[u8]) -> Vec<u8> {
let mut data = Vec::from(data);
block_pad(&mut data);
data
}
pub fn word_pad_len(len: usize) -> usize {
4 * ((len + 3) / 4)
}
pub fn word_pad(data: &mut Vec<u8>) {
let size = data.len();
data.resize(word_pad_len(size), 0);
}
pub fn word_padded(data: &[u8]) -> Vec<u8> {
let mut data = Vec::from(data);
word_pad(&mut data);
data
}