compile_rand/lib.rs
1//! # compile-rand
2//!
3//! This crate provides the `compile_rand!` macro, which will generate a random number of the given
4//! integer type at compile time.
5//!
6//! In other words, if – for whatever reason – you actually need [this XKCD comic][221]:
7//!
8//! [][221]
9//!
10//! ...then this crate will give it to you!
11//!
12//! ## Usage
13//!
14//! ```
15//! use compile_rand::compile_rand;
16//!
17//! let r = compile_rand!(i64);
18//! println!("{}", r); // A new number each time the program is compiled.
19//! ```
20//!
21//! [221]: https://xkcd.com/221/
22
23use proc_macro::TokenStream;
24use quote::quote;
25
26#[proc_macro]
27pub fn compile_rand(tokens: TokenStream) -> TokenStream {
28 macro_rules! random {
29 ($t:ty) => {{
30 let r = rand::random::<$t>();
31 quote! { #r }
32 }};
33 }
34 match tokens.to_string().as_str() {
35 "i8" => random!(i8),
36 "i16" => random!(i16),
37 "i32" => random!(i32),
38 "i64" => random!(i64),
39 "i128" => random!(i128),
40 "u8" => random!(u8),
41 "u16" => random!(u16),
42 "u32" => random!(u32),
43 "u64" => random!(u64),
44 "u128" => random!(u128),
45 _ => quote! { compile_error!("compile_rand must receive a Rust fixed integer type") },
46 }
47 .into()
48}