From 884081d414094ab1c8fee6d0d1c803d786937391 Mon Sep 17 00:00:00 2001 From: ErrorNoInternet Date: Sun, 9 Mar 2025 14:02:47 -0400 Subject: [PATCH] refactor(nochatreports): simplify crypt macro --- src/lua/nochatreports/crypt.rs | 52 ++++++++++++---------------------- src/lua/nochatreports/mod.rs | 14 ++------- 2 files changed, 20 insertions(+), 46 deletions(-) diff --git a/src/lua/nochatreports/crypt.rs b/src/lua/nochatreports/crypt.rs index 2a6096b..ad4b991 100644 --- a/src/lua/nochatreports/crypt.rs +++ b/src/lua/nochatreports/crypt.rs @@ -1,41 +1,25 @@ -macro_rules! crypt_with { - ($op:ident, $encoding:expr, $key:expr, $text:expr, $algo:ident) => { - match $encoding { - 1 => $algo::::$op($text, $key), - 2 => $algo::::$op($text, $key), - _ => $algo::::$op($text, $key), - } - .map_err(|error| Error::external(error.to_string()))? - }; -} - #[macro_export] macro_rules! crypt { - ($op:ident, $encoding:expr, $options:expr, $text:expr) => { + ($op:ident, $options:expr, $text:expr) => {{ + macro_rules! crypt_with { + ($algo:ident) => {{ + let encoding = $options.get("encoding").unwrap_or_default(); + let key = &$options.get::>("$key")?.inner; + match encoding { + 1 => $algo::::$op($text, &key), + 2 => $algo::::$op($text, &key), + _ => $algo::::$op($text, &key), + } + .map_err(|error| Error::external(error.to_string()))? + }}; + } + match $options.get("encryption").unwrap_or_default() { 1 => CaesarEncryption::$op(&$text, &$options.get("key")?) .map_err(|error| Error::external(error.to_string()))?, - 2 => crypt_with!( - $op, - $encoding, - &$options.get::>("key")?.inner, - &$text, - EcbEncryption - ), - 3 => crypt_with!( - $op, - $encoding, - &$options.get::>("key")?.inner, - &$text, - GcmEncryption - ), - _ => crypt_with!( - $op, - $encoding, - &$options.get::>("key")?.inner, - &$text, - Cfb8Encryption - ), + 2 => crypt_with!(EcbEncryption), + 3 => crypt_with!(GcmEncryption), + _ => crypt_with!(Cfb8Encryption), } - }; + }}; } diff --git a/src/lua/nochatreports/mod.rs b/src/lua/nochatreports/mod.rs index 1cb7ba7..7a8eebd 100644 --- a/src/lua/nochatreports/mod.rs +++ b/src/lua/nochatreports/mod.rs @@ -42,24 +42,14 @@ pub fn register_globals(lua: &Lua, globals: &Table) -> Result<()> { globals.set( "ncr_encrypt", lua.create_function(|_, (options, plaintext): (Table, String)| { - Ok(crypt!( - encrypt, - options.get("encoding").unwrap_or_default(), - options, - plaintext - )) + Ok(crypt!(encrypt, options, &plaintext)) })?, )?; globals.set( "ncr_decrypt", lua.create_function(|_, (options, ciphertext): (Table, String)| { - Ok(crypt!( - decrypt, - options.get("encoding").unwrap_or_default(), - options, - ciphertext - )) + Ok(crypt!(decrypt, options, &ciphertext)) })?, )?;