From c3b61ebe688e6e353b0fcd737f76851f78b8c74f Mon Sep 17 00:00:00 2001 From: Daniel Mueller Date: Wed, 29 Mar 2017 23:10:18 -0700 Subject: Use macros for generating commands Commands to the nitrokey all must follow a similar pattern in that they all require to have a constructor (i.e., a new() method) and need to implement the AsRef trait for byte slices. For we require more commands in the future, this change introduces macros that simplify creation of command objects. --- nitrocli/src/nitrokey.rs | 74 ++++++++++++++++++++++++++++++------------------ 1 file changed, 47 insertions(+), 27 deletions(-) (limited to 'nitrocli') diff --git a/nitrocli/src/nitrokey.rs b/nitrocli/src/nitrokey.rs index 0b055fe..37ba597 100644 --- a/nitrocli/src/nitrokey.rs +++ b/nitrocli/src/nitrokey.rs @@ -79,6 +79,51 @@ impl

From

for Report

} +macro_rules! defaultCommandType { + ( $name:ident ) => { + #[allow(dead_code)] + #[repr(packed)] + pub struct $name { + command: Command, + padding: [u8; 59], + } + } +} + +macro_rules! defaultCommandNew { + ( $name:ident, $command:ident ) => { + impl $name { + pub fn new() -> $name { + return $name{ + command: Command::$command, + padding: [0; 59], + }; + } + } + } +} + +macro_rules! defaultPayloadAsRef { + ( $name:ty ) => { + impl AsRef<[u8]> for $name { + fn as_ref(&self) -> &[u8] { + unsafe { + return mem::transmute::<&$name, &[u8; 60]>(self) + }; + } + } + } +} + +macro_rules! defaultCommand { + ( $name:ident, $command:ident ) => { + defaultCommandType!($name); + defaultCommandNew!($name, $command); + defaultPayloadAsRef!($name); + } +} + + #[allow(dead_code)] #[repr(packed)] pub struct EnableEncryptedVolumeCommand { @@ -109,34 +154,9 @@ impl EnableEncryptedVolumeCommand { } } -impl AsRef<[u8]> for EnableEncryptedVolumeCommand { - fn as_ref(&self) -> &[u8] { - unsafe { return mem::transmute::<&EnableEncryptedVolumeCommand, &[u8; 60]>(self) }; - } -} - - -#[allow(dead_code)] -#[repr(packed)] -pub struct DisableEncryptedVolumeCommand { - command: Command, - padding: [u8; 59], -} +defaultPayloadAsRef!(EnableEncryptedVolumeCommand); -impl DisableEncryptedVolumeCommand { - pub fn new() -> DisableEncryptedVolumeCommand { - return DisableEncryptedVolumeCommand { - command: Command::DisableEncryptedVolume, - padding: [0; 59], - }; - } -} - -impl AsRef<[u8]> for DisableEncryptedVolumeCommand { - fn as_ref(&self) -> &[u8] { - unsafe { return mem::transmute::<&DisableEncryptedVolumeCommand, &[u8; 60]>(self) }; - } -} +defaultCommand!(DisableEncryptedVolumeCommand, DisableEncryptedVolume); #[cfg(test)] -- cgit v1.2.1