jeudi 25 mars 2021

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




Aucun commentaire:

Enregistrer un commentaire