scale_decode/impls/
primitive_types.rs

1// Copyright (C) 2023 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the scale-decode crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::BasicVisitor;
17use crate::{
18    error::Error,
19    visitor::{decode_with_visitor, DecodeAsTypeResult, Visitor},
20    IntoVisitor,
21};
22use primitive_types::{H128, H160, H256, H384, H512, H768};
23use scale_type_resolver::TypeResolver;
24
25macro_rules! impl_visitor {
26    ($ty:ty: $len:literal) => {
27        impl<R: TypeResolver> Visitor for BasicVisitor<$ty, R> {
28            type Error = Error;
29            type Value<'scale, 'resolver> = $ty;
30            type TypeResolver = R;
31
32            fn unchecked_decode_as_type<'scale, 'resolver>(
33                self,
34                input: &mut &'scale [u8],
35                type_id: <Self::TypeResolver as TypeResolver>::TypeId,
36                types: &'resolver Self::TypeResolver,
37            ) -> crate::visitor::DecodeAsTypeResult<
38                Self,
39                Result<Self::Value<'scale, 'resolver>, Self::Error>,
40            > {
41                let res = decode_with_visitor(
42                    input,
43                    type_id,
44                    types,
45                    BasicVisitor::<[u8; $len / 8], R> { _marker: core::marker::PhantomData },
46                )
47                .map(|res| <$ty>::from(res));
48                DecodeAsTypeResult::Decoded(res)
49            }
50        }
51
52        impl IntoVisitor for $ty {
53            type AnyVisitor<R: TypeResolver> = BasicVisitor<$ty, R>;
54            fn into_visitor<R: TypeResolver>() -> Self::AnyVisitor<R> {
55                BasicVisitor { _marker: core::marker::PhantomData }
56            }
57        }
58    };
59}
60impl_visitor!(H128: 128);
61impl_visitor!(H160: 160);
62impl_visitor!(H256: 256);
63impl_visitor!(H384: 384);
64impl_visitor!(H512: 512);
65impl_visitor!(H768: 768);