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
use core::convert::TryFrom;
use proc_macro2::TokenStream as TokenStream2;
use syn::spanned::Spanned as _;
pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) {
use ::blake2::digest::{
Update as _,
VariableOutput as _,
};
let mut blake2 = blake2::VarBlake2b::new_keyed(&[], 32);
blake2.update(input);
blake2.finalize_variable(|result| output.copy_from_slice(result));
}
#[derive(Debug)]
pub struct Blake2x256Macro {
hash: [u8; 32],
input: syn::Lit,
}
impl Blake2x256Macro {
pub fn hash(&self) -> [u8; 32] {
self.hash
}
pub fn input(&self) -> &syn::Lit {
&self.input
}
}
impl TryFrom<TokenStream2> for Blake2x256Macro {
type Error = syn::Error;
fn try_from(input: TokenStream2) -> Result<Self, Self::Error> {
let input_span = input.span();
let lit = syn::parse2::<syn::Lit>(input).map_err(|error| {
format_err!(
input_span,
"expected string or byte string literal as input: {}",
error
)
})?;
let input_bytes = match lit {
syn::Lit::Str(ref lit_str) => lit_str.value().into_bytes(),
syn::Lit::ByteStr(ref byte_str) => byte_str.value(),
invalid => {
return Err(format_err!(
invalid.span(),
"expected string or byte string literal as input. found {:?}",
invalid,
))
}
};
let mut output = [0u8; 32];
blake2b_256(&input_bytes, &mut output);
Ok(Self {
hash: output,
input: lit,
})
}
}