use crate::core::store::frame::Frame;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageFormat {
MessagePack,
Json,
}
#[derive(Debug)]
pub enum StreamError {
Encode(String),
Decode(String),
}
impl std::fmt::Display for StreamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
StreamError::Encode(m) => write!(f, "stream encode error: {m}"),
StreamError::Decode(m) => write!(f, "stream decode error: {m}"),
}
}
}
impl std::error::Error for StreamError {}
pub fn frame_to_bytes(frame: &Frame, format: MessageFormat) -> Result<Vec<u8>, StreamError> {
match format {
MessageFormat::MessagePack => {
rmp_serde::to_vec_named(frame).map_err(|e| StreamError::Encode(e.to_string()))
}
MessageFormat::Json => {
serde_json::to_vec(frame).map_err(|e| StreamError::Encode(e.to_string()))
}
}
}
pub fn bytes_to_frame(bytes: &[u8], format: MessageFormat) -> Result<Frame, StreamError> {
match format {
MessageFormat::MessagePack => {
rmp_serde::from_slice(bytes).map_err(|e| StreamError::Decode(e.to_string()))
}
MessageFormat::Json => {
serde_json::from_slice(bytes).map_err(|e| StreamError::Decode(e.to_string()))
}
}
}