diff options
author | Daniel Mueller <deso@posteo.net> | 2017-03-29 23:10:18 -0700 |
---|---|---|
committer | Daniel Mueller <deso@posteo.net> | 2017-03-29 23:10:18 -0700 |
commit | c3b61ebe688e6e353b0fcd737f76851f78b8c74f (patch) | |
tree | 010a09addab4d77d7cb1b8ae164c3d4310633124 | |
parent | a0c6480aa6b1c6dad45b67e5bc7c29c5f0a4bb0e (diff) | |
download | nitrocli-c3b61ebe688e6e353b0fcd737f76851f78b8c74f.tar.gz nitrocli-c3b61ebe688e6e353b0fcd737f76851f78b8c74f.tar.bz2 |
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.
-rw-r--r-- | nitrocli/src/nitrokey.rs | 74 |
1 files changed, 47 insertions, 27 deletions
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<P> From<P> for Report<P> } +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)] |