1use std::io::{BufRead, Write};
5
6pub struct Prompt<R, W> {
7 pub reader: R,
8 pub writer: W,
9}
10
11impl<R, W> Prompt<R, W>
13where
14 R: BufRead,
15 W: Write,
16{
17 pub fn ask_text_entry(&mut self, question: &str) -> String {
18 write!(&mut self.writer, "{}", question).expect("Unable to write");
20 self.writer.flush().expect("Unable to flush");
21
22 let mut input = String::new();
24 self.reader.read_line(&mut input).unwrap();
25 let response = &input[..(input.len() - 1)]; let response = response.trim();
27
28 response.to_string()
30 }
31
32 pub fn ask_yes_no_question(&mut self, question: &str) -> bool {
33 write!(&mut self.writer, "{} (y/n) ", question).expect("Unable to write!");
35 self.writer.flush().expect("Unable to flush output!");
36
37 let mut input = String::new();
39 self.reader.read_line(&mut input).unwrap();
40 let ch = input.chars().next().unwrap();
41
42 ch == 'y'
44 }
45}
46
47#[test]
48fn test_text_entry_with_whitespace() {
49 let input = b"I love cookies! \n";
50 let mut output = Vec::new();
51
52 let answer = {
53 let mut prompt = Prompt {
54 reader: &input[..],
55 writer: &mut output,
56 };
57
58 prompt.ask_text_entry("Do you like cookies?")
59 };
60
61 let output = String::from_utf8(output).expect("Not UTF-8");
62
63 assert_eq!("Do you like cookies?", output); assert_eq!("I love cookies!", answer); }
66
67#[test]
68fn test_yes_no_expect_true() {
69 let input = b"y\n";
70 let mut output = Vec::new();
71
72 let answer = {
73 let mut prompt = Prompt {
74 reader: &input[..],
75 writer: &mut output,
76 };
77
78 prompt.ask_yes_no_question("Would you like to do things?")
79 };
80
81 let output = String::from_utf8(output).expect("Not UTF-8");
82
83 assert_eq!("Would you like to do things? (y/n) ", output);
84 assert_eq!(true, answer);
85}
86
87#[test]
88fn test_yes_no_expect_false() {
89 let input = b"\n";
90 let mut output = Vec::new();
91
92 let answer = {
93 let mut prompt = Prompt {
94 reader: &input[..],
95 writer: &mut output,
96 };
97
98 prompt.ask_yes_no_question("Would you like to do things?")
99 };
100
101 let output = String::from_utf8(output).expect("Not UTF-8");
102
103 assert_eq!("Would you like to do things? (y/n) ", output);
104 assert_eq!(false, answer);
105}