prompt_input/
primitive.rs

1use std::io::{self, Write};
2
3pub trait Promptable {
4    fn prompt(output: &str) -> Self;
5}
6
7pub trait PromptableWithOption
8where
9    Self: Sized,
10{
11    fn prompt(output: &str) -> Option<Self>;
12}
13
14impl Promptable for String {
15    fn prompt(output: &str) -> Self {
16        print!("{}", output);
17        io::stdout().flush().unwrap();
18
19        let mut input = String::new();
20        io::stdin()
21            .read_line(&mut input)
22            .expect("Failed to read the prompt");
23
24        input.pop();
25
26        input
27    }
28}
29
30impl PromptableWithOption for i8 {
31    fn prompt(output: &str) -> Option<Self> {
32        let input = String::prompt(output);
33
34        input.parse().ok()
35    }
36}
37
38impl PromptableWithOption for i16 {
39    fn prompt(output: &str) -> Option<Self> {
40        let input = String::prompt(output);
41
42        input.parse().ok()
43    }
44}
45
46impl PromptableWithOption for i32 {
47    fn prompt(output: &str) -> Option<Self> {
48        let input = String::prompt(output);
49
50        input.parse().ok()
51    }
52}
53
54impl PromptableWithOption for i64 {
55    fn prompt(output: &str) -> Option<Self> {
56        let input = String::prompt(output);
57
58        input.parse().ok()
59    }
60}
61
62impl PromptableWithOption for i128 {
63    fn prompt(output: &str) -> Option<Self> {
64        let input = String::prompt(output);
65
66        input.parse().ok()
67    }
68}
69
70impl PromptableWithOption for u8 {
71    fn prompt(output: &str) -> Option<Self> {
72        let input = String::prompt(output);
73
74        input.parse().ok()
75    }
76}
77
78impl PromptableWithOption for u16 {
79    fn prompt(output: &str) -> Option<Self> {
80        let input = String::prompt(output);
81
82        input.parse().ok()
83    }
84}