use crate::utils::{Maybe, NoMaybe};
use derive_where::derive_where;
use scale_decode::DecodeAsType;
use std::borrow::Cow;
pub trait Address {
type Target: DecodeAsType;
type IsDecodable: NoMaybe;
fn name(&self) -> &str;
fn validation_hash(&self) -> Option<[u8; 32]> {
None
}
}
impl<A: Address + ?Sized> Address for &'_ A {
type Target = A::Target;
type IsDecodable = A::IsDecodable;
fn name(&self) -> &str {
A::name(*self)
}
fn validation_hash(&self) -> Option<[u8; 32]> {
A::validation_hash(*self)
}
}
impl Address for str {
type Target = scale_value::Value;
type IsDecodable = Maybe;
fn name(&self) -> &str {
self
}
}
#[derive_where(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub struct StaticAddress<ReturnTy, IsDecodable> {
name: Cow<'static, str>,
hash: Option<[u8; 32]>,
marker: core::marker::PhantomData<(ReturnTy, IsDecodable)>,
}
pub type DynamicAddress<ReturnTy> = StaticAddress<ReturnTy, Maybe>;
impl<ReturnTy, IsDecodable> StaticAddress<ReturnTy, IsDecodable> {
#[doc(hidden)]
pub fn new_static(name: &'static str, hash: [u8; 32]) -> Self {
Self {
name: Cow::Borrowed(name),
hash: Some(hash),
marker: core::marker::PhantomData,
}
}
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into().into(),
hash: None,
marker: core::marker::PhantomData,
}
}
pub fn unvalidated(self) -> Self {
Self {
name: self.name,
hash: None,
marker: self.marker,
}
}
}
impl<Target: DecodeAsType, IsDecodable: NoMaybe> Address for StaticAddress<Target, IsDecodable> {
type Target = Target;
type IsDecodable = IsDecodable;
fn name(&self) -> &str {
&self.name
}
fn validation_hash(&self) -> Option<[u8; 32]> {
self.hash
}
}
pub fn dynamic<ReturnTy: DecodeAsType>(
custom_value_name: impl Into<String>,
) -> DynamicAddress<ReturnTy> {
DynamicAddress::new(custom_value_name)
}