numext_fixed_hash_hack/
lib.rs

1// Copyright 2018-2019 Cryptape Technologies LLC.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! This is a internal crate used by [numext-fixed-hash].
10//!
11//! **Notice:
12//! You should NOT use this crate directly.
13//! Please use [numext-fixed-hash] instead of this crate.**
14//!
15//! [numext-fixed-hash]: https://docs.rs/numext-fixed-hash
16
17extern crate nfhash_core;
18
19extern crate proc_macro;
20
21use quote::quote;
22use syn::parse_macro_input;
23
24macro_rules! impl_func {
25    ($name:ident, $type:ident) =>    {
26        #[proc_macro]
27        pub fn $name(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
28            let input = parse_macro_input!(input as syn::LitStr);
29            let expanded = {
30                let input = input.value().replace("_", "");
31                if input.len() < 3 || &input[..2] != "0x" {
32                    panic!("Input has to be a hexadecimal string with 0x-prefix.");
33                };
34                let input_str = &input[2..];
35                let value = match &input_str[..1] {
36                    "0" => {
37                        if input_str.len() > 1 {
38                            nfhash_core::$type::from_hex_str(input_str)
39                        } else {
40                            nfhash_core::$type::from_trimmed_hex_str(input_str)
41                        }
42                    },
43                    _ => {
44                        nfhash_core::$type::from_trimmed_hex_str(input_str)
45                    },
46                }
47                .unwrap_or_else(|err| {
48                    panic!("Failed to parse the input hexadecimal string: {}", err);
49                });
50                let eval_str = format!("{:?}", value);
51                let eval_ts: proc_macro2::TokenStream = eval_str.parse().unwrap_or_else(|_| {
52                    panic!("Failed to parse the string \"{}\" to TokenStream.", eval_str);
53                });
54                quote!(#eval_ts)
55            };
56            expanded.into()
57        }
58    };
59}
60
61#[cfg(feature = "bits_128")]
62impl_func!(h128, H128);
63#[cfg(feature = "bits_160")]
64impl_func!(h160, H160);
65#[cfg(feature = "bits_224")]
66impl_func!(h224, H224);
67#[cfg(feature = "bits_256")]
68impl_func!(h256, H256);
69#[cfg(feature = "bits_384")]
70impl_func!(h384, H384);
71#[cfg(feature = "bits_512")]
72impl_func!(h512, H512);
73#[cfg(feature = "bits_520")]
74impl_func!(h520, H520);
75#[cfg(feature = "bits_1024")]
76impl_func!(h1024, H1024);
77#[cfg(feature = "bits_2048")]
78impl_func!(h2048, H2048);
79#[cfg(feature = "bits_4096")]
80impl_func!(h4096, H4096);