io.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use std::io::Result;
  2. pub use byteorder::{ReadBytesExt, WriteBytesExt};
  3. pub type Reader<'a> = &'a [u8];
  4. pub type Writer = Vec<u8>;
  5. /// A type that can be serialized to and from bytes.
  6. /// Should only be implemented on types that own their data, i.e. `String` and not `&str`.
  7. pub trait Io : Sized {
  8. /// Read data from the reader.
  9. fn read(r: &mut Reader) -> Result<Self>;
  10. /// Write this data to the reader.
  11. fn write(&self, w: &mut Writer) -> Result<()>;
  12. /// Number of bytes this data will take up when written
  13. fn size(&self) -> usize;
  14. /// Create a Vec<u8> and write to it.
  15. /// Should only be used for highest level types or when sending packets.
  16. fn to_bytes(&self) -> Result<Vec<u8>> {
  17. let size = self.size();
  18. let mut bytes = Vec::with_capacity(size);
  19. self.write(&mut bytes)?;
  20. debug_assert_eq!(bytes.len(), size, "Io::size() was wrong");
  21. Ok(bytes)
  22. }
  23. }
  24. /// Like [Io] but when a length type is needed.
  25. /// All functions have a type parameter `Len` which should be an integer primitive.
  26. /// For example [String] encodes its content length then its contents.
  27. /// The user can select what type to use for length, which determines max string length.
  28. /// For custom types that implement this the length type should be passed to fields that implement LenIo.
  29. /// 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.
  30. /// The derive macro can be used for example with `#[io(len = u16)]` to set the length type to u16.
  31. pub trait LenIo : Sized {
  32. /// Read data from the reader.
  33. fn read<L: Len>(r: &mut Reader) -> Result<Self>;
  34. /// Write this data to the reader.
  35. fn write<L: Len> (&self, w: &mut Writer) -> Result<()>;
  36. /// Number of bytes this data will take up when written
  37. fn size<L: Len>(&self) -> usize;
  38. /// Create a Vec<u8> and write to it.
  39. /// Should only be used for highest level types or when sending packets.
  40. fn to_bytes<L: Len>(&self) -> Result<Vec<u8>> {
  41. let size = self.size::<L>();
  42. let mut bytes = Vec::with_capacity(size);
  43. self.write::<L>(&mut bytes)?;
  44. debug_assert_eq!(bytes.len(), size, "LenIo::size() was wrong");
  45. Ok(bytes)
  46. }
  47. }
  48. /// Any primitive integer that can be written.
  49. /// Used for `LenIo` functions.
  50. pub trait Len : Io + Into<u64> + TryFrom<u64> {}
  51. impl <T: Io + Into<u64> + TryFrom<u64>> Len for T {}