slowcat v1.0

This commit is contained in:
ddidderr 2023-02-23 14:10:17 +01:00
commit 1fa53efc72
Signed by: ddidderr
GPG Key ID: 3841F1C27E6F0E14
5 changed files with 67 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View File

@ -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"

13
Cargo.toml Normal file
View File

@ -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

3
rustfmt.toml Normal file
View File

@ -0,0 +1,3 @@
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
imports_layout = "HorizontalVertical"

43
src/main.rs Normal file
View File

@ -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();
}
}
}