Revision control

Copy as Markdown

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::io::{self, Write};
pub fn prompt_string<S: AsRef<str>>(prompt: S) -> Option<String> {
print!("{}: ", prompt.as_ref());
let _ = io::stdout().flush(); // Don't care if flush fails really.
let mut s = String::new();
io::stdin()
.read_line(&mut s)
.expect("Failed to read line...");
if let Some('\n') = s.chars().next_back() {
s.pop();
}
if let Some('\r') = s.chars().next_back() {
s.pop();
}
if s.is_empty() {
None
} else {
Some(s)
}
}
pub fn prompt_char(msg: &str) -> Option<char> {
prompt_string(msg).and_then(|r| r.chars().next())
}
pub fn prompt_usize<S: AsRef<str>>(prompt: S) -> Option<usize> {
if let Some(s) = prompt_string(prompt) {
match s.parse::<usize>() {
Ok(n) => Some(n),
Err(_) => {
println!("Couldn't parse!");
None
}
}
} else {
None
}
}