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

feat(primitives): implement map module #743

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ jobs:
with:
cache-on-failure: true
- name: cargo hack
run: cargo hack check --feature-powerset --depth 2
run: cargo hack check --feature-powerset --depth 1 --skip nightly

check-no-std:
name: check no_std ${{ matrix.features }}
Expand Down
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,18 @@ paste = "1.0"
num_enum = "0.7"
thiserror = "1.0"

# crypto
digest = "0.10"
k256 = { version = "0.13", default-features = false }
keccak-asm = { version = "0.1.0", default-features = false }
tiny-keccak = { version = "2.0", default-features = false }
sha3 = { version = "0.10.8", default-features = false }

# maps
hashbrown = { version = "0.14", default-features = false }
indexmap = { version = "2.5", default-features = false }
rustc-hash = { version = "2.0", default-features = false }

# misc
allocative = { version = "0.3.2", default-features = false }
alloy-rlp = { version = "0.3", default-features = false }
Expand Down
17 changes: 12 additions & 5 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,27 +36,34 @@ std = [
"alloy-dyn-abi?/std",
"alloy-sol-types?/std",
]
nightly = ["alloy-primitives/nightly"]

dyn-abi = ["sol-types", "dep:alloy-dyn-abi"]
json-abi = ["json", "serde", "dep:alloy-json-abi"]
json = ["alloy-sol-types?/json"]
sol-types = ["dep:alloy-sol-types"]

tiny-keccak = ["alloy-primitives/tiny-keccak"]
native-keccak = ["alloy-primitives/native-keccak"]
asm-keccak = ["alloy-primitives/asm-keccak"]
native-keccak = ["alloy-primitives/native-keccak"]
sha3-keccak = ["alloy-primitives/sha3-keccak"]
tiny-keccak = ["alloy-primitives/tiny-keccak"]

map = ["alloy-primitives/map"]
map-hashbrown = ["alloy-primitives/map-hashbrown"]
map-indexmap = ["alloy-primitives/map-indexmap"]
map-fxhash = ["alloy-primitives/map-fxhash"]

postgres = ["std", "alloy-primitives/postgres"]
getrandom = ["alloy-primitives/getrandom"]
rand = ["alloy-primitives/rand"]
rlp = ["alloy-primitives/rlp", "dep:alloy-rlp"]
serde = ["alloy-primitives/serde"]
k256 = ["alloy-primitives/k256"]
eip712 = ["alloy-sol-types?/eip712-serde", "alloy-dyn-abi?/eip712"]

postgres = ["std", "alloy-primitives/postgres"]
arbitrary = [
"std",
"alloy-primitives/arbitrary",
"alloy-sol-types?/arbitrary",
"alloy-dyn-abi?/arbitrary",
]
k256 = ["alloy-primitives/k256"]
eip712 = ["alloy-sol-types?/eip712-serde", "alloy-dyn-abi?/eip712"]
4 changes: 2 additions & 2 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub use alloy_json_abi as json_abi;
#[cfg(feature = "sol-types")]
#[doc(inline)]
pub use alloy_sol_types as sol_types;
#[cfg(all(doc, feature = "sol-types"))] // Show this re-export in docs instead of the wrapper below.
#[cfg(all(feature = "sol-types", doc))] // Show this re-export in docs instead of the wrapper below.
#[doc(no_inline)]
pub use sol_types::sol;

Expand All @@ -34,7 +34,7 @@ pub use alloy_rlp as rlp;
/// [`sol!`](sol_types::sol!) `macro_rules!` wrapper to set import attributes.
///
/// See [`sol!`](sol_types::sol!) for the actual macro documentation.
#[cfg(all(not(doc), feature = "sol-types"))] // Show the actual macro in docs.
#[cfg(all(feature = "sol-types", not(doc)))] // Show the actual macro in docs.
#[macro_export]
macro_rules! sol {
($($t:tt)*) => {
Expand Down
4 changes: 2 additions & 2 deletions crates/dyn-abi/src/arbitrary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use alloy_primitives::{Address, Function, B256, I256, U256};
use arbitrary::{size_hint, Unstructured};
use core::ops::RangeInclusive;
use proptest::{
collection::{hash_set as hash_set_strategy, vec as vec_strategy, VecStrategy},
collection::{vec as vec_strategy, VecStrategy},
prelude::*,
strategy::{Flatten, Map, Recursive, TupleUnion, WA},
};
Expand Down Expand Up @@ -240,7 +240,7 @@ macro_rules! custom_struct_strategy {
.prop_flat_map(move |sz| {
(
IDENT_STRATEGY,
hash_set_strategy(IDENT_STRATEGY, sz..=sz)
proptest::collection::hash_set(IDENT_STRATEGY, sz..=sz)
.prop_map(|prop_names| prop_names.into_iter().collect()),
vec_strategy(elem.clone(), sz..=sz),
)
Expand Down
46 changes: 37 additions & 9 deletions crates/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ itoa.workspace = true
ruint.workspace = true

# macros
cfg-if.workspace = true
derive_more = { workspace = true, features = [
"as_ref",
"add",
Expand All @@ -43,7 +44,7 @@ derive_more = { workspace = true, features = [
"into_iterator",
"display",
] }
cfg-if.workspace = true
paste.workspace = true

# keccak256
keccak-asm = { workspace = true, optional = true }
Expand All @@ -65,6 +66,11 @@ rand = { workspace = true, optional = true, features = ["getrandom"] }
# k256
k256 = { workspace = true, optional = true, features = ["ecdsa"] }

# map
hashbrown = { workspace = true, optional = true, features = ["inline-more"] }
indexmap = { workspace = true, optional = true }
rustc-hash = { workspace = true, optional = true }

# arbitrary
arbitrary = { workspace = true, optional = true }
derive_arbitrary = { workspace = true, optional = true }
Expand All @@ -90,24 +96,46 @@ std = [
"hex/std",
"ruint/std",
"alloy-rlp?/std",
"indexmap?/std",
"k256?/std",
"keccak-asm?/std",
"proptest?/std",
"rand?/std",
"rustc-hash?/std",
"serde?/std",
"k256?/std",
"sha3?/std",
]
nightly = [
"hex/nightly",
"ruint/nightly",
"hashbrown?/nightly",
"rustc-hash?/nightly",
]

tiny-keccak = []
native-keccak = []
asm-keccak = ["dep:keccak-asm"]
native-keccak = []
sha3-keccak = ["dep:sha3"]
tiny-keccak = []

map = ["dep:hashbrown"]
map-hashbrown = ["map"]
map-indexmap = ["map", "dep:indexmap"]
map-fxhash = ["map", "dep:rustc-hash"]

postgres = ["std", "dep:postgres-types", "ruint/postgres"]
getrandom = ["dep:getrandom"]
rand = ["dep:rand", "getrandom", "ruint/rand"]
k256 = ["dep:k256"]
rand = ["dep:rand", "getrandom", "ruint/rand", "rustc-hash?/rand"]
rlp = ["dep:alloy-rlp", "ruint/alloy-rlp"]
serde = ["dep:serde", "bytes/serde", "hex/serde", "ruint/serde"]
serde = [
"dep:serde",
"bytes/serde",
"hex/serde",
"ruint/serde",
"hashbrown?/serde",
"indexmap?/serde",
]

allocative = ["dep:allocative"]
arbitrary = [
"std",
"dep:arbitrary",
Expand All @@ -116,9 +144,9 @@ arbitrary = [
"dep:proptest-derive",
"ruint/arbitrary",
"ruint/proptest",
"indexmap?/arbitrary",
]
k256 = ["dep:k256"]
allocative = ["dep:allocative"]
postgres = ["std", "dep:postgres-types", "ruint/postgres"]

# `const-hex` compatibility feature for `hex`.
# Should not be needed most of the time.
Expand Down
8 changes: 5 additions & 3 deletions crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
)]
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "nightly", feature(hasher_prefixfree_extras))]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]

#[macro_use]
extern crate alloc;

use paste as _;
#[cfg(feature = "sha3-keccak")]
use sha3 as _;

use tiny_keccak as _;

#[cfg(feature = "postgres")]
Expand Down Expand Up @@ -42,8 +43,9 @@ pub use common::TxKind;

mod log;
pub use log::{IntoLogData, Log, LogData};
#[cfg(feature = "serde")]
mod log_serde;

#[cfg(feature = "map")]
pub mod map;

mod sealed;
pub use sealed::{Sealable, Sealed};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use crate::{Address, Bytes, B256};
use alloc::vec::Vec;

#[cfg(feature = "serde")]
mod serde;

/// An Ethereum event log object.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[cfg_attr(feature = "arbitrary", derive(derive_arbitrary::Arbitrary, proptest_derive::Arbitrary))]
pub struct LogData {
/// The indexed topic list.
Expand Down
156 changes: 156 additions & 0 deletions crates/primitives/src/map/fixed.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
use super::*;
use crate::{Address, FixedBytes, Selector, B256};
use cfg_if::cfg_if;
use core::hash::{BuildHasher, Hasher};

/// [`HashMap`] optimized for hashing [fixed-size byte arrays](FixedBytes).
pub type FbHashMap<const N: usize, V, S = DefaultHashBuilder> =
HashMap<FixedBytes<N>, V, BuildFbHasher<N, S>>;
/// [`HashSet`] optimized for hashing [fixed-size byte arrays](FixedBytes).
pub type FbHashSet<const N: usize, S = DefaultHashBuilder> =
HashSet<FixedBytes<N>, BuildFbHasher<N, S>>;

cfg_if! {
if #[cfg(feature = "map-indexmap")] {
/// [`IndexMap`] optimized for hashing [fixed-size byte arrays](FixedBytes).
pub type FbIndexMap<const N: usize, V, S = DefaultHashBuilder> =
indexmap::IndexMap<FixedBytes<N>, V, BuildFbHasher<N, S>>;
/// [`IndexSet`] optimized for hashing [fixed-size byte arrays](FixedBytes).
pub type FbIndexSet<const N: usize, S = DefaultHashBuilder> =
indexmap::IndexSet<FixedBytes<N>, BuildFbHasher<N, S>>;
}
}

macro_rules! fb_alias_maps {
($($ty:ident < $n:literal >),* $(,)?) => { paste::paste! {
$(
#[doc = concat!("[`HashMap`] optimized for hashing [`", stringify!($ty), "`].")]
pub type [<$ty HashMap>]<V, S = DefaultHashBuilder> =
HashMap<$ty, V, BuildFbHasher<$n, S>>;
#[doc = concat!("[`HashSet`] optimized for hashing [`", stringify!($ty), "`].")]
pub type [<$ty HashSet>]<S = DefaultHashBuilder> =
HashSet<$ty, BuildFbHasher<$n, S>>;

cfg_if! {
if #[cfg(feature = "map-indexmap")] {
#[doc = concat!("[`IndexMap`] optimized for hashing [`", stringify!($ty), "`].")]
pub type [<$ty IndexMap>]<V, S = DefaultHashBuilder> =
IndexMap<$ty, V, BuildFbHasher<$n, S>>;
#[doc = concat!("[`IndexSet`] optimized for hashing [`", stringify!($ty), "`].")]
pub type [<$ty IndexSet>]<S = DefaultHashBuilder> =
IndexSet<$ty, BuildFbHasher<$n, S>>;
}
}
)*
} };
}

fb_alias_maps!(Selector<4>, Address<20>, B256<32>);

macro_rules! assert_unchecked {
($e:expr) => {
if cfg!(debug_assertions) {
assert!($e);
} else if !$e {
unsafe { core::hint::unreachable_unchecked() }
}
};
}

/// [`BuildHasher`] optimized for hashing [fixed-size byte arrays](FixedBytes).
///
/// **NOTE:** this hasher accepts only `N`-length byte arrays! It is UB to hash anything else.
#[derive(Clone, Debug, Default)]
pub struct BuildFbHasher<const N: usize, S = DefaultHashBuilder> {
inner: S,
_marker: core::marker::PhantomData<[(); N]>,
}

impl<const N: usize, S: BuildHasher> BuildHasher for BuildFbHasher<N, S> {
type Hasher = FbHasher<N, S::Hasher>;

#[inline]
fn build_hasher(&self) -> Self::Hasher {
FbHasher { inner: self.inner.build_hasher(), _marker: core::marker::PhantomData }
}
}

/// [`Hasher`] optimized for hashing [fixed-size byte arrays](FixedBytes).
///
/// **NOTE:** this hasher accepts only `N`-length byte arrays! It is UB to hash anything else.
#[derive(Clone, Debug, Default)]
pub struct FbHasher<const N: usize, H> {
inner: H,
_marker: core::marker::PhantomData<[(); N]>,
}

impl<const N: usize, H: Hasher> Hasher for FbHasher<N, H> {
#[inline]
fn finish(&self) -> u64 {
self.inner.finish()
}

#[inline]
fn write(&mut self, mut bytes: &[u8]) {
assert_unchecked!(bytes.len() == N);

while let Some((chunk, rest)) = bytes.split_first_chunk() {
self.inner.write_usize(usize::from_ne_bytes(*chunk));
bytes = rest;
}
if usize::BITS > 64 {
if let Some((chunk, rest)) = bytes.split_first_chunk() {
self.inner.write_u64(u64::from_ne_bytes(*chunk));
bytes = rest;
}
}
if usize::BITS > 32 {
if let Some((chunk, rest)) = bytes.split_first_chunk() {
self.inner.write_u32(u32::from_ne_bytes(*chunk));
bytes = rest;
}
}
if usize::BITS > 16 {
if let Some((chunk, rest)) = bytes.split_first_chunk() {
self.inner.write_u16(u16::from_ne_bytes(*chunk));
bytes = rest;
}
}
if usize::BITS > 8 {
if let Some((chunk, rest)) = bytes.split_first_chunk() {
self.inner.write_u8(u8::from_ne_bytes(*chunk));
bytes = rest;
}
}

debug_assert!(bytes.is_empty());
}

#[cfg(feature = "nightly")]
#[inline]
fn write_length_prefix(&mut self, len: usize) {
assert_unchecked!(len == N);
// We can just skip hashing the length prefix entirely since we know it's always `N`.
}
}

#[cfg(test)]
mod tests {
use super::*;

macro_rules! hash_zero {
($n:expr) => {
BuildFbHasher::<$n>::default().hash_one(&FixedBytes::<$n>::ZERO)
};
}

#[test]
fn fb_hasher() {
// Just by running it once we test that it compiles and that debug assertions are correct.
ruint::const_for!(N in [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47] {
assert_ne!(hash_zero!(N), 0);
});
}
}
Loading
Loading