common_primitives/macros.rs
1// This file is part of Substrate.
2
3// Copyright (C) 2022 Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18// macro_rules! impl_incrementable {
19// ($($type:ty),+) => {
20// $(
21// impl Incrementable for $type {
22// fn increment(&self) -> Self {
23// let mut val = self.clone();
24// val.saturating_inc();
25// val
26// }
27//
28// fn initial_value() -> Self {
29// 0
30// }
31// }
32// )+
33// };
34// }
35// pub(crate) use impl_incrementable;
36#[macro_export]
37#[doc(hidden)]
38macro_rules! impl_codec_bitflags {
39 ($wrapper:ty, $size:ty, $bitflag_enum:ty) => {
40 impl MaxEncodedLen for $wrapper {
41 fn max_encoded_len() -> usize {
42 <$size>::max_encoded_len()
43 }
44 }
45 impl Encode for $wrapper {
46 fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
47 self.0.bits().using_encoded(f)
48 }
49 }
50 impl EncodeLike for $wrapper {}
51 impl Decode for $wrapper {
52 fn decode<I: parity_scale_codec::Input>(
53 input: &mut I,
54 ) -> core::result::Result<Self, parity_scale_codec::Error> {
55 let field = <$size>::decode(input)?;
56 Ok(Self(BitFlags::from_bits(field as $size).map_err(|_| "invalid value")?))
57 }
58 }
59
60 impl TypeInfo for $wrapper {
61 type Identity = Self;
62
63 fn type_info() -> Type {
64 Type::builder()
65 .path(Path::new("BitFlags", module_path!()))
66 .type_params(vec![TypeParameter::new("T", Some(meta_type::<$bitflag_enum>()))])
67 .composite(
68 Fields::unnamed()
69 .field(|f| f.ty::<$size>().type_name(stringify!($bitflag_enum))),
70 )
71 }
72 }
73 };
74}
75// pub(crate) use impl_codec_bitflags;