token_hex
is literally nothing more than the hex-encoding of token_bytes
, which is why you specify a number of bytes:
def token_hex(nbytes=None):
return binascii.hexlify(token_bytes(nbytes)).decode('ascii')
Thus while rust has nothing which does that out of the box (to say nothing of builtin) the solution is simple: generate random bytes, then hex-encode them.
Funnily enough the hex-encoding is the more annoying of the two (on the playground anyway) because &[u8]
doesn't implement LowerHex
but the playground has neither hex
nor rustc_serialize
(which I believe are the two most popular crates for hex encoding, if you don't want to hand-roll it).
Anyway,
use rand::RngCore;
use rustc_serialize::hex::ToHex;
fn main() {
// compile-time length, use `vec![0;len]` for runtime
let mut bytes = [0; 16];
rand::thread_rng().fill_bytes(&mut bytes);
// demo-ing both crates, either works
println!("{}", hex::encode(&bytes));
println!("{}", bytes.to_hex());
}
For a single-expression version you could use Rng::gen
but I don't think it works for runtime sizes, and I don't think it looks great either:
use rand::Rng;
fn main() {
println!("{}", hex::encode(&rand::thread_rng().gen::<[u8; 16]>()));
}