use capnp::message::{Builder, HeapAllocator}; use capnp::message::{ReaderOptions, TypedReader}; use capnp::serialize::{self, OwnedSegments}; use capnp::traits::{FromPointerReader, Owned}; use churn_domain::LogEvent; mod models_capnp; pub trait CapnpPackExt { type Return; fn serialize_capnp(&self) -> String; fn deserialize_capnp(content: &str) -> anyhow::Result; fn capnp_to_string(builder: &Builder) -> String { let msg = serialize::write_message_to_words(builder); std::str::from_utf8(msg.as_slice()) .expect("to be able to parse capnp as utf8") .to_string() } fn string_to_capnp<'a, S>(content: &'a str) -> TypedReader where S: Owned, { let log_event = serialize::read_message(content.as_bytes(), ReaderOptions::new()).unwrap(); let log_event = log_event.into_typed::(); log_event } } impl CapnpPackExt for LogEvent { type Return = Self; fn serialize_capnp(&self) -> String { let mut builder = Builder::new_default(); let mut log_event = builder.init_root::(); log_event.set_id(&self.id.to_string()); log_event.set_author(&self.author); log_event.set_content(&self.content); Self::capnp_to_string(&builder) } fn deserialize_capnp(content: &str) -> anyhow::Result { let log_event = Self::string_to_capnp::(content); let log_event = log_event.get()?; Ok(Self { id: uuid::Uuid::parse_str(log_event.get_id()?)?, author: log_event.get_author()?.into(), content: log_event.get_content()?.into(), }) } }