use std::any::type_name;
use bytes::BufMut;
use serde::Serialize;
use crate::protocol::ParseError;
pub trait JsonMessage: Serialize {
fn to_string(&self) -> String {
serde_json::to_string(self)
.unwrap_or_else(|_| panic!("failed to encode {} to JSON", type_name::<Self>()))
}
}
pub trait BinaryPayload<'a>: Sized + 'a {
fn parse_payload(data: &'a [u8]) -> Result<Self, ParseError>;
fn payload_size(&self) -> usize;
fn write_payload(&self, buf: &mut impl BufMut);
}
pub trait BinaryMessage<'a>: BinaryPayload<'a> {
const OPCODE: u8;
fn encoded_len(&self) -> usize {
1 + self.payload_size()
}
fn encode(&self, buf: &mut impl BufMut) {
buf.put_u8(Self::OPCODE);
self.write_payload(buf);
}
fn to_bytes(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(self.encoded_len());
self.encode(&mut buf);
buf
}
}