ethers_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 mut buffer = [0u8; $size * 8];
27				self.to_big_endian(&mut buffer);
28				s.encoder().encode_value(&buffer[leading_empty_bytes..]);
29			}
30		}
31
32		impl $crate::rlp::Decodable for $name {
33			fn decode(rlp: &$crate::rlp::Rlp) -> Result<Self, $crate::rlp::DecoderError> {
34				rlp.decoder().decode_value(|bytes| {
35					if !bytes.is_empty() && bytes[0] == 0 {
36						Err($crate::rlp::DecoderError::RlpInvalidIndirection)
37					} else if bytes.len() <= $size * 8 {
38						Ok($name::from(bytes))
39					} else {
40						Err($crate::rlp::DecoderError::RlpIsTooBig)
41					}
42				})
43			}
44		}
45	};
46}
47
48/// Add RLP serialization support to a fixed-sized hash type created by `construct_fixed_hash!`.
49#[macro_export]
50macro_rules! impl_fixed_hash_rlp {
51	($name: ident, $size: expr) => {
52		impl $crate::rlp::Encodable for $name {
53			fn rlp_append(&self, s: &mut $crate::rlp::RlpStream) {
54				s.encoder().encode_value(self.as_ref());
55			}
56		}
57
58		impl $crate::rlp::Decodable for $name {
59			fn decode(rlp: &$crate::rlp::Rlp) -> Result<Self, $crate::rlp::DecoderError> {
60				rlp.decoder().decode_value(|bytes| match bytes.len().cmp(&$size) {
61					$crate::core_::cmp::Ordering::Less => Err($crate::rlp::DecoderError::RlpIsTooShort),
62					$crate::core_::cmp::Ordering::Greater => Err($crate::rlp::DecoderError::RlpIsTooBig),
63					$crate::core_::cmp::Ordering::Equal => {
64						let mut t = [0u8; $size];
65						t.copy_from_slice(bytes);
66						Ok($name(t))
67					},
68				})
69			}
70		}
71	};
72}