Skip to content

Commit

Permalink
feat: use const-hex instead of hex (#25)
Browse files Browse the repository at this point in the history
* feat: use `const-hex` instead of `hex`

* fix: no-default-features
  • Loading branch information
DaniPopes authored May 10, 2023
1 parent 353a891 commit e2542f1
Show file tree
Hide file tree
Showing 17 changed files with 57 additions and 64 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ syn = "2.0"
arbitrary = { version = "1.3", default-features = false }
arrayvec = { version = "0.7.2", default-features = false }
bytes = { version = "1.4", default-features = false }
hex = { version = "0.4", default-features = false }
hex = { package = "const-hex", version = "1.2", default-features = false, features = ["hex"] }
hex-literal = "0.4"
proptest = { version = "1.1", default-features = false }
proptest-derive = "0.3"
Expand Down
5 changes: 2 additions & 3 deletions abi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ sol-type-parser.workspace = true
hex = { workspace = true, features = ["alloc"] }

thiserror = { workspace = true, optional = true }
serde = { workspace = true, optional = true }
serde = { workspace = true, optional = true, features = ["derive"] }

[dev-dependencies]
hex-literal.workspace = true

[features]
default = ["std", "hex/alloc"]
std = ["ethers-primitives/std", "hex/std", "serde?/std", "thiserror"]
# TODO: Can we remove std from here?
eip712-serde = ["std", "dep:serde"]
eip712-serde = ["dep:serde", "serde?/alloc", "ethers-primitives/serde"]
5 changes: 1 addition & 4 deletions abi/src/coder/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,12 +605,9 @@ impl TokenSeq for () {

#[cfg(test)]
mod tests {
use ethers_primitives::B256;

use super::*;
#[cfg(not(feature = "std"))]
use crate::no_std_prelude::*;
use crate::{sol_data, SolType};
use ethers_primitives::B256;

macro_rules! assert_type_check {
($sol:ty, $token:expr $(,)?) => {
Expand Down
15 changes: 7 additions & 8 deletions abi/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,31 +71,30 @@ pub(crate) use serde_helper::*;

#[cfg(feature = "eip712-serde")]
mod serde_helper {
use alloc::string::{String, ToString};
use ethers_primitives::U256;
use serde::{Deserialize, Deserializer};

/// Helper type to parse numeric strings, `u64` and `U256`
#[derive(Deserialize, Debug, Clone)]
#[serde(untagged)]
pub(crate) enum StringifiedNumeric {
String(String),
U256(U256),
Num(u64),
U256(U256),
String(String),
}

impl TryFrom<StringifiedNumeric> for U256 {
type Error = String;

fn try_from(value: StringifiedNumeric) -> Result<Self, Self::Error> {
match value {
StringifiedNumeric::U256(n) => Ok(n),
StringifiedNumeric::Num(n) => Ok(U256::from(n)),
StringifiedNumeric::U256(n) => Ok(n),
// TODO: this is probably unreachable, due to ruint U256 deserializing from a string
StringifiedNumeric::String(s) => {
if let Ok(val) = s.parse::<u128>() {
Ok(U256::from(val))
} else if s.starts_with("0x") {
U256::from_str_radix(s.strip_prefix("0x").unwrap(), 16)
.map_err(|err| err.to_string())
if let Some(s) = s.strip_prefix("0x") {
U256::from_str_radix(s, 16).map_err(|err| err.to_string())
} else {
U256::from_str_radix(&s, 10).map_err(|err| err.to_string())
}
Expand Down
1 change: 1 addition & 0 deletions dyn-abi/src/eip712/typed_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ impl<'de> Deserialize<'de> for TypedData {
D: serde::de::Deserializer<'de>,
{
#[derive(Deserialize)]
#[allow(missing_debug_implementations)]
struct TypedDataHelper {
#[serde(default)]
domain: Eip712Domain,
Expand Down
14 changes: 9 additions & 5 deletions primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@ ruint = { workspace = true, features = ["rlp", "serde"] }
# utility
derive_more = "0.99"
tiny-keccak = { workspace = true, features = ["keccak"] }
hex = { workspace = true, default-features = false }
hex.workspace = true

# optional
serde = { workspace = true, features = ["derive"], optional = true }
thiserror = { workspace = true, optional = true }

# rlp support
ethers-rlp = { workspace = true, optional = true }
Expand All @@ -37,8 +36,13 @@ proptest-derive = { workspace = true, optional = true }

[features]
default = ["std", "rlp", "serde", "hex/std"]
std = ["serde/std", "ethers-rlp?/std", "bytes?/std", "proptest?/std", "dep:thiserror"]
std = ["serde/std", "ethers-rlp?/std", "bytes?/std", "proptest?/std"]
rlp = ["dep:ethers-rlp", "dep:bytes"]
serde = ["dep:serde", "ruint/serde"]
arbitrary = ["ruint/arbitrary", "ruint/proptest", "dep:arbitrary", "dep:proptest", "dep:proptest-derive"]

arbitrary = [
"ruint/arbitrary",
"ruint/proptest",
"dep:arbitrary",
"dep:proptest",
"dep:proptest-derive",
]
9 changes: 2 additions & 7 deletions primitives/src/bits/address.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
#[cfg(feature = "std")]
use std::borrow::Borrow;

#[cfg(not(feature = "std"))]
use crate::{utils::keccak256, wrap_fixed_bytes, FixedBytes};
use alloc::{
borrow::Borrow,
format,
string::{String, ToString},
};

use crate::{utils::keccak256, wrap_fixed_bytes, FixedBytes};

/// Error type for address checksum validation
#[derive(Debug, Copy, Clone)]
pub enum AddressError {
Expand Down Expand Up @@ -157,6 +151,7 @@ impl Address {
#[cfg(test)]
mod test {
use super::Address;
use alloc::string::String;

#[test]
fn it_parses() {
Expand Down
9 changes: 1 addition & 8 deletions primitives/src/bits/fixed.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use core::{fmt, ops};

use derive_more::{AsMut, AsRef, Deref, DerefMut, From, Index, IndexMut};

/// A bytearray of fixed length.
Expand Down Expand Up @@ -65,23 +64,20 @@ impl<'a, const N: usize> From<&'a mut [u8; N]> for FixedBytes<N> {

impl<const N: usize> From<FixedBytes<N>> for [u8; N] {
#[inline]
#[track_caller]
fn from(s: FixedBytes<N>) -> Self {
s.0
}
}

impl<const N: usize> AsRef<[u8]> for FixedBytes<N> {
#[inline]
#[track_caller]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}

impl<const N: usize> AsMut<[u8]> for FixedBytes<N> {
#[inline]
#[track_caller]
fn as_mut(&mut self) -> &mut [u8] {
self.as_bytes_mut()
}
Expand Down Expand Up @@ -371,10 +367,7 @@ impl<const N: usize> core::str::FromStr for FixedBytes<N> {
let s = s.strip_prefix("0x").unwrap_or(s);

let mut buf = [0u8; N];
hex::decode_to_slice(s, buf.as_mut())?;
hex::decode_to_slice(s, &mut buf)?;
Ok(Self(buf))
}
}

#[cfg(test)]
mod test {}
4 changes: 0 additions & 4 deletions primitives/src/bits/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,31 +70,27 @@ macro_rules! wrap_fixed_bytes {

impl<'a> From<[u8; $n]> for $name {
#[inline]
#[track_caller]
fn from(bytes: [u8; $n]) -> Self {
Self(bytes.into())
}
}

impl<'a> From<&'a [u8; $n]> for $name {
#[inline]
#[track_caller]
fn from(bytes: &'a [u8; $n]) -> Self {
Self(bytes.into())
}
}

impl AsRef<[u8]> for $name {
#[inline]
#[track_caller]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}

impl AsMut<[u8]> for $name {
#[inline]
#[track_caller]
fn as_mut(&mut self) -> &mut [u8] {
self.as_bytes_mut()
}
Expand Down
2 changes: 0 additions & 2 deletions primitives/src/bits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ pub use fixed::FixedBytes;

mod macros;

// pub(self) mod hex;

// code stolen from: https://docs.rs/impl-serde/0.4.0/impl_serde/
#[cfg(feature = "serde")]
mod serialize;
Expand Down
3 changes: 1 addition & 2 deletions primitives/src/bits/rlp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use ethers_rlp::{Decodable, Encodable};

use super::FixedBytes;
use ethers_rlp::{Decodable, Encodable};

impl<const N: usize> Decodable for FixedBytes<N> {
fn decode(buf: &mut &[u8]) -> Result<Self, ethers_rlp::DecodeError> {
Expand Down
4 changes: 2 additions & 2 deletions primitives/src/bits/serialize.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::result::Result;

use super::FixedBytes;
use alloc::string::String;
use core::result::Result;

impl<const N: usize> serde::Serialize for FixedBytes<N> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
Expand Down
2 changes: 1 addition & 1 deletion primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

#![cfg_attr(not(feature = "std"), no_std)]

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

mod bits;
Expand Down
27 changes: 22 additions & 5 deletions primitives/src/signed/errors.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
use core::fmt;
use ruint::BaseConvertError;

/// The error type that is returned when parsing a signed integer.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
pub enum ParseSignedError {
/// Error that occurs when an invalid digit is encountered while parsing.
#[cfg_attr(feature = "std", error("Parsing Error: {0}"))]
Ruint(ruint::ParseError),

/// Error that occurs when the number is too large or too small (negative)
/// and does not fit in the target signed integer.
#[cfg_attr(feature = "std", error("number does not fit in the integer size"))]
IntegerOverflow,
}

Expand All @@ -27,8 +25,27 @@ impl From<ruint::ParseError> for ParseSignedError {
}
}

#[cfg(feature = "std")]
impl std::error::Error for ParseSignedError {}

impl fmt::Display for ParseSignedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Ruint(err) => write!(f, "Parsing Error: {err}"),
Self::IntegerOverflow => f.write_str("number does not fit in the integer size"),
}
}
}

/// The error type that is returned when conversion to or from a integer fails.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
#[cfg_attr(feature = "std", error("output of range integer conversion attempted"))]
pub struct BigIntConversionError;

#[cfg(feature = "std")]
impl std::error::Error for BigIntConversionError {}

impl fmt::Display for BigIntConversionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("output of range integer conversion attempted")
}
}
7 changes: 2 additions & 5 deletions primitives/src/signed/int.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use super::{errors, utils::*, Sign};
use alloc::string::{String, ToString};
use core::fmt;
use ruint::Uint;

#[cfg(not(feature = "std"))]
use alloc::{format, string::String};

use super::{errors, utils::*, Sign};

/// Signed integer wrapping a `ruint::Uint`.
///
/// This signed integer implementation is fully abstract across the number of
Expand Down
6 changes: 2 additions & 4 deletions primitives/src/signed/ops.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
use ruint::Uint;

use core::{cmp, iter, ops};

use super::{
utils::{handle_overflow, twos_complement},
Sign, Signed,
};
use core::{cmp, iter, ops};
use ruint::Uint;

// ops impl
impl<const BITS: usize, const LIMBS: usize> Signed<BITS, LIMBS> {
Expand Down
6 changes: 3 additions & 3 deletions primitives/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
pub use tiny_keccak::{Hasher, Keccak};

use crate::bits::FixedBytes;

/// Simple interface to keccak256 hash function
pub use tiny_keccak::{Hasher, Keccak};

/// Simple interface to the `keccak256` hash function.
pub fn keccak256(bytes: impl AsRef<[u8]>) -> FixedBytes<32> {
let mut output = [0u8; 32];
let mut hasher = Keccak::v256();
Expand Down

0 comments on commit e2542f1

Please sign in to comment.