Implement ask_uint() including tests

This commit is contained in:
Matthias Beyer 2016-04-06 18:05:49 +02:00
parent 747324ae85
commit 860888c06f

View file

@ -44,8 +44,31 @@ fn ask_bool_<R: BufRead>(s: &str, default: Option<bool>, input: &mut R) -> bool
}
}
pub fn ask_uint(s: &str) -> u64 {
unimplemented!()
/// Ask the user for an unsigned number. Optionally provide a default value. If none is provided,
/// this keeps loop{}ing
pub fn ask_uint(s: &str, default: Option<u64>) -> u64 {
ask_uint_(s, default, &mut BufReader::new(stdin()))
}
fn ask_uint_<R: BufRead>(s: &str, default: Option<u64>, input: &mut R) -> u64 {
use std::str::FromStr;
loop {
ask_question(s, false);
let mut s = String::new();
let _ = input.read_line(&mut s);
let u : Result<u64, _> = FromStr::from_str(&s[..]);
match u {
Ok(u) => { return u; },
Err(_) => {
if default.is_some() {
return default.unwrap();
} // else keep looping
}
}
}
}
pub fn ask_string(s: &str) -> String {
@ -73,6 +96,7 @@ mod test {
use std::io::BufReader;
use super::ask_bool_;
use super::ask_uint_;
#[test]
fn test_ask_bool_nodefault_yes() {
@ -146,4 +170,58 @@ mod test {
assert!(true == ask_bool_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_nodefault() {
let question = "Is this 1";
let default = None;
let answers = "1";
assert!(1 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_default() {
let question = "Is this 1";
let default = Some(1);
let answers = "1";
assert!(1 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_default_2_input_1() {
let question = "Is this 1";
let default = Some(2);
let answers = "1";
assert!(1 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_default_2_noinput() {
let question = "Is this 1";
let default = Some(2);
let answers = "\n";
assert!(2 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_default_2_several_noinput() {
let question = "Is this 1";
let default = Some(2);
let answers = "\n\n\n\n";
assert!(2 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
#[test]
fn test_ask_uint_default_2_wrong_input() {
let question = "Is this 1";
let default = Some(2);
let answers = "\n\n\nasfb\nsakjf\naskjf\n-2";
assert!(2 == ask_uint_(question, default, &mut BufReader::new(answers.as_bytes())));
}
}