use binrw::{
BinRead, BinWrite,
meta::{ReadEndian, WriteEndian},
};
#[derive(Debug, Clone)]
pub struct Packet(pub Vec<u8>);
impl Packet {
pub const MAX_SIZE: usize = u16::MAX as usize;
pub const MIN_SIZE: usize = 16;
pub fn to<T: for<'a> BinRead<Args<'a> = ()> + ReadEndian>(&self) -> Result<T, binrw::Error> {
T::read(&mut std::io::Cursor::new(&self.0))
}
}
impl std::ops::Deref for Packet {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub trait IntoPacket {
fn into_packet(self) -> Packet;
}
impl IntoPacket for Packet {
fn into_packet(self) -> Packet {
self
}
}
impl<T: for<'a> BinWrite<Args<'a> = ()> + WriteEndian> IntoPacket for &T {
fn into_packet(self) -> Packet {
let mut buffer = std::io::Cursor::new(Vec::new());
self.write(&mut buffer)
.expect("failed to convert `impl BinWrite` type to Packet");
Packet(buffer.into_inner())
}
}