open_dis_rust/common/pdu.rs
1// open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
2// Simulation (DIS) application protocol
3// Copyright (C) 2025 Cameron Howell
4//
5// Licensed under the BSD 2-Clause License
6
7use crate::common::GenericHeader;
8
9use super::dis_error::DISError;
10use bytes::{Buf, BytesMut};
11use std::any::Any;
12
13pub trait Pdu {
14 type Header: GenericHeader + Default;
15
16 /// # Errors
17 ///
18 /// Will return `DISError` if the calculated PDU length is greater than the maximum allowed size
19 fn calculate_length(&self) -> Result<u16, DISError>;
20
21 fn header(&self) -> &Self::Header;
22 fn header_mut(&mut self) -> &mut Self::Header;
23
24 fn finalize(&mut self) {
25 let len = self.calculate_length();
26 self.header_mut().set_length(len.unwrap_or_default());
27 }
28
29 /// # Errors
30 ///
31 /// Will return `DISError` if serialization fails, especially if the dynamically calculated PDU
32 /// length is greater than the maximum allowed size
33 fn serialize(&mut self, buf: &mut BytesMut) -> Result<(), DISError>;
34
35 /// # Errors
36 ///
37 /// Will return `DISError` if the PDU header provided is invalid
38 fn deserialize<B: Buf>(buf: &mut B) -> Result<Self, DISError>
39 where
40 Self: Sized;
41 /// # Errors
42 ///
43 /// Will return `DISError` if the PDU header provided is invalid
44 fn deserialize_without_header<B: Buf>(
45 buffer: &mut B,
46 pdu_header: Self::Header,
47 ) -> Result<Self, DISError>
48 where
49 Self: Sized;
50
51 fn as_any(&self) -> &dyn Any;
52}