How to Generate Random Unicode Strings in Rust?

How to Generate Random Unicode Strings in Rust?

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(())
}

Rust Playground link

2

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()
}

Playground

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.