aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNicholas Johnson <nick@nicholasjohnson.ch>2024-05-03 00:00:00 +0000
committerNicholas Johnson <nick@nicholasjohnson.ch>2024-05-03 00:00:00 +0000
commitd54b7c97b405fb07b18b14e86693a511094dbd7ca931b827dee1b10c74ef9e08 (patch)
treef7a82386456c212362efa83a41fc0865ea45d9b05cb348a073f51a0a6134e05f
parentceea3921157757b5743ae1bf6c687b5ec156cb44091dcf15a72765d2489275ba (diff)
downloadhitomezashi-rs-d54b7c97b405fb07b18b14e86693a511094dbd7ca931b827dee1b10c74ef9e08.tar.gz
hitomezashi-rs-d54b7c97b405fb07b18b14e86693a511094dbd7ca931b827dee1b10c74ef9e08.zip
Replace println!() with write!()
This prevents unnecessary locking, which speeds up the loops.
-rw-r--r--src/lib.rs17
1 files changed, 11 insertions, 6 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 481e7eb..a494a23 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -21,19 +21,22 @@
//! 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(is_opaque: bool) {
- print!(
+fn print_square(lock: &mut StdoutLock, is_opaque: bool) {
+ write!(
+ lock,
"{}",
if is_opaque {
OPAQUE_SQUARE
} else {
TRANSPARENT_SQUARE
}
- );
+ )
+ .unwrap();
}
/// Prints a two-colored Hitomezashi stitch pattern of the specified dimensions.
@@ -102,16 +105,18 @@ 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();
+
/* 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(cur_row[col]);
+ print_square(&mut lock, cur_row[col]);
cur_row.push(cur_row[col] ^ col_bits[col]);
}
- print_square(cur_row[cur_row.capacity() - 1]);
+ print_square(&mut lock, cur_row[cur_row.capacity() - 1]);
println!(); // End of base case
for row_bit in row_bits.iter() {
@@ -123,7 +128,7 @@ pub fn generate(width: usize, height: usize, skew: Option<f64>) {
.zip(alt_bits.iter())
.for_each(|(x1, &x2)| {
*x1 ^= x2 ^ row_bit;
- print_square(*x1);
+ print_square(&mut lock, *x1);
});
println!(); // End of recursive case