From e723d80a1673841ba27b407fa289b351f41dc973 Mon Sep 17 00:00:00 2001 From: Christian Lewe Date: Sat, 15 Feb 2025 22:44:48 +0100 Subject: [PATCH] refactor: Parse byte array instead of byte slice Update TupleVisitor{32,33} to pass its owned byte array to the parsing function instead of a mere byte slice. This gives us more flexibility inside the parsing function. --- src/key.rs | 20 ++++++++++---------- src/serde_util.rs | 6 +++--- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/key.rs b/src/key.rs index 308b93ada..3d18871eb 100644 --- a/src/key.rs +++ b/src/key.rs @@ -401,10 +401,10 @@ impl<'de> serde::Deserialize<'de> for SecretKey { "a hex string representing 32 byte SecretKey", )) } else { - let visitor = super::serde_util::Tuple32Visitor::new( - "raw 32 bytes SecretKey", - SecretKey::from_slice, - ); + let visitor = + super::serde_util::Tuple32Visitor::new("raw 32 bytes SecretKey", |bytes| { + SecretKey::from_byte_array(&bytes) + }); d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor) } } @@ -790,10 +790,10 @@ impl<'de> serde::Deserialize<'de> for PublicKey { "an ASCII hex string representing a public key", )) } else { - let visitor = super::serde_util::Tuple33Visitor::new( - "33 bytes compressed public key", - PublicKey::from_slice, - ); + let visitor = + super::serde_util::Tuple33Visitor::new("33 bytes compressed public key", |bytes| { + PublicKey::from_byte_array_compressed(&bytes) + }); d.deserialize_tuple(constants::PUBLIC_KEY_SIZE, visitor) } } @@ -1117,7 +1117,7 @@ impl<'de> serde::Deserialize<'de> for Keypair { let ctx = Secp256k1::signing_only(); #[allow(clippy::needless_borrow)] - Keypair::from_seckey_slice(&ctx, data) + Keypair::from_seckey_slice(&ctx, &data) }); d.deserialize_tuple(constants::SECRET_KEY_SIZE, visitor) } @@ -1597,7 +1597,7 @@ impl<'de> serde::Deserialize<'de> for XOnlyPublicKey { } else { let visitor = super::serde_util::Tuple32Visitor::new( "raw 32 bytes schnorr public key", - XOnlyPublicKey::from_slice, + |bytes| XOnlyPublicKey::from_byte_array(&bytes), ); d.deserialize_tuple(constants::SCHNORR_PUBLIC_KEY_SIZE, visitor) } diff --git a/src/serde_util.rs b/src/serde_util.rs index 8204a2f0b..51fdf829c 100644 --- a/src/serde_util.rs +++ b/src/serde_util.rs @@ -74,7 +74,7 @@ macro_rules! impl_tuple_visitor { impl $thing where - F: FnOnce(&[u8]) -> Result, + F: FnOnce([u8; $len]) -> Result, E: fmt::Display, { pub fn new(expectation: &'static str, parse_fn: F) -> Self { @@ -84,7 +84,7 @@ macro_rules! impl_tuple_visitor { impl<'de, F, T, E> de::Visitor<'de> for $thing where - F: FnOnce(&[u8]) -> Result, + F: FnOnce([u8; $len]) -> Result, E: fmt::Display, { type Value = T; @@ -106,7 +106,7 @@ macro_rules! impl_tuple_visitor { return Err(de::Error::invalid_length(i, &self)); } } - (self.parse_fn)(&bytes).map_err(de::Error::custom) + (self.parse_fn)(bytes).map_err(de::Error::custom) } } };