Skip to main content

random_string

Function random_string 

Source
pub fn random_string(len: usize, charset: &[u8]) -> Result<String>
Available on crate feature tier3 only.
Expand description

Generate a cryptographically-secure random string of exactly len characters drawn from charset (uniformly).

Selection uses Lemire rejection sampling against charset.len(), so the per-character distribution is uniform — no modulo bias.

Each character costs one rejection-sampled draw (typically one random_u64 syscall in the common case).

§Errors

  • Returns InvalidInput if charset is empty or contains a non-ASCII byte (byte >= 128).
  • Returns io::Error if the OS CSPRNG is unavailable.

§Example

use mod_rand::{tier3, charsets};
let s = tier3::random_string(16, charsets::ALPHANUMERIC)?;
assert_eq!(s.len(), 16);