tetsy_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 tetsy_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}
37
38/// Add Parity Codec serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
39#[macro_export]
40macro_rules! impl_fixed_hash_codec {
41	($name: ident, $len: expr) => {
42		impl $crate::codec::Encode for $name {
43			fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
44				self.0.using_encoded(f)
45			}
46		}
47
48		impl $crate::codec::EncodeLike for $name {}
49
50		impl $crate::codec::Decode for $name {
51			fn decode<I: $crate::codec::Input>(input: &mut I) -> core::result::Result<Self, $crate::codec::Error> {
52				<[u8; $len] as $crate::codec::Decode>::decode(input).map($name)
53			}
54		}
55	};
56}