use codec::{Decode, Encode, MaxEncodedLen};
use pezframe_support::traits::Get;
use pezsp_runtime::RuntimeDebug;
use pezsp_std::{marker::PhantomData, ops::Deref};
use scale_info::{Type, TypeInfo};
#[derive(RuntimeDebug)]
pub struct MaximalSizeExceededError {
pub value_size: usize,
pub maximal_size: usize,
}
#[derive(Clone, Decode, Encode, Eq, PartialEq)]
pub struct BoundedStorageValue<B, V> {
value: V,
_phantom: PhantomData<B>,
}
impl<B, V: pezsp_std::fmt::Debug> pezsp_std::fmt::Debug for BoundedStorageValue<B, V> {
fn fmt(&self, fmt: &mut pezsp_std::fmt::Formatter) -> pezsp_std::fmt::Result {
self.value.fmt(fmt)
}
}
impl<B: Get<u32>, V: Encode> BoundedStorageValue<B, V> {
pub fn try_from_inner(value: V) -> Result<Self, MaximalSizeExceededError> {
let value_size = value.encoded_size();
let maximal_size = B::get() as usize;
if value_size > maximal_size {
Err(MaximalSizeExceededError { value_size, maximal_size })
} else {
Ok(BoundedStorageValue { value, _phantom: Default::default() })
}
}
pub fn into_inner(self) -> V {
self.value
}
}
impl<B, V> Deref for BoundedStorageValue<B, V> {
type Target = V;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<B: 'static, V: TypeInfo + 'static> TypeInfo for BoundedStorageValue<B, V> {
type Identity = Self;
fn type_info() -> Type {
V::type_info()
}
}
impl<B: Get<u32>, V: Encode> MaxEncodedLen for BoundedStorageValue<B, V> {
fn max_encoded_len() -> usize {
B::get() as usize
}
}