Skip to main content

topsoil_core/traits/
error.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Traits for describing and constraining pallet error types.
8use codec::{Compact, Decode, Encode};
9use core::marker::PhantomData;
10
11/// Trait indicating that the implementing type is going to be included as a field in a variant of
12/// the `#[pallet::error]` enum type.
13///
14/// ## Notes
15///
16/// The pallet error enum has a maximum encoded size as defined by
17/// [`topsoil_core::MAX_MODULE_ERROR_ENCODED_SIZE`]. If the pallet error type exceeds this size
18/// limit, a static assertion during compilation will fail. The compilation error will be in the
19/// format of `error[E0080]: evaluation of constant value failed` due to the usage of
20/// const assertions.
21pub trait PalletError: Encode + Decode {
22	/// The maximum encoded size for the implementing type.
23	///
24	/// This will be used to check whether the pallet error type is less than or equal to
25	/// [`topsoil_core::MAX_MODULE_ERROR_ENCODED_SIZE`], and if it is, a compilation error will be
26	/// thrown.
27	const MAX_ENCODED_SIZE: usize;
28}
29
30macro_rules! impl_for_types {
31	(size: $size:expr, $($typ:ty),+) => {
32		$(
33			impl PalletError for $typ {
34				const MAX_ENCODED_SIZE: usize = $size;
35			}
36		)+
37	};
38}
39
40impl_for_types!(size: 0, (), crate::Never);
41impl_for_types!(size: 1, u8, i8, bool);
42impl_for_types!(size: 2, u16, i16, Compact<u8>);
43impl_for_types!(size: 4, u32, i32, Compact<u16>);
44impl_for_types!(size: 5, Compact<u32>);
45impl_for_types!(size: 8, u64, i64);
46impl_for_types!(size: 9, Compact<u64>);
47// Contains a u64 for secs and u32 for nanos, hence 12 bytes
48impl_for_types!(size: 12, core::time::Duration);
49impl_for_types!(size: 16, u128, i128);
50impl_for_types!(size: 17, Compact<u128>);
51
52impl<T> PalletError for PhantomData<T> {
53	const MAX_ENCODED_SIZE: usize = 0;
54}
55
56impl<T: PalletError> PalletError for core::ops::Range<T> {
57	const MAX_ENCODED_SIZE: usize = T::MAX_ENCODED_SIZE.saturating_mul(2);
58}
59
60impl<T: PalletError, const N: usize> PalletError for [T; N] {
61	const MAX_ENCODED_SIZE: usize = T::MAX_ENCODED_SIZE.saturating_mul(N);
62}
63
64impl<T: PalletError> PalletError for Option<T> {
65	const MAX_ENCODED_SIZE: usize = T::MAX_ENCODED_SIZE.saturating_add(1);
66}
67
68impl<T: PalletError, E: PalletError> PalletError for Result<T, E> {
69	const MAX_ENCODED_SIZE: usize = if T::MAX_ENCODED_SIZE > E::MAX_ENCODED_SIZE {
70		T::MAX_ENCODED_SIZE
71	} else {
72		E::MAX_ENCODED_SIZE
73	}
74	.saturating_add(1);
75}
76
77#[impl_trait_for_tuples::impl_for_tuples(1, 18)]
78impl PalletError for Tuple {
79	const MAX_ENCODED_SIZE: usize = {
80		let mut size = 0_usize;
81		for_tuples!( #(size = size.saturating_add(Tuple::MAX_ENCODED_SIZE);)* );
82		size
83	};
84}