Skip to main content

open_dis_rust/
any_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 std::ops::Range;
8
9use num_traits::FromPrimitive;
10
11use crate::{
12    DISError, DISResult,
13    constants::PDU_HEADER_SIZE,
14    pdu::Pdu,
15    records::ExerciseIdentifier,
16    siso::enums::{PduType, ProtocolFamily},
17};
18
19/// The header octet that holds the PDU type, in both kinds of PDU header
20const PDU_TYPE_OCTET: usize = 2;
21/// The header octets that hold the PDU's length, in both kinds of PDU header
22const LENGTH_OCTETS: Range<usize> = 8..10;
23
24/// Defines `AnyPdu` with one variant per PDU, named after its `PduType` variant.
25macro_rules! any_pdu {
26    ($($variant:ident => $module:ident::$pdu:ident,)+) => {
27        /// Any PDU, for decoding datagrams whose PDU type isn't known in advance
28        ///
29        /// Each variant holds one PDU and is named after its [`PduType`]. Decode with
30        /// [`AnyPdu::deserialize`], or [`AnyPdu::deserialize_all`] for a datagram that
31        /// may hold several PDUs, then `match` on the variants you handle:
32        ///
33        /// ```
34        /// use open_dis_rust::{prelude::*, simulation_management::AcknowledgePdu};
35        ///
36        /// # fn main() -> Result<(), DISError> {
37        /// let datagram = AcknowledgePdu::new().to_bytes()?;
38        ///
39        /// match AnyPdu::deserialize(&mut datagram.as_slice())? {
40        ///     AnyPdu::Acknowledge(ack) => println!("acknowledged request {}", ack.request_id),
41        ///     AnyPdu::EntityState(pdu) => println!("entity {:?}", pdu.entity_id),
42        ///     other => println!("ignoring {:?} PDU", other.pdu_type()),
43        /// }
44        /// # Ok(())
45        /// # }
46        /// ```
47        ///
48        /// Every PDU converts into an `AnyPdu` with `From`, so PDUs of different
49        /// types can be kept in one collection and sent with [`AnyPdu::serialize`].
50        ///
51        /// New variants may be added in minor releases, for example for a later
52        /// version of the standard, so a `match` needs a wildcard arm.
53        #[derive(Debug)]
54        #[non_exhaustive]
55        pub enum AnyPdu {
56            $(
57                #[doc = concat!(
58                    "[`", stringify!($pdu), "`](crate::", stringify!($module), "::",
59                    stringify!($pdu), ")"
60                )]
61                $variant(crate::$module::$pdu),
62            )+
63        }
64
65        impl AnyPdu {
66            fn deserialize_as(pdu_type: PduType, buf: &mut &[u8]) -> DISResult<Self> {
67                match pdu_type {
68                    $(
69                        PduType::$variant => {
70                            <crate::$module::$pdu as Pdu>::deserialize(buf).map(Self::$variant)
71                        }
72                    )+
73                    PduType::Other => Err(DISError::invalid_header(
74                        "PDU type 0 (Other) has no defined layout",
75                        None,
76                    )),
77                }
78            }
79
80            /// The PDU's type
81            #[must_use]
82            pub fn pdu_type(&self) -> PduType {
83                match self {
84                    $(Self::$variant(pdu) => pdu.pdu_type(),)+
85                }
86            }
87
88            /// The PDU's protocol family
89            #[must_use]
90            pub fn protocol_family(&self) -> ProtocolFamily {
91                match self {
92                    $(Self::$variant(pdu) => pdu.protocol_family(),)+
93                }
94            }
95
96            /// The exercise the PDU belongs to, from its header
97            #[must_use]
98            pub fn exercise_id(&self) -> ExerciseIdentifier {
99                match self {
100                    $(Self::$variant(pdu) => pdu.header().exercise_id,)+
101                }
102            }
103
104            /// Encodes the PDU and appends it to `buf`, as [`Pdu::serialize`] does.
105            ///
106            /// # Errors
107            ///
108            /// Will return `DISError` in the same cases as [`Pdu::serialize`].
109            pub fn serialize(&mut self, buf: &mut Vec<u8>) -> DISResult<()> {
110                match self {
111                    $(Self::$variant(pdu) => pdu.serialize(buf),)+
112                }
113            }
114        }
115
116        $(
117            impl From<crate::$module::$pdu> for AnyPdu {
118                fn from(pdu: crate::$module::$pdu) -> Self {
119                    Self::$variant(pdu)
120                }
121            }
122        )+
123    };
124}
125
126any_pdu! {
127    EntityState => entity_information::EntityStatePdu,
128    Fire => warfare::FirePdu,
129    Detonation => warfare::DetonationPdu,
130    Collision => entity_information::CollisionPdu,
131    ServiceRequest => logistics::ServiceRequestPdu,
132    ResupplyOffer => logistics::ResupplyOfferPdu,
133    ResupplyReceived => logistics::ResupplyReceivedPdu,
134    ResupplyCancel => logistics::ResupplyCancelPdu,
135    RepairComplete => logistics::RepairCompletePdu,
136    RepairResponse => logistics::RepairResponsePdu,
137    CreateEntity => simulation_management::CreateEntityPdu,
138    RemoveEntity => simulation_management::RemoveEntityPdu,
139    StartResume => simulation_management::StartResumePdu,
140    StopFreeze => simulation_management::StopFreezePdu,
141    Acknowledge => simulation_management::AcknowledgePdu,
142    ActionRequest => simulation_management::ActionRequestPdu,
143    ActionResponse => simulation_management::ActionResponsePdu,
144    DataQuery => simulation_management::DataQueryPdu,
145    SetData => simulation_management::SetDataPdu,
146    Data => simulation_management::DataPdu,
147    EventReport => simulation_management::EventReportPdu,
148    Comment => simulation_management::CommentPdu,
149    ElectromagneticEmissions => distributed_emissions::ElectromagneticEmissionsPdu,
150    Designator => distributed_emissions::DesignatorPdu,
151    Transmitter => radio_communications::TransmitterPdu,
152    Signal => radio_communications::SignalPdu,
153    Receiver => radio_communications::ReceiverPdu,
154    IFF => distributed_emissions::IFFPdu,
155    UnderwaterAcoustic => distributed_emissions::UnderwaterAcousticPdu,
156    SupplementalEmission => distributed_emissions::SupplementalEmissionPdu,
157    IntercomSignal => radio_communications::IntercomSignalPdu,
158    IntercomControl => radio_communications::IntercomControlPdu,
159    AggregateState => entity_management::AggregateStatePdu,
160    IsGroupOf => entity_management::IsGroupOfPdu,
161    TransferOwnership => entity_management::TransferOwnershipPdu,
162    IsPartOf => entity_management::IsPartOfPdu,
163    MinefieldState => minefield::MinefieldStatePdu,
164    MinefieldQuery => minefield::MinefieldQueryPdu,
165    MinefieldData => minefield::MinefieldDataPdu,
166    MinefieldResponseNack => minefield::MinefieldResponseNackPdu,
167    EnvironmentalProcess => synthetic_environment::EnvironmentalProcessPdu,
168    GriddedData => synthetic_environment::GriddedDataPdu,
169    PointObjectState => synthetic_environment::PointObjectStatePdu,
170    LinearObjectState => synthetic_environment::LinearObjectStatePdu,
171    ArealObjectState => synthetic_environment::ArealObjectStatePdu,
172    TimeSpacePositionInformation => live_entity_information::TimeSpacePositionInformationPdu,
173    Appearance => live_entity_information::AppearancePdu,
174    ArticulatedParts => live_entity_information::ArticulatedPartsPdu,
175    LiveEntityFire => live_entity_information::LiveEntityFirePdu,
176    LiveEntityDetonation => live_entity_information::LiveEntityDetonationPdu,
177    CreateEntityReliable => simulation_management_with_reliability::CreateEntityReliablePdu,
178    RemoveEntityReliable => simulation_management_with_reliability::RemoveEntityReliablePdu,
179    StartResumeReliable => simulation_management_with_reliability::StartResumeReliablePdu,
180    StopFreezeReliable => simulation_management_with_reliability::StopFreezeReliablePdu,
181    AcknowledgeReliable => simulation_management_with_reliability::AcknowledgeReliablePdu,
182    ActionRequestReliable => simulation_management_with_reliability::ActionRequestReliablePdu,
183    ActionResponseReliable => simulation_management_with_reliability::ActionResponseReliablePdu,
184    DataQueryReliable => simulation_management_with_reliability::DataQueryReliablePdu,
185    SetDataReliable => simulation_management_with_reliability::SetDataReliablePdu,
186    DataReliable => simulation_management_with_reliability::DataReliablePdu,
187    EventReportReliable => simulation_management_with_reliability::EventReportReliablePdu,
188    CommentReliable => simulation_management_with_reliability::CommentReliablePdu,
189    RecordReliable => simulation_management_with_reliability::RecordReliablePdu,
190    SetRecordReliable => simulation_management_with_reliability::SetRecordReliablePdu,
191    RecordQueryReliable => simulation_management_with_reliability::RecordQueryReliablePdu,
192    CollisionElastic => entity_information::CollisionElasticPdu,
193    EntityStateUpdate => entity_information::EntityStateUpdatePdu,
194    DirectedEnergyFire => warfare::DirectedEnergyFirePdu,
195    EntityDamageStatus => warfare::EntityDamageStatusPdu,
196    InformationOperationsAction => information_operations::InformationOperationsActionPdu,
197    InformationOperationsReport => information_operations::InformationOperationsReportPdu,
198    Attribute => entity_information::AttributePdu,
199}
200
201impl AnyPdu {
202    /// Decodes one PDU of any type from the front of `buf`, advancing `buf` past it
203    ///
204    /// The PDU type in the header picks the PDU to decode. As with
205    /// [`Pdu::deserialize`], exactly the number of octets given by the header's length
206    /// field are consumed, so another bundled PDU after it is left in `buf`. On error,
207    /// `buf` is left unchanged.
208    ///
209    /// # Errors
210    ///
211    /// Will return `DISError` if `buf` is shorter than a header, its PDU type is not a
212    /// defined PDU type, or the rest is not a valid PDU of that type.
213    pub fn deserialize(buf: &mut &[u8]) -> DISResult<Self> {
214        let Some(&octet) = buf.get(PDU_TYPE_OCTET) else {
215            return Err(DISError::buffer_underflow(PDU_HEADER_SIZE, buf.len()));
216        };
217        let pdu_type = PduType::from_u8(octet).ok_or_else(|| {
218            DISError::invalid_header(format!("{octet} is not a defined PDU type"), None)
219        })?;
220
221        let mut rest = *buf;
222        let pdu = Self::deserialize_as(pdu_type, &mut rest)?;
223        *buf = rest;
224        Ok(pdu)
225    }
226
227    /// Decodes every PDU in a datagram, which the standard allows to hold several
228    ///
229    /// Each item is the result of [`AnyPdu::deserialize`] on what is left of the datagram.
230    /// When a PDU cannot be decoded, such as one that is malformed or of a PDU type the
231    /// standard does not define, its error is yielded and decoding carries on after it if
232    /// its header's length field fits in the datagram. Otherwise, the error is the last item.
233    ///
234    /// ```
235    /// use open_dis_rust::{
236    ///     prelude::*,
237    ///     simulation_management::{AcknowledgePdu, CommentPdu},
238    /// };
239    ///
240    /// # fn main() -> Result<(), DISError> {
241    /// let mut datagram = Vec::new();
242    /// AcknowledgePdu::new().serialize(&mut datagram)?;
243    /// CommentPdu::new().serialize(&mut datagram)?;
244    ///
245    /// for pdu in AnyPdu::deserialize_all(&datagram) {
246    ///     println!("{:?}", pdu?.pdu_type());
247    /// }
248    /// # Ok(())
249    /// # }
250    /// ```
251    pub fn deserialize_all(datagram: &[u8]) -> impl Iterator<Item = DISResult<Self>> + '_ {
252        let mut rest = datagram;
253        std::iter::from_fn(move || {
254            if rest.is_empty() {
255                return None;
256            }
257            let result = Self::deserialize(&mut rest);
258            if result.is_err() {
259                rest = skip_pdu(rest).unwrap_or_default();
260            }
261            Some(result)
262        })
263    }
264
265    /// Encodes the PDU into a new buffer, as [`Pdu::to_bytes`] does.
266    ///
267    /// # Errors
268    ///
269    /// Will return `DISError` in the same cases as [`Pdu::serialize`].
270    pub fn to_bytes(&mut self) -> DISResult<Vec<u8>> {
271        let mut buf = Vec::new();
272        self.serialize(&mut buf)?;
273        Ok(buf)
274    }
275}
276
277/// What follows the PDU at the front of `buf`, going by its header's length field, or
278/// `None` if that length is shorter than a header or longer than `buf`.
279fn skip_pdu(buf: &[u8]) -> Option<&[u8]> {
280    let length = <[u8; 2]>::try_from(buf.get(LENGTH_OCTETS)?).ok()?;
281    let length = usize::from(u16::from_be_bytes(length));
282    if length < PDU_HEADER_SIZE {
283        return None;
284    }
285    buf.get(length..)
286}
287
288#[cfg(test)]
289mod tests {
290    #![allow(clippy::unwrap_used, clippy::indexing_slicing)]
291
292    use super::*;
293    use crate::{
294        entity_information::EntityStatePdu,
295        live_entity_information::TimeSpacePositionInformationPdu,
296        simulation_management::{AcknowledgePdu, CommentPdu},
297    };
298
299    fn bytes(pdu: impl Into<AnyPdu>) -> Vec<u8> {
300        pdu.into().to_bytes().unwrap()
301    }
302
303    #[test]
304    fn decodes_standard_and_live_entity_pdus() {
305        let es = bytes(EntityStatePdu::new());
306        let tspi = bytes(TimeSpacePositionInformationPdu::new());
307
308        assert!(matches!(
309            AnyPdu::deserialize(&mut es.as_slice()).unwrap(),
310            AnyPdu::EntityState(_)
311        ));
312        assert!(matches!(
313            AnyPdu::deserialize(&mut tspi.as_slice()).unwrap(),
314            AnyPdu::TimeSpacePositionInformation(_)
315        ));
316    }
317
318    #[test]
319    fn leaves_the_next_pdu_in_the_buffer() {
320        let mut datagram = bytes(AcknowledgePdu::new());
321        let first = datagram.len();
322        datagram.extend(bytes(CommentPdu::new()));
323
324        let mut buf = datagram.as_slice();
325        AnyPdu::deserialize(&mut buf).unwrap();
326        assert_eq!(buf, &datagram[first..]);
327    }
328
329    #[test]
330    fn errors_leave_the_buffer_unchanged() {
331        let mut datagram = bytes(AcknowledgePdu::new());
332        datagram.truncate(datagram.len() - 1);
333
334        let mut buf = datagram.as_slice();
335        assert!(AnyPdu::deserialize(&mut buf).is_err());
336        assert_eq!(buf, datagram.as_slice());
337    }
338
339    #[test]
340    fn rejects_undefined_and_other_pdu_types() {
341        for pdu_type in [0, 73, 255] {
342            let mut datagram = bytes(AcknowledgePdu::new());
343            datagram[PDU_TYPE_OCTET] = pdu_type;
344            assert!(matches!(
345                AnyPdu::deserialize(&mut datagram.as_slice()),
346                Err(DISError::InvalidHeader { .. })
347            ));
348        }
349    }
350
351    #[test]
352    fn rejects_buffers_shorter_than_the_pdu_type() {
353        assert!(matches!(
354            AnyPdu::deserialize(&mut [7, 1].as_slice()),
355            Err(DISError::BufferUnderflow { .. })
356        ));
357    }
358
359    #[test]
360    fn deserialize_all_reads_a_bundle() {
361        let mut datagram = bytes(AcknowledgePdu::new());
362        datagram.extend(bytes(EntityStatePdu::new()));
363        datagram.extend(bytes(CommentPdu::new()));
364
365        let types: Vec<PduType> = AnyPdu::deserialize_all(&datagram)
366            .map(|pdu| pdu.unwrap().pdu_type())
367            .collect();
368        assert_eq!(
369            types,
370            [PduType::Acknowledge, PduType::EntityState, PduType::Comment]
371        );
372    }
373
374    #[test]
375    fn deserialize_all_skips_a_pdu_it_cannot_decode() {
376        let mut bad = bytes(AcknowledgePdu::new());
377        bad[PDU_TYPE_OCTET] = 200;
378        let mut datagram = bad;
379        datagram.extend(bytes(CommentPdu::new()));
380
381        let results: Vec<_> = AnyPdu::deserialize_all(&datagram).collect();
382        assert_eq!(results.len(), 2);
383        assert!(results[0].is_err());
384        assert!(matches!(results[1], Ok(AnyPdu::Comment(_))));
385    }
386
387    #[test]
388    fn deserialize_all_stops_when_the_length_does_not_fit() {
389        let mut datagram = bytes(AcknowledgePdu::new());
390        datagram.extend(bytes(CommentPdu::new()));
391        datagram.truncate(datagram.len() - 1);
392
393        let results: Vec<_> = AnyPdu::deserialize_all(&datagram).collect();
394        assert_eq!(results.len(), 2);
395        assert!(results[0].is_ok());
396        assert!(results[1].is_err());
397    }
398
399    #[test]
400    fn deserialize_all_of_nothing_is_empty() {
401        assert_eq!(AnyPdu::deserialize_all(&[]).count(), 0);
402    }
403
404    #[test]
405    fn reports_the_header_fields() {
406        let mut pdu = AcknowledgePdu::new();
407        pdu.header_mut().exercise_id = ExerciseIdentifier::new(9);
408        let any = AnyPdu::from(pdu);
409
410        assert_eq!(any.pdu_type(), PduType::Acknowledge);
411        assert_eq!(any.protocol_family(), ProtocolFamily::SimulationManagement);
412        assert_eq!(any.exercise_id(), ExerciseIdentifier::new(9));
413    }
414}