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 { paste! { r.[]() } } fn write(&self, w: &mut Writer) -> Result<()> { paste! { w.[](*self) } } fn size(&self) -> usize { std::mem::size_of::() } } } } macro_rules! impl_le { ($type:ty) => { impl Io for $type { fn read(r: &mut Reader) -> Result { paste! { r.[]::() } } fn write(&self, w: &mut Writer) -> Result<()> { paste! { w.[]::(*self) } } fn size(&self) -> usize { std::mem::size_of::() } } } } impl Io for () { fn read(_: &mut Reader) -> Result { 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 { 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 { 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 Io for Option { fn read(r: &mut Reader) -> Result { 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(r: &mut Reader) -> Result { 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(&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(&self) -> usize { size_of::() + self.len() } } /// Generic Vec Io implementation. impl LenIo for Vec { fn read(r: &mut Reader) -> Result { let len = L::read(r)?; (0 .. len.into()) .map(|_| T::read(r)) .collect() } fn write(&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(&self) -> usize { size_of::() + self.iter().map(Io::size).sum::() } } /// Generic HashMap Io implementation. /// Writing allocates a vec of every key and sorts to ensure reliable output impl LenIo for HashMap { fn read(r: &mut Reader) -> Result { let len = L::read(r)?; (0 .. len.into()) .map(|_| Ok((K::read(r)?, V::read(r)?))) .collect() } fn write(&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::>(); keys.sort_unstable(); for key in keys { key.write(w)?; self[key].write(w)?; } Ok(()) } fn size(&self) -> usize { size_of::() + self.iter().map(|(k, v)| k.size() + v.size()).sum::() } } impl Io for Box { fn read(r: &mut Reader) -> Result { 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(r: &mut Reader) -> Result { L::read(r) .map(L::into) .map(Duration::from_millis) } fn write(&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(&self) -> usize { size_of::() } } // TODO: configurable precision rn its just ms // #[io(precision(millis))] or some shit impl Io for SystemTime { fn read(r: &mut Reader) -> Result { 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 Io for [T; N] { fn read(r: &mut Reader) -> Result { // 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::>>()? .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::() } } // basically Error::other but not requiring nightly fn other(error: impl Into>) -> Error { Error::new(ErrorKind::Other, error) } // discard error and use a string fn conversion(_: T) -> Error { other("failed to convert length to u64") }