bp_runtime/
storage_types.rs1use codec::{Decode, Encode, MaxEncodedLen};
21use frame_support::traits::Get;
22use scale_info::{Type, TypeInfo};
23use sp_runtime::RuntimeDebug;
24use sp_std::{marker::PhantomData, ops::Deref};
25
26#[derive(RuntimeDebug)]
28pub struct MaximalSizeExceededError {
29	pub value_size: usize,
31	pub maximal_size: usize,
33}
34
35#[derive(Clone, Decode, Encode, Eq, PartialEq)]
37pub struct BoundedStorageValue<B, V> {
38	value: V,
39	_phantom: PhantomData<B>,
40}
41
42impl<B, V: sp_std::fmt::Debug> sp_std::fmt::Debug for BoundedStorageValue<B, V> {
43	fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
44		self.value.fmt(fmt)
45	}
46}
47
48impl<B: Get<u32>, V: Encode> BoundedStorageValue<B, V> {
49	pub fn try_from_inner(value: V) -> Result<Self, MaximalSizeExceededError> {
53		let value_size = value.encoded_size();
57		let maximal_size = B::get() as usize;
58		if value_size > maximal_size {
59			Err(MaximalSizeExceededError { value_size, maximal_size })
60		} else {
61			Ok(BoundedStorageValue { value, _phantom: Default::default() })
62		}
63	}
64
65	pub fn into_inner(self) -> V {
67		self.value
68	}
69}
70
71impl<B, V> Deref for BoundedStorageValue<B, V> {
72	type Target = V;
73
74	fn deref(&self) -> &Self::Target {
75		&self.value
76	}
77}
78
79impl<B: 'static, V: TypeInfo + 'static> TypeInfo for BoundedStorageValue<B, V> {
80	type Identity = Self;
81
82	fn type_info() -> Type {
83		V::type_info()
84	}
85}
86
87impl<B: Get<u32>, V: Encode> MaxEncodedLen for BoundedStorageValue<B, V> {
88	fn max_encoded_len() -> usize {
89		B::get() as usize
90	}
91}