diff options
author | Nicholas Johnson <nick@nicholasjohnson.ch> | 2024-05-13 00:00:00 +0000 |
---|---|---|
committer | Nicholas Johnson <nick@nicholasjohnson.ch> | 2024-05-13 00:00:00 +0000 |
commit | c0a9f0a0f8085f8feb2e97b59f4538e1fc48d1fcfa08e970d11dab84a9d9fc04 (patch) | |
tree | f031c081d565486d497ddde556c0150538888248076865d9bfd2cc7b0e65c58f /src/lib.rs | |
parent | 6272a7eee2349788be6591006f0004b2902d157f3ef02de1c93844fbe1fd75f8 (diff) | |
download | hitomezashi-rs-c0a9f0a0f8085f8feb2e97b59f4538e1fc48d1fcfa08e970d11dab84a9d9fc04.tar.gz hitomezashi-rs-c0a9f0a0f8085f8feb2e97b59f4538e1fc48d1fcfa08e970d11dab84a9d9fc04.zip |
Use a buffered writer
Fewer system calls speeds up runtime.
Diffstat (limited to 'src/lib.rs')
-rw-r--r-- | src/lib.rs | 48 |
1 files changed, 26 insertions, 22 deletions
@@ -21,22 +21,23 @@ //! Classic two-colored Hitomezashi stitch pattern generator. use rand::distributions::{Bernoulli, Distribution}; -use std::io::{stdout, StdoutLock, Write}; - -const TRANSPARENT_SQUARE: char = ' '; -const OPAQUE_SQUARE: char = '█'; - -fn print_square(lock: &mut StdoutLock, is_opaque: bool) { - write!( - lock, - "{}", - if is_opaque { - OPAQUE_SQUARE - } else { - TRANSPARENT_SQUARE - } - ) - .unwrap(); +use std::io::{stdout, BufWriter, StdoutLock, Write}; + +const TRANSPARENT_SQUARE: &str = " "; +const OPAQUE_SQUARE: &str = "█"; + +fn print_square(stream: &mut BufWriter<StdoutLock>, is_opaque: bool) { + stream + .write_all( + if is_opaque { + OPAQUE_SQUARE + } else { + TRANSPARENT_SQUARE + } + .to_string() + .as_bytes(), + ) + .unwrap(); } /// Prints a two-colored Hitomezashi stitch pattern of the specified dimensions. @@ -105,19 +106,20 @@ pub fn generate(width: usize, height: usize, skew: Option<f64>) { let mut cur_row: Vec<bool> = Vec::with_capacity(width); - let mut lock = stdout().lock(); + let lock = stdout().lock(); + let mut stream = BufWriter::new(lock); /* Base case * * The first row has no preceding row, so it's computing using the column stitches */ cur_row.push(first_square); for col in 0..(cur_row.capacity() - 1) { - print_square(&mut lock, cur_row[col]); + print_square(&mut stream, cur_row[col]); cur_row.push(cur_row[col] ^ col_bits[col]); } - print_square(&mut lock, cur_row[cur_row.capacity() - 1]); - writeln!(&mut lock).unwrap(); // End of base case + print_square(&mut stream, cur_row[cur_row.capacity() - 1]); + stream.write_all(b"\n").unwrap(); // End of base case for row_bit in row_bits.iter() { /* Recursive case @@ -128,9 +130,11 @@ pub fn generate(width: usize, height: usize, skew: Option<f64>) { .zip(alt_bits.iter()) .for_each(|(x1, &x2)| { *x1 ^= x2 ^ row_bit; - print_square(&mut lock, *x1); + print_square(&mut stream, *x1); }); - writeln!(&mut lock).unwrap(); // End of recursive case + stream.write_all(b"\n").unwrap(); // End of recursive case } + + stream.flush().unwrap(); } |