Files
wotbreplay-parser/src/models/data/packet.rs
T

66 lines
1.9 KiB
Rust
Raw Normal View History

2023-04-29 22:17:12 +02:00
use std::io::Read;
use byteorder::{LittleEndian, ReadBytesExt};
use serde::Serialize;
use serde_with::serde_as;
2023-04-29 22:17:12 +02:00
use crate::models::data::payload::Payload;
use crate::result::Result;
2023-05-08 23:39:52 +02:00
use crate::Error;
2023-04-29 22:17:12 +02:00
2023-05-08 23:14:13 +02:00
/// «Packet» is a single traffic message in a replay,
/// packets tell us what is going on during the battle.
#[serde_as]
2023-04-29 22:17:12 +02:00
#[derive(Debug, Serialize)]
pub struct Packet {
2023-05-08 23:14:13 +02:00
/// Replay time, starting from zero.
#[serde(rename = "clock")]
pub clock_secs: f32,
/// Parsed packet payload.
2023-04-29 22:17:12 +02:00
pub payload: Payload,
2023-05-08 23:14:13 +02:00
/// Raw packet payload, excluding the clock and packet type, and including optional subtype.
///
/// This attribute requires the `raw-payload` feature.
#[cfg(feature = "raw-payload")]
#[serde_as(as = "serde_with::hex::Hex")]
pub raw_payload: Vec<u8>,
2023-04-29 22:17:12 +02:00
}
impl Packet {
2023-05-08 23:39:52 +02:00
/// Parse next packet from the reader.
///
/// # Returns
///
/// Parsed packet, or [`None`], when no packets are left.
2023-04-29 22:17:12 +02:00
pub fn from_reader(reader: &mut impl Read) -> Result<Option<Self>> {
2024-01-29 20:05:45 +01:00
let Ok(length) = reader.read_u32::<LittleEndian>() else {
return Ok(None);
};
2023-04-29 22:17:12 +02:00
let type_ = reader.read_u32::<LittleEndian>()?;
2023-05-08 23:14:13 +02:00
let clock_secs = reader.read_f32::<LittleEndian>()?;
let raw_payload = Self::read_raw_payload(reader, length as usize)?;
2023-05-08 23:39:52 +02:00
let payload = Payload::new(type_, &raw_payload).map_err(|source| {
Error::PacketPayloadParsingError {
source: Box::new(source),
type_,
clock_secs,
}
})?;
let this = Self {
2023-05-08 23:14:13 +02:00
clock_secs,
2023-05-08 23:39:52 +02:00
payload,
#[cfg(feature = "raw-payload")]
2023-05-08 23:14:13 +02:00
raw_payload,
};
2023-04-29 22:17:12 +02:00
Ok(Some(this))
}
2023-05-08 23:14:13 +02:00
fn read_raw_payload(reader: &mut impl Read, length: usize) -> Result<Vec<u8>> {
2024-01-29 20:05:45 +01:00
let mut buffer = vec![0; length];
2023-04-29 22:17:12 +02:00
reader.read_exact(&mut buffer)?;
Ok(buffer)
}
}