Skip to content

Commit

Permalink
feat: impl Compact for FixedBytes<N> (paradigmxyz#8222)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshieDo authored May 13, 2024
1 parent 12f1e9c commit 081796b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
3 changes: 2 additions & 1 deletion crates/storage/codecs/derive/src/compact/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ pub fn generate_from_to(ident: &Ident, fields: &FieldList, is_zstd: bool) -> Tok
/// Generates code to implement the `Compact` trait method `to_compact`.
fn generate_from_compact(fields: &FieldList, ident: &Ident, is_zstd: bool) -> TokenStream2 {
let mut lines = vec![];
let mut known_types = vec!["B256", "Address", "Bloom", "Vec", "TxHash", "BlockHash"];
let mut known_types =
vec!["B256", "Address", "Bloom", "Vec", "TxHash", "BlockHash", "FixedBytes"];

// Only types without `Bytes` should be added here. It's currently manually added, since
// it's hard to figure out with derive_macro which types have Bytes fields.
Expand Down
24 changes: 20 additions & 4 deletions crates/storage/codecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

pub use reth_codecs_derive::*;

use alloy_primitives::{Address, Bloom, Bytes, B256, B512, U256};
use alloy_primitives::{Address, Bloom, Bytes, FixedBytes, U256};
use bytes::Buf;

#[cfg(any(test, feature = "alloy"))]
Expand Down Expand Up @@ -301,9 +301,9 @@ impl<const N: usize> Compact for [u8; N] {
}
}

/// Implements the [`Compact`] trait for fixed size byte array types like [`B256`].
/// Implements the [`Compact`] trait for wrappers over fixed size byte array types.
#[macro_export]
macro_rules! impl_compact_for_bytes {
macro_rules! impl_compact_for_wrapped_bytes {
($($name:tt),+) => {
$(
impl Compact for $name {
Expand All @@ -324,8 +324,23 @@ macro_rules! impl_compact_for_bytes {
)+
};
}
impl_compact_for_wrapped_bytes!(Address, Bloom);

impl_compact_for_bytes!(Address, B256, B512, Bloom);
impl<const N: usize> Compact for FixedBytes<N> {
#[inline]
fn to_compact<B>(self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
self.0.to_compact(buf)
}

#[inline]
fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
let (v, buf) = <[u8; N]>::from_compact(buf, len);
(Self::from(v), buf)
}
}

impl Compact for bool {
/// `bool` vars go directly to the `StructFlags` and are not written to the buffer.
Expand Down Expand Up @@ -378,6 +393,7 @@ const fn decode_varuint_panic() -> ! {
#[cfg(test)]
mod tests {
use super::*;
use alloy_primitives::B256;

#[test]
fn compact_bytes() {
Expand Down

0 comments on commit 081796b

Please sign in to comment.