use codec::{Decode, Encode, Error, Input, MaxEncodedLen, Output};
use core::num::NonZeroU16;
use sp_runtime::RuntimeDebug;
use sp_std::vec::Vec;
pub type UdIndex = u16;
#[derive(
Clone, Copy, Default, Eq, PartialEq, RuntimeDebug, serde::Deserialize, serde::Serialize,
)]
pub struct FirstEligibleUd(pub Option<NonZeroU16>);
impl FirstEligibleUd {
pub fn min() -> Self {
Self(Some(NonZeroU16::new(1).expect("unreachable")))
}
}
impl From<UdIndex> for FirstEligibleUd {
fn from(ud_index: UdIndex) -> Self {
FirstEligibleUd(NonZeroU16::new(ud_index))
}
}
impl From<FirstEligibleUd> for Option<UdIndex> {
fn from(first_eligible_ud: FirstEligibleUd) -> Self {
first_eligible_ud.0.map(|ud_index| ud_index.get())
}
}
impl Encode for FirstEligibleUd {
fn size_hint(&self) -> usize {
self.as_u16().size_hint()
}
fn encode_to<W: Output + ?Sized>(&self, dest: &mut W) {
self.as_u16().encode_to(dest)
}
fn encode(&self) -> Vec<u8> {
self.as_u16().encode()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
self.as_u16().using_encoded(f)
}
}
impl codec::EncodeLike for FirstEligibleUd {}
impl Decode for FirstEligibleUd {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
Ok(match NonZeroU16::new(Decode::decode(input)?) {
Some(non_zero_u16) => Self(Some(non_zero_u16)),
None => Self(None),
})
}
}
impl MaxEncodedLen for FirstEligibleUd {
fn max_encoded_len() -> usize {
u16::max_encoded_len()
}
}
impl scale_info::TypeInfo for FirstEligibleUd {
type Identity = UdIndex;
fn type_info() -> scale_info::Type {
Self::Identity::type_info()
}
}
impl FirstEligibleUd {
#[inline(always)]
fn as_u16(&self) -> UdIndex {
self.0.map(|ud_index| ud_index.get()).unwrap_or_default()
}
}