1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2015-2017 Parity Technologies
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Serde serialization support for uint and fixed hash.

#[doc(hidden)]
pub extern crate serde;

#[doc(hidden)]
pub extern crate rustc_hex;

#[doc(hidden)]
pub mod serialize;

/// Add Serde serialization support to an integer created by `construct_uint!`.
#[macro_export]
macro_rules! impl_uint_serde {
	($name: ident, $len: expr) => {
		impl $crate::serde::Serialize for $name {
			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: $crate::serde::Serializer {
				let mut bytes = [0u8; $len * 8];
				self.to_big_endian(&mut bytes);
				$crate::serialize::serialize_uint(&bytes, serializer)
			}
		}

		impl<'de> $crate::serde::Deserialize<'de> for $name {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: $crate::serde::Deserializer<'de> {
				$crate::serialize::deserialize_check_len(deserializer, $crate::serialize::ExpectedLen::Between(0, $len * 8))
					.map(|x| (&*x).into())
			}
		}
	}
}

/// Add Serde serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
#[macro_export]
macro_rules! impl_fixed_hash_serde {
	($name: ident, $len: expr) => {
		impl $crate::serde::Serialize for $name {
			fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: $crate::serde::Serializer {
				$crate::serialize::serialize(&self.0, serializer)
			}
		}

		impl<'de> $crate::serde::Deserialize<'de> for $name {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: $crate::serde::Deserializer<'de> {
				$crate::serialize::deserialize_check_len(deserializer, $crate::serialize::ExpectedLen::Exact($len))
					.map(|x| $name::from_slice(&x))
			}
		}
	}
}