dia_args/
__.rs

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