use anyhow::{bail, Result, Error};
use crate::{CBOR, CBORError, CBORTagged, CBORCase};
pub trait CBORTaggedDecodable: TryFrom<CBOR> + CBORTagged {
fn from_untagged_cbor(cbor: CBOR) -> Result<Self> where Self: Sized;
fn from_tagged_cbor(cbor: CBOR) -> Result<Self> where Self: Sized {
match cbor.into_case() {
CBORCase::Tagged(tag, item) => {
let cbor_tags = Self::cbor_tags();
if cbor_tags.iter().any(|t| *t == tag) {
Self::from_untagged_cbor(item)
} else {
bail!(CBORError::WrongTag(cbor_tags[0].clone(), tag))
}
},
_ => bail!(CBORError::WrongType)
}
}
fn from_tagged_cbor_data(data: impl AsRef<[u8]>) -> Result<Self> where Self: Sized {
Self::from_tagged_cbor(CBOR::try_from_data(data).map_err(Error::msg)?)
}
fn from_untagged_cbor_data(data: impl AsRef<[u8]>) -> Result<Self> where Self: Sized {
Self::from_untagged_cbor(CBOR::try_from_data(data).map_err(Error::msg)?)
}
}