macro_rules! random { ($ty:ident $(, $seeds:expr)* $(,)?) => { ... }; }
Expand description
Compiletime random number generator.
Supported types are u8
, u16
, u32
, u64
, usize
, i8
, i16
, i32
, i64
, isize
, bool
, f32
and f64
.
The integer types generate a random value in their respective range.
The float types generate a random value in range of [1.0, 2.0)
.
While the result is generated at compiletime only the integer types are available in const contexts.
const RND: i32 = obfstr::random!(u8) as i32;
assert!(RND >= 0 && RND <= 255);
The behavior of the macro inside other macros can be surprising:
// When used as top-level input to macros, random works as expected
assert_ne!(obfstr::random!(u64), obfstr::random!(u64));
// When used inside the definition of a macro, random does not work as expected
macro_rules! inside {
() => {
assert_eq!(obfstr::random!(u64), obfstr::random!(u64));
};
}
inside!();
// When provided a unique seed, random works as expected
// Note that the seeds must evaluate to a literal!
macro_rules! seeded {
() => {
assert_ne!(obfstr::random!(u64, "lhs"), obfstr::random!(u64, "rhs"));
};
}
seeded!();
// Repeated usage in macros, random does not work as expected
macro_rules! repeated {
($($name:ident),*) => {
$(let $name = obfstr::random!(u64, "seed");)*
};
}
repeated!(a, b);
assert_eq!(a, b);
// Provide additional unique seeds, random works as expected
macro_rules! repeated_seeded {
($($name:ident),*) => {
$(let $name = obfstr::random!(u64, "seed", stringify!($name));)*
};
}
repeated_seeded!(c, d);
assert_ne!(c, d);