I'm implementing a fuzzer and I'd like to generate random unicode strings. I came up with this solution, however, it's very inefficient and seldomly produces some string. Is there a better way to generate unicode strings?
Thank you.
use rand::{thread_rng, Error, Rng};
use std::convert::TryFrom;
fn main() -> Result<(), Error> {
let mut rng = thread_rng();
let mut arr: Vec<u32> = vec![0; 1024];
rng.try_fill(&mut arr[..])?;
println!(
"{:?}",
arr.iter()
.map(|u| char::try_from(*u))
.flatten()
.collect::<String>()
);
Ok(())
}
1 Answer
Use something like this:
fn get_random_string(len: usize) -> String {
rand::thread_rng()
.sample_iter::<char, _>(rand::distributions::Standard)
.take(len)
.collect()
}
You might want to filter control characters, if you want to print it. Also the character distribution is very unlike any UTF-8 strings you might encounter in the wild.