use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct AssetUuid(uuid::Uuid);
impl AssetUuid {
pub fn random() -> Self {
Self(uuid::Uuid::new_v4())
}
pub fn from_content(bytes: &[u8]) -> Self {
Self(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, bytes))
}
pub fn from_bytes(bytes: [u8; 16]) -> Self {
Self(uuid::Uuid::from_bytes(bytes))
}
pub fn as_bytes(&self) -> &[u8; 16] {
self.0.as_bytes()
}
pub fn to_uuid(&self) -> uuid::Uuid {
self.0
}
pub fn from_uuid(uuid: uuid::Uuid) -> Self {
Self(uuid)
}
}
impl fmt::Debug for AssetUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AssetUuid({})", self.0)
}
}
impl fmt::Display for AssetUuid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for AssetUuid {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let uuid = uuid::Uuid::parse_str(s)?;
Ok(Self(uuid))
}
}
impl From<uuid::Uuid> for AssetUuid {
fn from(uuid: uuid::Uuid) -> Self {
Self(uuid)
}
}
impl From<AssetUuid> for uuid::Uuid {
fn from(asset_uuid: AssetUuid) -> Self {
asset_uuid.0
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct TypedPayload(pub serde_json::Value);
impl Default for TypedPayload {
fn default() -> Self {
Self(serde_json::Value::Null)
}
}
impl Serialize for TypedPayload {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
self.0.serialize(serializer)
} else {
let encoded = serde_json::to_string(&self.0).map_err(serde::ser::Error::custom)?;
encoded.serialize(serializer)
}
}
}
impl<'de> Deserialize<'de> for TypedPayload {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if deserializer.is_human_readable() {
serde_json::Value::deserialize(deserializer).map(TypedPayload)
} else {
let encoded = String::deserialize(deserializer)?;
serde_json::from_str(&encoded)
.map(TypedPayload)
.map_err(serde::de::Error::custom)
}
}
}