impls.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. use crate::*;
  2. use std::{
  3. collections::HashMap,
  4. hash::Hash,
  5. io::{Error, ErrorKind, Read, Result, Write},
  6. mem::size_of,
  7. ops::Deref,
  8. time::{Duration, SystemTime, UNIX_EPOCH}
  9. };
  10. use arrayvec::ArrayVec;
  11. use paste::paste;
  12. macro_rules! impl_basic {
  13. ($type:ty) => {
  14. impl Io for $type {
  15. fn read(r: &mut Reader) -> Result<Self> {
  16. paste! {
  17. r.[<read_ $type>]()
  18. }
  19. }
  20. fn write(&self, w: &mut Writer) -> Result<()> {
  21. paste! {
  22. w.[<write_ $type>](*self)
  23. }
  24. }
  25. fn size(&self) -> usize {
  26. std::mem::size_of::<Self>()
  27. }
  28. }
  29. }
  30. }
  31. macro_rules! impl_le {
  32. ($type:ty) => {
  33. impl Io for $type {
  34. fn read(r: &mut Reader) -> Result<Self> {
  35. paste! {
  36. r.[<read_ $type>]::<LE>()
  37. }
  38. }
  39. fn write(&self, w: &mut Writer) -> Result<()> {
  40. paste! {
  41. w.[<write_ $type>]::<LE>(*self)
  42. }
  43. }
  44. fn size(&self) -> usize {
  45. std::mem::size_of::<Self>()
  46. }
  47. }
  48. }
  49. }
  50. impl Io for () {
  51. fn read(_: &mut Reader) -> Result<Self> {
  52. Ok(())
  53. }
  54. fn write(&self, _: &mut Writer) -> Result<()> {
  55. Ok(())
  56. }
  57. fn size(&self) -> usize {
  58. 0
  59. }
  60. }
  61. impl_basic!(u8);
  62. impl_le!(u16);
  63. impl_le!(u32);
  64. impl_le!(u64);
  65. impl_le!(u128);
  66. impl_basic!(i8);
  67. impl_le!(i16);
  68. impl_le!(i32);
  69. impl_le!(i64);
  70. impl_le!(i128);
  71. impl_le!(f32);
  72. impl_le!(f64);
  73. impl Io for bool {
  74. fn read(r: &mut Reader) -> Result<Self> {
  75. u8::read(r)
  76. .map(|b| b != 0)
  77. }
  78. fn write(&self, w: &mut Writer) -> Result<()> {
  79. if *self {
  80. 1u8
  81. } else {
  82. 0u8
  83. }.write(w)
  84. }
  85. fn size(&self) -> usize {
  86. 1
  87. }
  88. }
  89. /// Treat usize as u64 on all platforms to allow for better compatibility.
  90. #[cfg(feature = "usize")]
  91. impl Io for usize {
  92. fn read(r: &mut Reader) -> Result<Self> {
  93. u64::read(r)?
  94. .try_into()
  95. .map_err(other)
  96. }
  97. fn write(&self, w: &mut Writer) -> Result<()> {
  98. u64::try_from(*self)
  99. .map_err(other)?
  100. .write(w)
  101. }
  102. fn size(&self) -> usize {
  103. 8
  104. }
  105. }
  106. /// Optional item Io implementation
  107. /// This uses an entire byte to store being present, so if you are doing an optional
  108. /// enum it's best to give the enum its own none variant.
  109. impl<T: Io> Io for Option<T> {
  110. fn read(r: &mut Reader) -> Result<Self> {
  111. if !bool::read(r)? {
  112. return Ok(None);
  113. }
  114. T::read(r).map(Some)
  115. }
  116. fn write(&self, w: &mut Writer) -> Result<()> {
  117. if let Some(inner) = self {
  118. true.write(w)?;
  119. inner.write(w)
  120. } else {
  121. false.write(w)
  122. }
  123. }
  124. fn size(&self) -> usize {
  125. 1 + match self {
  126. Some(inner) => inner.size(),
  127. None => 0
  128. }
  129. }
  130. }
  131. /// String LenIo implementation
  132. impl LenIo for String {
  133. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  134. let len: u64 = L::read(r)?.into();
  135. let mut bytes = vec![0; len as usize];
  136. r.read_exact(&mut bytes)?;
  137. Self::from_utf8(bytes)
  138. .map_err(other)
  139. }
  140. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  141. let len = L::try_from(self.len() as u64)
  142. .map_err(|_| "conversion to u64 failed")
  143. .map_err(other)?;
  144. len.write(w)?;
  145. w.write_all(self.as_bytes())
  146. }
  147. fn size<L: Len>(&self) -> usize {
  148. size_of::<L>() + self.len()
  149. }
  150. }
  151. /// Generic Vec Io implementation.
  152. impl<T: Io> LenIo for Vec<T> {
  153. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  154. let len = L::read(r)?;
  155. (0 .. len.into())
  156. .map(|_| T::read(r))
  157. .collect()
  158. }
  159. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  160. let len = L::try_from(self.len() as u64)
  161. .map_err(conversion)?;
  162. len.write(w)?;
  163. for item in self {
  164. item.write(w)?;
  165. }
  166. Ok(())
  167. }
  168. fn size<L: Len>(&self) -> usize {
  169. size_of::<L>() + self.iter().map(Io::size).sum::<usize>()
  170. }
  171. }
  172. /// Generic HashMap Io implementation.
  173. /// Writing allocates a vec of every key and sorts to ensure reliable output
  174. impl<K: Hash + Io + Ord, V: Io> LenIo for HashMap<K, V> {
  175. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  176. let len = L::read(r)?;
  177. (0 .. len.into())
  178. .map(|_| Ok((K::read(r)?, V::read(r)?)))
  179. .collect()
  180. }
  181. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  182. let len = L::try_from(self.len() as u64)
  183. .map_err(conversion)?;
  184. len.write(w)?;
  185. // sorting has some overhead though probably not much overall
  186. let mut keys = self.keys().collect::<Vec<_>>();
  187. keys.sort_unstable();
  188. for key in keys {
  189. key.write(w)?;
  190. self[key].write(w)?;
  191. }
  192. Ok(())
  193. }
  194. fn size<L: Len>(&self) -> usize {
  195. size_of::<L>() + self.iter().map(|(k, v)| k.size() + v.size()).sum::<usize>()
  196. }
  197. }
  198. impl<T: Io> Io for Box<T> {
  199. fn read(r: &mut Reader) -> Result<Self> {
  200. T::read(r).map(Box::new)
  201. }
  202. fn write(&self, w: &mut Writer) -> Result<()> {
  203. self.deref().write(w)
  204. }
  205. fn size(&self) -> usize {
  206. self.deref().size()
  207. }
  208. }
  209. /// Always saved as milliseconds, but with configurable max value.
  210. /// You can use u16 when you know values are under a minute, or u64 for unix timestamps.
  211. impl LenIo for Duration {
  212. fn read<L: Len>(r: &mut Reader) -> Result<Self> {
  213. L::read(r)
  214. .map(L::into)
  215. .map(Duration::from_millis)
  216. }
  217. fn write<L: Len>(&self, w: &mut Writer) -> Result<()> {
  218. let ms = u64::try_from(self.as_millis())
  219. .map_err(other)?;
  220. L::try_from(ms)
  221. .map_err(conversion)?
  222. .write(w)
  223. }
  224. fn size<L: Len>(&self) -> usize {
  225. size_of::<L>()
  226. }
  227. }
  228. // TODO: configurable precision rn its just ms
  229. // #[io(precision(millis))] or some shit
  230. impl Io for SystemTime {
  231. fn read(r: &mut Reader) -> Result<Self> {
  232. u64::read(r)
  233. .map(Duration::from_millis)
  234. .map(|offset| UNIX_EPOCH + offset)
  235. }
  236. fn write(&self, w: &mut Writer) -> Result<()> {
  237. u64::try_from(self.duration_since(UNIX_EPOCH)
  238. .map_err(other)
  239. .map(|offset| offset.as_millis())?)
  240. .map_err(other)?
  241. .write(w)
  242. }
  243. fn size(&self) -> usize {
  244. 0u64.size()
  245. }
  246. }
  247. impl<T: Io, const N: usize> Io for [T; N] {
  248. fn read(r: &mut Reader) -> Result<Self> {
  249. // this is used as a workaround for https://github.com/rust-lang/rust/issues/89379 not being stable
  250. // :(((( literally 1 line and no unsafe
  251. let array = [(); N]
  252. .iter()
  253. .map(|_| T::read(r))
  254. .collect::<Result<ArrayVec<T, N>>>()?
  255. .into_inner();
  256. // SAFETY: this will never fail since [(); N] always has N items
  257. Ok(unsafe { array.unwrap_unchecked() })
  258. }
  259. fn write(&self, w: &mut Writer) -> Result<()> {
  260. self.iter()
  261. .map(|item| item.write(w))
  262. .collect()
  263. }
  264. fn size(&self) -> usize {
  265. self.iter().map(Io::size).sum::<usize>()
  266. }
  267. }
  268. // basically Error::other but not requiring nightly
  269. fn other(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
  270. Error::new(ErrorKind::Other, error)
  271. }
  272. // discard error and use a string
  273. fn conversion<T>(_: T) -> Error {
  274. other("failed to convert length to u64")
  275. }