From cafc3a6f8cfb9f82343c1d3fe843c7f8d7ef1136 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sun, 20 Jan 2019 21:05:58 +0000 Subject: Refactor CommandError::RngError into Error::RandError We reserve CommandError for errors returned by the Nitrokey device. Errors during random number generation should have their own type. --- src/error.rs | 19 ++++++++++--------- src/util.rs | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/error.rs b/src/error.rs index 3f60af2..dfe1680 100644 --- a/src/error.rs +++ b/src/error.rs @@ -11,6 +11,8 @@ pub enum Error { CommandError(CommandError), /// Placeholder for testing. CommunicationError(CommunicationError), + /// An error that occured during random number generation. + RandError(rand_core::Error), } impl From for Error { @@ -19,11 +21,18 @@ impl From for Error { } } +impl From for Error { + fn from(error: rand_core::Error) -> Self { + Error::RandError(error) + } +} + impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { Error::CommandError(ref err) => Some(err), Error::CommunicationError(_) => None, + Error::RandError(ref err) => Some(err), } } } @@ -33,6 +42,7 @@ impl fmt::Display for Error { match *self { Error::CommandError(ref err) => write!(f, "Command error: {}", err), Error::CommunicationError(_) => write!(f, "Placeholder"), + Error::RandError(ref err) => write!(f, "RNG error: {}", err), } } } @@ -78,8 +88,6 @@ pub enum CommandError { InvalidHexString, /// The target buffer was smaller than the source. TargetBufferTooSmall, - /// An error occurred during random number generation. - RngError, } /// Placeholder for testing. @@ -119,7 +127,6 @@ impl CommandError { "The supplied string is not in hexadecimal format".into() } CommandError::TargetBufferTooSmall => "The target buffer is too small".into(), - CommandError::RngError => "An error occurred during random number generation".into(), } } } @@ -153,9 +160,3 @@ impl From for CommandError { } } } - -impl From for CommandError { - fn from(_error: rand_core::Error) -> Self { - CommandError::RngError - } -} diff --git a/src/util.rs b/src/util.rs index 8855275..06bb854 100644 --- a/src/util.rs +++ b/src/util.rs @@ -71,7 +71,7 @@ pub fn get_last_error() -> Error { } pub fn generate_password(length: usize) -> Result, Error> { - let mut rng = OsRng::new().map_err(CommandError::from)?; + let mut rng = OsRng::new()?; let mut data = vec![0u8; length]; rng.fill_bytes(&mut data[..]); Ok(data) -- cgit v1.2.1