Better password input
This commit is contained in:
parent
a19d2e245d
commit
10f6654005
|
@ -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 {
|
||||
|
|
|
@ -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.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
27
src/extra.rs
27
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<W: Write>(&mut self, writer: &mut W) -> Option<String>;
|
||||
fn read_passwd<W: Write>(&mut self, writer: &mut W) -> Result<Option<String>, TerminalError>;
|
||||
}
|
||||
|
||||
impl<R: Read> ReadExt for R {
|
||||
fn read_passwd<W: Write>(&mut self, writer: &mut W) -> Option<String> {
|
||||
let _raw = if let Ok(x) = writer.into_raw_mode() {
|
||||
x
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
fn read_passwd<W: Write>(&mut self, writer: &mut W) -> Result<Option<String>, 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))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue