[dev] use generic type (that implements Write trait) for print functions

also simplify `stdin.lock()` and `stdout.lock()`
This commit is contained in:
ddidderr 2023-01-02 15:37:44 +01:00
parent caf96b30dc
commit c1488ddb5c
Signed by: ddidderr
GPG Key ID: 3841F1C27E6F0E14

View File

@ -8,7 +8,6 @@ use std::{
Error as IoError, Error as IoError,
ErrorKind, ErrorKind,
Read, Read,
StdoutLock,
Write, Write,
}, },
}; };
@ -28,7 +27,10 @@ where
} }
#[inline(always)] #[inline(always)]
fn print_time_color(output: &mut StdoutLock) -> Result<(), std::io::Error> { fn print_time_color<T>(output: &mut T) -> Result<(), std::io::Error>
where
T: Write,
{
let date_now = Local::now().format(TIME_FORMAT); let date_now = Local::now().format(TIME_FORMAT);
let color_green = "\x1b\x5b\x30\x3b\x33\x32\x6d"; let color_green = "\x1b\x5b\x30\x3b\x33\x32\x6d";
@ -38,7 +40,10 @@ fn print_time_color(output: &mut StdoutLock) -> Result<(), std::io::Error> {
} }
#[inline(always)] #[inline(always)]
fn print_delete_line(output: &mut StdoutLock) -> LogtimesResult { fn print_delete_line<T>(output: &mut T) -> LogtimesResult
where
T: Write,
{
// tput dl1 und tput hpa 0 // tput dl1 und tput hpa 0
let bytes = "\x1b\x5b\x4d\x1b\x5b\x31\x47"; let bytes = "\x1b\x5b\x4d\x1b\x5b\x31\x47";
write!(output, "{}", bytes) write!(output, "{}", bytes)
@ -53,11 +58,8 @@ fn run() -> LogtimesResult {
.expect("Could not open log file") .expect("Could not open log file")
}); });
let out = stdout(); let mut out = stdout().lock();
let mut output = out.lock(); let mut inp = stdin().lock();
let inp = stdin();
let mut input = inp.lock();
let mut buf = [0; 1]; let mut buf = [0; 1];
@ -65,7 +67,7 @@ fn run() -> LogtimesResult {
loop { loop {
// read 1 char // read 1 char
if let Err(e) = input.read_exact(&mut buf) { if let Err(e) = inp.read_exact(&mut buf) {
if e.kind() == ErrorKind::UnexpectedEof { if e.kind() == ErrorKind::UnexpectedEof {
return Ok(()); return Ok(());
} else { } else {
@ -80,10 +82,10 @@ fn run() -> LogtimesResult {
// [timestamp] actual content\n // [timestamp] actual content\n
// also write the line to the log file if there is one // also write the line to the log file if there is one
if buf[0] == 0xa { if buf[0] == 0xa {
print_delete_line(&mut output)?; print_delete_line(&mut out)?;
print_time_color(&mut output)?; print_time_color(&mut out)?;
output.write_all(&linebuf)?; out.write_all(&linebuf)?;
output.flush()?; out.flush()?;
if let Some(ref mut f) = log_file { if let Some(ref mut f) = log_file {
print_time(f)?; print_time(f)?;
@ -96,8 +98,8 @@ fn run() -> LogtimesResult {
continue; continue;
} }
output.write_all(&buf)?; out.write_all(&buf)?;
output.flush()?; out.flush()?;
} }
} }