impl_rlp/
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//! RLP serialization support for uint and fixed hash.
10
11#![cfg_attr(not(feature = "std"), no_std)]
12
13#[doc(hidden)]
14pub use rlp;
15
16#[doc(hidden)]
17pub use core as core_;
18
19/// Add RLP serialization support to an integer created by `construct_uint!`.
20#[macro_export]
21macro_rules! impl_uint_rlp {
22	($name: ident, $size: expr) => {
23		impl $crate::rlp::Encodable for $name {
24			fn rlp_append(&self, s: &mut $crate::rlp::RlpStream) {
25				let leading_empty_bytes = $size * 8 - (self.bits() + 7) / 8;
26				let buffer = self.to_big_endian();
27				s.encoder().encode_value(&buffer[leading_empty_bytes..]);
28			}
29		}
30
31		impl $crate::rlp::Decodable for $name {
32			fn decode(rlp: &$crate::rlp::Rlp) -> Result<Self, $crate::rlp::DecoderError> {
33				rlp.decoder().decode_value(|bytes| {
34					if !bytes.is_empty() && bytes[0] == 0 {
35						Err($crate::rlp::DecoderError::RlpInvalidIndirection)
36					} else if bytes.len() <= $size * 8 {
37						Ok($name::from_big_endian(bytes))
38					} else {
39						Err($crate::rlp::DecoderError::RlpIsTooBig)
40					}
41				})
42			}
43		}
44	};
45}
46
47/// Add RLP serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
48#[macro_export]
49macro_rules! impl_fixed_hash_rlp {
50	($name: ident, $size: expr) => {
51		impl $crate::rlp::Encodable for $name {
52			fn rlp_append(&self, s: &mut $crate::rlp::RlpStream) {
53				s.encoder().encode_value(self.as_ref());
54			}
55		}
56
57		impl $crate::rlp::Decodable for $name {
58			fn decode(rlp: &$crate::rlp::Rlp) -> Result<Self, $crate::rlp::DecoderError> {
59				rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) {
60					$crate::core_::cmp::Ordering::Less => Err($crate::rlp::DecoderError::RlpIsTooShort),
61					$crate::core_::cmp::Ordering::Greater => Err($crate::rlp::DecoderError::RlpIsTooBig),
62					$crate::core_::cmp::Ordering::Equal => {
63						let mut t = [0u8; $size];
64						t.copy_from_slice(bytes);
65						Ok($name(t))
66					},
67				})
68			}
69		}
70	};
71}