impls.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. use crate::*;
  2. use std::{
  3. any::type_name,
  4. collections::HashMap,
  5. hash::Hash,
  6. io::{Error, Read, Result, Write},
  7. mem::size_of,
  8. ops::Deref,
  9. time::{Duration, SystemTime, UNIX_EPOCH}
  10. };
  11. use arrayvec::ArrayVec;
  12. use pastey::paste;
  13. macro_rules! impl_basic {
  14. ($type:ty) => {
  15. impl Io for $type {
  16. fn read(r: &mut Reader) -> Result<Self> {
  17. paste! {
  18. r.[<read_ $type>]()
  19. }
  20. }
  21. fn write(&self, w: &mut Writer) -> Result<()> {
  22. paste! {
  23. w.[<write_ $type>](*self)
  24. }
  25. }
  26. fn size(&self) -> usize {
  27. std::mem::size_of::<Self>()
  28. }
  29. }
  30. }
  31. }
  32. macro_rules! impl_le {
  33. ($type:ty) => {
  34. impl Io for $type {
  35. fn read(r: &mut Reader) -> Result<Self> {
  36. paste! {
  37. r.[<read_ $type>]::<LE>()
  38. }
  39. }
  40. fn write(&self, w: &mut Writer) -> Result<()> {
  41. paste! {
  42. w.[<write_ $type>]::<LE>(*self)
  43. }
  44. }
  45. fn size(&self) -> usize {
  46. std::mem::size_of::<Self>()
  47. }
  48. }
  49. }
  50. }
  51. impl Io for () {
  52. fn read(_: &mut Reader) -> Result<Self> {
  53. Ok(())
  54. }
  55. fn write(&self, _: &mut Writer) -> Result<()> {
  56. Ok(())
  57. }
  58. fn size(&self) -> usize {
  59. 0
  60. }
  61. }
  62. impl_basic!(u8);
  63. impl_le!(u16);
  64. impl_le!(u32);
  65. impl_le!(u64);
  66. impl_le!(u128);
  67. impl_basic!(i8);
  68. impl_le!(i16);
  69. impl_le!(i32);
  70. impl_le!(i64);
  71. impl_le!(i128);
  72. impl_le!(f32);
  73. impl_le!(f64);
  74. impl Io for bool {
  75. fn read(r: &mut Reader) -> Result<Self> {
  76. u8::read(r)
  77. .map(|b| b != 0)
  78. }
  79. fn write(&self, w: &mut Writer) -> Result<()> {
  80. if *self {
  81. 1u8
  82. } else {
  83. 0u8
  84. }.write(w)
  85. }
  86. fn size(&self) -> usize {
  87. 1
  88. }
  89. }
  90. /// UTF-8 encoded unicode codepoint.
  91. #[cfg(feature = "char")]
  92. impl Io for char {
  93. fn read(r: &mut Reader) -> Result<Self> {
  94. use utf8_chars::BufReadCharsExt;
  95. r.read_char()?
  96. .ok_or_else(|| Error::other("unexpected EOF"))
  97. }
  98. fn write(&self, w: &mut Writer) -> Result<()> {
  99. let mut buf = [0; 4];
  100. w.write_all(self.encode_utf8(&mut buf).as_bytes())
  101. }
  102. fn size(&self) -> usize {
  103. // bit wasteful but eh
  104. let mut buf = [0; 4];
  105. self.encode_utf8(&mut buf).len()
  106. }
  107. }
  108. /// Treat usize as u64 on all platforms to allow for better compatibility.
  109. #[cfg(feature = "usize")]
  110. impl Io for usize {
  111. fn read(r: &mut Reader) -> Result<Self> {
  112. u64::read(r)?
  113. .try_into()
  114. .map_err(Error::other)
  115. }
  116. fn write(&self, w: &mut Writer) -> Result<()> {
  117. u64::try_from(*self)
  118. .map_err(Error::other)?
  119. .write(w)
  120. }
  121. fn size(&self) -> usize {
  122. 8
  123. }
  124. }
  125. /// Optional item Io implementation
  126. /// This uses an entire byte to store being present, so if you are doing an optional
  127. /// enum it's best to give the enum its own none variant.
  128. impl<T: Io> Io for Option<T> {
  129. fn read(r: &mut Reader) -> Result<Self> {
  130. if !bool::read(r)? {
  131. return Ok(None);
  132. }
  133. T::read(r).map(Some)
  134. }
  135. fn write(&self, w: &mut Writer) -> Result<()> {
  136. if let Some(inner) = self {
  137. true.write(w)?;
  138. inner.write(w)
  139. } else {
  140. false.write(w)
  141. }
  142. }
  143. fn size(&self) -> usize {
  144. 1 + match self {
  145. Some(inner) => inner.size(),
  146. None => 0
  147. }
  148. }
  149. }
  150. /// Result Io implementation
  151. impl<T: Io, E: Io> Io for std::result::Result<T, E> {
  152. fn read(r: &mut Reader) -> Result<Self> {
  153. if bool::read(r)? {
  154. T::read(r).map(Ok)
  155. } else {
  156. E::read(r).map(Err)
  157. }
  158. }
  159. fn write(&self, w: &mut Writer) -> Result<()> {
  160. self.is_ok().write(w)?;
  161. match self {
  162. Ok(inner) => inner.write(w),
  163. Err(e) => e.write(w)
  164. }
  165. }
  166. fn size(&self) -> usize {
  167. 1 + match self {
  168. Ok(inner) => inner.size(),
  169. Err(e) => e.size()
  170. }
  171. }
  172. }
  173. /// String LenIo implementation
  174. impl LenIo for String {
  175. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  176. let len: u64 = L::read(r)?.into();
  177. let mut bytes = vec![0; len as usize];
  178. r.read_exact(&mut bytes)?;
  179. Self::from_utf8(bytes)
  180. .map_err(Error::other)
  181. }
  182. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  183. self.as_str().write::<L>(w)
  184. }
  185. fn size<L: Len>(&self) -> usize {
  186. self.as_str().size::<L>()
  187. }
  188. }
  189. /// Generic Vec Io implementation.
  190. impl<T: Io> LenIo for Vec<T> {
  191. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  192. let len = L::read(r)?;
  193. (0 .. len.into())
  194. .map(|_| T::read(r))
  195. .collect()
  196. }
  197. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  198. (self as &[T]).write::<L>(w)
  199. }
  200. fn size<L: Len>(&self) -> usize {
  201. (self as &[T]).size::<L>()
  202. }
  203. }
  204. /// Generic HashMap Io implementation.
  205. /// Writing allocates a vec of every key and sorts to ensure reliable output
  206. impl<K: Hash + Io + Ord, V: Io> LenIo for HashMap<K, V> {
  207. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  208. let len = L::read(r)?;
  209. (0 .. len.into())
  210. .map(|_| Ok((K::read(r)?, V::read(r)?)))
  211. .collect()
  212. }
  213. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  214. let len = self.len() as u64;
  215. let len = L::try_from(len)
  216. .map_err(|_| conversion_error(len, type_name::<L>()))?;
  217. len.write(w)?;
  218. // sorting has some overhead though probably not much overall
  219. let mut keys = self.keys().collect::<Vec<_>>();
  220. keys.sort_unstable();
  221. for key in keys {
  222. key.write(w)?;
  223. self[key].write(w)?;
  224. }
  225. Ok(())
  226. }
  227. fn size<L: Len>(&self) -> usize {
  228. size_of::<L>() + self.iter().map(|(k, v)| k.size() + v.size()).sum::<usize>()
  229. }
  230. }
  231. impl<T: Io> Io for Box<T> {
  232. fn read(r: &mut Reader) -> Result<Self> {
  233. T::read(r).map(Box::new)
  234. }
  235. fn write(&self, w: &mut Writer) -> Result<()> {
  236. self.deref().write(w)
  237. }
  238. fn size(&self) -> usize {
  239. self.deref().size()
  240. }
  241. }
  242. /// Always saved as milliseconds, but with configurable max value.
  243. /// You can use u16 when you know values are under a minute, or u64 for unix timestamps.
  244. impl LenIo for Duration {
  245. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  246. L::read(r)
  247. .map(L::into)
  248. .map(Duration::from_millis)
  249. }
  250. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  251. let ms = u64::try_from(self.as_millis())
  252. .map_err(Error::other)?;
  253. L::try_from(ms)
  254. .map_err(|_| conversion_error(ms, type_name::<L>()))?
  255. .write(w)
  256. }
  257. fn size<L: Len>(&self) -> usize {
  258. size_of::<L>()
  259. }
  260. }
  261. // TODO: configurable precision rn its just ms
  262. // #[io(precision(millis))] or some shit
  263. impl Io for SystemTime {
  264. fn read(r: &mut Reader) -> Result<Self> {
  265. u64::read(r)
  266. .map(Duration::from_millis)
  267. .map(|offset| UNIX_EPOCH + offset)
  268. }
  269. fn write(&self, w: &mut Writer) -> Result<()> {
  270. u64::try_from(self.duration_since(UNIX_EPOCH)
  271. .map_err(Error::other)
  272. .map(|offset| offset.as_millis())?)
  273. .map_err(Error::other)?
  274. .write(w)
  275. }
  276. fn size(&self) -> usize {
  277. 0u64.size()
  278. }
  279. }
  280. impl<T: Io, const N: usize> Io for [T; N] {
  281. fn read(r: &mut Reader) -> Result<Self> {
  282. // this is used as a workaround for https://github.com/rust-lang/rust/issues/89379 not being stable
  283. // :(((( literally 1 line and no unsafe
  284. let array = [(); N]
  285. .iter()
  286. .map(|_| T::read(r))
  287. .collect::<Result<ArrayVec<T, N>>>()?
  288. .into_inner();
  289. // SAFETY: this will never fail since [(); N] always has N items
  290. Ok(unsafe { array.unwrap_unchecked() })
  291. }
  292. fn write(&self, w: &mut Writer) -> Result<()> {
  293. self.iter()
  294. .try_for_each(|item| item.write(w))
  295. }
  296. fn size(&self) -> usize {
  297. self.iter().map(Io::size).sum::<usize>()
  298. }
  299. }
  300. /// Write-only `str` LenIo implementation.
  301. /// Errors at runtime if you try to read it.
  302. impl LenIo for &str {
  303. fn read<L: Len>(_: &mut Reader) -> Result<Self> {
  304. Err(immutable_read())
  305. }
  306. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  307. let len = self.len() as u64;
  308. let len = L::try_from(len)
  309. .map_err(|_| conversion_error(len, type_name::<L>()))?;
  310. len.write(w)?;
  311. w.write_all(self.as_bytes())
  312. }
  313. fn size<L: Len>(&self) -> usize {
  314. size_of::<L>() + self.len()
  315. }
  316. }
  317. /// Write-only unbounded slice LenIo implementation.
  318. /// Errors at runtime if you try to read it.
  319. impl<T: Io> LenIo for &[T] {
  320. fn read<L: Len>(_: &mut Reader) -> Result<Self> {
  321. Err(immutable_read())
  322. }
  323. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  324. let len = self.len() as u64;
  325. let len = L::try_from(len)
  326. .map_err(|_| conversion_error(len, type_name::<L>()))?;
  327. len.write(w)?;
  328. for item in *self {
  329. item.write(w)?;
  330. }
  331. Ok(())
  332. }
  333. fn size<L: Len>(&self) -> usize {
  334. size_of::<L>() + self.iter().map(Io::size).sum::<usize>()
  335. }
  336. }
  337. /// Write-only Io implementation for references.
  338. /// Errors are runtime if you try to read it.
  339. impl<T: Io> Io for &T {
  340. fn read(_: &mut Reader) -> Result<Self> {
  341. Err(immutable_read())
  342. }
  343. fn write(&self, w: &mut Writer) -> Result<()> {
  344. T::write(*self, w)
  345. }
  346. fn size(&self) -> usize {
  347. T::size(*self)
  348. }
  349. }
  350. fn conversion_error(len: u64, ty: &str) -> Error {
  351. Error::other(format!("cannot store length {len} as {ty}"))
  352. }
  353. fn immutable_read() -> Error {
  354. Error::other("immutable references cannot be read into")
  355. }