use alloc::string::String;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::cbor::canonical;
use crate::cbor_bytes::CborBytes;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Envelope {
pub kind: String,
pub schema: String,
pub version: u32,
pub body: CborBytes,
}
impl Envelope {
pub fn ensure_canonical(&self) -> canonical::Result<()> {
self.body.ensure_canonical()
}
}
#[cfg(feature = "serde")]
impl Envelope {
pub fn new<T: serde::Serialize>(
kind: impl Into<String>,
schema: impl Into<String>,
version: u32,
body: &T,
) -> canonical::Result<Self> {
let bytes = canonical::to_canonical_cbor(body)?;
Ok(Self {
kind: kind.into(),
schema: schema.into(),
version,
body: CborBytes::new(bytes),
})
}
pub fn decode_body<T: serde::de::DeserializeOwned>(&self) -> canonical::Result<T> {
self.body.ensure_canonical()?;
self.body.decode::<T>()
}
}