Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: bytes handles numeric arrays and bytearrays in deser #202

Merged
merged 6 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ proptest-derive = { workspace = true, optional = true }

[dev-dependencies]
serde_json.workspace = true
serde = { workspace = true, features = ["derive"] }

[features]
default = ["std"]
Expand Down
87 changes: 50 additions & 37 deletions crates/primitives/src/bits/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,102 +67,102 @@ macro_rules! wrap_fixed_bytes {
#[repr(transparent)]
$vis struct $name(#[into_iterator(owned, ref, ref_mut)] pub $crate::FixedBytes<$n>);

impl ::core::convert::From<[u8; $n]> for $name {
impl $crate::private::From<[u8; $n]> for $name {
#[inline]
fn from(value: [u8; $n]) -> Self {
Self($crate::FixedBytes(value))
}
}

impl ::core::convert::From<$name> for [u8; $n] {
impl $crate::private::From<$name> for [u8; $n] {
#[inline]
fn from(value: $name) -> Self {
value.0 .0
}
}

impl<'a> ::core::convert::From<&'a [u8; $n]> for $name {
impl<'a> $crate::private::From<&'a [u8; $n]> for $name {
#[inline]
fn from(value: &'a [u8; $n]) -> Self {
Self($crate::FixedBytes(*value))
}
}

impl ::core::convert::TryFrom<&[u8]> for $name {
type Error = ::core::array::TryFromSliceError;
impl $crate::private::TryFrom<&[u8]> for $name {
type Error = $crate::private::core::array::TryFromSliceError;

#[inline]
fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
<&Self>::try_from(slice).map(|this| *this)
}
}

impl ::core::convert::TryFrom<&mut [u8]> for $name {
type Error = ::core::array::TryFromSliceError;
impl $crate::private::TryFrom<&mut [u8]> for $name {
type Error = $crate::private::core::array::TryFromSliceError;

#[inline]
fn try_from(slice: &mut [u8]) -> Result<Self, Self::Error> {
Self::try_from(&*slice)
}
}

impl<'a> ::core::convert::TryFrom<&'a [u8]> for &'a $name {
type Error = ::core::array::TryFromSliceError;
impl<'a> $crate::private::TryFrom<&'a [u8]> for &'a $name {
type Error = $crate::private::core::array::TryFromSliceError;

#[inline]
#[allow(unsafe_code)]
fn try_from(slice: &'a [u8]) -> Result<&'a $name, Self::Error> {
// SAFETY: `$name` is `repr(transparent)` for `FixedBytes<$n>`
// and consequently `[u8; $n]`
<&[u8; $n] as ::core::convert::TryFrom<&[u8]>>::try_from(slice)
<&[u8; $n] as $crate::private::TryFrom<&[u8]>>::try_from(slice)
.map(|array_ref| unsafe { core::mem::transmute(array_ref) })
}
}

impl<'a> ::core::convert::TryFrom<&'a mut [u8]> for &'a mut $name {
type Error = ::core::array::TryFromSliceError;
impl<'a> $crate::private::TryFrom<&'a mut [u8]> for &'a mut $name {
type Error = $crate::private::core::array::TryFromSliceError;

#[inline]
#[allow(unsafe_code)]
fn try_from(slice: &'a mut [u8]) -> Result<&'a mut $name, Self::Error> {
// SAFETY: `$name` is `repr(transparent)` for `FixedBytes<$n>`
// and consequently `[u8; $n]`
<&mut [u8; $n] as ::core::convert::TryFrom<&mut [u8]>>::try_from(slice)
<&mut [u8; $n] as $crate::private::TryFrom<&mut [u8]>>::try_from(slice)
.map(|array_ref| unsafe { core::mem::transmute(array_ref) })
}
}

impl ::core::convert::AsRef<[u8; $n]> for $name {
impl $crate::private::AsRef<[u8; $n]> for $name {
#[inline]
fn as_ref(&self) -> &[u8; $n] {
&self.0 .0
}
}

impl ::core::convert::AsMut<[u8; $n]> for $name {
impl $crate::private::AsMut<[u8; $n]> for $name {
#[inline]
fn as_mut(&mut self) -> &mut [u8; $n] {
&mut self.0 .0
}
}

impl ::core::convert::AsRef<[u8]> for $name {
impl $crate::private::AsRef<[u8]> for $name {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0 .0
}
}

impl ::core::convert::AsMut<[u8]> for $name {
impl $crate::private::AsMut<[u8]> for $name {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
&mut self.0 .0
}
}

impl ::core::fmt::Debug for $name {
impl $crate::private::core::fmt::Debug for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
::core::fmt::Debug::fmt(&self.0, f)
$crate::private::core::fmt::Debug::fmt(&self.0, f)
}
}

Expand Down Expand Up @@ -254,63 +254,63 @@ macro_rules! wrap_fixed_bytes {
#[macro_export]
macro_rules! impl_fixed_bytes_traits {
(impl<$($const:ident)?> Borrow<$t:ty> for $b:ty) => {
impl<$($const N: usize)?> ::core::borrow::Borrow<$t> for $b {
impl<$($const N: usize)?> $crate::private::Borrow<$t> for $b {
#[inline]
fn borrow(&self) -> &$t {
::core::borrow::Borrow::borrow(&self.0)
$crate::private::Borrow::borrow(&self.0)
}
}
};

(impl<$($const:ident)?> BorrowMut<$t:ty> for $b:ty) => {
impl<$($const N: usize)?> ::core::borrow::BorrowMut<$t> for $b {
impl<$($const N: usize)?> $crate::private::BorrowMut<$t> for $b {
#[inline]
fn borrow_mut(&mut self) -> &mut $t {
::core::borrow::BorrowMut::borrow_mut(&mut self.0)
$crate::private::BorrowMut::borrow_mut(&mut self.0)
}
}
};

(impl<$($const:ident)?> cmp::$tr:ident<$a:ty> for $b:ty where fn $fn:ident -> $ret:ty $(, [$e:expr])?) => {
impl<$($const N: usize)?> ::core::cmp::$tr<$a> for $b {
impl<$($const N: usize)?> $crate::private::$tr<$a> for $b {
#[inline]
fn $fn(&self, other: &$a) -> $ret {
::core::cmp::$tr::$fn(&self.0 $([$e])?, other)
$crate::private::$tr::$fn(&self.0 $([$e])?, other)
}
}

impl<$($const N: usize)?> ::core::cmp::$tr<$b> for $a {
impl<$($const N: usize)?> $crate::private::$tr<$b> for $a {
#[inline]
fn $fn(&self, other: &$b) -> $ret {
::core::cmp::$tr::$fn(self, &other.0 $([$e])?)
$crate::private::$tr::$fn(self, &other.0 $([$e])?)
}
}

impl<$($const N: usize)?> ::core::cmp::$tr<&$a> for $b {
impl<$($const N: usize)?> $crate::private::$tr<&$a> for $b {
#[inline]
fn $fn(&self, other: &&$a) -> $ret {
::core::cmp::$tr::$fn(&self.0 $([$e])?, *other)
$crate::private::$tr::$fn(&self.0 $([$e])?, *other)
}
}

impl<$($const N: usize)?> ::core::cmp::$tr<$b> for &$a {
impl<$($const N: usize)?> $crate::private::$tr<$b> for &$a {
#[inline]
fn $fn(&self, other: &$b) -> $ret {
::core::cmp::$tr::$fn(*self, &other.0 $([$e])?)
$crate::private::$tr::$fn(*self, &other.0 $([$e])?)
}
}

impl<$($const N: usize)?> ::core::cmp::$tr<$a> for &$b {
impl<$($const N: usize)?> $crate::private::$tr<$a> for &$b {
#[inline]
fn $fn(&self, other: &$a) -> $ret {
::core::cmp::$tr::$fn(&self.0 $([$e])?, other)
$crate::private::$tr::$fn(&self.0 $([$e])?, other)
}
}

impl<$($const N: usize)?> ::core::cmp::$tr<&$b> for $a {
impl<$($const N: usize)?> $crate::private::$tr<&$b> for $a {
#[inline]
fn $fn(&self, other: &&$b) -> $ret {
::core::cmp::$tr::$fn(self, &other.0 $([$e])?)
$crate::private::$tr::$fn(self, &other.0 $([$e])?)
}
}
};
Expand Down Expand Up @@ -339,9 +339,21 @@ macro_rules! impl_fixed_bytes_traits {
$crate::impl_fixed_bytes_traits!(
impl<$($const)?> cmp::PartialOrd<[u8]> for $t
where
fn partial_cmp -> ::core::option::Option<::core::cmp::Ordering>,
fn partial_cmp -> $crate::private::Option<$crate::private::Ordering>,
[..] // slices $t
);

impl<$($const N: usize)?> $crate::hex::FromHex for $t {
type Error = $crate::hex::FromHexError;

#[inline]
fn from_hex<T>(hex: T) -> Result<Self, Self::Error>
where
T: $crate::private::AsRef<[u8]>
{
$crate::hex::FromHex::from_hex(hex).map(Self)
}
}
};
}

Expand All @@ -359,7 +371,8 @@ macro_rules! impl_getrandom {

/// Instantiates a new fixed hash with cryptographically random content.
#[inline]
pub fn try_random() -> ::core::result::Result<Self, $crate::private::getrandom::Error> {
pub fn try_random() -> $crate::private::Result<Self, $crate::private::getrandom::Error>
{
$crate::FixedBytes::try_random().map(Self)
}
}
Expand Down
84 changes: 80 additions & 4 deletions crates/primitives/src/bits/serde.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,80 @@
use super::FixedBytes;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use core::fmt;
use serde::{
de::{self, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};

impl<const N: usize> Serialize for FixedBytes<N> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut buf = hex::Buffer::<N, true>::new();
serializer.serialize_str(buf.format(&self.0))
if serializer.is_human_readable() {
let mut buf = hex::Buffer::<N, true>::new();
serializer.serialize_str(buf.format(&self.0))
} else {
serializer.serialize_bytes(self.as_slice())
}
}
}

impl<'de, const N: usize> Deserialize<'de> for FixedBytes<N> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
hex::deserialize::<'de, D, [u8; N]>(deserializer).map(Self)
struct FixedVisitor<const N: usize>;

impl<'de, const N: usize> Visitor<'de> for FixedVisitor<N> {
type Value = FixedBytes<N>;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{} bytes, represented as a hex string of length {}, an array of u8, or raw bytes",
N,
N * 2
)
}

fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {
<[u8; N]>::try_from(v)
.map(FixedBytes)
prestwich marked this conversation as resolved.
Show resolved Hide resolved
.map_err(de::Error::custom)
}

fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut bytes = [0u8; N];

bytes.iter_mut().enumerate().try_for_each(|(i, b)| {
*b = seq.next_element()?.ok_or_else(|| {
de::Error::invalid_length(i, &format!("exactly {} bytes", N).as_str())
})?;
Ok(())
})?;

if let Ok(Some(_)) = seq.next_element::<u8>() {
return Err(de::Error::invalid_length(
N + 1,
&format!("exactly {} bytes", N).as_str(),
))
}

Ok(FixedBytes(bytes))
}

fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
<FixedBytes<N> as hex::FromHex>::from_hex(v).map_err(de::Error::custom)
}
}

deserializer.deserialize_any(FixedVisitor::<N>)
DaniPopes marked this conversation as resolved.
Show resolved Hide resolved
}
}

#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct TestCase<const N: usize> {
fixed: FixedBytes<N>,
}

#[test]
fn serde() {
Expand All @@ -25,4 +83,22 @@ mod tests {
assert_eq!(ser, "\"0x000000000123456789abcdef\"");
assert_eq!(serde_json::from_str::<FixedBytes<12>>(&ser).unwrap(), bytes);
}

#[test]
fn serde_num_array() {
let json = serde_json::json! {{"fixed": [0,1,2,3,4]}};

assert_eq!(
serde_json::from_value::<TestCase<5>>(json.clone())
.unwrap()
.fixed,
FixedBytes([0, 1, 2, 3, 4])
);

assert!(format!(
"{}",
serde_json::from_value::<TestCase<4>>(json.clone()).unwrap_err()
)
.contains("invalid length 5, expected exactly 4 bytes"),);
}
}
9 changes: 9 additions & 0 deletions crates/primitives/src/bytes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ impl core::str::FromStr for Bytes {
}
}

impl hex::FromHex for Bytes {
type Error = hex::FromHexError;

#[inline]
fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
hex::decode(hex).map(Self::from)
}
}

impl Bytes {
/// Creates a new empty `Bytes`.
///
Expand Down
Loading