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
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::{
fmt,
io::{self, Stdin, Write},
str::FromStr,
};
pub fn input<T: FromStr>(msg: &str) -> Result<T, T::Err> {
Input::new().msg(msg).get()
}
#[derive(Debug)]
pub struct Input<'msg> {
message: Option<&'msg str>,
buf: String,
std_in: Stdin,
}
impl<'msg> Input<'msg> {
pub fn msg(mut self, msg: &'msg str) -> Self {
self.message = Some(msg);
self
}
}
impl Default for Input<'_> {
fn default() -> Self {
Self::new()
}
}
impl Input<'_> {
pub fn new() -> Self {
Self {
message: None,
buf: String::new(),
std_in: io::stdin(),
}
}
pub fn get<T: FromStr>(&mut self) -> Result<T, T::Err> {
self.buf.clear();
if let Some(message) = self.message {
print!("{}", message);
io::stdout().flush().ignore();
}
self.std_in.read_line(&mut self.buf).ignore();
self.buf.trim().parse()
}
}
impl Input<'_> {
pub fn read<T: FromStr>(&mut self) -> Result<T, T::Err> {
self.get()
}
pub fn read_line<T: FromStr>(&mut self) -> Result<T, T::Err> {
self.get()
}
}
pub trait Ignorable {
fn ignore(self);
}
impl<T, E> Ignorable for Result<T, E>
where
T: fmt::Debug,
E: fmt::Display,
{
fn ignore(self) {
match self {
Ok(x) => log::trace!("ignoring {:?}", x),
Err(e) => log::error!("ignoring error {}", e),
}
}
}
impl<T> Ignorable for Option<T>
where
T: fmt::Debug,
{
fn ignore(self) {
if let Some(x) = self {
log::trace!("ignoring {:?}", x)
} else {
log::error!("ignoring a None Value")
}
}
}