plm_rs/
prompt.rs

1// License: Apache 2.0
2// Author: Jared Wolff
3
4use std::io::{BufRead, Write};
5
6pub struct Prompt<R, W> {
7    pub reader: R,
8    pub writer: W,
9}
10
11// Returns a string response. Newline removed.
12impl<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        // Ask the question
19        write!(&mut self.writer, "{}", question).expect("Unable to write");
20        self.writer.flush().expect("Unable to flush");
21
22        // Parse input
23        let mut input = String::new();
24        self.reader.read_line(&mut input).unwrap();
25        let response = &input[..(input.len() - 1)]; // Drop the newline character
26        let response = response.trim();
27
28        // Return a copy
29        response.to_string()
30    }
31
32    pub fn ask_yes_no_question(&mut self, question: &str) -> bool {
33        // Ask the question
34        write!(&mut self.writer, "{} (y/n) ", question).expect("Unable to write!");
35        self.writer.flush().expect("Unable to flush output!");
36
37        // Parse input
38        let mut input = String::new();
39        self.reader.read_line(&mut input).unwrap();
40        let ch = input.chars().next().unwrap();
41
42        // Return result
43        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); // output to stdout
64    assert_eq!("I love cookies!", answer); // input
65}
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}