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
// License: see LICENSE file at root directory of `master` branch

//! # 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
///
/// The function will flush stdout when done.
pub fn lock_write_out<B>(bytes: B) -> Result<()> where B: AsRef<[u8]> {
    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    stdout.write_all(bytes.as_ref())?;
    stdout.flush()
}

/// # Locks stderr and writes to it
///
/// The function will flush stderr when done.
pub fn lock_write_err<B>(bytes: B) -> Result<()> where B: AsRef<[u8]> {
    let stderr = io::stderr();
    let mut stderr = stderr.lock();
    stderr.write_all(bytes.as_ref())?;
    stderr.flush()
}