ethers_impl_serde/
lib.rs

1// Copyright 2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Serde serialization support for uint and fixed hash.
10
11#![no_std]
12
13#[macro_use]
14extern crate alloc;
15
16#[cfg(feature = "std")]
17extern crate std;
18
19#[doc(hidden)]
20pub use serde;
21
22#[doc(hidden)]
23pub mod serialize;
24
25/// Add Serde serialization support to an integer created by `construct_uint!`.
26#[macro_export]
27macro_rules! impl_uint_serde {
28	($name: ident, $len: expr) => {
29		impl $crate::serde::Serialize for $name {
30			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
31			where
32				S: $crate::serde::Serializer,
33			{
34				let mut slice = [0u8; 2 + 2 * $len * 8];
35				let mut bytes = [0u8; $len * 8];
36				self.to_big_endian(&mut bytes);
37				$crate::serialize::serialize_uint(&mut slice, &bytes, serializer)
38			}
39		}
40
41		impl<'de> $crate::serde::Deserialize<'de> for $name {
42			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
43			where
44				D: $crate::serde::Deserializer<'de>,
45			{
46				let mut bytes = [0u8; $len * 8];
47				let wrote = $crate::serialize::deserialize_check_len(
48					deserializer,
49					$crate::serialize::ExpectedLen::Between(0, &mut bytes),
50				)?;
51				Ok(bytes[0..wrote].into())
52			}
53		}
54	};
55}
56
57/// Add Serde serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
58#[macro_export]
59macro_rules! impl_fixed_hash_serde {
60	($name: ident, $len: expr) => {
61		impl $crate::serde::Serialize for $name {
62			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
63			where
64				S: $crate::serde::Serializer,
65			{
66				let mut slice = [0u8; 2 + 2 * $len];
67				$crate::serialize::serialize_raw(&mut slice, &self.0, serializer)
68			}
69		}
70
71		impl<'de> $crate::serde::Deserialize<'de> for $name {
72			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
73			where
74				D: $crate::serde::Deserializer<'de>,
75			{
76				let mut bytes = [0u8; $len];
77				$crate::serialize::deserialize_check_len(
78					deserializer,
79					$crate::serialize::ExpectedLen::Exact(&mut bytes),
80				)?;
81				Ok($name(bytes))
82			}
83		}
84	};
85}