Skip to content

Commit

Permalink
feat: support no_std (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
yjhmelody authored Jan 24, 2024
1 parent d67b3af commit a300200
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 20 deletions.
22 changes: 16 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,16 @@ repository = "https://github.com/alloy-rs/trie"
exclude = [".github/", "deny.toml", "release.toml", "rustfmt.toml"]

[dependencies]
alloy-primitives = { version = "0.6", features = ["rlp"] }
alloy-rlp = { version = "0.3", features = ["derive"] }
alloy-primitives = { version = "0.6", default-features = false, features = ["rlp"] }
alloy-rlp = { version = "0.3", default-features = false, features = ["derive"] }
derive_more = "0.99"
nybbles = "0.1"
hashbrown = { version = "0.14", features = ["ahash", "inline-more"] }
nybbles = { version = "0.1", default-features = false }
smallvec = "1.11"
tracing = "0.1"
tracing = { version = "0.1", default-features = false }

# serde
serde = { version = "1.0", features = ["derive"], optional = true }
serde = { version = "1.0", default-features = false, features = ["derive"], optional = true }

# arbitrary
arbitrary = { version = "1.3", optional = true }
Expand All @@ -42,8 +43,17 @@ plain_hasher = "0.2"
triehash = "0.8.4"

[features]
serde = ["dep:serde", "alloy-primitives/serde", "nybbles/serde"]
default = ["std"]
std = [
"alloy-primitives/std",
"alloy-rlp/std",
"nybbles/std",
"tracing/std",
"serde?/std",
]
serde = ["dep:serde", "alloy-primitives/serde", "hashbrown/serde", "nybbles/serde"]
arbitrary = [
"std",
"dep:arbitrary",
"dep:derive_arbitrary",
"dep:proptest",
Expand Down
23 changes: 16 additions & 7 deletions src/hash_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ use super::{
nodes::{word_rlp, BranchNode, ExtensionNode, LeafNode},
BranchNodeCompact, Nibbles, TrieMask, EMPTY_ROOT_HASH,
};
#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeMap, fmt::Debug, format, vec, vec::Vec};
use alloy_primitives::{keccak256, Bytes, B256};
use std::{
collections::{BTreeMap, HashMap},
fmt::Debug,
};
use core::cmp;
#[cfg(not(feature = "std"))]
use hashbrown::HashMap;
#[cfg(feature = "std")]
use std::collections::{BTreeMap, HashMap};
use tracing::trace;

mod value;
Expand Down Expand Up @@ -79,7 +82,7 @@ impl HashBuilder {
/// Call [HashBuilder::split] to get the updates to branch nodes.
pub fn set_updates(&mut self, retain_updates: bool) {
if retain_updates {
self.updated_branch_nodes = Some(HashMap::default());
self.updated_branch_nodes = Some(HashMap::new());
}
}

Expand All @@ -101,6 +104,7 @@ impl HashBuilder {
}

/// Print the current stack of the Hash Builder.
#[cfg(feature = "std")]
pub fn print_stack(&self) {
println!("============ STACK ===============");
for item in &self.stack {
Expand Down Expand Up @@ -191,7 +195,7 @@ impl HashBuilder {
let preceding_len = self.groups.len().saturating_sub(1);

let common_prefix_len = succeeding.common_prefix_length(current.as_slice());
let len = std::cmp::max(preceding_len, common_prefix_len);
let len = cmp::max(preceding_len, common_prefix_len);
assert!(len < current.len());

trace!(
Expand Down Expand Up @@ -417,8 +421,13 @@ impl HashBuilder {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap;
use alloy_primitives::{b256, hex, keccak256, B256, U256};
use alloy_rlp::Encodable;
#[cfg(not(feature = "std"))]
use hashbrown::HashMap;
#[cfg(feature = "std")]
use std::collections::{BTreeMap, HashMap};

fn triehash_trie_root<I, K, V>(iter: I) -> B256
Expand Down Expand Up @@ -574,7 +583,7 @@ mod tests {

#[test]
fn test_root_rlp_hashed_data() {
let data = HashMap::from([
let data: HashMap<_, _, _> = HashMap::from([
(B256::with_last_byte(1), U256::from(2)),
(B256::with_last_byte(3), U256::from(4)),
]);
Expand Down
3 changes: 3 additions & 0 deletions src/hash_builder/proof_retainer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use crate::Nibbles;
#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeMap, vec::Vec};
use alloy_primitives::Bytes;
#[cfg(feature = "std")]
use std::collections::BTreeMap;

/// Proof retainer is used to store proofs during merkle trie construction.
Expand Down
7 changes: 5 additions & 2 deletions src/hash_builder/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
#[cfg(not(feature = "std"))]
use alloc::{vec, vec::Vec};
use alloy_primitives::B256;
use core::fmt;

/// The current value of the hash builder.
#[derive(Clone, PartialEq)]
Expand All @@ -11,8 +14,8 @@ pub enum HashBuilderValue {
Bytes(Vec<u8>),
}

impl std::fmt::Debug for HashBuilderValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl fmt::Debug for HashBuilderValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Bytes(bytes) => write!(f, "Bytes({:?})", alloy_primitives::hex::encode(bytes)),
Self::Hash(hash) => write!(f, "Hash({:?})", hash),
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
#![deny(unused_must_use, rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

pub mod nodes;
pub use nodes::BranchNodeCompact;
Expand All @@ -22,6 +26,10 @@ pub mod hash_builder;
pub use hash_builder::HashBuilder;

mod mask;
#[cfg(feature = "std")]
use hashbrown as _;
#[cfg(not(feature = "std"))]
pub use hashbrown::HashMap;
pub use mask::TrieMask;

#[doc(no_inline)]
Expand Down
2 changes: 2 additions & 0 deletions src/nodes/branch.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use super::{super::TrieMask, rlp_node, CHILD_INDEX_RANGE};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use alloy_primitives::B256;
use alloy_rlp::{BufMut, EMPTY_STRING_CODE};

Expand Down
7 changes: 5 additions & 2 deletions src/nodes/extension.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use super::{super::Nibbles, rlp_node};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use alloy_rlp::{BufMut, Encodable};
use core::fmt;
use smallvec::SmallVec;

/// An intermediate node that exists solely to compress the trie's paths. It contains a path segment
Expand Down Expand Up @@ -43,8 +46,8 @@ impl Encodable for ExtensionNode<'_> {
}
}

impl std::fmt::Debug for ExtensionNode<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl fmt::Debug for ExtensionNode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExtensionNode")
.field("prefix", &alloy_primitives::hex::encode(&self.prefix))
.field("node", &alloy_primitives::hex::encode(self.node))
Expand Down
10 changes: 8 additions & 2 deletions src/nodes/leaf.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use super::{super::Nibbles, rlp_node};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use alloy_rlp::{BufMut, Encodable};
use smallvec::SmallVec;

use core::fmt;

/// A leaf node represents the endpoint or terminal node in the trie. In other words, a leaf node is
/// where actual values are stored.
///
Expand Down Expand Up @@ -43,8 +47,8 @@ impl Encodable for LeafNode<'_> {
}
}

impl std::fmt::Debug for LeafNode<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl fmt::Debug for LeafNode<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LeafNode")
.field("key", &alloy_primitives::hex::encode(&self.key))
.field("value", &alloy_primitives::hex::encode(self.value))
Expand All @@ -55,6 +59,8 @@ impl std::fmt::Debug for LeafNode<'_> {
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "std"))]
use alloc::vec;
use alloy_primitives::hex;

// From manual regression test
Expand Down
4 changes: 3 additions & 1 deletion src/nodes/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! Various branch nodes produced by the hash builder.

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use alloy_primitives::{keccak256, B256};
use alloy_rlp::EMPTY_STRING_CODE;
use std::ops::Range;
use core::ops::Range;

mod branch;
pub use branch::{BranchNode, BranchNodeCompact};
Expand Down

0 comments on commit a300200

Please sign in to comment.