1
use std::io;
2
use std::io::BufRead;
3

            
4
/// Prints a prompt and reads a line of input.
5
2
fn prompt<R>(prompt_text: &str, mut reader: R) -> String
6
2
where
7
2
    R: BufRead,
8
2
{
9
2
    println!("{}", prompt_text);
10
2
    let mut input = String::new();
11
2
    reader.read_line(&mut input).expect("Failed to read input.");
12
2
    input.trim().to_lowercase()
13
2
}
14

            
15
/// Prints a prompt and reads a line of input from stdin.
16
pub fn prompt_stdin(prompt_text: &str) -> String {
17
    prompt(prompt_text, io::stdin().lock())
18
}
19

            
20
#[cfg(test)]
21
mod tests {
22
    use super::*;
23

            
24
    #[test]
25
2
    fn test_prompt() {
26
2
        // GIVEN a prompt with expected text
27
2
        let prompt_text = "Enter some text:";
28
2
        let expected = "hello";
29
2
        let reader = std::io::Cursor::new(expected);
30
2

            
31
2
        // WHEN the user enters text
32
2
        let actual = prompt(prompt_text, reader);
33
2

            
34
2
        // THEN it should match the expected one
35
2
        assert_eq!(actual, expected);
36
2
    }
37
}