Skip to main content

open_dis_rust/
pdu.rs

1//     open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
2//                     Simulation (DIS) application protocol
3//     Copyright (C) 2026 Cameron Howell
4//
5//     Licensed under the BSD 2-Clause License
6
7use super::{
8    constants::PDU_HEADER_SIZE, dis_error::DISError, live_entity_records::LiveEntityPduHeader,
9    records::PduHeader,
10};
11use crate::siso::enums::{PduType, ProtocolFamily};
12use std::fmt::Debug;
13
14/// A DIS Protocol Data Unit
15///
16/// Something that can be encoded to and decoded from the bytes of the
17/// DIS wire format
18pub trait Pdu {
19    /// The PDU's header: [`PduHeader`] for most PDUs, or [`LiveEntityPduHeader`] for the
20    /// Live Entity Information/Interaction family. [`StandardPdu`] and [`LiveEntityPdu`]
21    /// represent the two variants.
22    type Header: Copy + Debug + Default + PartialEq + Eq;
23
24    /// The PDU's type. It is fixed for each PDU struct, and `serialize` writes it into
25    /// the header.
26    fn pdu_type(&self) -> PduType;
27
28    /// The PDU's protocol family. It is fixed for each PDU struct, and `serialize` writes
29    /// it into the header.
30    fn protocol_family(&self) -> ProtocolFamily;
31
32    /// The PDU's total encoded length in octets, header included
33    /// # Errors
34    ///
35    /// Will return `DISError` if the calculated PDU length is greater than the maximum allowed size
36    fn calculate_length(&self) -> Result<u16, DISError>;
37
38    /// The PDU's header.
39    fn header(&self) -> &Self::Header;
40    /// A mutable reference to the PDU's header to change its exercise ID, timestamp, or status.
41    fn header_mut(&mut self) -> &mut Self::Header;
42
43    /// Runs the PDU's update rules and sets the header's length without encoding it.
44    /// Errors are ignored here; [`serialize`](Pdu::serialize) reports them.
45    fn finalize(&mut self);
46
47    /// Encodes the PDU and appends it to `buf`
48    ///
49    /// Before encoding, this sets the header's PDU type, protocol family, and length
50    /// along with every count, length, and flag field that depends on the PDU's contents.
51    /// Anything already in `buf` is kept, so several PDUs can be written into one buffer.
52    ///
53    /// # Errors
54    ///
55    /// Will return `DISError` if serialization fails, especially if the dynamically calculated PDU
56    /// length is greater than the maximum allowed size
57    fn serialize(&mut self, buf: &mut Vec<u8>) -> Result<(), DISError>;
58
59    /// Encodes the PDU into a new buffer
60    ///
61    /// # Errors
62    ///
63    /// Will return `DISError` in the same case as [`serialize`](Pdu::serialize).
64    fn to_bytes(&mut self) -> Result<Vec<u8>, DISError> {
65        let mut buf = Vec::new();
66        self.serialize(&mut buf)?;
67        Ok(buf)
68    }
69
70    /// Decodes one PDU from the front of `buf`, advancing `buf` past it
71    ///
72    /// Exactly the number of octets given by the header's length field
73    /// are consumed, so anything after them, such as another bundled PDU,
74    /// is left in `buf`.
75    ///
76    /// # Errors
77    ///
78    /// Will return `DISError` if `buf` does not start with a valid PDU
79    fn deserialize(buf: &mut &[u8]) -> Result<Self, DISError>
80    where
81        Self: Sized;
82
83    /// Decodes a PDU body from the front of `buf` using a header that has
84    /// already been deserialized.
85    ///
86    /// # Errors
87    ///
88    /// Will return `DISError` if the PDU header provided is invalid
89    fn deserialize_without_header(
90        buf: &mut &[u8],
91        pdu_header: Self::Header,
92    ) -> Result<Self, DISError>
93    where
94        Self: Sized;
95}
96
97/// A PDU with the standard 12-octet [`PduHeader`], which carries a [`PduStatus`](crate::records::PduStatus) record.
98/// Every PDU outside the Live Entity Information/Interaction family is one.
99///
100/// It is implemented for every `Pdu<Header = PduHeader>`, so it is a shorter way to write
101/// that bound:
102///
103/// ```
104/// use open_dis_rust::prelude::*;
105///
106/// fn set_exercise(pdu: &mut impl StandardPdu, exercise_id: ExerciseIdentifier) {
107///     pdu.header_mut().exercise_id = exercise_id;
108/// }
109/// ```
110pub trait StandardPdu: Pdu<Header = PduHeader> {}
111
112impl<T: Pdu<Header = PduHeader> + ?Sized> StandardPdu for T {}
113
114/// A PDU of the Live Entity Information/Interaction family, whose
115/// [`LiveEntityPduHeader`] has a subprotocol number where other PDUs have
116/// their PDU Status record.
117///
118/// It is implemented for every `Pdu<Header = LiveEntityPduHeader>`. A function that takes
119/// one does not accept standard PDUs:
120///
121/// ```compile_fail
122/// use open_dis_rust::{entity_information::EntityStatePdu, prelude::*};
123///
124/// fn subprotocol(pdu: &impl LiveEntityPdu) {}
125/// subprotocol(&EntityStatePdu::new());
126/// ```
127pub trait LiveEntityPdu: Pdu<Header = LiveEntityPduHeader> {}
128
129impl<T: Pdu<Header = LiveEntityPduHeader> + ?Sized> LiveEntityPdu for T {}
130
131/// The header fields that encoding sets from the PDU. Private to the crate so that
132/// those fields stay read-only for users.
133pub trait DerivedFields {
134    #[cfg(test)]
135    fn length(&self) -> u16;
136    fn set_pdu_type(&mut self, value: PduType);
137    fn set_protocol_family(&mut self, value: ProtocolFamily);
138    fn set_length(&mut self, value: u16);
139}
140
141pub fn total_length(header_len: usize, body_len: usize) -> Result<u16, DISError> {
142    use crate::constants::MAX_PDU_SIZE_OCTETS;
143    let size = header_len.saturating_add(body_len);
144    u16::try_from(size)
145        .ok()
146        .filter(|_| size <= MAX_PDU_SIZE_OCTETS)
147        .ok_or(DISError::PduSizeExceeded {
148            size,
149            max_size: MAX_PDU_SIZE_OCTETS,
150        })
151}
152
153/// Encodes `header` followed by `body` onto the end of `buf`, then rewrites the
154/// header with the PDU's real length. `buf` is restored if anything fails.
155pub fn write_pdu<H, B>(header: &mut H, body: &B, buf: &mut Vec<u8>) -> Result<(), DISError>
156where
157    H: DerivedFields + deku::DekuWriter<()>,
158    B: deku::DekuWriter<()>,
159{
160    let start = buf.len();
161    let result = (|| {
162        crate::wire::write(&*header, buf).map_err(DISError::from_wire)?;
163        crate::wire::write(body, buf).map_err(DISError::from_wire)?;
164        let body_len = buf
165            .len()
166            .saturating_sub(start)
167            .saturating_sub(PDU_HEADER_SIZE);
168        let length = total_length(PDU_HEADER_SIZE, body_len)?;
169        header.set_length(length);
170
171        let mut encoded = Vec::with_capacity(PDU_HEADER_SIZE);
172        crate::wire::write(&*header, &mut encoded).map_err(DISError::from_wire)?;
173        buf.get_mut(start..start.saturating_add(encoded.len()))
174            .ok_or_else(|| DISError::serialization_error("PDU header was not written", None))?
175            .copy_from_slice(&encoded);
176        Ok(())
177    })();
178    if result.is_err() {
179        buf.truncate(start);
180    }
181    result
182}
183
184pub fn take_body<'a>(
185    buf: &mut &'a [u8],
186    declared_len: u16,
187    header_len: usize,
188) -> Result<&'a [u8], DISError> {
189    let body_len = usize::from(declared_len)
190        .checked_sub(header_len)
191        .ok_or_else(|| {
192            DISError::invalid_header(
193                format!("PDU length {declared_len} is shorter than its {header_len}-octet header"),
194                None,
195            )
196        })?;
197    let (body, rest) = buf
198        .split_at_checked(body_len)
199        .ok_or_else(|| DISError::buffer_underflow(body_len, buf.len()))?;
200    *buf = rest;
201    Ok(body)
202}
203
204pub fn check_body_used(body: &[u8], declared_len: u16) -> Result<(), DISError> {
205    if body.is_empty() {
206        Ok(())
207    } else {
208        Err(DISError::deserialization_error(
209            format!(
210                "PDU length {declared_len} is {} octets longer than its fields",
211                body.len()
212            ),
213            None,
214        ))
215    }
216}
217
218macro_rules! impl_pdu {
219    ($name:ty, $header:ty, $pdu_type:expr, $family:expr $(,)?) => {
220        impl $crate::pdu::Pdu for $name {
221            type Header = $header;
222
223            fn pdu_type(&self) -> $crate::siso::enums::PduType {
224                $pdu_type
225            }
226
227            fn protocol_family(&self) -> $crate::siso::enums::ProtocolFamily {
228                $family
229            }
230
231            fn calculate_length(&self) -> Result<u16, $crate::DISError> {
232                let body = $crate::wire::encoded_len(self).map_err($crate::DISError::from_wire)?;
233                $crate::pdu::total_length($crate::constants::PDU_HEADER_SIZE, body)
234            }
235
236            fn header(&self) -> &Self::Header {
237                &self.header
238            }
239
240            fn header_mut(&mut self) -> &mut Self::Header {
241                &mut self.header
242            }
243
244            /// Run the update rules and set the header length. Errors are
245            /// ignored here; `serialize` reports them.
246            fn finalize(&mut self) {
247                let _ = deku::DekuUpdate::update(self);
248                let length = self.calculate_length().unwrap_or_default();
249                $crate::pdu::DerivedFields::set_length(&mut self.header, length);
250            }
251
252            fn serialize(&mut self, buf: &mut Vec<u8>) -> Result<(), $crate::DISError> {
253                $crate::pdu::DerivedFields::set_pdu_type(&mut self.header, $pdu_type);
254                $crate::pdu::DerivedFields::set_protocol_family(&mut self.header, $family);
255                deku::DekuUpdate::update(self).map_err($crate::DISError::from_wire)?;
256                let mut header = self.header;
257                $crate::pdu::write_pdu(&mut header, &*self, buf)?;
258                self.header = header;
259                Ok(())
260            }
261
262            fn deserialize(buf: &mut &[u8]) -> Result<Self, $crate::DISError>
263            where
264                Self: Sized,
265            {
266                let header: $header =
267                    $crate::wire::read(buf).map_err($crate::DISError::from_wire)?;
268                let found = header.pdu_type();
269                if found != $pdu_type {
270                    return Err($crate::DISError::invalid_header(
271                        format!("expected PDU type {:?}, got {found:?}", $pdu_type),
272                        None,
273                    ));
274                }
275                Self::deserialize_without_header(buf, header)
276            }
277
278            fn deserialize_without_header(
279                buf: &mut &[u8],
280                header: Self::Header,
281            ) -> Result<Self, $crate::DISError>
282            where
283                Self: Sized,
284            {
285                let declared = header.length();
286                let mut body =
287                    $crate::pdu::take_body(buf, declared, $crate::constants::PDU_HEADER_SIZE)?;
288                let mut pdu: Self =
289                    $crate::wire::read(&mut body).map_err($crate::DISError::from_wire)?;
290                $crate::pdu::check_body_used(body, declared)?;
291                pdu.header = header;
292                Ok(pdu)
293            }
294        }
295
296        impl $name {
297            /// A default PDU with its header's type, family and length set.
298            #[must_use]
299            pub fn new() -> Self {
300                let mut pdu = Self::default();
301                $crate::pdu::DerivedFields::set_pdu_type(&mut pdu.header, $pdu_type);
302                $crate::pdu::DerivedFields::set_protocol_family(&mut pdu.header, $family);
303                $crate::pdu::Pdu::finalize(&mut pdu);
304                pdu
305            }
306        }
307    };
308}
309
310#[cfg(test)]
311macro_rules! pdu_tests {
312    (
313           $mod_name:ident, $pdu:ty,
314           pdu_type: $pdu_type:expr,
315           default_bits: $default_bits:expr,
316           wrong_type: $other:ty $(,)?
317       ) => {
318        mod $mod_name {
319            use super::*;
320
321            #[test]
322            fn decodes_as_any_pdu() {
323                let mut pdu = <$pdu>::new();
324                let original = to_bytes(&mut pdu);
325
326                let mut decoded = $crate::AnyPdu::deserialize(&mut original.as_slice())
327                    .expect("deserialize failed");
328
329                assert_eq!(decoded.pdu_type(), $pdu_type);
330                assert_eq!(decoded.to_bytes().expect("serialize failed"), original);
331            }
332
333            #[test]
334            fn new_sets_pdu_type() {
335                let pdu = <$pdu>::new();
336                assert_eq!(pdu.header().pdu_type(), $pdu_type);
337                assert_eq!(pdu.pdu_type(), $pdu_type);
338            }
339
340            #[test]
341            fn new_sets_default_length() {
342                const DEFAULT_LENGTH: u16 = $default_bits / $crate::wire::BITS_PER_BYTE;
343                let pdu = <$pdu>::new();
344                assert_eq!(pdu.header().length, DEFAULT_LENGTH);
345            }
346
347            #[test]
348            fn serialized_length_matches_header() {
349                let mut pdu = <$pdu>::new();
350                let bytes = to_bytes(&mut pdu);
351                assert_eq!(bytes.len(), usize::from(pdu.header().length));
352            }
353
354            #[test]
355            fn round_trip_is_byte_identical() {
356                let mut pdu = <$pdu>::new();
357                let original = to_bytes(&mut pdu);
358
359                let mut buf: &[u8] = &original;
360                let mut decoded = <$pdu>::deserialize(&mut buf).expect("deserialize failed");
361
362                assert!(buf.is_empty(), "deserialize left bytes unread");
363                assert_eq!(decoded.header, pdu.header);
364                assert_eq!(to_bytes(&mut decoded), original);
365            }
366
367            #[test]
368            fn rejects_wrong_pdu_type() {
369                let mut other = <$other>::new();
370                let bytes = to_bytes(&mut other);
371                assert!(<$pdu>::deserialize(&mut bytes.as_slice()).is_err());
372            }
373        }
374    };
375}
376
377pub(crate) use impl_pdu;
378#[cfg(test)]
379pub(crate) use pdu_tests;
380
381#[cfg(test)]
382mod tests {
383    use super::*;
384    use crate::{
385        LiveEntityPdu, StandardPdu,
386        entity_information::EntityStatePdu,
387        live_entity_information::TimeSpacePositionInformationPdu,
388        records::{ExerciseIdentifier, VariableDatumRecord},
389        simulation_management::{AcknowledgePdu, CommentPdu},
390        siso::enums::PduType,
391    };
392
393    fn exercise_of(pdu: &impl StandardPdu) -> ExerciseIdentifier {
394        pdu.header().exercise_id
395    }
396
397    fn subprotocol_of(
398        pdu: &impl LiveEntityPdu,
399    ) -> crate::siso::enums::DISLiveEntitySubprotocolNumber {
400        pdu.header().subprotocol_number
401    }
402
403    #[test]
404    fn pdus_are_told_apart_by_their_header() {
405        assert_eq!(
406            exercise_of(&EntityStatePdu::new()),
407            ExerciseIdentifier::new(1)
408        );
409        let tspi = TimeSpacePositionInformationPdu::new();
410        assert_eq!(subprotocol_of(&tspi), tspi.header().subprotocol_number);
411    }
412
413    #[test]
414    fn standard_pdus_can_be_trait_objects() {
415        let mut pdus: Vec<Box<dyn StandardPdu>> = vec![
416            Box::new(EntityStatePdu::new()),
417            Box::new(AcknowledgePdu::new()),
418        ];
419        let types: Vec<PduType> = pdus.iter().map(|pdu| pdu.pdu_type()).collect();
420        assert_eq!(types, [PduType::EntityState, PduType::Acknowledge]);
421        let mut buf = Vec::new();
422        for pdu in &mut pdus {
423            pdu.serialize(&mut buf).unwrap();
424        }
425        assert_eq!(buf.len(), 144 + 32);
426    }
427
428    #[test]
429    fn pdu_type_and_family_are_known_before_encoding() {
430        let pdu = TimeSpacePositionInformationPdu::default();
431        assert_eq!(pdu.pdu_type(), PduType::TimeSpacePositionInformation);
432        assert_eq!(
433            pdu.protocol_family(),
434            crate::siso::enums::ProtocolFamily::LiveEntityInformationInteraction
435        );
436    }
437
438    #[test]
439    fn serialize_appends_to_existing_contents() {
440        let mut buf = vec![0xAA, 0xBB];
441        let mut pdu = AcknowledgePdu::new();
442        pdu.serialize(&mut buf).unwrap();
443        assert_eq!(buf.get(..2), Some(&[0xAA, 0xBB][..]));
444        assert_eq!(buf.len(), 2 + usize::from(pdu.header().length));
445        assert_eq!(buf.get(2..), Some(pdu.to_bytes().unwrap().as_slice()));
446    }
447
448    #[test]
449    fn serialize_leaves_buffer_unchanged_on_error() {
450        let mut pdu = CommentPdu::new();
451        for i in 0..9 {
452            pdu.variable_datum_records.push(VariableDatumRecord {
453                datum_id: i,
454                length_bits: 8000,
455                value: vec![0; 1000],
456            });
457        }
458        let mut buf = vec![1, 2, 3];
459        assert!(matches!(
460            pdu.serialize(&mut buf),
461            Err(DISError::PduSizeExceeded { .. })
462        ));
463        assert_eq!(buf, [1, 2, 3]);
464    }
465
466    #[test]
467    fn deserialize_reads_one_pdu_and_leaves_the_rest() {
468        let mut buf = Vec::new();
469        EntityStatePdu::new().serialize(&mut buf).unwrap();
470        AcknowledgePdu::new().serialize(&mut buf).unwrap();
471
472        let mut rest = buf.as_slice();
473        EntityStatePdu::deserialize(&mut rest).unwrap();
474        assert_eq!(rest.len(), 32);
475        AcknowledgePdu::deserialize(&mut rest).unwrap();
476        assert!(rest.is_empty());
477    }
478
479    #[test]
480    fn wire_format_error_describes_the_problem() {
481        let mut bytes = AcknowledgePdu::new().to_bytes().unwrap();
482        if let Some(version) = bytes.first_mut() {
483            *version = 99;
484        }
485        let err = AcknowledgePdu::deserialize(&mut bytes.as_slice()).unwrap_err();
486        let DISError::WireFormat(inner) = &err else {
487            panic!("expected a wire format error, got {err:?}");
488        };
489        assert!(
490            err.to_string()
491                .contains("99 is not a defined ProtocolVersion value")
492        );
493        assert!(
494            inner
495                .to_string()
496                .contains("99 is not a defined ProtocolVersion value")
497        );
498        // The message is complete on its own; nothing is repeated as a source.
499        assert!(std::error::Error::source(inner).is_none());
500    }
501}