lazuli_core/net/
input.rs

1//! Module for handling input from a socket. Contains several helper functions for reading data from a socket.
2//! This module also provides functions that return IOResults, which in turn can be used with the ? operator.
3
4use std::{io::Read, mem, net::TcpStream};
5
6use log::trace;
7
8use crate::{PacketHeader, Result, UnknownType};
9
10/// Reads the header of a packet from a TcpStream.
11#[inline]
12pub fn input_header(stream: &mut TcpStream) -> Result<PacketHeader<UnknownType>> {
13    let mut header = [0; mem::size_of::<PacketHeader<UnknownType>>()];
14
15    stream.read_exact(&mut header)?;
16
17    trace!("Read header: {:?}", header);
18
19    let header = unsafe { PacketHeader::from_bytes_unchecked(header.as_slice()) };
20
21    Ok(header)
22}
23
24/// Reads the data of a packet from a TcpStream.
25/// The header type is UnknownType because this method is intended to be used in tandem with input_header,
26/// or any other method that reads from a socket, where the type will be unknown.
27#[inline]
28pub fn input_data(stream: &mut TcpStream, header: &PacketHeader<UnknownType>) -> Result<Vec<u8>> {
29    let mut data = vec![0; header.payload_size as usize];
30
31    trace!("Reading {} bytes of data", header.payload_size);
32
33    // We want the slice of the data, otherwise (at least in my testing) it will keep reading forever.
34    // This is probably wrong, but it works for now.
35    stream.read_exact(&mut data[0..header.payload_size as usize])?;
36
37    trace!("Read data: {:?}", data);
38
39    Ok(data)
40}
41
42/// Verifies the checksum of a packet.
43///
44/// This function is mainly a convenience function for verifying the checksum of a packet.
45/// It runs PacketHeader::verify_checksum, but converts a bool to an IOResult.
46#[inline]
47pub fn verify_checksum(header: &PacketHeader<UnknownType>, data: &[u8]) -> Result<()> {
48    if header.verify_checksum(data) {
49        Ok(())
50    } else {
51        Err(std::io::Error::new(
52            std::io::ErrorKind::InvalidData,
53            "Checksums do not match",
54        ))
55    }
56}