From 66f22f7fb47197298702a0fefff17c81667b2739 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Thu, 7 Jun 2018 16:05:22 +0200 Subject: Implement std::fmt::Display for CommandError The std::fmt::Display implementation provides a human-readable error message for a CommandError. It is intended to be used in error messages displayed to the user. --- src/util.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/util.rs b/src/util.rs index 75de799..d764baa 100644 --- a/src/util.rs +++ b/src/util.rs @@ -3,6 +3,7 @@ use nitrokey_sys; use rand::{OsRng, Rng}; use std; use std::ffi::{CStr, CString}; +use std::fmt; use std::os::raw::{c_char, c_int}; /// Error types returned by Nitrokey device or by the library. @@ -27,7 +28,7 @@ pub enum CommandError { NotSupported, /// This command is unknown. UnknownCommand, - /// AES decryptionfailed. + /// AES decryption failed. AesDecryptionFailed, /// An unknown error occured. Unknown, @@ -114,6 +115,30 @@ pub fn get_cstring>>(s: T) -> Result { CString::new(s).or(Err(CommandError::InvalidString)) } +impl fmt::Display for CommandError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let msg = match *self { + CommandError::WrongCrc => "A packet with a wrong checksum has been sent or received", + CommandError::WrongSlot => "The given OTP slot does not exist", + CommandError::SlotNotProgrammed => "The given OTP slot is not programmed", + CommandError::WrongPassword => "The given password is wrong", + CommandError::NotAuthorized => { + "You are not authorized for this command or provided a wrong temporary password" + } + CommandError::Timestamp => "An error occured when getting or setting the time", + CommandError::NoName => "You did not provide a name for the OTP slot", + CommandError::NotSupported => "This command is not supported by this device", + CommandError::UnknownCommand => "This command is unknown", + CommandError::AesDecryptionFailed => "AES decryption failed", + CommandError::Unknown => "An unknown error occured", + CommandError::InvalidString => "You passed a string containing a null byte", + CommandError::InvalidSlot => "The given slot is invalid", + CommandError::RngError => "An error occured during random number generation", + }; + write!(f, "{}", msg) + } +} + impl From for CommandError { fn from(value: c_int) -> Self { match value { -- cgit v1.2.3