use serde::{Deserialize, Serialize};
use crate::normalizer::Outcome;
const JSON: u8 = 1;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope {
pub source: String,
pub version: u32,
pub outcome: Outcome,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("not an encoded outcome: {0}")]
pub struct WireError(String);
impl Envelope {
pub fn new(source: impl Into<String>, version: u32, outcome: Outcome) -> Self {
Self {
source: source.into(),
version,
outcome,
}
}
pub fn encode(&self) -> Vec<u8> {
let mut bytes = vec![JSON];
if serde_json::to_writer(&mut bytes, self).is_err() {
bytes.truncate(1);
}
bytes
}
pub fn decode(bytes: &[u8]) -> Result<Self, WireError> {
match bytes.split_first() {
Some((&JSON, json)) => {
serde_json::from_slice(json).map_err(|error| WireError(error.to_string()))
}
Some((format, _)) => Err(WireError(format!("unknown format {format}"))),
None => Err(WireError("no bytes".to_owned())),
}
}
}