#![doc = include_str!("../README.md")]
mod codecs;
pub mod json;
pub mod varint;
use std::fmt;
use serde::{Serialize, Serializer};
use serde_json::Value;
use xmachines_runtime::system::SystemView;
pub use codecs::{Codec, Codecs};
#[derive(Clone, Copy)]
pub enum Snapshot<'a> {
Value(&'a Value),
View(&'a SystemView<'a>),
}
impl Serialize for Snapshot<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Snapshot::Value(v) => v.serialize(serializer),
Snapshot::View(v) => v.serialize(serializer),
}
}
}
impl<'a> From<&'a Value> for Snapshot<'a> {
fn from(value: &'a Value) -> Self {
Snapshot::Value(value)
}
}
impl<'a> From<&'a SystemView<'a>> for Snapshot<'a> {
fn from(view: &'a SystemView<'a>) -> Self {
Snapshot::View(view)
}
}
pub trait EventCodec: Send + Sync {
fn decode(&self, bytes: &[u8]) -> Result<Value, Error>;
fn encode(&self, event: &Value, out: &mut Vec<u8>) -> Result<(), Error>;
}
pub trait SnapshotCodec: Send + Sync {
fn format(&self) -> u8;
fn compact(&self) -> bool {
false
}
fn encode(&self, snapshot: Snapshot<'_>, out: &mut Vec<u8>) -> Result<(), Error>;
fn decode(&self, record: &[u8]) -> Result<Value, Error>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Decode(String),
Encode(String),
Schema(String),
UnknownFormat(u8),
Conflict(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Decode(m) | Error::Encode(m) | Error::Schema(m) | Error::Conflict(m) => f.write_str(m),
Error::UnknownFormat(format) => write!(f, "no codec reads snapshot records of format {format}"),
}
}
}
impl std::error::Error for Error {}