2016-03-07 21:19:35 +00:00
|
|
|
use std::io::{Read, Write};
|
2016-03-08 07:51:34 +00:00
|
|
|
use {IntoRawMode, TerminalError};
|
2016-03-07 17:42:11 +00:00
|
|
|
|
|
|
|
/// Extension to `Read` trait.
|
|
|
|
pub trait ReadExt {
|
|
|
|
/// Read a password.
|
2016-03-08 09:08:50 +00:00
|
|
|
///
|
|
|
|
/// EOT and ETX will abort the prompt, returning `None`. Newline or carriage return will
|
|
|
|
/// complete the password input.
|
2016-03-08 07:51:34 +00:00
|
|
|
fn read_passwd<W: Write>(&mut self, writer: &mut W) -> Result<Option<String>, TerminalError>;
|
2016-03-07 17:42:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<R: Read> ReadExt for R {
|
2016-03-08 07:51:34 +00:00
|
|
|
fn read_passwd<W: Write>(&mut self, writer: &mut W) -> Result<Option<String>, TerminalError> {
|
|
|
|
let _raw = try!(writer.into_raw_mode());
|
2016-03-07 17:42:11 +00:00
|
|
|
let mut string = String::with_capacity(30);
|
|
|
|
|
2016-03-08 10:04:09 +00:00
|
|
|
for c in self.bytes() {
|
2016-03-08 07:51:34 +00:00
|
|
|
match c {
|
|
|
|
Err(_) => return Err(TerminalError::StdinError),
|
2016-03-08 10:04:09 +00:00
|
|
|
Ok(b'\0') | Ok(b'\x03') | Ok(b'\x04') => return Ok(None),
|
|
|
|
Ok(b'\n') | Ok(b'\r') => return Ok(Some(string)),
|
|
|
|
Ok(c) => string.push(c as char),
|
2016-03-07 17:42:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-08 07:51:34 +00:00
|
|
|
Ok(Some(string))
|
2016-03-07 17:42:11 +00:00
|
|
|
}
|
|
|
|
}
|