Skip to content

Commit

Permalink
chore: improve Display and Debug for BlockId
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Dec 6, 2024
1 parent 7bda8ec commit 3988612
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 49 deletions.
77 changes: 49 additions & 28 deletions crates/eips/src/eip1898.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use alloy_primitives::{hex::FromHexError, ruint::ParseError, BlockHash, B256, U64};
use alloy_rlp::{bytes, Decodable, Encodable, Error as RlpError};
use core::{
fmt::{self, Debug, Display, Formatter},
fmt::{self, Formatter},
num::ParseIntError,
str::FromStr,
};
Expand Down Expand Up @@ -35,7 +35,7 @@ impl BlockWithParent {
/// - If true, a RPC call should additionally raise if the block is not in the canonical chain.
///
/// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1898.md#specification>
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename = "camelCase"))]
pub struct RpcBlockHash {
Expand Down Expand Up @@ -71,20 +71,33 @@ impl AsRef<B256> for RpcBlockHash {
}
}

impl Display for RpcBlockHash {
impl fmt::Display for RpcBlockHash {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let Self { block_hash, require_canonical } = self;
if *require_canonical == Some(true) {
write!(f, "canonical ")?
f.write_str("canonical ")?;
}
write!(f, "hash {block_hash}")
}
}

impl fmt::Debug for RpcBlockHash {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.require_canonical {
Some(require_canonical) => f
.debug_struct("RpcBlockHash")
.field("block_hash", &self.block_hash)
.field("require_canonical", &require_canonical)
.finish(),
None => fmt::Debug::fmt(&self.block_hash, f),
}
write!(f, "hash {}", block_hash)
}
}

/// A block Number (or tag - "latest", "earliest", "pending")
///
/// This enum allows users to specify a block in a flexible manner.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum BlockNumberOrTag {
/// Latest block
#[default]
Expand Down Expand Up @@ -191,7 +204,7 @@ impl FromStr for BlockNumberOrTag {
"safe" => Self::Safe,
"earliest" => Self::Earliest,
"pending" => Self::Pending,
_number => {
s => {
if let Some(hex_val) = s.strip_prefix("0x") {
u64::from_str_radix(hex_val, 16)?.into()
} else {
Expand All @@ -204,17 +217,23 @@ impl FromStr for BlockNumberOrTag {

impl fmt::Display for BlockNumberOrTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Number(x) => write!(f, "0x{x:x}"),
Self::Latest => f.write_str("latest"),
Self::Finalized => f.write_str("finalized"),
Self::Safe => f.write_str("safe"),
Self::Earliest => f.write_str("earliest"),
Self::Pending => f.write_str("pending"),
match *self {
Self::Number(x) => write!(f, "number 0x{x:x}"),
Self::Latest => f.pad("latest"),
Self::Finalized => f.pad("finalized"),
Self::Safe => f.pad("safe"),
Self::Earliest => f.pad("earliest"),
Self::Pending => f.pad("pending"),
}
}
}

impl fmt::Debug for BlockNumberOrTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}

/// Error thrown when parsing a [BlockNumberOrTag] from a string.
#[derive(Debug)]
pub enum ParseBlockNumberError {
Expand All @@ -238,7 +257,7 @@ impl std::error::Error for ParseBlockNumberError {
}
}

impl Display for ParseBlockNumberError {
impl fmt::Display for ParseBlockNumberError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ParseIntErr(err) => write!(f, "{err}"),
Expand Down Expand Up @@ -271,7 +290,7 @@ impl From<HexStringMissingPrefixError> for ParseBlockNumberError {
#[non_exhaustive]
pub struct HexStringMissingPrefixError;

impl Display for HexStringMissingPrefixError {
impl fmt::Display for HexStringMissingPrefixError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("hex string without 0x prefix")
}
Expand All @@ -281,16 +300,14 @@ impl core::error::Error for HexStringMissingPrefixError {}

/// A Block Identifier.
/// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1898.md>
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum BlockId {
/// A block hash and an optional bool that defines if it's canonical
Hash(RpcBlockHash),
/// A block number
Number(BlockNumberOrTag),
}

// === impl BlockId ===

impl BlockId {
/// Returns the block hash if it is [BlockId::Hash]
pub const fn as_block_hash(&self) -> Option<BlockHash> {
Expand Down Expand Up @@ -543,16 +560,20 @@ impl<'de> serde::Deserialize<'de> for BlockId {
}
}

impl Display for BlockId {
impl fmt::Display for BlockId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Hash(hash) => write!(f, "{}", hash),
Self::Number(num) => {
if num.is_number() {
return write!(f, "number {}", num);
}
write!(f, "{}", num)
}
Self::Hash(hash) => hash.fmt(f),
Self::Number(num) => num.fmt(f),
}
}
}

impl fmt::Debug for BlockId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Hash(hash) => hash.fmt(f),
Self::Number(num) => num.fmt(f),
}
}
}
Expand All @@ -568,7 +589,7 @@ pub enum ParseBlockIdError {
FromHexError(FromHexError),
}

impl Display for ParseBlockIdError {
impl fmt::Display for ParseBlockIdError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::ParseIntError(err) => write!(f, "{err}"),
Expand Down
9 changes: 3 additions & 6 deletions crates/eips/src/eip2718.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@
use crate::alloc::vec::Vec;
use alloy_primitives::{keccak256, Sealed, B256};
use alloy_rlp::{Buf, BufMut, Header, EMPTY_STRING_CODE};
use core::{
fmt,
fmt::{Display, Formatter},
};
use core::fmt;

// https://eips.ethereum.org/EIPS/eip-2718#transactiontype-only-goes-up-to-0x7f
const TX_TYPE_BYTE_MAX: u8 = 0x7f;
Expand All @@ -28,8 +25,8 @@ pub enum Eip2718Error {
/// Result type for [EIP-2718] decoding.
pub type Eip2718Result<T, E = Eip2718Error> = core::result::Result<T, E>;

impl Display for Eip2718Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
impl fmt::Display for Eip2718Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RlpError(err) => write!(f, "{err}"),
Self::UnexpectedType(t) => write!(f, "Unexpected type flag. Got {t}."),
Expand Down
8 changes: 4 additions & 4 deletions crates/json-rpc/src/common.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::{de::Visitor, Deserialize, Serialize};
use std::fmt::Display;
use std::fmt;

/// A JSON-RPC 2.0 ID object. This may be a number, a string, or null.
///
Expand Down Expand Up @@ -44,8 +44,8 @@ impl From<String> for Id {
}
}

impl Display for Id {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Number(n) => write!(f, "{n}"),
Self::String(s) => f.write_str(s),
Expand Down Expand Up @@ -74,7 +74,7 @@ impl<'de> Deserialize<'de> for Id {
impl Visitor<'_> for IdVisitor {
type Value = Id;

fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a string, a number, or null")
}

Expand Down
12 changes: 6 additions & 6 deletions crates/rpc-types-eth/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
//! Block RPC types.
use core::ops::{Deref, DerefMut};

use crate::Transaction;
use alloc::{collections::BTreeMap, vec::Vec};
use alloy_consensus::{BlockHeader, Sealed, TxEnvelope};
use alloy_eips::eip4895::Withdrawals;
pub use alloy_eips::{
calc_blob_gasprice, calc_excess_blob_gas, BlockHashOrNumber, BlockId, BlockNumHash,
BlockNumberOrTag, ForkBlock, RpcBlockHash,
};
use alloy_network_primitives::{
BlockResponse, BlockTransactions, HeaderResponse, TransactionResponse,
};
use alloy_primitives::{Address, BlockHash, Bloom, Bytes, Sealable, B256, B64, U256};
use alloy_rlp::Encodable;
use core::ops::{Deref, DerefMut};

pub use alloy_eips::{
calc_blob_gasprice, calc_excess_blob_gas, BlockHashOrNumber, BlockId, BlockNumHash,
BlockNumberOrTag, ForkBlock, RpcBlockHash,
};

/// Block representation
#[derive(Clone, Debug, PartialEq, Eq)]
Expand Down
8 changes: 3 additions & 5 deletions crates/serde/src/storage.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use core::str::FromStr;

use alloc::collections::BTreeMap;
use alloy_primitives::{ruint::ParseError, Bytes, B256, U256};
use core::fmt::{Display, Formatter};
use core::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize};

/// A storage key type that can be serialized to and from a hex string up to 32 bytes. Used for
Expand Down Expand Up @@ -79,8 +77,8 @@ impl FromStr for JsonStorageKey {
}
}

impl Display for JsonStorageKey {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
impl fmt::Display for JsonStorageKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Hash(hash) => hash.fmt(f),
Self::Number(num) => alloc::format!("{num:#x}").fmt(f),
Expand Down

0 comments on commit 3988612

Please sign in to comment.