1use binrw::{
4 BinRead, BinWrite,
5 meta::{ReadEndian, WriteEndian},
6};
7
8pub trait Packet:
10 for<'r> BinRead<Args<'r> = ()> + ReadEndian + for<'w> BinWrite<Args<'w> = ()> + WriteEndian
11{
12 fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self, Error> {
14 Self::read(&mut std::io::Cursor::new(bytes.as_ref())).map_err(Error)
15 }
16
17 fn to_bytes(&self) -> Vec<u8> {
19 let mut buf = std::io::Cursor::new(Vec::new());
20 self.write(&mut buf).unwrap_or_else(|err| {
21 panic!(
22 "failed to serialize `{}`: {err}",
23 std::any::type_name::<Self>()
24 )
25 });
26
27 buf.into_inner()
28 }
29}
30
31#[derive(Debug)]
33pub struct Error(binrw::Error);
34
35impl std::fmt::Display for Error {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 self.0.fmt(f)
38 }
39}
40
41impl std::error::Error for Error {}