1use crate::ParseError;
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use std::str::FromStr;
4
5const LENGTH: usize = 32;
6type HexBuffer<const PREFIX: bool> = const_hex::Buffer<LENGTH, PREFIX>;
7
8#[derive(Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
15pub struct U256([u8; LENGTH]);
16
17impl U256 {
18 pub const ZERO: Self = Self([0; LENGTH]);
20
21 pub const fn strict_from_str(hex: &str) -> Self {
28 let hex = remove_0x_prefix(hex.as_bytes());
29 if hex.is_empty() {
30 panic!("input hex string must be non-empty");
31 } else if hex.len() > 2 * LENGTH {
32 panic!("input hex string is too long for U256");
33 }
34 let mut buf = [b'0'; 2 * LENGTH];
35 let (_, part) = buf.split_at_mut(2 * LENGTH - hex.len());
36 let mut i = 0;
37 while i < hex.len() {
38 part[i] = hex[i];
39 i += 1;
40 }
41 match const_hex::const_decode_to_array(&buf) {
42 Err(_) => panic!("input hex string has wrong character"),
43 Ok(addr) => Self(addr),
44 }
45 }
46 pub const fn into_inner(self) -> [u8; LENGTH] {
48 self.0
49 }
50 pub const fn as_slice(&self) -> &[u8] {
52 &self.0
53 }
54}
55
56impl From<u64> for U256 {
57 fn from(value: u64) -> Self {
59 let mut bytes = [0u8; LENGTH];
60 bytes[LENGTH - 8..].copy_from_slice(&value.to_be_bytes());
61 Self(bytes)
62 }
63}
64
65impl From<[u8; LENGTH]> for U256 {
66 fn from(bytes: [u8; LENGTH]) -> Self {
67 Self(bytes)
68 }
69}
70
71impl TryFrom<&[u8]> for U256 {
72 type Error = std::array::TryFromSliceError;
73 fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
75 <[u8; LENGTH]>::try_from(bytes).map(Self)
76 }
77}
78
79impl From<U256> for [u8; LENGTH] {
80 fn from(value: U256) -> Self {
81 value.0
82 }
83}
84
85impl AsRef<[u8]> for U256 {
86 fn as_ref(&self) -> &[u8] {
87 &self.0
88 }
89}
90
91impl std::fmt::Debug for U256 {
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
93 let mut buffer = HexBuffer::<true>::new();
94 let hex = buffer.format(&self.0);
95 f.write_str(hex)
96 }
97}
98
99impl std::fmt::Display for U256 {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
101 let mut buffer = HexBuffer::<true>::new();
102 let hex = buffer.format(&self.0);
103 f.write_str(hex)
104 }
105}
106
107impl FromStr for U256 {
108 type Err = ParseError;
109 fn from_str(hex: &str) -> Result<Self, Self::Err> {
110 let hex = remove_0x_prefix(hex.as_bytes());
111 if hex.is_empty() || hex.len() > 2 * LENGTH {
112 return Err(ParseError::new("expected 1 to 64 hex digits"));
113 }
114 let mut buf = [b'0'; 2 * LENGTH];
115 buf[2 * LENGTH - hex.len()..].copy_from_slice(hex);
116 const_hex::decode_to_array(buf)
117 .map(Self)
118 .map_err(|err| match err {
119 const_hex::FromHexError::InvalidHexCharacter { c, .. } => {
121 ParseError::new(format!("invalid hex character {c:?}"))
122 }
123 err => ParseError::new(format!("invalid hex: {err}")),
124 })
125 }
126}
127
128impl<'de> Deserialize<'de> for U256 {
129 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
130 where
131 D: Deserializer<'de>,
132 {
133 if deserializer.is_human_readable() {
134 struct HexVisitor;
135
136 impl serde::de::Visitor<'_> for HexVisitor {
137 type Value = U256;
138 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.write_str("up to 64 hex digits with an optional 0x prefix")
140 }
141 fn visit_str<E: serde::de::Error>(self, hex: &str) -> Result<Self::Value, E> {
142 hex.parse().map_err(E::custom)
143 }
144 }
145
146 deserializer.deserialize_str(HexVisitor)
147 } else {
148 #[derive(Deserialize)]
152 #[serde(rename = "U256")]
153 struct Value([u8; LENGTH]);
154
155 let value = Value::deserialize(deserializer)?;
156 Ok(Self(value.0))
157 }
158 }
159}
160
161impl Serialize for U256 {
162 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
163 where
164 S: Serializer,
165 {
166 if serializer.is_human_readable() {
167 let mut buffer = HexBuffer::<true>::new();
168 let hex = buffer.format(&self.0);
169 hex.serialize(serializer)
170 } else {
171 serializer.serialize_newtype_struct("U256", &self.0)
173 }
174 }
175}
176
177#[inline]
179const fn remove_0x_prefix(hex: &[u8]) -> &[u8] {
180 match hex {
181 [b'0', b'x', rest @ ..] => rest,
182 _ => hex,
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn u256_strict_from_str() {
192 assert_eq!(U256::from(0x0), U256::strict_from_str("0x0"));
193 assert_eq!(U256::from(0x1), U256::strict_from_str("0x1"));
194 assert_eq!(U256::from(0x10), U256::strict_from_str("0x10"));
195 assert_eq!(U256::from(0x999), U256::strict_from_str("0x999"));
196 assert_eq!(U256::from(0xabcd), U256::strict_from_str("0xabcd"));
197 assert_eq!(U256::from(0xab52_cdef), U256::strict_from_str("0xab52cdef"));
198 }
199
200 #[test]
201 fn human_readable_serde_parses_like_from_str() {
202 let full = "0x0000000000000000000000000000000000000000000000000000000000000abc";
203 for hex in ["0xabc", "abc", "0x0abc", full] {
204 let expected: U256 = hex.parse().unwrap();
205 assert_eq!(expected, U256::from(0xabc));
206 assert_eq!(
207 serde_json::from_str::<U256>(&format!("\"{hex}\"")).unwrap(),
208 expected
209 );
210 }
211 assert_eq!(
212 serde_json::to_string(&U256::from(0xabc)).unwrap(),
213 format!("\"{full}\"")
214 );
215
216 for invalid in ["", "0x", "0xg", &format!("{full}0")] {
217 assert!(invalid.parse::<U256>().is_err(), "{invalid}");
218 assert!(
219 serde_json::from_str::<U256>(&format!("\"{invalid}\"")).is_err(),
220 "{invalid}"
221 );
222 }
223 assert!(serde_json::from_str::<U256>("1").is_err());
224 }
225
226 #[test]
227 fn bcs_round_trips_as_32_bytes() {
228 let value = U256::from(0xabc);
229 let bytes = bcs::to_bytes(&value).unwrap();
230
231 assert_eq!(bytes, value.as_slice());
232 assert_eq!(bcs::from_bytes::<U256>(&bytes).unwrap(), value);
233 assert_eq!(value.as_ref(), value.as_slice());
234 }
235}