1use std::fmt::Debug;
4use std::io::{self, Write};
5use std::str::FromStr;
6
7pub struct Input<T> {
8 message: String,
9 _type: std::marker::PhantomData<T>,
10}
11
12impl<T> Input<T>
13where
14 T: FromStr,
15 T::Err: Debug,
16{
17 pub fn new() -> Self {
18 Self {
19 message: String::new(),
20 _type: std::marker::PhantomData,
21 }
22 }
23
24 pub fn message(mut self, message: &str) -> Self {
25 self.message = message.to_string();
26 self
27 }
28
29 pub fn get_input(self) -> Result<T, String> {
30 print!("{}", self.message);
31 io::stdout().flush().expect("Failed to flush stdout");
32
33 let mut input = String::new();
34 io::stdin()
35 .read_line(&mut input)
36 .expect("Failed to read line");
37
38 let input = input.trim().to_string();
39
40 match input.parse::<T>() {
41 Ok(value) => Ok(value),
42 Err(_) => Err(String::from("Not a valid input")),
43 }
44 }
45}
46
47pub fn input<T>() -> Input<T>
48where
49 T: FromStr,
50 T::Err: Debug,
51{
52 Input::new()
53}