1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
extern crate tutil; use std::io; use std::io::Write; use self::tutil::crayon::Color::{Red, Yellow}; use self::tutil::crayon::Style; #[cfg(test)] mod tests { #[test] fn it_works() { } } pub fn build_choices(choices: &[&str]) -> String { let mut label = "(".to_owned(); let mut first = true; for x in choices { if first { first = false; } else { label.push_str(", "); } label.push_str(x); } label.push_str(")"); return label; } #[allow(dead_code)] pub fn choice_with_color(text: &str, choices: &[&str], crayon: Style) -> String { let mut label = text.to_owned(); let mut input: String; let mut found = false; label.push_str(" "); label.push_str(build_choices(choices).trim()); loop { input = prompt_with_color(label.trim(), crayon); for x in choices { if x.to_lowercase().find(input.to_lowercase().as_str()) == Some(0) { found = true; input = x.to_string(); } } if found { break } else { println!("{}", Red.bold().paint("Error! Invalid choice")); } } return input; } #[allow(dead_code)] pub fn choice(text: &str, choices: &[&str]) -> String { return choice_with_color(text, choices, Yellow.bold()); } #[allow(dead_code)] pub fn prompt_with_color(text: &str, crayon: Style) -> String { print!("{}> ", crayon.paint(text)); io::stdout().flush().expect("Failed to flush"); let mut input = String::new(); match io::stdin().read_line(&mut input) { Ok(_n) => (), Err(error) => println!("error: {}", error), } return input.trim().to_string(); } #[allow(dead_code)] pub fn prompt(text: &str) -> String { return prompt_with_color(text, Yellow.bold()); }