1#![allow(missing_docs)]
3use core::{
4 array::TryFromSliceError,
5 borrow::{
6 Borrow,
7 BorrowMut,
8 },
9 convert::TryFrom,
10 fmt,
11 ops::{
12 Deref,
13 DerefMut,
14 },
15 str,
16};
17
18#[cfg(feature = "random")]
19use rand::{
20 distributions::{
21 Distribution,
22 Standard,
23 },
24 Rng,
25};
26
27#[cfg(all(feature = "alloc", feature = "typescript"))]
28use alloc::format;
29
30macro_rules! key {
31 ($i:ident, $s:expr) => {
32 #[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
34 #[repr(transparent)]
35 #[cfg_attr(feature = "typescript", wasm_bindgen::prelude::wasm_bindgen)]
36 #[derive(
37 fuel_types::canonical::Serialize, fuel_types::canonical::Deserialize,
38 )]
39 pub struct $i([u8; $s]);
40
41 key_methods!($i, $s);
42
43 #[cfg(feature = "random")]
44 impl Distribution<$i> for Standard {
45 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $i {
46 $i(rng.gen())
47 }
48 }
49 };
50}
51
52macro_rules! key_with_big_array {
53 ($i:ident, $s:expr) => {
54 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
56 #[repr(transparent)]
57 #[cfg_attr(feature = "typescript", wasm_bindgen::prelude::wasm_bindgen)]
58 #[derive(
59 fuel_types::canonical::Serialize, fuel_types::canonical::Deserialize,
60 )]
61 pub struct $i([u8; $s]);
62
63 key_methods!($i, $s);
64
65 impl Default for $i {
66 fn default() -> $i {
67 $i([0u8; $s])
68 }
69 }
70
71 #[cfg(feature = "random")]
72 impl Distribution<$i> for Standard {
73 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $i {
74 let mut bytes = $i::default();
75
76 rng.fill_bytes(bytes.as_mut());
77
78 bytes
79 }
80 }
81 };
82}
83
84macro_rules! key_methods {
85 ($i:ident, $s:expr) => {
86 impl $i {
87 pub const LEN: usize = $s;
89
90 pub const fn new(bytes: [u8; $s]) -> Self {
92 Self(bytes)
93 }
94
95 pub const fn zeroed() -> $i {
97 $i([0; $s])
98 }
99
100 #[cfg(feature = "unsafe")]
101 #[allow(unsafe_code)]
102 pub unsafe fn from_slice_unchecked(bytes: &[u8]) -> Self {
110 $i($crate::bytes::from_slice_unchecked(bytes))
111 }
112
113 pub fn from_bytes_ref_checked(bytes: &[u8]) -> Option<&Self> {
117 let bytes: &[u8; $s] = bytes.get(..$s)?.try_into().ok()?;
118 Some(Self::from_bytes_ref(bytes))
119 }
120
121 pub fn from_bytes_ref(bytes: &[u8; $s]) -> &Self {
125 #[allow(unsafe_code)]
131 unsafe {
132 &*(bytes.as_ptr() as *const Self)
133 }
134 }
135
136 pub const fn size(&self) -> usize {
138 Self::LEN
139 }
140 }
141
142 #[cfg(feature = "typescript")]
143 #[wasm_bindgen::prelude::wasm_bindgen]
144 impl $i {
145 #[wasm_bindgen(js_name = from_bytes)]
152 pub fn from_bytes_typescript(bytes: &[u8]) -> Self {
153 Self(bytes.try_into().expect(
154 format!("The size of the arrays it not {} size", $s).as_str(),
155 ))
156 }
157
158 #[wasm_bindgen(js_name = zeroed)]
160 pub fn zeroed_typescript() -> $i {
161 Self::zeroed()
162 }
163
164 #[wasm_bindgen(js_name = size)]
166 pub fn size_typescript(&self) -> usize {
167 self.size()
168 }
169 }
170
171 #[cfg(feature = "random")]
172 impl rand::Fill for $i {
173 fn try_fill<R: rand::Rng + ?Sized>(
174 &mut self,
175 rng: &mut R,
176 ) -> Result<(), rand::Error> {
177 rng.fill_bytes(self.as_mut());
178
179 Ok(())
180 }
181 }
182
183 impl Deref for $i {
184 type Target = [u8; $s];
185
186 fn deref(&self) -> &[u8; $s] {
187 &self.0
188 }
189 }
190
191 impl Borrow<[u8; $s]> for $i {
192 fn borrow(&self) -> &[u8; $s] {
193 &self.0
194 }
195 }
196
197 impl BorrowMut<[u8; $s]> for $i {
198 fn borrow_mut(&mut self) -> &mut [u8; $s] {
199 &mut self.0
200 }
201 }
202
203 impl DerefMut for $i {
204 fn deref_mut(&mut self) -> &mut [u8; $s] {
205 &mut self.0
206 }
207 }
208
209 impl AsRef<[u8]> for $i {
210 fn as_ref(&self) -> &[u8] {
211 &self.0
212 }
213 }
214
215 impl AsMut<[u8]> for $i {
216 fn as_mut(&mut self) -> &mut [u8] {
217 &mut self.0
218 }
219 }
220
221 impl From<[u8; $s]> for $i {
222 fn from(bytes: [u8; $s]) -> Self {
223 Self(bytes)
224 }
225 }
226
227 impl From<$i> for [u8; $s] {
228 fn from(salt: $i) -> [u8; $s] {
229 salt.0
230 }
231 }
232
233 impl TryFrom<&[u8]> for $i {
234 type Error = TryFromSliceError;
235
236 fn try_from(bytes: &[u8]) -> Result<$i, TryFromSliceError> {
237 <[u8; $s]>::try_from(bytes).map(|b| b.into())
238 }
239 }
240
241 impl fmt::LowerHex for $i {
242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243 if f.alternate() {
244 write!(f, "0x")?
245 }
246
247 if let Some(w) = f
248 .width()
249 .and_then(|w| Self::LEN.saturating_mul(2).checked_div(w))
250 {
251 self.0.chunks(w).try_for_each(|c| {
252 write!(f, "{:02x}", c.iter().fold(0u8, |acc, x| acc ^ x))
253 })
254 } else {
255 self.0.iter().try_for_each(|b| write!(f, "{:02x}", &b))
256 }
257 }
258 }
259
260 impl fmt::UpperHex for $i {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 if f.alternate() {
263 write!(f, "0x")?
264 }
265
266 if let Some(w) = f
267 .width()
268 .and_then(|w| Self::LEN.saturating_mul(2).checked_div(w))
269 {
270 self.0.chunks(w).try_for_each(|c| {
271 write!(f, "{:02X}", c.iter().fold(0u8, |acc, x| acc ^ x))
272 })
273 } else {
274 self.0.iter().try_for_each(|b| write!(f, "{:02X}", &b))
275 }
276 }
277 }
278
279 impl fmt::Debug for $i {
280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281 <Self as fmt::LowerHex>::fmt(&self, f)
282 }
283 }
284
285 impl fmt::Display for $i {
286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287 <Self as fmt::LowerHex>::fmt(&self, f)
288 }
289 }
290
291 impl str::FromStr for $i {
292 type Err = &'static str;
293
294 fn from_str(s: &str) -> Result<Self, Self::Err> {
295 const ERR: &str = concat!("Invalid encoded byte in ", stringify!($i));
296 let mut ret = $i::zeroed();
297 let s = s.strip_prefix("0x").unwrap_or(s);
298 hex::decode_to_slice(&s, &mut ret.0).map_err(|_| ERR)?;
299 Ok(ret)
300 }
301 }
302
303 #[cfg(feature = "serde")]
304 impl serde::Serialize for $i {
305 #[inline(always)]
306 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
307 where
308 S: serde::Serializer,
309 {
310 use alloc::format;
311 use serde::ser::SerializeTuple;
312 if serializer.is_human_readable() {
313 serializer.serialize_str(&format!("{:x}", &self))
314 } else {
315 let mut arr = serializer.serialize_tuple($s)?;
317 for elem in &self.0 {
318 arr.serialize_element(elem)?;
319 }
320 arr.end()
321 }
322 }
323 }
324
325 #[cfg(feature = "serde")]
326 impl<'de> serde::Deserialize<'de> for $i {
327 #[inline(always)]
328 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
329 where
330 D: serde::Deserializer<'de>,
331 {
332 use serde::de::Error;
333 if deserializer.is_human_readable() {
334 let s: alloc::string::String =
335 serde::Deserialize::deserialize(deserializer)?;
336 s.parse().map_err(D::Error::custom)
337 } else {
338 deserializer.deserialize_tuple($s, ArrayVisitor).map(Self)
339 }
340 }
341 }
342 };
343}
344
345key!(Address, 32);
346key!(AssetId, 32);
347key!(BlobId, 32);
348key!(ContractId, 32);
349key!(TxId, 32);
350key!(Bytes4, 4);
351key!(Bytes8, 8);
352key!(Bytes20, 20);
353key!(Bytes32, 32);
354key!(Nonce, 32);
355key!(MessageId, 32);
356key!(Salt, 32);
357
358key_with_big_array!(Bytes64, 64);
359
360impl ContractId {
361 pub const SEED: [u8; 4] = 0x4655454C_u32.to_be_bytes();
365}
366
367impl AssetId {
368 pub const BASE: AssetId = AssetId::zeroed();
369}
370
371impl From<u64> for Nonce {
372 fn from(value: u64) -> Self {
373 let mut default = [0u8; 32];
374 default[..8].copy_from_slice(&value.to_be_bytes());
375 default.into()
376 }
377}
378
379#[cfg(feature = "serde")]
381struct ArrayVisitor<const S: usize>;
382
383#[cfg(feature = "serde")]
384impl<'de, const S: usize> serde::de::Visitor<'de> for ArrayVisitor<S> {
385 type Value = [u8; S];
386
387 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
388 write!(formatter, "an array of {S} bytes")
389 }
390
391 #[inline(always)]
392 fn visit_borrowed_bytes<E>(self, items: &'de [u8]) -> Result<Self::Value, E> {
393 let mut result = [0u8; S];
394 result.copy_from_slice(items);
395 Ok(result)
396 }
397
398 #[cfg(feature = "alloc")]
399 #[inline(always)]
400 fn visit_byte_buf<E>(self, v: alloc::vec::Vec<u8>) -> Result<Self::Value, E>
401 where
402 E: serde::de::Error,
403 {
404 self.visit_borrowed_bytes(v.as_slice())
405 }
406
407 #[inline(always)]
408 fn visit_seq<A>(self, mut value: A) -> Result<Self::Value, A::Error>
409 where
410 A: serde::de::SeqAccess<'de>,
411 {
412 let mut arr = [0u8; S];
413 for (i, elem) in arr.iter_mut().enumerate() {
414 *elem = value
415 .next_element()?
416 .ok_or_else(|| serde::de::Error::invalid_length(i, &self))?;
417 }
418 Ok(arr)
419 }
420}
421
422#[cfg(all(test, feature = "serde"))]
424mod tests_serde {
425 use rand::{
426 rngs::StdRng,
427 SeedableRng,
428 };
429
430 use super::*;
431
432 #[test]
434 fn test_human_readable() {
435 let rng = &mut StdRng::seed_from_u64(8586);
436 let original: Address = rng.gen();
437 let serialized = serde_json::to_string(&original).expect("Serialization failed");
438 assert_eq!(
439 serialized,
440 "\"7bbd8a4ea06e94461b959ab18d35802bbac3cf47e2bf29195f7db2ce41630cd7\""
441 );
442 let recreated: Address =
443 serde_json::from_str(&serialized).expect("Deserialization failed");
444 assert_eq!(original, recreated);
445 }
446
447 #[test]
449 fn test_not_human_readable() {
450 let rng = &mut StdRng::seed_from_u64(8586);
451 let original: Address = rng.gen();
452 let serialized = postcard::to_stdvec(&original).expect("Serialization failed");
453 let expected_vec = original.0.to_vec();
454 assert_eq!(&serialized, &expected_vec);
455 let recreated: Address =
456 postcard::from_bytes(&serialized).expect("Deserialization failed");
457 assert_eq!(original, recreated);
458 }
459
460 #[test]
462 fn test_not_human_readable_incorrect_deser() {
463 let rng = &mut StdRng::seed_from_u64(8586);
464 let original: Address = rng.gen();
465 let mut serialized =
466 postcard::to_stdvec(&original).expect("Serialization failed");
467 serialized.pop();
468 let res: Result<Address, _> = postcard::from_bytes(&serialized);
469 res.expect_err("Deserialization should have failed");
470 }
471
472 #[test]
474 fn test_bincode() {
475 let rng = &mut StdRng::seed_from_u64(8586);
476 let original: Address = rng.gen();
477 let serialized = bincode::serialize(&original).expect("Serialization failed");
478 let recreated: Address =
479 bincode::deserialize(&serialized).expect("Deserialization failed");
480 assert_eq!(original, recreated);
481 }
482}