1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/*
==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--==--
Dia-Args
Copyright (C) 2018-2019, 2021-2024 Anonymous
There are several releases over multiple years,
they are listed as ranges, such as: "2018-2019".
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--::--
*/
//! # Some kit
use {
core::{
fmt::Debug,
str::FromStr,
},
std::io::{self, BufRead, Error, ErrorKind, Write},
crate::Result,
};
/// # Reads a line from stdin, trims and converts it to `T`
pub fn read_line<T>() -> Result<T> where T: FromStr, <T as FromStr>::Err: Debug {
let stdin = io::stdin();
let mut stdin = stdin.lock();
let mut buf = String::with_capacity(64);
stdin.read_line(&mut buf)?;
let buf = buf.trim();
T::from_str(buf).map_err(|err| Error::new(ErrorKind::InvalidData, format!("{:?} is invalid: {:?}", buf, err)))
}
/// # Locks stdout and writes to it
///
/// - For simplicity, any error will be caught and printed out via `eprintln!()`.
/// - The function will flush stdout when done.
pub fn lock_write_out<B>(bytes: B) where B: AsRef<[u8]> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
if let Err(err) = (|| {
stdout.write_all(bytes.as_ref())?;
stdout.flush()
})() {
eprintln!("{}", __!("{}", err));
}
}
/// # Locks stderr and writes to it
///
/// - For simplicity, any error will be caught and printed out via `eprintln!()`.
/// - The function will flush stderr when done.
pub fn lock_write_err<B>(bytes: B) where B: AsRef<[u8]> {
let stderr = io::stderr();
let mut stderr = stderr.lock();
if let Err(err) = (|| {
stderr.write_all(bytes.as_ref())?;
stderr.flush()
})() {
eprintln!("{}", __!("{}", err));
}
}