| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322 |
- use crate::*;
- use std::{
- collections::HashMap,
- hash::Hash,
- io::{Error, ErrorKind, Read, Result, Write},
- mem::size_of,
- ops::Deref,
- time::{Duration, SystemTime, UNIX_EPOCH}
- };
- use arrayvec::ArrayVec;
- use paste::paste;
- macro_rules! impl_basic {
- ($type:ty) => {
- impl Io for $type {
- fn read(r: &mut Reader) -> Result<Self> {
- paste! {
- r.[<read_ $type>]()
- }
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- paste! {
- w.[<write_ $type>](*self)
- }
- }
- fn size(&self) -> usize {
- std::mem::size_of::<Self>()
- }
- }
- }
- }
- macro_rules! impl_le {
- ($type:ty) => {
- impl Io for $type {
- fn read(r: &mut Reader) -> Result<Self> {
- paste! {
- r.[<read_ $type>]::<LE>()
- }
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- paste! {
- w.[<write_ $type>]::<LE>(*self)
- }
- }
- fn size(&self) -> usize {
- std::mem::size_of::<Self>()
- }
- }
- }
- }
- impl Io for () {
- fn read(_: &mut Reader) -> Result<Self> {
- Ok(())
- }
- fn write(&self, _: &mut Writer) -> Result<()> {
- Ok(())
- }
- fn size(&self) -> usize {
- 0
- }
- }
- impl_basic!(u8);
- impl_le!(u16);
- impl_le!(u32);
- impl_le!(u64);
- impl_le!(u128);
- impl_basic!(i8);
- impl_le!(i16);
- impl_le!(i32);
- impl_le!(i64);
- impl_le!(i128);
- impl_le!(f32);
- impl_le!(f64);
- impl Io for bool {
- fn read(r: &mut Reader) -> Result<Self> {
- u8::read(r)
- .map(|b| b != 0)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- if *self {
- 1u8
- } else {
- 0u8
- }.write(w)
- }
- fn size(&self) -> usize {
- 1
- }
- }
- /// Treat usize as u64 on all platforms to allow for better compatibility.
- #[cfg(feature = "usize")]
- impl Io for usize {
- fn read(r: &mut Reader) -> Result<Self> {
- u64::read(r)?
- .try_into()
- .map_err(other)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- u64::try_from(*self)
- .map_err(other)?
- .write(w)
- }
- fn size(&self) -> usize {
- 8
- }
- }
- /// Optional item Io implementation
- /// This uses an entire byte to store being present, so if you are doing an optional
- /// enum it's best to give the enum its own none variant.
- impl<T: Io> Io for Option<T> {
- fn read(r: &mut Reader) -> Result<Self> {
- if !bool::read(r)? {
- return Ok(None);
- }
- T::read(r).map(Some)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- if let Some(inner) = self {
- true.write(w)?;
- inner.write(w)
- } else {
- false.write(w)
- }
- }
- fn size(&self) -> usize {
- 1 + match self {
- Some(inner) => inner.size(),
- None => 0
- }
- }
- }
- /// String LenIo implementation
- impl LenIo for String {
- fn read<L: Len>(r: &mut Reader) -> Result<Self> {
- let len: u64 = L::read(r)?.into();
- let mut bytes = vec![0; len as usize];
- r.read_exact(&mut bytes)?;
- Self::from_utf8(bytes)
- .map_err(other)
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let len = L::try_from(self.len() as u64)
- .map_err(|_| "conversion to u64 failed")
- .map_err(other)?;
- len.write(w)?;
- w.write_all(self.as_bytes())
- }
- fn size<L: Len>(&self) -> usize {
- size_of::<L>() + self.len()
- }
- }
- /// Generic Vec Io implementation.
- impl<T: Io> LenIo for Vec<T> {
- fn read<L: Len>(r: &mut Reader) -> Result<Self> {
- let len = L::read(r)?;
- (0 .. len.into())
- .map(|_| T::read(r))
- .collect()
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let len = L::try_from(self.len() as u64)
- .map_err(conversion)?;
- len.write(w)?;
- for item in self {
- item.write(w)?;
- }
- Ok(())
- }
- fn size<L: Len>(&self) -> usize {
- size_of::<L>() + self.iter().map(Io::size).sum::<usize>()
- }
- }
- /// Generic HashMap Io implementation.
- /// Writing allocates a vec of every key and sorts to ensure reliable output
- impl<K: Hash + Io + Ord, V: Io> LenIo for HashMap<K, V> {
- fn read<L: Len>(r: &mut Reader) -> Result<Self> {
- let len = L::read(r)?;
- (0 .. len.into())
- .map(|_| Ok((K::read(r)?, V::read(r)?)))
- .collect()
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let len = L::try_from(self.len() as u64)
- .map_err(conversion)?;
- len.write(w)?;
- // sorting has some overhead though probably not much overall
- let mut keys = self.keys().collect::<Vec<_>>();
- keys.sort_unstable();
- for key in keys {
- key.write(w)?;
- self[key].write(w)?;
- }
- Ok(())
- }
- fn size<L: Len>(&self) -> usize {
- size_of::<L>() + self.iter().map(|(k, v)| k.size() + v.size()).sum::<usize>()
- }
- }
- impl<T: Io> Io for Box<T> {
- fn read(r: &mut Reader) -> Result<Self> {
- T::read(r).map(Box::new)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- self.deref().write(w)
- }
- fn size(&self) -> usize {
- self.deref().size()
- }
- }
- /// Always saved as milliseconds, but with configurable max value.
- /// You can use u16 when you know values are under a minute, or u64 for unix timestamps.
- impl LenIo for Duration {
- fn read<L: Len>(r: &mut Reader) -> Result<Self> {
- L::read(r)
- .map(L::into)
- .map(Duration::from_millis)
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let ms = u64::try_from(self.as_millis())
- .map_err(other)?;
- L::try_from(ms)
- .map_err(conversion)?
- .write(w)
- }
- fn size<L: Len>(&self) -> usize {
- size_of::<L>()
- }
- }
- // TODO: configurable precision rn its just ms
- // #[io(precision(millis))] or some shit
- impl Io for SystemTime {
- fn read(r: &mut Reader) -> Result<Self> {
- u64::read(r)
- .map(Duration::from_millis)
- .map(|offset| UNIX_EPOCH + offset)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- u64::try_from(self.duration_since(UNIX_EPOCH)
- .map_err(other)
- .map(|offset| offset.as_millis())?)
- .map_err(other)?
- .write(w)
- }
- fn size(&self) -> usize {
- 0u64.size()
- }
- }
- impl<T: Io, const N: usize> Io for [T; N] {
- fn read(r: &mut Reader) -> Result<Self> {
- // this is used as a workaround for https://github.com/rust-lang/rust/issues/89379 not being stable
- // :(((( literally 1 line and no unsafe
- let array = [(); N]
- .iter()
- .map(|_| T::read(r))
- .collect::<Result<ArrayVec<T, N>>>()?
- .into_inner();
- // SAFETY: this will never fail since [(); N] always has N items
- Ok(unsafe { array.unwrap_unchecked() })
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- self.iter()
- .map(|item| item.write(w))
- .collect()
- }
- fn size(&self) -> usize {
- self.iter().map(Io::size).sum::<usize>()
- }
- }
- // basically Error::other but not requiring nightly
- fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
- Error::new(ErrorKind::Other, error)
- }
- // discard error and use a string
- fn conversion<T>(_: T) -> Error {
- other("failed to convert length to u64")
- }
|