diff options
author | Robin Krahl <robin.krahl@ireas.org> | 2019-01-23 03:46:09 +0000 |
---|---|---|
committer | Robin Krahl <robin.krahl@ireas.org> | 2019-01-23 04:02:24 +0000 |
commit | 5540ca5e76ffe5efe27d8819efb9e62066a10219 (patch) | |
tree | e2892e73f30a9f55f1d257b9e16f1ed7d99b9bed /src/util.rs | |
parent | e31009064eaaef9153ad5da3911aa0a939a050c2 (diff) | |
download | nitrokey-rs-5540ca5e76ffe5efe27d8819efb9e62066a10219.tar.gz nitrokey-rs-5540ca5e76ffe5efe27d8819efb9e62066a10219.tar.bz2 |
Refactor and clean up all code
This includes:
- using idiomatic Rust
- limiting the scope of unsafe blocks
- simplifying code
Diffstat (limited to 'src/util.rs')
-rw-r--r-- | src/util.rs | 35 |
1 files changed, 17 insertions, 18 deletions
diff --git a/src/util.rs b/src/util.rs index 2542a7b..f8ad9c9 100644 --- a/src/util.rs +++ b/src/util.rs @@ -29,32 +29,31 @@ pub enum LogLevel { } pub fn owned_str_from_ptr(ptr: *const c_char) -> String { - unsafe { - return CStr::from_ptr(ptr).to_string_lossy().into_owned(); - } + unsafe { CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned() } pub fn result_from_string(ptr: *const c_char) -> Result<String, Error> { if ptr.is_null() { return Err(Error::UnexpectedError); } - unsafe { - let s = owned_str_from_ptr(ptr); - free(ptr as *mut c_void); - // An empty string can both indicate an error or be a valid return value. In this case, we - // have to check the last command status to decide what to return. - if s.is_empty() { - get_last_result().map(|_| s) - } else { - Ok(s) - } + let s = owned_str_from_ptr(ptr); + unsafe { free(ptr as *mut c_void) }; + // An empty string can both indicate an error or be a valid return value. In this case, we + // have to check the last command status to decide what to return. + if s.is_empty() { + get_last_result().map(|_| s) + } else { + Ok(s) } } pub fn get_command_result(value: c_int) -> Result<(), Error> { - match value { - 0 => Ok(()), - other => Err(Error::from(other)), + if value == 0 { + Ok(()) + } else { + Err(Error::from(value)) } } @@ -63,10 +62,10 @@ pub fn get_last_result() -> Result<(), Error> { } pub fn get_last_error() -> Error { - return match get_last_result() { + match get_last_result() { Ok(()) => Error::UnexpectedError, Err(err) => err, - }; + } } pub fn generate_password(length: usize) -> Result<Vec<u8>, Error> { |