| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417 |
- use crate::*;
- use std::{
- any::type_name,
- collections::HashMap,
- hash::Hash,
- io::{Error, Read, Result, Write},
- mem::size_of,
- ops::Deref,
- time::{Duration, SystemTime, UNIX_EPOCH}
- };
- use arrayvec::ArrayVec;
- use pastey::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
- }
- }
- /// UTF-8 encoded unicode codepoint.
- #[cfg(feature = "char")]
- impl Io for char {
- fn read(r: &mut Reader) -> Result<Self> {
- use utf8_chars::BufReadCharsExt;
- r.read_char()?
- .ok_or_else(|| Error::other("unexpected EOF"))
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- let mut buf = [0; 4];
- w.write_all(self.encode_utf8(&mut buf).as_bytes())
- }
- fn size(&self) -> usize {
- // bit wasteful but eh
- let mut buf = [0; 4];
- self.encode_utf8(&mut buf).len()
- }
- }
- /// 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(Error::other)
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- u64::try_from(*self)
- .map_err(Error::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
- }
- }
- }
- /// Result Io implementation
- impl<T: Io, E: Io> Io for std::result::Result<T, E> {
- fn read(r: &mut Reader) -> Result<Self> {
- if bool::read(r)? {
- T::read(r).map(Ok)
- } else {
- E::read(r).map(Err)
- }
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- self.is_ok().write(w)?;
- match self {
- Ok(inner) => inner.write(w),
- Err(e) => e.write(w)
- }
- }
- fn size(&self) -> usize {
- 1 + match self {
- Ok(inner) => inner.size(),
- Err(e) => e.size()
- }
- }
- }
- /// 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(Error::other)
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- self.as_str().write::<L>(w)
- }
- fn size<L: Len>(&self) -> usize {
- self.as_str().size::<L>()
- }
- }
- /// 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<()> {
- (self as &[T]).write::<L>(w)
- }
- fn size<L: Len>(&self) -> usize {
- (self as &[T]).size::<L>()
- }
- }
- /// 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 = self.len() as u64;
- let len = L::try_from(len)
- .map_err(|_| conversion_error(len, type_name::<L>()))?;
- 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(Error::other)?;
- L::try_from(ms)
- .map_err(|_| conversion_error(ms, type_name::<L>()))?
- .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(Error::other)
- .map(|offset| offset.as_millis())?)
- .map_err(Error::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()
- .try_for_each(|item| item.write(w))
- }
- fn size(&self) -> usize {
- self.iter().map(Io::size).sum::<usize>()
- }
- }
- /// Write-only `str` LenIo implementation.
- /// Errors at runtime if you try to read it.
- impl LenIo for &str {
- fn read<L: Len>(_: &mut Reader) -> Result<Self> {
- Err(immutable_read())
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let len = self.len() as u64;
- let len = L::try_from(len)
- .map_err(|_| conversion_error(len, type_name::<L>()))?;
- len.write(w)?;
- w.write_all(self.as_bytes())
- }
- fn size<L: Len>(&self) -> usize {
- size_of::<L>() + self.len()
- }
- }
- /// Write-only unbounded slice LenIo implementation.
- /// Errors at runtime if you try to read it.
- impl<T: Io> LenIo for &[T] {
- fn read<L: Len>(_: &mut Reader) -> Result<Self> {
- Err(immutable_read())
- }
- fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
- let len = self.len() as u64;
- let len = L::try_from(len)
- .map_err(|_| conversion_error(len, type_name::<L>()))?;
- 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>()
- }
- }
- /// Write-only Io implementation for references.
- /// Errors are runtime if you try to read it.
- impl<T: Io> Io for &T {
- fn read(_: &mut Reader) -> Result<Self> {
- Err(immutable_read())
- }
- fn write(&self, w: &mut Writer) -> Result<()> {
- T::write(*self, w)
- }
- fn size(&self) -> usize {
- T::size(*self)
- }
- }
- fn conversion_error(len: u64, ty: &str) -> Error {
- Error::other(format!("cannot store length {len} as {ty}"))
- }
- fn immutable_read() -> Error {
- Error::other("immutable references cannot be read into")
- }
|