sts10 / phraze

Generate random passphrases
https://sts10.github.io/2023/10/24/phraze-passphrase-generator.html
Mozilla Public License 2.0
24 stars 3 forks source link

Simplify build.rs with write macro #10

Closed wezm closed 1 year ago

wezm commented 1 year ago

This is incomplete (posting as an example) but just wanted to point out using the write macro can simplify the code generation in build.rs.

sts10 commented 1 year ago

Oh neat!

By "incomplete," I'm hoping you just meant that the write! macro could be used throughout the function. Cuz that's what I did before merging:

/// Write the words from the word list file into a Rust Array for program's use.
fn words(mut f_dest: &File, const_name: &str, fname_src: &str, list_size: usize) {
    // Declare a new Rust constant that is an array of slices.
    // To maximize efficiency, make it the exact size of this word list.
    write!(f_dest, "const {const_name}: &[&str; {list_size}] = &[").unwrap();

    // Read words in and add them to this array
    let f_src = BufReader::new(File::open(fname_src).unwrap());
    for word in f_src.lines() {
        match word {
            // We're writing a Rust Array programmtically, so need the word to be surround by
            // double quotes and have a comma between words.
            Ok(word) => write!(f_dest, "\"{word}\",").unwrap(),
            Err(_e) => panic!("Error reading line from built-in list"),
        }
    }

    // Close array syntax
    f_dest.write_all(b"];").unwrap();
}

Tests pass! And benchmark is roughly the same. Thanks!

wezm commented 1 year ago

By "incomplete," I'm hoping you just meant that the write! macro could be used throughout the function.

Yep that's what I meant.