use crate::imp::core::bytes::Bytes32;
use crate::imp::core::codec::{Decode, DecodeError, Decoder, Encode, Encoder};
use crate::imp::core::error::CoreError;
use alloc::format;
use alloc::string::{String, ToString};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Capsule {
pub store_id: Bytes32,
pub root_hash: Bytes32,
}
impl Capsule {
pub fn canonical(&self) -> String {
format!("{}:{}", self.store_id.to_hex(), self.root_hash.to_hex())
}
pub fn from_canonical(s: &str) -> Result<Capsule, CoreError> {
let mut parts = s.split(':');
let store_id_hex = parts
.next()
.ok_or_else(|| CoreError::Parse("capsule: missing store id".to_string()))?;
let root_hash_hex = parts
.next()
.ok_or_else(|| CoreError::Parse("capsule: missing root hash".to_string()))?;
if parts.next().is_some() {
return Err(CoreError::Parse(
"capsule: too many ':' segments".to_string(),
));
}
let store_id = Bytes32::from_hex(store_id_hex)?;
let root_hash = Bytes32::from_hex(root_hash_hex)?;
Ok(Capsule {
store_id,
root_hash,
})
}
}
impl core::fmt::Display for Capsule {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}:{}", self.store_id.to_hex(), self.root_hash.to_hex())
}
}
impl Encode for Capsule {
fn encode(&self, enc: &mut Encoder) {
self.store_id.encode(enc);
self.root_hash.encode(enc);
}
}
impl Decode for Capsule {
fn decode(dec: &mut Decoder<'_>) -> Result<Self, DecodeError> {
Ok(Capsule {
store_id: Bytes32::decode(dec)?,
root_hash: Bytes32::decode(dec)?,
})
}
}