1use std::{
20 collections::VecDeque,
21 io::{Error, Result},
22};
23
24pub use async_trait::async_trait;
25pub use futures_lite::{
26 io::Cursor, AsyncRead, AsyncReadExt as FutAsyncReadExt, AsyncWrite,
27 AsyncWriteExt as FutAsyncWriteExt,
28};
29
30use crate::{endian, VarInt};
31
32#[async_trait]
34pub trait AsyncEncodable {
35 async fn encode_async<W: AsyncWrite + Unpin + Send>(&self, w: &mut W) -> Result<usize>;
39}
40
41#[async_trait]
43pub trait AsyncDecodable: Sized {
44 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self>;
45}
46
47pub async fn serialize_async<T: AsyncEncodable + ?Sized>(data: &T) -> Vec<u8> {
49 let mut encoder = Vec::new();
50 let len = data.encode_async(&mut encoder).await.unwrap();
51 assert_eq!(len, encoder.len());
52 encoder
53}
54
55pub async fn deserialize_async_limited_partial<T: AsyncDecodable>(
60 data: &[u8],
61 max_len: usize,
62) -> Result<(T, usize)> {
63 let (len, _) = deserialize_async_partial::<VarInt>(data).await?;
64 let obj_len = len.0 as usize;
65
66 if obj_len > max_len {
67 return Err(Error::other("Data size exceeds set `max_len`"))
68 }
69
70 deserialize_async_partial(data).await
71}
72
73pub async fn deserialize_async_partial<T: AsyncDecodable>(data: &[u8]) -> Result<(T, usize)> {
76 let mut decoder = Cursor::new(data);
77 let rv = AsyncDecodable::decode_async(&mut decoder).await?;
78 let consumed = decoder.position() as usize;
79
80 Ok((rv, consumed))
81}
82
83pub async fn deserialize_async_limited<T: AsyncDecodable>(
88 data: &[u8],
89 max_len: usize,
90) -> Result<T> {
91 let (len, _) = deserialize_async_partial::<VarInt>(data).await?;
92 let obj_len = len.0 as usize;
93
94 if obj_len > max_len {
95 return Err(Error::other("Data size exceeds set `max_len`"))
96 }
97
98 deserialize_async(data).await
99}
100
101pub async fn deserialize_async<T: AsyncDecodable>(data: &[u8]) -> Result<T> {
104 let (rv, consumed) = deserialize_async_partial(data).await?;
105
106 if consumed != data.len() {
108 return Err(Error::other("Data not consumed fully on deserialization"))
109 }
110
111 Ok(rv)
112}
113
114#[async_trait]
116pub trait AsyncWriteExt {
117 async fn write_u128_async(&mut self, v: u128) -> Result<()>;
119 async fn write_u64_async(&mut self, v: u64) -> Result<()>;
121 async fn write_u32_async(&mut self, v: u32) -> Result<()>;
123 async fn write_u16_async(&mut self, v: u16) -> Result<()>;
125 async fn write_u8_async(&mut self, v: u8) -> Result<()>;
127
128 async fn write_i128_async(&mut self, v: i128) -> Result<()>;
130 async fn write_i64_async(&mut self, v: i64) -> Result<()>;
132 async fn write_i32_async(&mut self, v: i32) -> Result<()>;
134 async fn write_i16_async(&mut self, v: i16) -> Result<()>;
136 async fn write_i8_async(&mut self, v: i8) -> Result<()>;
138
139 async fn write_f64_async(&mut self, v: f64) -> Result<()>;
141 async fn write_f32_async(&mut self, v: f32) -> Result<()>;
143
144 async fn write_bool_async(&mut self, v: bool) -> Result<()>;
146
147 async fn write_slice_async(&mut self, v: &[u8]) -> Result<()>;
149}
150
151#[async_trait]
153pub trait AsyncReadExt {
154 async fn read_u128_async(&mut self) -> Result<u128>;
156 async fn read_u64_async(&mut self) -> Result<u64>;
158 async fn read_u32_async(&mut self) -> Result<u32>;
160 async fn read_u16_async(&mut self) -> Result<u16>;
162 async fn read_u8_async(&mut self) -> Result<u8>;
164
165 async fn read_i128_async(&mut self) -> Result<i128>;
167 async fn read_i64_async(&mut self) -> Result<i64>;
169 async fn read_i32_async(&mut self) -> Result<i32>;
171 async fn read_i16_async(&mut self) -> Result<i16>;
173 async fn read_i8_async(&mut self) -> Result<i8>;
175
176 async fn read_f64_async(&mut self) -> Result<f64>;
178 async fn read_f32_async(&mut self) -> Result<f32>;
180
181 async fn read_bool_async(&mut self) -> Result<bool>;
183
184 async fn read_slice_async(&mut self, slice: &mut [u8]) -> Result<()>;
186}
187
188#[async_trait]
189impl<W: AsyncWrite + Unpin + Send> AsyncWriteExt for W {
190 #[inline]
191 async fn write_u128_async(&mut self, v: u128) -> Result<()> {
192 self.write_all(&endian::u128_to_array_le(v)).await
193 }
194
195 #[inline]
196 async fn write_u64_async(&mut self, v: u64) -> Result<()> {
197 self.write_all(&endian::u64_to_array_le(v)).await
198 }
199
200 #[inline]
201 async fn write_u32_async(&mut self, v: u32) -> Result<()> {
202 self.write_all(&endian::u32_to_array_le(v)).await
203 }
204
205 #[inline]
206 async fn write_u16_async(&mut self, v: u16) -> Result<()> {
207 self.write_all(&endian::u16_to_array_le(v)).await
208 }
209
210 #[inline]
211 async fn write_u8_async(&mut self, v: u8) -> Result<()> {
212 self.write_all(&[v]).await
213 }
214
215 #[inline]
216 async fn write_i128_async(&mut self, v: i128) -> Result<()> {
217 self.write_all(&endian::i128_to_array_le(v)).await
218 }
219
220 #[inline]
221 async fn write_i64_async(&mut self, v: i64) -> Result<()> {
222 self.write_all(&endian::i64_to_array_le(v)).await
223 }
224
225 #[inline]
226 async fn write_i32_async(&mut self, v: i32) -> Result<()> {
227 self.write_all(&endian::i32_to_array_le(v)).await
228 }
229
230 #[inline]
231 async fn write_i16_async(&mut self, v: i16) -> Result<()> {
232 self.write_all(&endian::i16_to_array_le(v)).await
233 }
234
235 #[inline]
236 async fn write_i8_async(&mut self, v: i8) -> Result<()> {
237 self.write_all(&[v as u8]).await
238 }
239
240 #[inline]
241 async fn write_f64_async(&mut self, v: f64) -> Result<()> {
242 self.write_all(&endian::f64_to_array_le(v)).await
243 }
244
245 #[inline]
246 async fn write_f32_async(&mut self, v: f32) -> Result<()> {
247 self.write_all(&endian::f32_to_array_le(v)).await
248 }
249
250 #[inline]
251 async fn write_bool_async(&mut self, v: bool) -> Result<()> {
252 self.write_all(&[v as u8]).await
253 }
254
255 #[inline]
256 async fn write_slice_async(&mut self, v: &[u8]) -> Result<()> {
257 self.write_all(v).await
258 }
259}
260
261#[async_trait]
262impl<R: AsyncRead + Unpin + Send> AsyncReadExt for R {
263 #[inline]
264 async fn read_u128_async(&mut self) -> Result<u128> {
265 let mut val = [0; 16];
266 self.read_exact(&mut val[..]).await?;
267 Ok(endian::slice_to_u128_le(&val))
268 }
269
270 #[inline]
271 async fn read_u64_async(&mut self) -> Result<u64> {
272 let mut val = [0; 8];
273 self.read_exact(&mut val[..]).await?;
274 Ok(endian::slice_to_u64_le(&val))
275 }
276
277 #[inline]
278 async fn read_u32_async(&mut self) -> Result<u32> {
279 let mut val = [0; 4];
280 self.read_exact(&mut val[..]).await?;
281 Ok(endian::slice_to_u32_le(&val))
282 }
283
284 #[inline]
285 async fn read_u16_async(&mut self) -> Result<u16> {
286 let mut val = [0; 2];
287 self.read_exact(&mut val[..]).await?;
288 Ok(endian::slice_to_u16_le(&val))
289 }
290
291 #[inline]
292 async fn read_u8_async(&mut self) -> Result<u8> {
293 let mut val = [0; 1];
294 self.read_exact(&mut val[..]).await?;
295 Ok(val[0])
296 }
297
298 #[inline]
299 async fn read_i128_async(&mut self) -> Result<i128> {
300 let mut val = [0; 16];
301 self.read_exact(&mut val[..]).await?;
302 Ok(endian::slice_to_i128_le(&val))
303 }
304
305 #[inline]
306 async fn read_i64_async(&mut self) -> Result<i64> {
307 let mut val = [0; 8];
308 self.read_exact(&mut val[..]).await?;
309 Ok(endian::slice_to_i64_le(&val))
310 }
311
312 #[inline]
313 async fn read_i32_async(&mut self) -> Result<i32> {
314 let mut val = [0; 4];
315 self.read_exact(&mut val[..]).await?;
316 Ok(endian::slice_to_i32_le(&val))
317 }
318
319 #[inline]
320 async fn read_i16_async(&mut self) -> Result<i16> {
321 let mut val = [0; 2];
322 self.read_exact(&mut val[..]).await?;
323 Ok(endian::slice_to_i16_le(&val))
324 }
325
326 #[inline]
327 async fn read_i8_async(&mut self) -> Result<i8> {
328 let mut val = [0; 1];
329 self.read_exact(&mut val[..]).await?;
330 Ok(val[0] as i8)
331 }
332
333 #[inline]
334 async fn read_f64_async(&mut self) -> Result<f64> {
335 let mut val = [0; 8];
336 self.read_exact(&mut val[..]).await?;
337 Ok(endian::slice_to_f64_le(&val))
338 }
339
340 #[inline]
341 async fn read_f32_async(&mut self) -> Result<f32> {
342 let mut val = [0; 4];
343 self.read_exact(&mut val[..]).await?;
344 Ok(endian::slice_to_f32_le(&val))
345 }
346
347 #[inline]
348 async fn read_bool_async(&mut self) -> Result<bool> {
349 AsyncReadExt::read_i8_async(self).await.map(|bit| bit != 0)
350 }
351
352 #[inline]
353 async fn read_slice_async(&mut self, slice: &mut [u8]) -> Result<()> {
354 self.read_exact(slice).await
355 }
356}
357
358macro_rules! impl_int_encodable {
359 ($ty:ident, $meth_dec:ident, $meth_enc:ident) => {
360 #[async_trait]
361 impl AsyncDecodable for $ty {
362 #[inline]
363 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
364 AsyncReadExt::$meth_dec(d).await.map($ty::from_le)
365 }
366 }
367
368 #[async_trait]
369 impl AsyncEncodable for $ty {
370 #[inline]
371 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
372 s.$meth_enc(self.to_le()).await?;
373 Ok(core::mem::size_of::<$ty>())
374 }
375 }
376 };
377}
378
379impl_int_encodable!(u8, read_u8_async, write_u8_async);
380impl_int_encodable!(u16, read_u16_async, write_u16_async);
381impl_int_encodable!(u32, read_u32_async, write_u32_async);
382impl_int_encodable!(u64, read_u64_async, write_u64_async);
383impl_int_encodable!(u128, read_u128_async, write_u128_async);
384
385impl_int_encodable!(i8, read_i8_async, write_i8_async);
386impl_int_encodable!(i16, read_i16_async, write_i16_async);
387impl_int_encodable!(i32, read_i32_async, write_i32_async);
388impl_int_encodable!(i64, read_i64_async, write_i64_async);
389impl_int_encodable!(i128, read_i128_async, write_i128_async);
390
391macro_rules! tuple_encode {
392 ($($x:ident),*) => (
393 #[async_trait]
394 impl<$($x: AsyncEncodable + Sync),*> AsyncEncodable for ($($x),*) {
395 #[inline]
396 #[allow(non_snake_case)]
397 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
398 let &($(ref $x),*) = self;
399 let mut len = 0;
400 $(len += $x.encode_async(s).await?;)*
401 Ok(len)
402 }
403 }
404
405 #[async_trait]
406 impl<$($x: AsyncDecodable + Send),*> AsyncDecodable for ($($x),*) {
407 #[inline]
408 #[allow(non_snake_case)]
409 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
410 Ok(($({let $x = AsyncDecodable::decode_async(d).await?; $x }),*))
411 }
412 }
413 )
414}
415
416tuple_encode!(T0, T1);
417tuple_encode!(T0, T1, T2);
418tuple_encode!(T0, T1, T2, T3);
419tuple_encode!(T0, T1, T2, T3, T4);
420tuple_encode!(T0, T1, T2, T3, T4, T5);
421tuple_encode!(T0, T1, T2, T3, T4, T5, T6);
422tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
423
424#[macro_export]
426macro_rules! encode_payload_async {
427 ($buf:expr, $($args:expr),*) => {{ $( $args.encode_async($buf).await?;)* }}
428}
429
430#[async_trait]
431impl AsyncEncodable for VarInt {
432 #[inline]
433 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
434 match self.0 {
435 0..=0xFC => {
436 (self.0 as u8).encode_async(s).await?;
437 Ok(1)
438 }
439
440 0xFD..=0xFFFF => {
441 s.write_u8_async(0xFD).await?;
442 (self.0 as u16).encode_async(s).await?;
443 Ok(3)
444 }
445
446 0x10000..=0xFFFFFFFF => {
447 s.write_u8_async(0xFE).await?;
448 (self.0 as u32).encode_async(s).await?;
449 Ok(5)
450 }
451
452 _ => {
453 s.write_u8_async(0xFF).await?;
454 self.0.encode_async(s).await?;
455 Ok(9)
456 }
457 }
458 }
459}
460
461#[async_trait]
462impl AsyncDecodable for VarInt {
463 #[inline]
464 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
465 let n = AsyncReadExt::read_u8_async(d).await?;
466 match n {
467 0xFF => {
468 let x = AsyncReadExt::read_u64_async(d).await?;
469 if x < 0x100000000 {
470 return Err(Error::other("Non-minimal VarInt"))
471 }
472 Ok(VarInt(x))
473 }
474
475 0xFE => {
476 let x = AsyncReadExt::read_u32_async(d).await?;
477 if x < 0x10000 {
478 return Err(Error::other("Non-minimal VarInt"))
479 }
480 Ok(VarInt(x as u64))
481 }
482
483 0xFD => {
484 let x = AsyncReadExt::read_u16_async(d).await?;
485 if x < 0xFD {
486 return Err(Error::other("Non-minimal VarInt"))
487 }
488 Ok(VarInt(x as u64))
489 }
490
491 n => Ok(VarInt(n as u64)),
492 }
493 }
494}
495
496#[async_trait]
498impl AsyncEncodable for usize {
499 #[inline]
500 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
501 s.write_u64_async(*self as u64).await?;
502 Ok(8)
503 }
504}
505
506#[async_trait]
507impl AsyncDecodable for usize {
508 #[inline]
509 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
510 Ok(AsyncReadExt::read_u64_async(d).await? as usize)
511 }
512}
513
514#[async_trait]
515impl AsyncEncodable for f64 {
516 #[inline]
517 async fn encode_async<S: AsyncWriteExt + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
518 s.write_f64_async(*self).await?;
519 Ok(core::mem::size_of::<f64>())
520 }
521}
522
523#[async_trait]
524impl AsyncDecodable for f64 {
525 #[inline]
526 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
527 AsyncReadExt::read_f64_async(d).await
528 }
529}
530
531#[async_trait]
532impl AsyncEncodable for f32 {
533 #[inline]
534 async fn encode_async<S: AsyncWriteExt + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
535 s.write_f32_async(*self).await?;
536 Ok(core::mem::size_of::<f32>())
537 }
538}
539
540#[async_trait]
541impl AsyncDecodable for f32 {
542 #[inline]
543 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
544 AsyncReadExt::read_f32_async(d).await
545 }
546}
547
548#[async_trait]
549impl AsyncEncodable for bool {
550 #[inline]
551 async fn encode_async<S: AsyncWriteExt + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
552 s.write_bool_async(*self).await?;
553 Ok(1)
554 }
555}
556
557#[async_trait]
558impl AsyncDecodable for bool {
559 #[inline]
560 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
561 AsyncReadExt::read_bool_async(d).await
562 }
563}
564
565#[async_trait]
566impl<T: AsyncEncodable + Sync> AsyncEncodable for Vec<T> {
567 #[inline]
568 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
569 let mut len = 0;
570 len += VarInt(self.len() as u64).encode_async(s).await?;
571 for val in self {
572 len += val.encode_async(s).await?;
573 }
574 Ok(len)
575 }
576}
577
578#[async_trait]
579impl<T: AsyncDecodable + Send> AsyncDecodable for Vec<T> {
580 #[inline]
581 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
582 let len = VarInt::decode_async(d).await?.0;
583 let mut ret = Vec::new();
584 ret.try_reserve(len as usize).map_err(|_| std::io::ErrorKind::InvalidData)?;
585 for _ in 0..len {
586 ret.push(AsyncDecodable::decode_async(d).await?);
587 }
588 Ok(ret)
589 }
590}
591
592#[async_trait]
593impl<T: AsyncEncodable + Sync> AsyncEncodable for VecDeque<T> {
594 #[inline]
595 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
596 let mut len = 0;
597 len += VarInt(self.len() as u64).encode_async(s).await?;
598 for val in self {
599 len += val.encode_async(s).await?;
600 }
601 Ok(len)
602 }
603}
604
605#[async_trait]
606impl<T: AsyncDecodable + Send> AsyncDecodable for VecDeque<T> {
607 #[inline]
608 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
609 let len = VarInt::decode_async(d).await?.0;
610 let mut ret = VecDeque::new();
611 ret.try_reserve(len as usize).map_err(|_| std::io::ErrorKind::InvalidData)?;
612 for _ in 0..len {
613 ret.push_back(AsyncDecodable::decode_async(d).await?);
614 }
615 Ok(ret)
616 }
617}
618
619#[async_trait]
620impl<T: AsyncEncodable + Sync> AsyncEncodable for Option<T> {
621 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
622 let mut len = 0;
623 if let Some(v) = self {
624 len += true.encode_async(s).await?;
625 len += v.encode_async(s).await?;
626 } else {
627 len += false.encode_async(s).await?;
628 }
629 Ok(len)
630 }
631}
632
633#[async_trait]
634impl<T: AsyncDecodable> AsyncDecodable for Option<T> {
635 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
636 let valid: bool = AsyncDecodable::decode_async(d).await?;
637 let val = if valid { Some(AsyncDecodable::decode_async(d).await?) } else { None };
638 Ok(val)
639 }
640}
641
642#[async_trait]
643impl<T, const N: usize> AsyncEncodable for [T; N]
644where
645 T: AsyncEncodable + Sync,
646{
647 #[inline]
648 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
649 let mut len = 0;
650 for elem in self.iter() {
651 len += elem.encode_async(s).await?;
652 }
653
654 Ok(len)
655 }
656}
657
658#[async_trait]
659impl<T, const N: usize> AsyncDecodable for [T; N]
660where
661 T: AsyncDecodable + Send + core::fmt::Debug,
662{
663 #[inline]
664 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
665 let mut ret = vec![];
666 for _ in 0..N {
667 ret.push(AsyncDecodable::decode_async(d).await?);
668 }
669
670 Ok(ret.try_into().unwrap())
671 }
672}
673
674#[async_trait]
675impl AsyncEncodable for String {
676 #[inline]
677 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
678 let b = self.as_bytes();
679 let b_len = b.len();
680 let vi_len = VarInt(b_len as u64).encode_async(s).await?;
681 s.write_slice_async(b).await?;
682 Ok(vi_len + b_len)
683 }
684}
685
686#[async_trait]
687impl AsyncEncodable for &str {
688 #[inline]
689 async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
690 let b = self.as_bytes();
691 let b_len = b.len();
692 let vi_len = VarInt(b_len as u64).encode_async(s).await?;
693 s.write_slice_async(b).await?;
694 Ok(vi_len + b_len)
695 }
696}
697
698#[async_trait]
699impl AsyncDecodable for String {
700 #[inline]
701 async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<String> {
702 match String::from_utf8(AsyncDecodable::decode_async(d).await?) {
703 Ok(v) => Ok(v),
704 Err(_) => Err(Error::other("Invalid UTF-8 for string")),
705 }
706 }
707}