slowcat v1.0

This commit is contained in:
2023-02-23 14:10:17 +01:00
commit 7220ddcb60
5 changed files with 67 additions and 0 deletions

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
for i in 0..data.len() {
out.write_all(&data[i..i + 1]).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();
}
}
}