From 860888c06ff4d4c528717b098978e942013260fb Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 6 Apr 2016 18:05:49 +0200 Subject: [PATCH] Implement ask_uint() including tests --- libimaginteraction/src/ask.rs | 82 ++++++++++++++++++++++++++++++++++- 1 file changed, 80 insertions(+), 2 deletions(-) diff --git a/libimaginteraction/src/ask.rs b/libimaginteraction/src/ask.rs index 76a43bba..c50ba8b7 100644 --- a/libimaginteraction/src/ask.rs +++ b/libimaginteraction/src/ask.rs @@ -44,8 +44,31 @@ fn ask_bool_(s: &str, default: Option, 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 { + ask_uint_(s, default, &mut BufReader::new(stdin())) +} + +fn ask_uint_(s: &str, default: Option, 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 = 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()))); + } + }