use crate::RoleName;
use holo_hash::AgentPubKey;
use holo_hash::DnaHash;
use holochain_serialized_bytes::prelude::*;
use std::fmt;
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
SerializedBytes,
Ord,
PartialOrd,
)]
pub struct CellId(DnaHash, AgentPubKey);
pub const CLONE_ID_DELIMITER: &str = ".";
#[derive(Clone, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CloneId(pub RoleName);
impl CloneId {
pub fn new(role_name: &RoleName, clone_index: u32) -> Self {
CloneId(format!(
"{}{}{}",
role_name, CLONE_ID_DELIMITER, clone_index
))
}
pub fn as_base_role_name(&self) -> RoleName {
let (role_name, _) = self.0.split_once(CLONE_ID_DELIMITER).unwrap();
role_name.into()
}
pub fn as_clone_index(&self) -> u32 {
let (_, clone_index) = self.0.split_once(CLONE_ID_DELIMITER).unwrap();
clone_index.parse::<u32>().unwrap()
}
pub fn as_app_role_name(&self) -> &RoleName {
&self.0
}
}
impl fmt::Display for CloneId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}{}{}",
self.as_base_role_name(),
CLONE_ID_DELIMITER,
self.as_clone_index()
)
}
}
#[derive(Debug, thiserror::Error)]
pub enum CloneIdError {
#[error("Multiple occurrences of reserved character '{CLONE_ID_DELIMITER}' found in app role name: {0}")]
MultipleDelimiters(RoleName),
#[error("Malformed clone index in app role name: {0}")]
MalformedCloneIndex(RoleName),
#[error("The role name is not composed of two parts separated by the clone id delimiter: {0}")]
MalformedCloneId(RoleName),
}
impl TryFrom<RoleName> for CloneId {
type Error = CloneIdError;
fn try_from(value: RoleName) -> Result<Self, Self::Error> {
let parts: Vec<&str> = value.split(CLONE_ID_DELIMITER).collect();
if parts.len() > 2 {
return Err(CloneIdError::MultipleDelimiters(value));
}
if parts.len() < 2 {
return Err(CloneIdError::MalformedCloneId(value));
}
let role_name = parts[0];
let clone_index = parts[1]
.parse::<u32>()
.map_err(|_| CloneIdError::MalformedCloneIndex(value.clone()))?;
Ok(Self::new(&role_name.into(), clone_index))
}
}
impl fmt::Display for CellId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Cell({}, {})", self.dna_hash(), self.agent_pubkey())
}
}
impl CellId {
pub fn new(dna_hash: DnaHash, agent_pubkey: AgentPubKey) -> Self {
CellId(dna_hash, agent_pubkey)
}
pub fn dna_hash(&self) -> &DnaHash {
&self.0
}
pub fn agent_pubkey(&self) -> &AgentPubKey {
&self.1
}
pub fn into_dna_and_agent(self) -> (DnaHash, AgentPubKey) {
(self.0, self.1)
}
}
impl From<(DnaHash, AgentPubKey)> for CellId {
fn from(pair: (DnaHash, AgentPubKey)) -> Self {
Self(pair.0, pair.1)
}
}