Skip to content

Commit

Permalink
refactor: change the inner type of Hex
Browse files Browse the repository at this point in the history
  • Loading branch information
Eason committed Aug 29, 2023
1 parent 22d97b7 commit 9c37ae5
Showing 1 changed file with 38 additions and 77 deletions.
115 changes: 38 additions & 77 deletions protocol/src/types/primitive.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
use std::cmp::Ordering;
use std::{fmt, str::FromStr};

pub use ethereum_types::{
BigEndianHash, Bloom, Public, Secret, Signature, H128, H160, H256, H512, H520, H64, U128, U256,
U512, U64,
};
use zeroize::Zeroizing;

use std::cmp::Ordering;
use std::{fmt, str::FromStr};

use bytes::BytesMut;
use faster_hex::withpfx_lowercase;
use ophelia::{PublicKey, UncompressedPublicKey};
use overlord::DurationConfig;
use rlp_derive::{RlpDecodable, RlpEncodable};
use serde::{de, Deserialize, Serialize};
use serde::{de, ser, Deserialize, Serialize};

use common_crypto::Secp256k1PublicKey;
use common_hasher::keccak256;

use crate::codec::{hex_decode, hex_encode, serialize_uint};
use crate::codec::{deserialize_address, hex_decode, hex_encode, serialize_uint};
use crate::types::{BlockNumber, Bytes, TypesError};
use crate::{ProtocolError, ProtocolResult};

Expand Down Expand Up @@ -72,21 +74,19 @@ impl Hasher {
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Hex(String);
pub struct Hex(Bytes);

impl Hex {
pub fn empty() -> Self {
Hex(String::from(HEX_PREFIX))
Hex(Bytes::default())
}

pub fn is_empty(&self) -> bool {
self.0.len() == 2
self.0.is_empty()
}

pub fn encode<T: AsRef<[u8]>>(src: T) -> Self {
let mut s = HEX_PREFIX.to_string();
s.push_str(&hex_encode(src));
Hex(s)
Hex(BytesMut::from(src.as_ref()).freeze())
}

pub fn decode(s: String) -> ProtocolResult<Bytes> {
Expand All @@ -106,20 +106,19 @@ impl Hex {
HEX_PREFIX.to_string() + &s
};

let _ = hex_decode(&s[2..])?;
Ok(Hex(s))
Ok(Hex(hex_decode(&s[2..])?.into()))
}

pub fn as_string(&self) -> String {
self.0.to_owned()
HEX_PREFIX.to_string() + &hex_encode(self.0.as_ref())
}

pub fn as_string_trim0x(&self) -> String {
(self.0[2..]).to_owned()
hex_encode(self.0.as_ref())
}

pub fn as_bytes(&self) -> Bytes {
Bytes::from(hex_decode(&self.0[2..]).expect("impossible, already checked in from_string"))
self.0.clone()
}

fn is_prefixed(s: &str) -> bool {
Expand All @@ -129,40 +128,16 @@ impl Hex {

impl Default for Hex {
fn default() -> Self {
Hex(String::from("0x0000000000000000"))
Hex(vec![0u8; 8].into())
}
}

impl Serialize for Hex {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
serializer.serialize_str(&self.0)
}
}

struct HexVisitor;

impl<'de> de::Visitor<'de> for HexVisitor {
type Value = Hex;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Expect a hex string")
}

fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: de::Error,
{
Hex::from_string(v).map_err(|e| de::Error::custom(e.to_string()))
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
S: ser::Serializer,
{
Hex::from_string(v.to_owned()).map_err(|e| de::Error::custom(e.to_string()))
withpfx_lowercase::serialize(&self.0, serializer)
}
}

Expand All @@ -171,7 +146,7 @@ impl<'de> Deserialize<'de> for Hex {
where
D: de::Deserializer<'de>,
{
deserializer.deserialize_string(HexVisitor)
Ok(Hex(withpfx_lowercase::deserialize(deserializer)?))
}
}

Expand All @@ -197,42 +172,18 @@ impl Serialize for Address {
where
S: serde::ser::Serializer,
{
serializer.serialize_bytes(self.0.as_bytes())
serializer.serialize_str(&self.eip55())
}
}

// struct AddressVisitor;

// impl<'de> de::Visitor<'de> for AddressVisitor {
// type Value = Address;

// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
// formatter.write_str("Expect a bech32 string")
// }

// fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
// where
// E: de::Error,
// {
// Address::from_str(&v).map_err(|e| de::Error::custom(e.to_string()))
// }

// fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
// where
// E: de::Error,
// {
// Address::from_str(&v).map_err(|e| de::Error::custom(e.to_string()))
// }
// }

// impl<'de> Deserialize<'de> for Address {
// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
// where
// D: de::Deserializer<'de>,
// {
// deserializer.deserialize_string(AddressVisitor)
// }
// }
impl<'de> Deserialize<'de> for Address {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: de::Deserializer<'de>,
{
Ok(Address(deserialize_address(deserializer)?))
}
}

impl Address {
pub fn from_pubkey_bytes<B: AsRef<[u8]>>(bytes: B) -> ProtocolResult<Self> {
Expand Down Expand Up @@ -545,6 +496,16 @@ mod tests {
let _ = Hex::decode(hex).unwrap();
}

#[test]
fn test_hex_codec() {
let data = H256::random();
let hex = Hex::encode(data.0);
assert_eq!(
serde_json::to_string(&hex).unwrap(),
serde_json::to_string(&data).unwrap()
);
}

#[test]
fn test_default_values() {
let bytes = Hex::empty();
Expand Down

0 comments on commit 9c37ae5

Please sign in to comment.