referrerpolicy=no-referrer-when-downgrade

pallet_revive/evm/api/
byte.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17//! Define Byte wrapper types for encoding and decoding hex strings
18
19use super::hex_serde::HexCodec;
20use alloc::{vec, vec::Vec};
21use alloy_core::hex;
22use codec::{Decode, Encode};
23use core::{
24	fmt::{Debug, Display, Formatter, Result as FmtResult},
25	str::FromStr,
26};
27use scale_info::TypeInfo;
28use serde::{Deserialize, Serialize};
29
30impl FromStr for Bytes {
31	type Err = hex::FromHexError;
32	fn from_str(s: &str) -> Result<Self, Self::Err> {
33		let data = hex::decode(s.trim_start_matches("0x"))?;
34		Ok(Bytes(data))
35	}
36}
37
38macro_rules! impl_hex {
39    ($type:ident, $inner:ty, $default:expr) => {
40        #[derive(Encode, Decode, Eq, PartialEq, Ord, PartialOrd, TypeInfo, Clone, Serialize, Deserialize, Hash)]
41        #[doc = concat!("`", stringify!($inner), "`", " wrapper type for encoding and decoding hex strings")]
42        pub struct $type(#[serde(with = "crate::evm::api::hex_serde")] pub $inner);
43
44        impl Default for $type {
45            fn default() -> Self {
46                $type($default)
47            }
48        }
49
50        impl From<$inner> for $type {
51            fn from(inner: $inner) -> Self {
52                $type(inner)
53            }
54        }
55
56        impl Debug for $type {
57            fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
58				let hex_str = self.0.to_hex();
59				let truncated = &hex_str[..hex_str.len().min(100)];
60				let ellipsis = if hex_str.len() > 100 { "..." } else { "" };
61                write!(f, concat!(stringify!($type), "({}{})"), truncated,ellipsis)
62            }
63        }
64
65        impl Display for $type {
66            fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
67                write!(f, "{}", self.0.to_hex())
68            }
69        }
70    };
71}
72
73impl Bytes {
74	/// See `Vec::is_empty`
75	pub fn is_empty(&self) -> bool {
76		self.0.is_empty()
77	}
78}
79
80impl_hex!(Byte, u8, 0u8);
81impl_hex!(Bytes, Vec<u8>, vec![]);
82impl_hex!(Bytes8, [u8; 8], [0u8; 8]);
83impl_hex!(Bytes32, [u8; 32], [0u8; 32]);
84impl_hex!(Bytes256, [u8; 256], [0u8; 256]);
85
86#[test]
87fn serialize_works() {
88	let a = Byte(42);
89	let s = serde_json::to_string(&a).unwrap();
90	assert_eq!(s, "\"0x2a\"");
91	let b = serde_json::from_str::<Byte>(&s).unwrap();
92	assert_eq!(a, b);
93
94	let a = Bytes(b"bello world".to_vec());
95	let s = serde_json::to_string(&a).unwrap();
96	assert_eq!(s, "\"0x62656c6c6f20776f726c64\"");
97	let b = serde_json::from_str::<Bytes>(&s).unwrap();
98	assert_eq!(a, b);
99
100	let a = Bytes256([42u8; 256]);
101	let s = serde_json::to_string(&a).unwrap();
102	let b = serde_json::from_str::<Bytes256>(&s).unwrap();
103	assert_eq!(a, b);
104}