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 bytes = self.to_little_endian();
23				bytes.using_encoded(f)
24			}
25		}
26
27		impl $crate::codec::EncodeLike for $name {}
28
29		impl $crate::codec::Decode for $name {
30			fn decode<I: $crate::codec::Input>(input: &mut I) -> core::result::Result<Self, $crate::codec::Error> {
31				<[u8; $len * 8] as $crate::codec::Decode>::decode(input).map(|b| $name::from_little_endian(&b))
32			}
33		}
34
35		impl $crate::codec::DecodeWithMemTracking for $name {}
36
37		impl $crate::codec::MaxEncodedLen for $name {
38			fn max_encoded_len() -> usize {
39				::core::mem::size_of::<$name>()
40			}
41		}
42	};
43}
44
45/// Add Parity Codec serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
46#[macro_export]
47macro_rules! impl_fixed_hash_codec {
48	($name: ident, $len: expr) => {
49		impl $crate::codec::Encode for $name {
50			fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
51				self.0.using_encoded(f)
52			}
53		}
54
55		impl $crate::codec::EncodeLike for $name {}
56
57		impl $crate::codec::Decode for $name {
58			fn decode<I: $crate::codec::Input>(input: &mut I) -> core::result::Result<Self, $crate::codec::Error> {
59				<[u8; $len] as $crate::codec::Decode>::decode(input).map($name)
60			}
61		}
62
63		impl $crate::codec::DecodeWithMemTracking for $name {}
64
65		impl $crate::codec::MaxEncodedLen for $name {
66			fn max_encoded_len() -> usize {
67				::core::mem::size_of::<$name>()
68			}
69		}
70	};
71}