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 bytes = self.to_big_endian();
36				$crate::serialize::serialize_uint(&mut slice, &bytes, serializer)
37			}
38		}
39
40		impl<'de> $crate::serde::Deserialize<'de> for $name {
41			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
42			where
43				D: $crate::serde::Deserializer<'de>,
44			{
45				let mut bytes = [0u8; $len * 8];
46				let wrote = $crate::serialize::deserialize_check_len(
47					deserializer,
48					$crate::serialize::ExpectedLen::Between(0, &mut bytes),
49				)?;
50				Ok(Self::from_big_endian(&bytes[0..wrote]))
51			}
52		}
53	};
54}
55
56/// Add Serde serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
57#[macro_export]
58macro_rules! impl_fixed_hash_serde {
59	($name: ident, $len: expr) => {
60		impl $crate::serde::Serialize for $name {
61			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
62			where
63				S: $crate::serde::Serializer,
64			{
65				let mut slice = [0u8; 2 + 2 * $len];
66				$crate::serialize::serialize_raw(&mut slice, &self.0, serializer)
67			}
68		}
69
70		impl<'de> $crate::serde::Deserialize<'de> for $name {
71			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
72			where
73				D: $crate::serde::Deserializer<'de>,
74			{
75				let mut bytes = [0u8; $len];
76				$crate::serialize::deserialize_check_len(
77					deserializer,
78					$crate::serialize::ExpectedLen::Exact(&mut bytes),
79				)?;
80				Ok($name(bytes))
81			}
82		}
83	};
84}