| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- use std::io::Result;
- pub use byteorder::{ReadBytesExt, WriteBytesExt};
- pub type Reader<'a> = &'a [u8];
- pub type Writer = Vec<u8>;
- /// A type that can be serialized to and from bytes.
- /// Should only be implemented on types that own their data, i.e. `String` and not `&str`.
- pub trait Io : Sized {
- /// Read data from the reader.
- fn read(r: &mut Reader) -> Result<Self>;
- /// Write this data to the reader.
- fn write(&self, w: &mut Writer) -> Result<()>;
- /// Number of bytes this data will take up when written
- fn size(&self) -> usize;
- /// Create a Vec<u8> and write to it.
- /// Should only be used for highest level types or when sending packets.
- fn to_bytes(&self) -> Result<Vec<u8>> {
- let size = self.size();
- let mut bytes = Vec::with_capacity(size);
- self.write(&mut bytes)?;
- debug_assert_eq!(bytes.len(), size, "Io::size() was wrong");
- Ok(bytes)
- }
- }
- /// Like [Io] but when a length type is needed.
- /// All functions have a type parameter `Len` which should be an integer primitive.
- /// For example [String] encodes its content length then its contents.
- /// The user can select what type to use for length, which determines max string length.
- /// For custom types that implement this the length type should be passed to fields that implement LenIo.
- /// If you do not write any length fields that could benefit from this, do not use LenIo and use `Io` instead with the derive macro.
- /// The derive macro can be used for example with `#[io(len = u16)]` to set the length type to u16.
- pub trait LenIo : Sized {
- /// Read data from the reader.
- fn read<L: Len>(r: &mut Reader) -> Result<Self>;
- /// Write this data to the reader.
- fn write<L: Len> (&self, w: &mut Writer) -> Result<()>;
- /// Number of bytes this data will take up when written
- fn size<L: Len>(&self) -> usize;
- /// Create a Vec<u8> and write to it.
- /// Should only be used for highest level types or when sending packets.
- fn to_bytes<L: Len>(&self) -> Result<Vec<u8>> {
- let size = self.size::<L>();
- let mut bytes = Vec::with_capacity(size);
- self.write::<L>(&mut bytes)?;
- debug_assert_eq!(bytes.len(), size, "LenIo::size() was wrong");
- Ok(bytes)
- }
- }
- /// Any primitive integer that can be written.
- /// Used for `LenIo` functions.
- pub trait Len : Io + Into<u64> + TryFrom<u64> {}
- impl <T: Io + Into<u64> + TryFrom<u64>> Len for T {}
|