use bc_rand::random_data;
use bc_ur::prelude::*;
use crate::{Error, Result, tags};
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct ARID([u8; Self::ARID_SIZE]);
impl ARID {
pub const ARID_SIZE: usize = 32;
pub fn new() -> Self {
let data = random_data(Self::ARID_SIZE);
Self::from_data_ref(data).unwrap()
}
pub fn from_data(data: [u8; Self::ARID_SIZE]) -> Self { Self(data) }
pub fn from_data_ref(data: impl AsRef<[u8]>) -> Result<Self> {
let data = data.as_ref();
if data.len() != Self::ARID_SIZE {
return Err(Error::invalid_size(
"ARID",
Self::ARID_SIZE,
data.len(),
));
}
let mut arr = [0u8; Self::ARID_SIZE];
arr.copy_from_slice(data);
Ok(Self::from_data(arr))
}
pub fn data(&self) -> &[u8; Self::ARID_SIZE] { &self.0 }
pub fn as_bytes(&self) -> &[u8] { self.as_ref() }
pub fn from_hex(hex: impl AsRef<str>) -> Self {
Self::from_data_ref(hex::decode(hex.as_ref()).unwrap()).unwrap()
}
pub fn hex(&self) -> String { hex::encode(self.as_bytes()) }
pub fn short_description(&self) -> String { hex::encode(&self.0[0..4]) }
}
impl AsRef<[u8]> for ARID {
fn as_ref(&self) -> &[u8] { &self.0 }
}
impl Default for ARID {
fn default() -> Self { Self::new() }
}
impl<'a> From<&'a ARID> for &'a [u8] {
fn from(value: &'a ARID) -> Self { &value.0 }
}
impl CBORTagged for ARID {
fn cbor_tags() -> Vec<Tag> { tags_for_values(&[tags::TAG_ARID]) }
}
impl From<ARID> for CBOR {
fn from(value: ARID) -> Self { value.tagged_cbor() }
}
impl CBORTaggedEncodable for ARID {
fn untagged_cbor(&self) -> CBOR { CBOR::to_byte_string(self.as_bytes()) }
}
impl TryFrom<CBOR> for ARID {
type Error = dcbor::Error;
fn try_from(cbor: CBOR) -> dcbor::Result<Self> {
Self::from_tagged_cbor(cbor)
}
}
impl CBORTaggedDecodable for ARID {
fn from_untagged_cbor(untagged_cbor: CBOR) -> dcbor::Result<Self> {
let data = CBOR::try_into_byte_string(untagged_cbor)?;
Ok(Self::from_data_ref(data)?)
}
}
impl std::fmt::Debug for ARID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ARID({})", self.hex())
}
}
impl std::fmt::Display for ARID {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ARID({})", self.hex())
}
}
impl PartialOrd for ARID {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.0.cmp(&other.0))
}
}