|
1 | 1 | extern crate proc_macro;
|
2 | 2 |
|
| 3 | +use getrandom; |
3 | 4 | use proc_macro::TokenStream;
|
4 | 5 | use proc_macro_hack::proc_macro_hack;
|
5 |
| -use rand::rngs::OsRng; |
6 |
| -use rand::Rng; |
| 6 | +use std::mem; |
| 7 | + |
| 8 | +// Ideally we would use the proper interface for this through the rand crate, |
| 9 | +// but due to https://github.com/rust-lang/cargo/issues/5730 this leads to |
| 10 | +// issues for no_std crates that try to use rand themselves. So instead we skip |
| 11 | +// rand and generate random bytes straight from the OS. |
| 12 | +fn gen_random<T>() -> T { |
| 13 | + let mut out = [0u8; 16]; |
| 14 | + getrandom::getrandom(&mut out).unwrap(); |
| 15 | + unsafe { mem::transmute_copy(&out) } |
| 16 | +} |
7 | 17 |
|
8 | 18 | #[proc_macro_hack]
|
9 | 19 | pub fn const_random(input: TokenStream) -> TokenStream {
|
10 | 20 | match &input.to_string()[..] {
|
11 |
| - "u8" => format!("0x{:x}", OsRng.gen::<u8>()).parse().unwrap(), |
12 |
| - "u16" => format!("0x{:x}", OsRng.gen::<u16>()).parse().unwrap(), |
13 |
| - "u32" => format!("0x{:x}", OsRng.gen::<u32>()).parse().unwrap(), |
14 |
| - "u64" => format!("0x{:x}", OsRng.gen::<u64>()).parse().unwrap(), |
15 |
| - "u128" => format!("0x{:x}", OsRng.gen::<u128>()).parse().unwrap(), |
16 |
| - "i8" => format!("0x{:x}", OsRng.gen::<i8>()).parse().unwrap(), |
17 |
| - "i16" => format!("0x{:x}", OsRng.gen::<i16>()).parse().unwrap(), |
18 |
| - "i32" => format!("0x{:x}", OsRng.gen::<i32>()).parse().unwrap(), |
19 |
| - "i64" => format!("0x{:x}", OsRng.gen::<i64>()).parse().unwrap(), |
20 |
| - "i128" => format!("0x{:x}", OsRng.gen::<i128>()).parse().unwrap(), |
| 21 | + "u8" => format!("0x{:x}", gen_random::<u8>()).parse().unwrap(), |
| 22 | + "u16" => format!("0x{:x}", gen_random::<u16>()).parse().unwrap(), |
| 23 | + "u32" => format!("0x{:x}", gen_random::<u32>()).parse().unwrap(), |
| 24 | + "u64" => format!("0x{:x}", gen_random::<u64>()).parse().unwrap(), |
| 25 | + "u128" => format!("0x{:x}", gen_random::<u128>()).parse().unwrap(), |
| 26 | + "i8" => format!("0x{:x}", gen_random::<i8>()).parse().unwrap(), |
| 27 | + "i16" => format!("0x{:x}", gen_random::<i16>()).parse().unwrap(), |
| 28 | + "i32" => format!("0x{:x}", gen_random::<i32>()).parse().unwrap(), |
| 29 | + "i64" => format!("0x{:x}", gen_random::<i64>()).parse().unwrap(), |
| 30 | + "i128" => format!("0x{:x}", gen_random::<i128>()).parse().unwrap(), |
21 | 31 | _ => panic!("Invalid integer type"),
|
22 | 32 | }
|
23 |
| - |
24 | 33 | }
|
0 commit comments