commit 1fa53efc72624fe393cbdf52d5aea461f71b0af4 Author: ddidderr Date: Thu Feb 23 14:10:17 2023 +0100 slowcat v1.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..a5348a1 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "slowcat" +version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..156bb23 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "slowcat" +version = "1.0.0" +edition = "2021" + +[dependencies] + +[profile.release] +lto = true +strip = true +debug = false +panic = "unwind" +codegen-units = 1 diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..e270811 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +group_imports = "StdExternalCrate" +imports_granularity = "Crate" +imports_layout = "HorizontalVertical" diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..8f569c4 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,43 @@ +use std::{ + env, + io::{stdin, stdout, Read, StdoutLock, Write}, + time::Duration, +}; + +static DEFAULT_HZ: u32 = 100; + +fn output_slow(data: &[u8], hz: u32, out: &mut StdoutLock) { + // write 1 byte at a time + data.iter().for_each(|&b| { + out.write_all(&[b]).unwrap(); + out.flush().unwrap(); + + // sleep according to given frequency + std::thread::sleep(Duration::from_secs_f64(1.0 / hz as f64)); + }); +} + +fn main() { + let hz: u32 = env::args() + .nth(1) + .map_or(DEFAULT_HZ, |s| s.parse().unwrap()); + + let mut out = stdout().lock(); + let mut buf = [0u8; 8 * 1024]; + + // read 8k + while let Ok(n) = stdin().read(&mut buf) { + if n == 0 { + break; // EOF + } + + let data = &buf[..n]; + if hz != 0 { + // slow output with delay according to given frequency + output_slow(data, hz, &mut out); + } else { + // normal output without delay if given frequency is zero + out.write_all(data).unwrap(); + } + } +}