use crate::WireError;
pub trait Sealable: Sized {
fn to_bin(&self) -> Result<Vec<u8>, WireError>;
fn from_bin(bytes: &[u8]) -> Result<Self, WireError>;
}
#[cfg(feature = "reference-frame")]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Frame {
pub frame_id: u64,
pub timestamp_ms: u64,
pub payload: Vec<u8>,
}
#[cfg(feature = "reference-frame")]
impl Sealable for Frame {
fn to_bin(&self) -> Result<Vec<u8>, WireError> {
bincode::serialize(self).map_err(WireError::encode)
}
fn from_bin(bytes: &[u8]) -> Result<Self, WireError> {
bincode::deserialize(bytes).map_err(WireError::decode)
}
}
#[cfg(feature = "reference-frame")]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Input {
pub sequence: u64,
pub timestamp_ms: u64,
pub payload: Vec<u8>,
}
#[cfg(feature = "reference-frame")]
impl Sealable for Input {
fn to_bin(&self) -> Result<Vec<u8>, WireError> {
bincode::serialize(self).map_err(WireError::encode)
}
fn from_bin(bytes: &[u8]) -> Result<Self, WireError> {
bincode::deserialize(bytes).map_err(WireError::decode)
}
}
#[cfg(all(test, feature = "reference-frame"))]
mod tests {
use super::*;
#[test]
fn frame_roundtrip() {
let f = Frame {
frame_id: 42,
timestamp_ms: 1_700_000_000_000,
payload: b"hello".to_vec(),
};
let bytes = f.to_bin().unwrap();
let decoded = Frame::from_bin(&bytes).unwrap();
assert_eq!(f, decoded);
}
#[test]
fn input_roundtrip() {
let i = Input {
sequence: 7,
timestamp_ms: 1_700_000_000_050,
payload: b"click".to_vec(),
};
let bytes = i.to_bin().unwrap();
let decoded = Input::from_bin(&bytes).unwrap();
assert_eq!(i, decoded);
}
#[test]
fn from_bin_rejects_garbage() {
assert!(Frame::from_bin(&[0xFFu8; 4]).is_err());
}
}