1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use crate::{Compact, Encode};
use impl_trait_for_tuples::impl_for_tuples;
use core::{mem, marker::PhantomData};
pub trait MaxEncodedLen: Encode {
fn max_encoded_len() -> usize;
}
macro_rules! impl_primitives {
( $($t:ty),+ ) => {
$(
impl MaxEncodedLen for $t {
fn max_encoded_len() -> usize {
mem::size_of::<$t>()
}
}
)+
};
}
impl_primitives!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, bool);
macro_rules! impl_compact {
($( $t:ty => $e:expr; )*) => {
$(
impl MaxEncodedLen for Compact<$t> {
fn max_encoded_len() -> usize {
$e
}
}
)*
};
}
impl_compact!(
u8 => 2;
u16 => 4;
u32 => 5;
u64 => 9;
u128 => 17;
);
#[impl_for_tuples(18)]
impl MaxEncodedLen for Tuple {
fn max_encoded_len() -> usize {
let mut len: usize = 0;
for_tuples!( #( len = len.saturating_add(Tuple::max_encoded_len()); )* );
len
}
}
impl<T: MaxEncodedLen, const N: usize> MaxEncodedLen for [T; N] {
fn max_encoded_len() -> usize {
T::max_encoded_len().saturating_mul(N)
}
}
impl<T: MaxEncodedLen> MaxEncodedLen for Option<T> {
fn max_encoded_len() -> usize {
T::max_encoded_len().saturating_add(1)
}
}
impl<T, E> MaxEncodedLen for Result<T, E>
where
T: MaxEncodedLen,
E: MaxEncodedLen,
{
fn max_encoded_len() -> usize {
T::max_encoded_len().max(E::max_encoded_len()).saturating_add(1)
}
}
impl<T> MaxEncodedLen for PhantomData<T> {
fn max_encoded_len() -> usize {
0
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! test_compact_length {
($(fn $name:ident($t:ty);)*) => {
$(
#[test]
fn $name() {
assert_eq!(Compact(<$t>::MAX).encode().len(), Compact::<$t>::max_encoded_len());
}
)*
};
}
test_compact_length!(
fn compact_u8(u8);
fn compact_u16(u16);
fn compact_u32(u32);
fn compact_u64(u64);
fn compact_u128(u128);
);
}