Advertisement
niedzwiedzw

Untitled

Jan 9th, 2023
1,555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.06 KB | None | 0 0
  1. pub struct PacketReader<'reader, R> {
  2.    pub reader: &'reader mut R,
  3.     pub buffer: std::vec::Vec<u8>,
  4. }
  5. impl<'reader, R> PacketReader<'reader, R>
  6. where
  7.     R: tokio::io::AsyncRead + Unpin,
  8. {
  9.     pub fn new(reader: &'reader mut R) -> Self {
  10.        Self {
  11.            reader,
  12.            buffer: Default::default(),
  13.        }
  14.    }
  15.    pub async fn read<T>(&mut self) -> Result<PaddedMessage<T>>
  16.    where
  17.        T: Serialize + DeserializeOwned,
  18.    {
  19.        let size = self.reader.read_u32().await?;
  20.        let buffer_size = size as usize;
  21.  
  22.        assert_eq!(
  23.            buffer_size as u32, size,
  24.            "packet too large for this architecture..."
  25.        );
  26.        self.buffer.resize(buffer_size, 0);
  27.        let _ = self
  28.            .reader
  29.            .read_exact(&mut self.buffer)
  30.            .await
  31.            .wrap_err_with(|| format!("reading the expected data of size {size}"))?;
  32.        let value = from_bytes::<T>(&mut self.buffer).wrap_err("deserializing packet data")?;
  33.        Ok(PaddedMessage { size, value })
  34.    }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement