use std::collections::BTreeSet;
use content_addressable::{ContentAddressable, ContentError, ContentId, MerkleNode};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct UnitId(ContentId);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PacketId(ContentId);
macro_rules! id_newtype {
($t:ident, $what:literal) => {
impl $t {
#[doc = concat!("Borrow the underlying content id of this ", $what, ".")]
#[must_use]
pub const fn as_content_id(&self) -> &ContentId {
&self.0
}
#[doc = concat!("Consume this ", $what, " id, yielding the content id.")]
#[must_use]
pub const fn into_content_id(self) -> ContentId {
self.0
}
}
impl From<ContentId> for $t {
fn from(id: ContentId) -> Self {
Self(id)
}
}
impl std::fmt::Display for $t {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for $t {
type Err = <ContentId as std::str::FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<ContentId>().map(Self)
}
}
};
}
id_newtype!(UnitId, "unit");
id_newtype!(PacketId, "packet");
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PacketBody {
pub units: Vec<UnitId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct Packet(MerkleNode<PacketBody>);
pub type RawPacket = MerkleNode<PacketBody>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PacketAdmitError {
#[error(
"decoded packet has {parents} parents: v0 mints a CHAIN, so a packet has zero \
parents (genesis) or exactly one. A node with several has no single `prior`, \
so it is neither genesis nor following — a third state no constructor can mint \
and no forensic reader can name."
)]
NotAChain {
parents: usize,
},
}
impl Packet {
#[must_use]
pub fn genesis(units: Vec<UnitId>) -> Self {
Self(MerkleNode::genesis(PacketBody { units }))
}
#[must_use]
pub fn following(prior: PacketId, units: Vec<UnitId>) -> Self {
Self(MerkleNode::new(
PacketBody { units },
[prior.into_content_id()],
))
}
#[must_use]
pub fn units(&self) -> &[UnitId] {
&self.0.payload().units
}
#[must_use]
pub fn parents(&self) -> &BTreeSet<ContentId> {
self.0.parents()
}
#[must_use]
pub fn prior(&self) -> Option<PacketId> {
let mut it = self.0.parents().iter();
match (it.next(), it.next()) {
(Some(one), None) => Some(PacketId::from(*one)),
_ => None,
}
}
#[must_use]
pub fn is_genesis(&self) -> bool {
self.0.parents().is_empty()
}
pub fn id(&self) -> Result<PacketId, ContentError> {
self.0.id().map(PacketId::from)
}
}
impl TryFrom<RawPacket> for Packet {
type Error = PacketAdmitError;
fn try_from(raw: RawPacket) -> Result<Self, Self::Error> {
let parents = raw.parents().len();
if parents > 1 {
return Err(PacketAdmitError::NotAChain { parents });
}
Ok(Self(raw))
}
}
impl ContentAddressable for Packet {
fn canonical_form(&self) -> Result<Vec<u8>, ContentError> {
self.0.canonical_form()
}
}