ethers_impl_codec/
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//! Parity Codec serialization support for uint and fixed hash.
10
11#![cfg_attr(not(feature = "std"), no_std)]
12
13#[doc(hidden)]
14pub use parity_scale_codec as codec;
15
16/// Add Parity Codec serialization support to an integer created by `construct_uint!`.
17#[macro_export]
18macro_rules! impl_uint_codec {
19	($name: ident, $len: expr) => {
20		impl $crate::codec::Encode for $name {
21			fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
22				let mut bytes = [0u8; $len * 8];
23				self.to_little_endian(&mut bytes);
24				bytes.using_encoded(f)
25			}
26		}
27
28		impl $crate::codec::EncodeLike for $name {}
29
30		impl $crate::codec::Decode for $name {
31			fn decode<I: $crate::codec::Input>(input: &mut I) -> core::result::Result<Self, $crate::codec::Error> {
32				<[u8; $len * 8] as $crate::codec::Decode>::decode(input).map(|b| $name::from_little_endian(&b))
33			}
34		}
35
36		impl $crate::codec::MaxEncodedLen for $name {
37			fn max_encoded_len() -> usize {
38				::core::mem::size_of::<$name>()
39			}
40		}
41	};
42}
43
44/// Add Parity Codec serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
45#[macro_export]
46macro_rules! impl_fixed_hash_codec {
47	($name: ident, $len: expr) => {
48		impl $crate::codec::Encode for $name {
49			fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
50				self.0.using_encoded(f)
51			}
52		}
53
54		impl $crate::codec::EncodeLike for $name {}
55
56		impl $crate::codec::Decode for $name {
57			fn decode<I: $crate::codec::Input>(input: &mut I) -> core::result::Result<Self, $crate::codec::Error> {
58				<[u8; $len] as $crate::codec::Decode>::decode(input).map($name)
59			}
60		}
61
62		impl $crate::codec::MaxEncodedLen for $name {
63			fn max_encoded_len() -> usize {
64				::core::mem::size_of::<$name>()
65			}
66		}
67	};
68}