larust_http/random.rs
1use rand::Rng;
2use std::fmt::Write;
3
4/// `byte_len` cryptographically-strong random bytes, hex-encoded - for
5/// anywhere a short, unpredictable, URL/filename-safe token is needed
6/// (a CSRF token, a generated upload filename) but a full `uuid` dependency
7/// would be overkill for. `rand` is already a dependency of this crate for
8/// exactly this reason.
9pub fn random_hex(byte_len: usize) -> String {
10 let mut bytes = vec![0u8; byte_len];
11 rand::thread_rng().fill(&mut bytes[..]);
12
13 let mut hex = String::with_capacity(byte_len * 2);
14 for byte in bytes {
15 // `write!` into a `String` never fails.
16 let _ = write!(hex, "{byte:02x}");
17 }
18 hex
19}