diff --git a/examples/read.rs b/examples/read.rs index 6d0dd33..64ceb91 100644 --- a/examples/read.rs +++ b/examples/read.rs @@ -6,14 +6,15 @@ use std::io::{Write, stdout, stdin}; fn main() { let stdout = stdout(); let mut stdout = stdout.lock(); - let mut stdin = stdin(); + let stdin = stdin(); + let mut stdin = stdin.lock(); stdout.write(b"password: ").unwrap(); stdout.flush().unwrap(); let pass = stdin.read_passwd(&mut stdout); - if let Some(pass) = pass { + if let Ok(Some(pass)) = pass { stdout.write(pass.as_bytes()).unwrap(); stdout.write(b"\n").unwrap(); } else { diff --git a/src/error.rs b/src/error.rs index 76a029d..627b20d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -12,6 +12,8 @@ pub enum TerminalError { TermSizeError, /// Failed to write to stdout. StdoutError, + /// Failed to read from stdin. + StdinError, } impl TerminalError { @@ -21,6 +23,7 @@ impl TerminalError { TerminalError::SetAttrError => "Failed to set Terminal attribute.", TerminalError::TermSizeError => "Failed to get terminal size.", TerminalError::StdoutError => "Failed to write to stdout.", + TerminalError::StdinError => "Failed to read from stdin.", } } } diff --git a/src/extra.rs b/src/extra.rs index 13ff74b..7e4444e 100644 --- a/src/extra.rs +++ b/src/extra.rs @@ -1,33 +1,26 @@ use std::io::{Read, Write}; -use IntoRawMode; +use {IntoRawMode, TerminalError}; /// Extension to `Read` trait. pub trait ReadExt { /// Read a password. - fn read_passwd(&mut self, writer: &mut W) -> Option; + fn read_passwd(&mut self, writer: &mut W) -> Result, TerminalError>; } impl ReadExt for R { - fn read_passwd(&mut self, writer: &mut W) -> Option { - let _raw = if let Ok(x) = writer.into_raw_mode() { - x - } else { - return None; - }; + fn read_passwd(&mut self, writer: &mut W) -> Result, TerminalError> { + let _raw = try!(writer.into_raw_mode()); let mut string = String::with_capacity(30); for c in self.chars() { - match if let Ok(c) = c { - c - } else { - return None; - } { - '\x00' | '\x03' | '\x04' => return None, - '\r' => return Some(string), - b => string.push(b), + match c { + Err(_) => return Err(TerminalError::StdinError), + Ok('\0') | Ok('\x03') | Ok('\x04') => return Ok(None), + Ok('\n') | Ok('\r') => return Ok(Some(string)), + Ok(c) => string.push(c), } } - Some(string) + Ok(Some(string)) } }