Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

open-dis-rust is an open-source Rust implementation of the IEEE 1278.1-2012 Distributed Interactive Simulation (DIS) application protocol. This crate defines strongly typed Rust structures for each Protocol Data Unit (PDU) along with the records and SISO-REF-010 enumerations associated with them. It also gives you the code to turn those structs into bytes on the wire and back again.

let mut pdu = EntityStatePdu::new();
pdu.entity_id = EntityIdentifier::new(SimulationAddress::new(1, 1), 1);
pdu.force_id = ForceId::Friendly;

let bytes: Vec<u8> = pdu.to_bytes()?; // ready to send over UDP

What is DIS?

DIS is an IEEE standard that enables independently constructed simulations to share one virtual world in real time. Flight simulators, ground vehicle trainers, constructive wargames, radio simulators, and live range instrumentation can all join the same exercise. Each one broadcasts PDUs that describe its own entities and events and reads the PDUs from other participants in the simulation.

A few PDUs carry most of the traffic in a typical exercise:

PDUPurpose
Entity StateDescribes a simulation entity, including what it is, where it is, how it is moving, and what it looks like
Fire / DetonationA munition was fired, and it detonated at a certain location
Transmitter / Signal / ReceiverSimulates radio traffic, including actual audio
Start/Resume, Stop/Freeze, AcknowledgeSimulation management for controlling the exercise

DIS has no central server. Simlators usually exchange PDUs over UDP broadcast or multicast, and every participant decides for itself which PDUs to act on.

What this crate does

  • Defines all 72 PDU types defined in the IEEE 1278.1-2012 across every protocol family that has PDUs, including Live Entity, Information Operations, and Simulation Management with Reliability, to name a few.
  • Encodes and decodes PDUs in network (big-endian) byte order, and checks the declared PDU length against the actual contents.
  • Fills in derived fields for you when serializing. These include the PDU type, protocol family, total length, record counts, and padding.
  • Provides SISO-REF-010 enumerations implemented as Rust enums.
  • Avoids unsafe code and panics. Malformed input comes back as DISError instead of crashing the simulation.

What this crate leaves to you

This crate is a protocol codec, not a complete DIS framework. Any consumer application is responsible for:

  • Networking. Any transport mode works, but it is strongly recommended to use UDP in distributed simulation environments. The examples in this crate all use UDP either via the Rust standard library or with tokio.
  • Timing. This includes heartbeats and timing out entities that have gone stale.
  • Dead reckoning. This crate carries the dead reckoning parameters, but extrapolating positions between updates is up to the consumer.
  • Coordinate conversion. DIS locations are geocentric (ECEF) coordinates in meters. Converting to and from latitude, longitude, and altitude needs a separate crate or custom implementation.

How this book is organized

  • Installation and the Quickstart get you sending and receiving PDUs in a few minutes.
  • Guides walk through common tasks in more detail.
  • Development explains how the crate is built, for contributors.

For the full API, see the API documentation on docs.rs.

Project status and feedback

This crate is free and open source under the BSD 2-Clause License. If you find a PDU, record, or enumeration that doesn’t match the standard, or one that another DIS implementation is unable to parse, please open an issue and attach a packet capture if you can. Captures from real exercises are the fastest way to find and fix interoperability problems. Since DIS is commonly used in military exercises, ensure that you do NOT post any classified data when submitting tickets.

Installation

Requirements

  • Rust 1.85 or newer. The crate uses the Rust 2024 edition, which first shipped in Rust 1.85. Check the installed version with rustc --version and update with rustup update stable.
  • Cargo, which comes with Rust. If you don’t have Rust yet, install it with rustup.

This crate is pure Rust with no system libraries to install, so it builds anywhere that Rust does, including Linux, macOS, and Windows.

Add the crate to your project

From your project’s directory, run:

cargo add open-dis-rust

Or add the dependency to Cargo.toml yourself:

[dependencies]
open-dis-rust = "1"

PDUs are encoded into a standard Vec<u8> and decoded from a &[u8], so you do not need third-party crates to use them.

The package name uses hyphens, but in Rust code, the crate is referred to with underscores:

use open_dis_rust::entity_information::EntityStatePdu;

Async networking (optional)

The crate doesn’t depend on any networking library; however, the tokio crate is among the gold standards of Rust networking and async I/O.

cargo add tokio --features full

The Quickstart guide uses std::net::UdpSocket, so tokio is not needed to follow along.

Validate

To quickly test the crate, place the following code in your application’s src/main.rs:

use open_dis_rust::prelude::*;
use open_dis_rust::simulation_management::AcknowledgePdu;

fn main() {
    let mut pdu = AcknowledgePdu::new();
    let bytes = pdu.to_bytes().expect("serialize failed");
    println!("open-dis-rust {} encoded the following {}-byte PDU: {:?}",
        open_dis_rust::get_version(),
        bytes.len(),
        pdu
    );
}

Then, execute cargo run to see a printout of the crate version and a view into the PDU.

Build from source

If you plan on contributing to the development of the crate, or if you want to modify the code for your own project, simply clone down the repo and build it yourself. You will need git and Rust.

git clone https://github.com/crhowell3/open-dis-rust.git
cd open-dis-rust

cargo build --release
cargo test -q

If you make modifications and wish to test them against personal projects, add this to your Cargo.toml:

[dependencies]
open-dis-rust = { path = "path/to/open-dis-rust" }

Read documentation offline

The API reference is published on docs.rs. To build it locally and open it in your browser:

cargo doc --open

To preview this book locally, install mdBook and serve it from the book folder:

cargo install mdbook
mdbook serve book --open

Quickstart

In this walkthrough, you’ll run two small programs. One broadcasts an Entity State PDU for a tank once a second. The other listens for PDUs and prints what it hears. This walkthrough takes about 5 minutes.

Both programs live in the repository’s examples directory. You can run them from a clone of the repository, as shown at the end of this page, or copy them into your own project.

1. Send an Entity State PDU

An Entity State PDU is the heartbeat of DIS. Every simulator sends one for each entity it owns, at regular intervals, so that everyone else knows where that entity is and what it is doing.

//     open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
//                     Simulation (DIS) application protocol
//     Copyright (C) 2026 Cameron Howell
//
//     Licensed under the BSD 2-Clause License

use std::{error::Error, net::UdpSocket, thread, time::Duration};

use open_dis_rust::prelude::*;
use open_dis_rust::{
    entity_information::EntityStatePdu,
    records::{
        EntityIdentifier, EntityMarking, EntityType, ExerciseIdentifier, Vector, WorldCoordinates,
    },
    siso::enums::{Country, DeadReckoningAlgorithm, EntityKind, ForceId},
};

fn main() -> Result<(), Box<dyn Error>> {
    // Bind to any free local port and send to a receiver on port 3000.
    let socket = UdpSocket::bind("0.0.0.0:0")?;
    socket.connect("127.0.0.1:3000")?;

    // Build an Entity State PDU describing one tank.
    let mut pdu = EntityStatePdu::new();
    pdu.header_mut().exercise_id = ExerciseIdentifier::new(1);
    let simulation_address = SimulationAddress::new(1, 1);
    pdu.entity_id = EntityIdentifier::new(simulation_address, 1); // site 1, application 1, entity 1
    pdu.force_id = ForceId::Friendly;
    // 1:1:225:1:1:3:0 is the SISO-REF-010 entity type for an M1A2 Abrams.
    pdu.entity_type = EntityType::new(
        EntityKind::Platform,
        1,
        Country::UnitedStatesofAmerica,
        1,
        1,
        3,
        0,
    );
    pdu.entity_marking =
        EntityMarking::from_ascii("TANK01").ok_or("a marking is up to 11 ASCII characters")?;
    pdu.entity_linear_velocity = Vector::new(10.0, 0.0, 0.0); // m/s, world frame
    pdu.dead_reckoning_parameters.dead_reckoning_algorithm =
        DeadReckoningAlgorithm::DRMConstantVelocityLowAccelerationLinearMotionEntity;

    // Location is geocentric (ECEF) meters. This point is on the equator at 0 degrees longitude.
    let mut x = 6_378_137.0;

    for _ in 0..10 {
        pdu.entity_location = WorldCoordinates::new(x, 0.0, 0.0);
        pdu.header_mut().timestamp = Timestamp::now();

        // serialize() fills in the PDU type, family, length and all counts.
        let bytes = pdu.to_bytes()?;
        socket.send(&bytes)?;
        println!("sent {}-byte Entity State PDU, x = {x:.1}", bytes.len());

        x += 10.0;
        thread::sleep(Duration::from_secs(1));
    }

    Ok(())
}

A few things to notice:

  • EntityStatePdu::new() gives you a PDU with sensible defaults and the header already set up. You only fill in the fields you care about.
  • Entity IDs consist of three numbers: site, application, and entity IDs. Together they must be unique within the exercise. It should be noted that this crate does NOt enforce this constraint. That is completely up to the consumer to ensure uniqueness.
  • Entity types come from the SISO-REF-010 enumerations.
  • Locations are geocentric (ECEF) coordinates in meters.
  • to_bytes() (and serialize()) fills in the PDU type, protocol family, length, and every count field before encoding. You should not have to fill out header.length yourself.

2. Receive and decode PDUs

The receiver binds to UDP port 3000, which is traditionally the port used for DIS traffic per the standard. It decodes each datagram with AnyPdu, which reads the header to determine what kind of PDU arrived and decodes it as that type.

//     open-dis-rust - Rust implementation of the IEEE 1278.1-2012 Distributed Interactive
//                     Simulation (DIS) application protocol
//     Copyright (C) 2026 Cameron Howell
//
//     Licensed under the BSD 2-Clause License

use std::{error::Error, net::UdpSocket};

use open_dis_rust::prelude::*;

fn main() -> Result<(), Box<dyn Error>> {
    let socket = UdpSocket::bind("0.0.0.0:3000")?;
    println!("listening on {}", socket.local_addr()?);

    let mut buf = [0u8; MAX_PDU_SIZE_OCTETS];
    loop {
        let (n, from) = socket.recv_from(&mut buf)?;
        let Some(mut datagram) = buf.get(..n) else {
            continue;
        };

        // The header says which PDU it is, and AnyPdu decodes it as that type
        match AnyPdu::deserialize(&mut datagram) {
            Ok(AnyPdu::EntityState(pdu)) => println!(
                "{from}: entity {}:{}:{} '{}' at ({:.1}, {:.1}, {:.1})",
                pdu.entity_id.simulation_address.site_id,
                pdu.entity_id.simulation_address.application_id,
                pdu.entity_id.entity_id,
                pdu.entity_marking.as_ascii().unwrap_or("?"),
                pdu.entity_location.x_coordinate,
                pdu.entity_location.y_coordinate,
                pdu.entity_location.z_coordinate,
            ),
            Ok(other) => println!("{from}: ignoring {:?} PDU", other.pdu_type()),
            Err(e) => eprintln!("{from}: undecodable datagram: {e}"),
        }
    }
}

AnyPdu has one variant per PDU type, named after its PduType, so you match on the ones you wish to explicitly handle. deserialize returns an error instead of panicking when a datagram is truncated or malformed. A receiver on a shared network might expect to receive some bad PDUs at times.

3. Run the examples

In one terminal, start the receiver:

cargo run --example quickstart_receive

In a second terminal, start the sender:

cargo run --example quickstart_send

The sender reports each PDU it sends:

sent 144-byte Entity State PDU, x = 6378137.0
sent 144-byte Entity State PDU, x = 6378147.0
sent 144-byte Entity State PDU, x = 6378157.0

The receiver prints the tank moving 10 meters along the x-axis each second:

listening on 0.0.0.0:3000
127.0.0.1:35774: entity 1:1:1 'TANK01' at (6378137.0, 0.0, 0.0)
127.0.0.1:35774: entity 1:1:1 'TANK01' at (6378147.0, 0.0, 0.0)
127.0.0.1:35774: entity 1:1:1 'TANK01' at (6378157.0, 0.0, 0.0)

NOTE: Source ports will differ as they are chosen at runtime.

4. Observe packets in Wireshark (optional)

Wireshark includes a dissector for the DIS protocol, which makes it the easiest way to check what your application is actually putting out on the wire.

How to use the DIS dissector:

  1. Start a capture on the loopback interface.
  2. Enter dis in the display filter bar.
  3. Run the sender again.

Each packet should decode as an Entity State PDU, with the entity ID, entity type, marking, and location you set. If the dissector does not recognize the traffic, check that you are sending on the correct port (3000), or right-click a packet and choose Decode As… -> DIS.

Sending to other machines

The sender in this example talks only to 127.0.0.1. To reach other simulators on your network, send to your subnet’s broadcast address or to a multicast group your exercise agrees on. For broadcast, enable it on the socket first:

let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.set_broadcast(true)?;
socket.connect("192.168.1.255:3000")?;  // replace with your subnet's broadcast address

Every participant must also use the same exercise ID, which this example sets to 1. This rule is not enforced by this crate, but it is specified in the DIS standard. Most DIS applications ignore PDUs from other exercises.

Next steps

Identifiers & Exercises

Every PDU says which exercise it belongs to and who sent it. This page explains the numbers DIS uses for that and how they map to types in open-dis-rust.

Exercises

An exercise is one shared simulated world. Several exercises can run on the same network at once, such as a training event and a test. They are kept discrete and disjoint via the exercise ID in the header of every PDU.

  • The exercise ID is one octet, so it ranges from 1 to 255.
  • Every participant in an exercise must use the same ID. The exercise organizer usually assigns it.
  • Receivers ignore PDUs from other exercises. Nothing in the protocol enforces this, so your application(s) must handle this on their own.

PDUs created with new() use exercise ID 1 by default. Set your own before sending:

use open_dis_rust::prelude::*;

pdu.header_mut().exercise_id = ExerciseIdentifier::new(3);

The exercise ID is octet 1 of every PDU, so you can filter before decoding anything:

fn is_same_exercise(datagram: &[u8], exercise_id: u8) -> bool {
    datagram.get(1) == Some(&exercise_id)
}

Sites and applications

Within an exercise, every simulation program has a simulation address: a pair of 16-bit numbers used for identification.

  • The site usually identifies a facility or organization.
  • The application identifies one running simulation program at that site.

Together they must be unique in the exercise. Like the exercise ID, they are agreed in advance rather than assigned by the protocol. In open-dis-rust, they are stored in SimulationAddress:

use open_dis_rust::records::SimulationAddress;

let me = SimulationAddress::new(1, 100); // site 1, application 100

Entities

An entity is anything in the simulated world that a simulation owns and reports on, such as a vehicle, an aircraft, a person, or a munition in flight. Its entity ID is its simulation address plus a 16-bit entity number:

use open_dis_rust::records::{EntityIdentifier, SimulationAddress};

let me = SimulationAddress::new(1, 100);
let tank = EntityIdentifier::new(me, 7); // entity 7 of site 1, application 100

The application that owns an entity picks its entity numbers. Use each number for only one entity during an exercise. If you reuse a number after an entity is destroyed, other simulators may confuse the new entity with the old one.

Entity number 0 means “no entity”. An entity ID with entity number 0 refers to the simulation application itself, which is how simulation management PDUs address a whole simulator:

let my_application = EntityIdentifier::new(me, 0);

Special values

These constants in constants have fixed meanings:

ConstantValueMeaning
NO_SITE, NO_APPLIC, NO_ENTITY0None, or not applicable.
ALL_SITES, ALL_APPLIC, ALL_ENTITIES0xFFFFEvery site, application, or entity.
RQST_ASSIGN_ID0xFFFEAsk the receiver to assign an entity number.

For example, to send a Start/Resume PDU to every simulator in the exercise:

use open_dis_rust::constants::{ALL_APPLIC, ALL_ENTITIES, ALL_SITES};

let mut start = StartResumePdu::new();
start.originating_entity_id = EntityIdentifier::new(SimulationAddress::new(1, 100), 0);
start.receiving_entity_id =
    EntityIdentifier::new(SimulationAddress::new(ALL_SITES, ALL_APPLIC), ALL_ENTITIES);

Other PDUs use 0 to mean “no target”. A Fire PDU for a shot with no intended target sets the target entity ID to all zeros.

Other identifiers

Several other things in DIS are identified the same way: a simulation address plus a number that the owning application assigns.

IdentifierRust typeIdentifiesUsed in
Entity IDEntityIdentifierAn entityMost PDUs
Event IDEventIdentifierOne event, such as a shotFire, Detonation, Collision, emissions PDUs
Object IDObjectIdentifierAn environmental object, such as a minefield marker or a craterPoint, Linear, and Areal Object State
Aggregate IDAggregateIdentifierA group of entities, such as a platoonAggregate State
Minefield IDMinefieldIdentifierA minefieldMinefield PDUs
Simulation IDSimulationIdentifierA simulation applicationTransfer Ownership, Information Operations

Event IDs link related PDUs. When an entity fires, the Fire PDU and the Detonation PDU for that shot carry the same event ID, so receivers can match the two. Generally, you should monotonically increment the number for each successive event, wrapping around once you reach the 16-bit maximum (65535).

Radios and intercoms are identified by an entity ID plus a 16-bit radio or intercom number because one entity can carry several. The Transmitter, Signal, and Receiver PDUs for one radio all use the same entity_id and radio_id.

Live entity identifiers

The Live Entity PDUs (types 46-50) use smaller fields to save bandwidth on instrumented live ranges. LEEntityId has an 8-bit site number, an 8-bit application number, and a 16-bit entity number. If your simulation exchanges data with live entities, keep its site and application numbers below 256 so that they can be represented in both forms.

Protocol Families & PDU Status

Protocol families

IEEE 1278.1-2012 groups its 72 PDU types into protocol families by purpose. The family is in octet 3 of every PDU header next to the PDU type. You never set it yourself: serialize() fills it in automatically.

In open-dis-rust, each family is a module, and the PDUs for that family are defined in each.

#FamilyModuleWhat it’s forPDUs
1Entity Information/Interactionentity_informationWhere entities are, what they look like, and collisions5
2WarfarewarfareWeapons fire, detonations and damage4
3LogisticslogisticsResupply and repair between entities6
4Radio Communicationsradio_communicationsSimulated radios and intercoms, including audio5
5Simulation Managementsimulation_managementStarting, stopping and controlling the exercise12
6Distributed Emission Regenerationdistributed_emissionsRadar, jammers, sonar, IFF and laser designators5
7Entity Managemententity_managementGroups, aggregates and transferring ownership of entities4
8MinefieldminefieldMinefields and the mines in them4
9Synthetic Environmentsynthetic_environmentWeather, terrain changes and environmental objects5
10Simulation Management with Reliabilitysimulation_management_with_reliabilityThe same jobs as family 5, with acknowledgements and retries15
11Live Entity Information/Interactionlive_entity_informationCompact PDUs for live, instrumented entities on a range5
13Information Operationsinformation_operationsCyber and electronic warfare effects2

Family 0 means “other”, and family 12 is reserved for the Non Real-Time service. Neither has any PDUs.

Which families you need

Most applications need only a few families:

  • Every participant should send and receive Entity Information and respond to Simulation Management.
  • Combat simulations may use Warfare.
  • Radio and voice simulations may use Radio Communications.
  • Sensor and electronic warfare simulations use Distributed Emission Regeneration.

Reliable and unreliable simulation management

Families 5 and 10 are leveraged for the same tasks. Family 5 PDUs are sent once, and the sender cannot tell whether they arrived. Family 10 PDUs carry a required reliability service field that asks the receiver to acknowledge them, and the sender retries until it gets a reply. Use family 10 when a lost message would cause real problems, i.e., when creating or removing entities across simulators.

PDU Status

Octet 10 of the PDU header holds the PDU Status record. It has a few one- and two-bit flags that tell a receiver how to treat the PDU. A new PDU has all of these flags cleared, which is correct for most traffic.

You reach the flags through header.pdu_status:

use open_dis_rust::siso::enums::LVCIndicator;

pdu.header_mut().pdu_status.set_lvc(LVCIndicator::Virtual);

Status flags

LVC Indicator. Whether the PDU comes from a live system (real equipment on a range), a virtual one (a person within a simulator) or a constructive one (a computer-controlled simulation, such as a wargame). Many exercises mix all three, and receivers sometimes treat them differently such as by hiding constructive entities from a live display. Setting it is optional; the default is NoStatement.

Transferred Entity Indicator (TEI). Set when the entity a PDU describes is now owned by a different simulation from the one that created it. That happens after the Transfer Ownership PDU moves an entity from one simulator to another. Receivers use it to know that the entity is still the same one, even though a different application is now sending its updates.

Coupled Extension Indicator (CEI). Set when the PDU has an Attribute PDU coupled to it, carrying extra data that extends this PDU. Receivers that see this flag should wait for the matching Attribute PDU before acting on the data.

PDU-specific bits. Bits 4 and 5 mean different things for different PDUs. For example, in a Fire PDU, bit 4 says whether a munition or an expendable, such as chaff, was fired. In radio PDUs, bits 4 and 5 say whether the radio is attached to an entity.

Wire Format Conventions lists the exact bit positions and the method for reading and writing each flag.

Live Entity PDUs

The five Live Entity PDUs don’t have a PDU Status record. Their header, LiveEntityPduHeader, uses the same octet for a subprotocol number instead, which says how the rest of the PDU is encoded.

Every PDU’s header() returns its own header type, so the compiler keeps the two apart. Generic code names the kind of PDU it works with by its header: the prelude’s StandardPdu is any PDU with a PduHeader, and LiveEntityPdu is any PDU with a LiveEntityPduHeader.

use open_dis_rust::{prelude::*, siso::enums::LVCIndicator};

fn mark_virtual(pdu: &mut impl StandardPdu) {
    pdu.header_mut().pdu_status.set_lvc(LVCIndicator::Virtual);
}

Passing a Live Entity PDU to mark_virtual is a compile error. Code that works with every PDU uses Pdu, which has the components that both types share such as pdu_type() and serialize().

Before a datagram is decoded, its protocol family (octet 3, the same place in both headers) says which kind it is: ProtocolFamily::LiveEntityInformationInteraction for a Live Entity PDU.

Timestamps

Every PDU header has a 32-bit timestamp saying when the data in it was valid. Receivers use it to tell how old the data is, to put PDUs in order, and to extrapolate entity positions forward to the present.

Time since the hour

A DIS timestamp counts time since the start of the current hour, not since a fixed date. Bits 31 to 1 hold that time in units of 3600/2³¹ seconds, which is about 1.676 microseconds. Bit 0 says what kind of timestamp it is.

 31                                                           1   0
┌─────────────────────────────────────────────────────────────┬───┐
│ time since the start of the hour, in units of 3600/2³¹ s    │ A │
└─────────────────────────────────────────────────────────────┴───┘
                                                  A = 1: absolute, 0: relative

At the start of each hour, the count resets to 0. A receiver comparing timestamps must accommodate for this, as show below.

Absolute and relative time

Absolute timestamps (bit 0 set) are measured against real-world UTC. They only work if every participant’s clock is synchronized, usually with RTP or, for tighter accuracy, PTP. Because every PDU then shares one time base, receivers can compare timestamps from different simulators directly. This is the usual choice for networked exercises.

Relative timestamps (bit 0 clear) are measured against each simulator’s own clock, so they can only be compared with other timestamps from the same simulator. This is useful when clocks cannot be synchronized or when a simulation runs faster or slower than real time.

Whichever is chosen, every participant in an exercise should agree on it.

The Timestamp type

The crate represents timestamps with records::Timestamp, which is also in the prelude. Header timestamps and the time inside Clock Time records both use it.

Creating timestamps:

CallGives
Timestamp::now()An absolute timestamp for the current UTC time, from the system clock
Timestamp::absolute(time_past_hour)An absolute timestamp for a given time, as a Duration
Timestamp::relative(time)A relative timestamp, for example from the time since your simulation started
Timestamp::from_raw(u32)A timestamp from its 32-bit wire value

absolute and relative discard whole hours, so you can pass a time since midnight, or since the simulation started, directly.

Reading timestamps:

CallGives
is_absolute()Whether bit 0 is set
time_past_hour()The time since the start of the hour, as a Duration
later.duration_since(earlier)The time between two timestamps, allowing for the hour wrapping around
to_raw()The 32-bit wire value

Timestamp implements Display, which prints the time past the hour and its kind, such as 35:26.232076 abs, which is handy for logging.

A timestamp’s resolution is about 1.676 µs, so a value converted to a Timestamp and back can differ from the original by up to about 0.84 µs.

Setting the timestamp before sending

new() timestamps a PDU with Timestamp::now() once, when the PDU is created. If you keep a PDU and send it repeatedly, as you normally would for Entity State heartbeats, set the timestamp again before each send:

use open_dis_rust::prelude::*;

pdu.header_mut().timestamp = Timestamp::now();
pdu.serialize(&mut buf)?;

The timestamp is only as accurate as your system clock, so make sure the machine is synchronized.

To send relative timestamps, build them from your own simulation clock:

use std::time::Instant;

let started = Instant::now();
// ...
pdu.header_mut().timestamp = Timestamp::relative(started.elapsed());

How old is a PDU?

duration_since handles the hour boundary: a timestamp from 59:59, compared with one from 00:01, is 2 seconds earlier, not almost an hour.

use std::time::Duration;

let age = Timestamp::now().duration_since(pdu.header().timestamp);
if age < Duration::from_secs(30 * 60) {
    // Extrapolate the entity's position forward by `age` using its dead reckoning parameters
}

Because timestamps repeat every hour, a timestamp slightly ahead of your clock, from a sender whose clock runs fast, comes out as an age of nearly an hour. Treat ages above 30 minutes as being from the future, and don’t extrapolate those entities backwards.

Only compare timestamps of the same kind: absolute with absolute, or relative with relative from the same simulator.

Clock Time records

Some PDUs need to say which hour, not just the time within it. Simulation Management PDUs such as Start/Resume use a Clock Time record (ClockTime) for this. It has two fields:

  • hour: the number of hours since 00:00 UTC on 1 January 1970.
  • time_past_hour: the time within that hour, as a Timestamp.

To build one for the current time, use ClockTime::now():

use open_dis_rust::records::ClockTime;

start.real_world_time = ClockTime::now();

To build one yourself, pass the hour and a Timestamp:

use std::time::Duration;
use open_dis_rust::records::{ClockTime, Timestamp};

// 06:00 UTC on 1 January 2026 is 490,902 hours after the Unix epoch
let dawn = ClockTime::new(490_902, Timestamp::absolute(Duration::ZERO));

Enumerations (SISO-REF-010)

This crate adheres to the IEEE 1278.1-2012 DIS standard, and that standard leverages enumerations defined in a separate document, SISO-REF-010, Reference for Enumerations for Simulation Interoperability.

SISO-REF-010 is published by the Simulation Interoperability Standards Organization (SISO) and is free to download. It is revised regularly to add new countries, platforms, weapons, and emitters. Unlike the IEEE standard, it changes from year to year.

This crate specifically leverages the enumerations defined in SISO-REF-010-2023.

How enumerations appear in the crate

All enumerations are in siso::enums. Each comes from one table in SISO-REF-010, which identifies its tables by a UID number. They take three forms:

  • Rust enums for fields with a fixed list of possible values. Most enumerated fields in a PDU use these types directly.
  use open_dis_rust::siso::enums::ForceId;

  pdu.force_id = ForceId::Friendly;
  • Bit flags for fields where several options can be set at once. These use the bitflags crate, so you combine them with |.
  use open_dis_rust::siso::bit_records::FrozenBehavior;

  // Keep the simulation clock running and keep sending updates while frozen.
  stop.frozen_behavior = FrozenBehavior::RunSimulationClock | FrozenBehavior::TransmitUpdates;
  • Plain integers for fields whose meaning depends on another field. An entity type’s category, for example, means one thing for a land vehicle and another for an aircraft. The crate has an enum for each of those tables, but the field itself is a plain old data type, such as a u8.

SISO-REF-010 also defines bit layouts: fields whose bits are split into smaller fields, such as an entity’s appearance. Those are in siso::appearance and siso::bit_records, with a getter and setter for each field.

Finding a value

Variant names follow the names in SISO-REF-010, with spaces and punctuation removed. For example, “United States of America” becomes UnitedStatesofAmerica, and “Able to Comply” becomes AbleToComply. Search the API documentation for the name, or search src/siso/enums.rs for the table name or its UID number.

Values unknown to the crate

When decoding, a value that is not in the crate’s table is an error. The whole PDU fails with DISError::WireFormat. This usually happens when another simulator uses a newer version of SISO-REF-010. See Conformance Notes for details.

If you encounter an issue like this, please report it with the value and the PDU type.

Deprecated values

When SISO retires a value, it stays in the tables so that old traffic can still be read, but it should not be used in new PDUs. The crate marks these variants #[deprecated], so the compiler warns you if you use one:

warning: use of deprecated unit variant `open_dis_rust::siso::enums::LandDomainCategories::CivilianVehicle`: Deprecated in SISO-REF-010-2023

Creating a PDU

IEEE 1278.1-2012 defines 72 PDUs, and open-dis-rust implements all of them.

Importing PDUs

Each protocol family is a module, and each PDU is a struct in its family’s module. Protocol Families lists them. Import the PDU you need along with the prelude for the common types and traits:

use open_dis_rust::{prelude::*, simulation_management::AcknowledgePdu};

Constructing PDUs

new() gives a PDU that is ready to send: its header has the correct PDU type, protocol family, and length, exercise ID 1, and the current time. Every other field has a sensible default value.

let mut ack = AcknowledgePdu::new();

Set the header

Read the header with header() and change it with header_mut(). Set the exercise ID and, for a PDU you send more than once, the timestamp:

ack.header_mut().exercise_id = ExerciseIdentifier::new(3);
ack.header_mut().timestamp = Timestamp::now();

The PDU type, protocol family, and length are read-only. Encoding fills them in from the PDU, so they cannot disagree with its contents.

Set the fields

Every other field is public. Simple fields take a plain value:

ack.request_id = 14;

Fields that are records, such as identifiers, take a record. Build it with its new function, or change its fields one at a time:

let me = SimulationAddress::new(1, 100);
ack.originating_entity_id = EntityIdentifier::new(me, 0);
ack.receiving_entity_id.entity_id = 12;

Counts and lengths that depend on other fields, such as the number of records in a list, are set when the PDU is encoded, so you only fill in the list itself. Wire Format Conventions lists them.

Send it

Sending PDUs shows how to encode the PDU and send it over UDP.

Sending PDUs

While the network protocol is not required to be UDP, this crate has been validated against UDP topology, and the example code provided uses UDP as the protocol.

Dependencies

This demonstration utilizes the open_dis_rust crate and tokio:

cargo add open-dis-rust
cargo add tokio --features full

Create and Serialize the PDU

Create the PDU and fill it its fields as described in Creating a PDU:

use open_dis_rust::{prelude::*, simulation_management::AcknowledgePdu};

let mut ack = AcknowledgePdu::new();
ack.request_id = 42;

Then, serialize it. to_bytes returns a new Vec<u8> holding the encoded PDU:

let bytes: Vec<u8> = ack.to_bytes()?;

The PDU has now been serialized into a byte array and is ready to be sent.

Initializing a UDP Socket

We need to select an address and a port to send the message. For this exercise, we will assume the address is localhost (127.0.0.1), and we will use port 3000. To create the socket, we use the tokio crate:

use std::io;
use tokio::net::UdpSocket;

use open_dis_rust::{prelude::*, simulation_management::AcknowledgePdu};

#[tokio::main]
async fn main() -> io::Result<()> {
    // Let the operating system pick the local port, and send to port 3000.
    let socket = UdpSocket::bind("0.0.0.0:0").await?;
    socket.connect("127.0.0.1:3000").await?;

    let mut ack = AcknowledgePdu::new();
    ack.request_id = 42;

    let bytes = ack
        .to_bytes()
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    socket.send(&bytes).await?;

    Ok(())
}

DISError implements std::error::Error, so it converts into an io::Error, or a Box<dyn Error>, for use with ?.

Anything listening on port 3000 of the local machine receives the PDU. The next guide shows how to receive and decode it.

Using the bytes crate

If your application already uses bytes, for example through a tokio codec, encode into a Vec<u8> and convert it. Bytes::from takes over the vector’s memory without copying:

let bytes = bytes::Bytes::from(ack.to_bytes()?);

When receiving, a Bytes or BytesMut dereferences to &[u8], so you can pass &mut &buf[..] straight to deserialize.

Receiving PDUs

This guide receives and decodes PDUs using tokio for networking. The same dependencies are used as in Sending PDUs.

Decode a PDU

deserialize decodes one PDU from the front of a byte slice. It takes the slice by mutable reference and advances it past the PDU it read:

let mut datagram: &[u8] = &buf[..n];
let ack = AcknowledgePdu::deserialize(&mut datagram)?;

If the bytes are not a valid Acknowledge PDU, it returns a DISError instead. Errors describes each type of error.

Receive and decode

A receiver usually handles several PDU types and ignores the rest. AnyPdu::deserialize reads the PDU type from the header and decodes the PDU as that type. AnyPdu has one variant per PDU type, named after its PduType, so you match on the ones you handle:

use std::io;
use tokio::net::UdpSocket;

use open_dis_rust::prelude::*;

#[tokio::main]
async fn main() -> io::Result<()> {
    let socket = UdpSocket::bind("0.0.0.0:3000").await?;
    let mut buf = vec![0u8; MAX_PDU_SIZE_OCTETS];

    loop {
        let (n, from) = socket.recv_from(&mut buf).await?;
        let mut datagram = buf.get(..n).unwrap_or_default();

        match AnyPdu::deserialize(&mut datagram) {
            Ok(AnyPdu::Acknowledge(ack)) => {
                println!("{from}: acknowledged request {}", ack.request_id);
            }
            Ok(AnyPdu::EntityState(pdu)) => println!("{from}: entity {:?}", pdu.entity_id),
            Ok(other) => println!("{from}: ignoring {:?} PDU", other.pdu_type()),
            Err(e) => eprintln!("{from}: undecodable datagram: {e}"),
        }
    }
}

A few things to note:

  • Size the buffer for the largest PDU. MAX_PDU_SIZE_OCTETS is 8192. A smaller buffer could truncate larger PDUs, and attempting to decode a truncated PDU results in DISError::BufferUnderflow.
  • Decode only the bytes you received. buf.get(..n) limits the slice to the datagram, so leftover bytes from an earlier, longer datagram cannot be read.
  • Expect errors. On a shared network or distributed simulation environment, some traffic could naturally fail to decode. Log it and keep receiving rather than hard stopping your program.

If you only handle one or two PDU types, you can skip decoding the rest: PduHeader::get_pdu_type reads just the 12-octet header, and then you can call deserialize on the concrete type, such as EntityStatePdu::deserialize.

Several PDUs in a single datagram

A datagram can hold more than one PDU. AnyPdu::deserialize_all decodes each of them in turn. Wire Format Conventions shows how.

Conformance Notes

This page records how closely open-dis-rust follows IEEE 1278.1-2012. This includes what has been checked, how the crate behaves at the edges of the standard, and where it is currently known to differ. This page will be updated as issues are found and eventually fixed.

If you find a difference that is not listed here, please report it, ideally with a packet capture.

How the crate is checked

  • Review against the standard. PDU and record layouts have been manually reviewed field by field against the IEEE 1278.1-2012 standard document.
  • Round-trip tests. Every PDU has tests that encode it, decode the result, and check that the bytes match. These tests catch bugs where encoding and decoding may differ, but it fails to catch cases where both follow the same wrong layout.

What has been checked and matches

  • PDU header. The 12-octet layout, field order, and sizes are correct for both the standard header and the Live Entity header.
  • PDU Status record. The bit assignments are correct, including the per-PDU meanings of bits 4 and 5.
  • Timestamps. Encoded in units of 3600/2³¹ seconds past the hour, with the low bit set for absolute time.
  • Byte order. Every field is big-endian, and floating-point values are IEEE 754.
  • Size limit. PDUs larger than 8192 octets are rejected when encoding.
  • Fixed-size fields. For nearly all PDUs, the fixed part of the layout is correct.

Decoding behavior

These choices are stricter than some other DIS implementations. They matter most when you receive traffic from simulators you do not control.

  • Undefined enumeration values are rejected. If any enumerated field holds a value that is not in the crate’s SISO-REF-010 tables, such as a newly assigned country code, the whole PDU fails to decode with a WireFormat error. Newer simulators may send values the crate does not know about yet.
  • Extra octets are rejected. If a PDU’s length field is longer than the fields the crate reads, decoding fails with a DeserializationError.
  • The protocol version is not checked. Any version from 1 to 7 is accepted, and the PDU is decoded with the 2012 layout. Most DIS 6 (1998) PDUs decode correctly this way because their layouts did not change in the 2012 version.
  • The protocol family is not checked against the PDU type.
  • Padding is preserved. Padding fields are read and kept, so a decoded PDU re-encodes to identical bytes. PDUs you build yourself always send zero padding.

Known differences

Each of these produces bytes that differ from the standard in some way. The eventual goal is to have this list be completely empty; that is, all known differences have been addressed.

Underwater Acoustic PDU

  • The emitter system data length and beam data length fields aren’t computed, so they’re always sent as 0.
  • To verify: Shaft RPM Rate of Change is encoded as a 32-bit integer; it may need to be a 32-bit float.

Electromagnetic Emission PDU

The system data length and beam data length fields aren’t computed, so they’re always sent as 0. Receivers that use these lengths to step through the records can’t parse the PDU.

Linear Object State PDU

The general segment appearance in each Linear Segment Parameter record is 32 bits instead of 16, which makes each segment 66 octets instead of 64.

Gridded Data PDU

Grid data records that use representation type 0 are padded to a 16-bit boundary instead of a 32-bit one. Types 1 and 2 are padded correctly.

Minefield Response NACK PDU

Missing PDU sequence numbers are encoded as 64-bit values with no padding. The standard calls for 8-bit values padded to a 32-bit boundary.

Directed Energy Fire PDU

  • The PDU carries Damage Description records (record type 4500). It should carry DE Precision Aimpoint (4000) or DE Area Aimpoint (4001) records.
  • To verify: the 32-bit field after Wavelength is treated as padding; it may be Peak Irradiance, a 32-bit float.

Simplified records

These PDUs encode correctly when the affected records are empty, but the records are modeled more simply than the standard defines them.

Aggregate State PDU

The silent aggregate and silent entity lists are encoded as plain entity types. The standard defines Silent Aggregate System records (12 octets each) and Silent Entity System records (variable length, with appearance records).

Is Group Of PDU

Grouped entity descriptions are encoded as 64-bit values. In the standard, their size and contents depend on the grouped entity category.

Environmental Process PDU

Environment records include only their 8-octet header. The geometry and state data that follows the header isn’t represented.

Intercom Control PDU

Intercom communications parameter records have a fixed 32-bit body, although the standard allows them to be any length given by their record length field.

IFF PDU

Layer 1 and layer 2 are decoded into fields. Any further layers, such as Mode 5 and Mode S data, are kept as raw octets in IffLayers::other_layers.

Still to verify

These may differ from the standard. They need checking against the text of IEEE 1278.1-2012 or against captures.

Record Specification record

Used by the Transfer Ownership and Set Record-R PDUs. The crate treats the record length as a number of octets and doesn’t pad the record values. The standard may define the length in bits, require a 32-bit padding field after the record set serial number, and pad the values to a 64-bit boundary.

Live Entity Fire and Detonation PDUs

The flag fields are kept as plain integers, and every optional field is always encoded. The standard may use the flags to mark some fields as present or absent.

Fields kept as raw values

These fields encode correctly, but the crate doesn’t interpret them for you. You read and write their bits yourself, using the SISO-REF-010 enumerations.

  • Entity capabilities, in the Entity State and Appearance PDUs. EntityCapabilities holds the 32 bits, whose layout depends on the entity’s kind and domain. Entity appearance has typed views instead: EntityAppearance::view reads it with the layout for an EntityType.
  • Variable parameter records. These are kept as four generic fields rather than as typed articulated or attached part records.
  • Modulation parameters in the Transmitter PDU. Beam antenna patterns are decoded; spherical harmonic patterns are not supported yet, and a Transmitter PDU with one fails to decode.
  • Signal and Intercom Signal data.
  • Specific object appearance in the Point and Linear Object State PDUs. For an areal minefield, ArealObjectStateMinefieldAppearance reads it, and the general object appearance has its own type, ObjectStateAppearanceGeneral.
  • Object modifications in the Point Object State PDU and Linear Segment Parameter records (UIDs 240 and 241). The Areal Object State PDU’s is typed.

The Damage Description record defaults to a record type and length of 0. Set them to 4500 and 40 when you build one yourself.

PDU Coverage

IEEE 1278.1-2012 defines 72 PDU types. open-dis-rust implements all 72. This page lists every type with its number, protocol family, Rust type, and status.

StatusCountMeaning
Complete56Implemented, with no known differences from the standard.
Partial5Implemented, but some variable-length records are kept as raw values or are simplified.
Known Issues6Implemented, but at least one field is encoded differently from the standard.
To Verify5Implemented, but at least one field may differ from the standard and still needs to be verified.
Not Implemented0Not available yet.

Each status other than Complete links to the details on the Conformance Notes page. Complete means no problems are known; it does not mean the PDU has been certified against other implementations.

List of PDU types

TypePDUFamilyRust typeStatus
1Entity StateEntity InformationEntityStatePduComplete
2FireWarfareFirePduComplete
3DetonationWarfareDetonationPduComplete
4CollisionEntity InformationCollisionPduComplete
5Service RequestLogisticsServiceRequestPduComplete
6Resupply OfferLogisticsResupplyOfferPduComplete
7Resupply ReceivedLogisticsResupplyReceivedPduComplete
8Resupply CancelLogisticsResupplyCancelPduComplete
9Repair CompleteLogisticsRepairCompletePduComplete
10Repair ResponseLogisticsRepairResponsePduComplete
11Create EntitySimulation MgmtCreateEntityPduComplete
12Remove EntitySimulation MgmtRemoveEntityPduComplete
13Start/ResumeSimulation MgmtStartResumePduComplete
14Stop/FreezeSimulation MgmtStopFreezePduComplete
15AcknowledgeSimulation MgmtAcknowledgePduComplete
16Action RequestSimulation MgmtActionRequestPduComplete
17Action ResponseSimulation MgmtActionResponsePduComplete
18Data QuerySimulation MgmtDataQueryPduComplete
19Set DataSimulation MgmtSetDataPduComplete
20DataSimulation MgmtDataPduComplete
21Event ReportSimulation MgmtEventReportPduComplete
22CommentSimulation MgmtCommentPduComplete
23Electromagnetic EmissionDistributed EmissionElectromagneticEmissionsPduKnown issues
24DesignatorDistributed EmissionDesignatorPduComplete
25TransmitterRadioTransmitterPduComplete
26SignalRadioSignalPduComplete
27ReceiverRadioReceiverPduComplete
28IFFDistributed EmissionIFFPduPartial
29Underwater AcousticDistributed EmissionUnderwaterAcousticPduKnown issues
30Supplemental EmissionDistributed EmissionSupplementalEmissionPduComplete
31Intercom SignalRadioIntercomSignalPduComplete
32Intercom ControlRadioIntercomControlPduPartial
33Aggregate StateEntity MgmtAggregateStatePduPartial
34Is Group OfEntity MgmtIsGroupOfPduPartial
35Transfer OwnershipEntity MgmtTransferOwnershipPduTo verify
36Is Part OfEntity MgmtIsPartOfPduComplete
37Minefield StateMinefieldMinefieldStatePduComplete
38Minefield QueryMinefieldMinefieldQueryPduComplete
39Minefield DataMinefieldMinefieldDataPduComplete
40Minefield Response NACKMinefieldMinefieldResponseNackPduKnown issues
41Environmental ProcessSynthetic EnvEnvironmentalProcessPduPartial
42Gridded DataSynthetic EnvGriddedDataPduKnown issues
43Point Object StateSynthetic EnvPointObjectStatePduComplete
44Linear Object StateSynthetic EnvLinearObjectStatePduKnown issues
45Areal Object StateSynthetic EnvArealObjectStatePduComplete
46Time Space Position Information (TSPI)Live EntityTimeSpacePositionInformationPduComplete
47AppearanceLive EntityAppearancePduComplete
48Articulated PartsLive EntityArticulatedPartsPduComplete
49Live Entity FireLive EntityLiveEntityFirePduTo verify
50Live Entity DetonationLive EntityLiveEntityDetonationPduTo verify
51Create Entity-RSimulation Mgmt-RCreateEntityReliablePduComplete
52Remove Entity-RSimulation Mgmt-RRemoveEntityReliablePduComplete
53Start/Resume-RSimulation Mgmt-RStartResumeReliablePduComplete
54Stop/Freeze-RSimulation Mgmt-RStopFreezeReliablePduComplete
55Acknowledge-RSimulation Mgmt-RAcknowledgeReliablePduComplete
56Action Request-RSimulation Mgmt-RActionRequestReliablePduTo verify
57Action Response-RSimulation Mgmt-RActionResponseReliablePduComplete
58Data Query-RSimulation Mgmt-RDataQueryReliablePduComplete
59Set Data-RSimulation Mgmt-RSetDataReliablePduComplete
60Data-RSimulation Mgmt-RDataReliablePduComplete
61Event Report-RSimulation Mgmt-REventReportReliablePduComplete
62Comment-RSimulation Mgmt-RCommentReliablePduComplete
63Record-RSimulation Mgmt-RRecordReliablePduComplete
64Set Record-RSimulation Mgmt-RSetRecordReliablePduTo verify
65Record Query-RSimulation Mgmt-RRecordQueryReliablePduComplete
66Collision-ElasticEntity InformationCollisionElasticPduComplete
67Entity State UpdateEntity InformationEntityStateUpdatePduComplete
68Directed Energy FireWarfareDirectedEnergyFirePduKnown issues
69Entity Damage StatusWarfareEntityDamageStatusPduComplete
70Information Operations ActionInformation OpsInformationOperationsActionPduComplete
71Information Operations ReportInformation OpsInformationOperationsReportPduComplete
72AttributeEntity InformationAttributePduComplete

The family column uses short names. Each Rust type lives in the module for its family; for example, open_dis_rust::warfare::FirePdu. PDU type 0 (Other) is a placeholder in the enumeration, and there is no corresponding PDU.

Headers

Two header types are used:

  • PduHeader for every family except Live Entity.
  • LiveEntityPduHeader for the five Live Entity PDUs (types 46-50). It has the same 12-octet size, but it carries a subprotocol number where the PDU Status record would be.

Both are covered on the Wire Format Conventions page.

Wire Format Conventions

This page summarizes how DIS PDUs are laid out on the wire and what open-dis-rust does for you when it encodes them. This is a quick reference; for a complete guide, check out the IEEE 1278.1-2012 documentation.

Basics

  • Byte order. Every multi-octet field is big-endian (network byte order).
  • Floating point. 32- and 64-bit floats are in IEEE 754 format.
  • Units. Unless the original standard document specifies otherwise, lengths are in meters, angles in radians, time in seconds, and velocities in meters per second.
  • Coordinates. World coordinates are geocentric (ECEF) coordinates in meters encoded as 64-bit floats.
  • Maximum size. A PDU can be at most 8192 octets. Encoding a larger PDU fails with DISError::PduSizeExceeded.

The PDU header

Every PDU starts with a 12-octet header.

OctetsFieldSizeNotes
0Protocol Version8 bitsEncoded as 7 for IEEE 1278.1-2012
1Exercise ID8 bitsMust match across all participants in an exercise
2PDU Type8 bitsSee PDU Coverage
3Protocol Family8 bits
4-7Timestamp32 bitsSee Timestamps
8-9Length16 bitsTotal PDU length in octets, including the header
10PDU Status8 bitsSee PDU Status
11Padding8 bits

In LiveEntityPduHeader, octet 10 holds the subprotocol number instead of the PDU Status record.

To check a datagram’s PDU type without decoding the whole PDU, use PduHeader::get_pdu_type. It reads only the header.

Timestamps

The timestamp counts time since the start of the current hour. Bits 31 to 1 hold the time in units of 3600/2³¹ seconds, which is about 1.676 µs. Bit 0 is 1 for an absolute timestamp (synchronized to real time) and 0 for a relative.

The header’s timestamp field is a Timestamp. Timestamp::now() gives an absolute timestamp for the current UTC time. new() sets it once when you create a PDU, so set it again before each send if you reuse a PDU:

pdu.header_mut().timestamp = Timestamp::now();

For relative timestamps, use Timestamp::relative(duration). See Timestamps for the rest of the type.

PDU Status

BitsFieldApplies to
0Transferred Entity Indicator (TEI)PDUs that identify an entity
1-2LVC IndicatorAll PDUs
3Coupled Extension Indicator (CEI)All PDUs
4-5Depends on PDU typeSee below
6-7Reserved

Bits 4 and 5 mean different things depending on the PDU:

PDUBits 4-5Accessor
FireFire Type Indicator (bit 4)fti / set_fti
DetonationDetonation Type Indicatordti / set_dti
Transmitter, Signal, ReceiverRadio Attached Indicatorrai / set_rai
Intercom Signal, Intercom ControlIntercom Attached Indicatoriai / set_iai
IFFIFF Simulation Mode (bit 4), Active Interrogation Indicator (bit 5)ism / set_ism, aii / set_aii

The accessors are on records::PduStatus, which you reach through header.pdu_status. The fields every PDU can use have accessors, too: tei / set_tei, lvc / set_lvc, and cei / set_cei.

The two-bit fields can hold 3, which none of the enumerations define, so dti, rai, and iai return an Option. A decoded record keeps every bit as received, including bits 6 and 7, and to_raw and from_raw give the whole octet.

What encoding fills in for you

serialize() sets these fields from the PDU’s contents, so you never set them yourself:

  • The header’s PDU type, protocol family, and length.
  • Every count field, such as the number of variable parameter records or datum records, from the length of the matching Vec.
  • Record length fields in variable-length records, such as attribute records and variable transmitter parameters.
  • Flag fields that say which optional fields are present. PDUs that have optional fields include the TSPI PDU, the Appearance PDU, and the Minefield Data PDU.
  • Padding, which is always written as 0.

You set the exercise ID, the timestamp, and the PDU Status bits. The protocol version defaults to 7, which represents IEEE 1278.1-2012.

new() also runs these updates, so a freshly created PDU already has the right length in its header. Read the header’s PDU type, protocol family, and length with its pdu_type(), protocol_family(), and length() methods. The PDU’s own pdu_type() and protocol_family() methods give the same values and work even before the header is set.

Strings

Entity Marking is one character-set octet followed by exactly 11 character octets. Shorter strings are padded when encoded. Longer ones are cut to 11 octets, so keep markings short.

Several PDUs in one datagram

The standard allows more than one PDU in a single datagram. deserialize reads exactly the number of octets given by the PDU’s length field and leaves the rest in the buffer. AnyPdu::deserialize_all uses this to decode every PDU in a datagram:

for pdu in AnyPdu::deserialize_all(datagram) {
    match pdu {
        Ok(AnyPdu::EntityState(pdu)) => {
            // ...
        }
        Ok(_) => {} // a PDU we do not care to handle
        Err(e) => eprintln!("dropping a PDU: {e}"),
    }
}

When one PDU fails to decode, its error is yielded and decoding carries on with the next PDU, as long as the failed PDU’s length field fits in the datagram. If it does not, the rest of the datagram cannot be split into PDUs, so the error is the last item.

To send a bundle, serialize each PDU into the same buffer, one after another, and keep the total under the network’s maximum datagram size.

Errors

Every fallible operation in open-dis-rust returns Result<T, DISError>. The crate never panics on bad input, so a malformed or unexpected PDU always comes back to you as an error you can handle.

DISError implements std::error::Error and Display. The alias DISResult<T> can be imported as a shorthand for Result<T, DISError>.

Possibly encountered errors

These are the variants the crate currently returns. The messages are the actual Display output.

WireFormat

The bytes do not form a valid PDU. This is the most common decoding error. It has three typical causes:

  • The buffer ends partway through a field, usually because the datagram was shorter than the 12-octet header:
  PDU wire format error: Not enough data, need 16 bits (or 2 bytes)
  • An enumerated field holds a value the crate doesn’t define. This includes the protocol version in the header:
  PDU wire format error: Parse error: 99 is not a defined ProtocolVersion value
  PDU wire format error: Parse error: 32513 is not a defined AcknowledgeFlag value
  • A record’s fields are inconsistent, for example a count or length field that doesn’t match the data. This also happens when encoding a record you built yourself:
  PDU wire format error: VariableDatumRecord: 16 bits needs 2 octets, but value has 3

The variant holds a WireFormatError, whose message describes the problem. The error from the crate’s internal encoding library isn’t exposed, so match on WireFormat(_) and use the message.

InvalidHeader

The header was read but does not fit the PDU you asked for.

Invalid PDU header: expected PDU type EntityState, got Acknowledge
Invalid PDU header: PDU length 4 is shorter than its 12-octet header

The first is a normal event on a busy network. It means you called deserialize on the wrong type, which you can avoid by checking PduHeader::get_pdu_type first, or by decoding with AnyPdu::deserialize. AnyPdu reports an undefined PDU type as an InvalidHeader too.

BufferUnderflow

The header’s length field promises more octets than the buffer holds. This usually means the datagram was truncated, or your receive buffer was too small.

Buffer underflow: tried to read 20 bytes, but only 8 bytes remain

Make receive buffers at least MAX_PDU_SIZE_OCTETS (8192) octets.

DeserializationError

The PDU decoded, but its length field covers more octets than its fields use.

PDU deserialization error: PDU length 36 is 4 octets longer than its fields

This can mean the sender uses a newer or extended version of the PDU, or that the crate is missing a field. See Conformance Notes.

PduSizeExceeded

Encoding would produce a PDU larger than the 8192-octet limit, usually because of too many records or a very large datum value.

PDU size exceeds maximum allowed: 9104 > 8192

Split the data across several PDUs.

Reserved variants

SerializationError exists for internal failures while encoding, which should not happen in practice. Keep a catch-all arm in your match so that variants added in future releases do not break your code.

Errors that are not reported

new() and finalize() cannot return errors. If a PDU’s contents are invalid, they leave the header length at 0 and carry on. serialize() runs the same checks and does report the error, so always check its result.

Handling errors in a receiver

On a shared network, some traffic will always fail to decode. It might come from another exercise, a newer simulator or a damaged packet. A receiver should log the problem and move on like so:

use open_dis_rust::prelude::*;
use open_dis_rust::entity_information::EntityStatePdu;

fn handle(datagram: &[u8]) {
    let Some(PduType::EntityState) = PduHeader::get_pdu_type(datagram) else {
        return; // not a PDU we care about
    };

    let mut bytes = datagram;

    match EntityStatePdu::deserialize(&mut bytes) {
        Ok(pdu) => {
            // use the PDU
        }
        Err(DISError::BufferUnderflow { .. }) => {
            eprintln!("truncated Entity State PDU; is the receive buffer big enough?");
        }
        Err(DISError::WireFormat(e)) => {
            eprintln!("undecodable Entity State PDU: {e}");
        }
        Err(e) => eprintln!("dropping Entity State PDU: {e}"),
    }
}

Architecture

This page explains how open-dis-rust is put together: where things live, how a PDU becomes bytes and vice versa, and the rules the code follows. Read it before making changes to the crate.

Layout

src/
├── lib.rs                         the crate root: the modules below, the prelude, and the
│                                  Pdu traits and DISError re-exported
│
│   IEEE 1278.1-2012
├── entity_information.rs          ┐
├── warfare.rs                     │
├── logistics.rs                   │  the PDUs, one module per protocol family
├── ...                            │
├── information_operations.rs      ┘
├── records.rs                     the §6.2 and Annex B records PDUs are built from, in
│                                  section order, including PduHeader and PduStatus
├── records/tests.rs               record tests
├── live_entity_records.rs         LiveEntityPduHeader, FixedBinary8/16 and the compact
│                                  records used by Live Entity PDUs
├── constants.rs                   the standard's symbolic values and size limits
│
│   SISO-REF-010-2023
├── siso/
│   ├── mod.rs                     impl_deku_enum! and impl_deku_bitflags!
│   ├── enums.rs                   the generated enumerations
│   ├── enums/tests.rs             encoding tests for every enumeration
│   ├── appearance.rs              typed views of the appearance layouts (§17.11)
│   ├── appearance/tests.rs        appearance tests
│   └── bit_records.rs             the other SISO bit layouts
│
│   the crate's own code, private and re-exported from the root
├── any_pdu.rs                     AnyPdu, for decoding a PDU of any type
├── pdu.rs                         the Pdu, StandardPdu and LiveEntityPdu traits, and the
│                                  impl_pdu! and pdu_tests! macros
├── dis_error.rs                   DISError, DISResult and WireFormatError
└── wire.rs                        bridges byte slices and vectors to deku, plus encoding helpers

Every public module has one source:

  • IEEE 1278.1-2012. PDUs live in the module for their family. The records they share live in records.rs in the order of §6.2 of the standard. A part that only one PDU uses, such as Mine or ShaftRPMs, lives next to that PDU.
  • SISO-REF-010-2023. Anything whose layout or values SISO-REF-010 defines lives in siso. A record that IEEE 1278.1 defines stays in records even when its fields use SISO enumerations, as PduStatus does.
  • The crate. The Pdu traits, AnyPdu, DISError and the prelude are the crate’s own API. Their modules are private, and the crate root re-exports them, so each has one path.

Conveniences stay with the type they serve rather than in a utilities module: Timestamp::now(), EntityAppearance::view() and every from_raw/to_raw are methods on their types. The same goes for types the crate adds to give a standard concept a Rust shape, such as AppearanceView or SimulationManagementId. Their docs say that they’re conveniences.

Deku

This crate leverages deku for most of its data encoding. PDUs and records are plain structs that derive deku’s DekuRead and DekuWrite, and deku generates the code to read and write their fields in order. Attributes on each field describe anything that is not a fixed-size value: counts, lengths, optional fields, and padding.

There are two attribute forms.

PDU structs are always big-endian:

#[derive(Debug, Default, deku::DekuRead, deku::DekuWrite)]
#[deku(endian = "big")]
pub struct ServiceRequestPdu { … }

Records take their byte order from whatever contains them, and default to big-endian when used on their own:

#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
#[deku(
    endian = "endian",
    ctx = "endian: deku::ctx::Endian",
    ctx_default = "deku::ctx::Endian::Big"
)]
pub struct EntityIdentifier {
    pub simulation_address: SimulationAddress,
    pub entity_id: u16,
}

Header and body

Every PDU struct starts with its header, marked #[deku(skip)]:

pub struct ServiceRequestPdu {
    #[deku(skip)]
    header: PduHeader,
    pub receiving_entity_id: EntityIdentifier,
    ...
}

deku only handles the body. The header is read and written separately by the code that impl_pdu! generates, because its length field depends on the size of the body, and because receivers need to read the header before they know which PDU type to decode.

impl_pdu!

impl_pdu! turns a deku struct into a PDU. One line per PDU:

crate::pdu::impl_pdu!(ServiceRequestPdu, PduHeader, PduType::ServiceRequest, ProtocolFamily::Logistics);

It implements the Pdu trait and adds a new() constructor. The generated methods work like this:

Encoding (serialize):

  1. Set the header’s PDU type and protocol family.
  2. Run deku’s update rules (DekuUpdate::update), which recompute derived fields such as counts, lengths and flags from the data. See Derived fields.
  3. Append the header and then the body to the caller’s Vec<u8>.
  4. Compute the total length, header plus body, and fail if it’s over 8192 octets.
  5. Rewrite the header in place with the real length. If any step fails, the vector is truncated back to its original length so callers never see a partial PDU.

Decoding (deserialize):

  1. Read the 12-octet header.
  2. Check that its PDU type matches the struct being decoded.
  3. Take exactly the number of octets the Length field gives. Fail if the buffer is shorter.
  4. Decode the body from those octets only, so a bad PDU can’t read into the next one.
  5. Fail if any of those octets weren’t used.
  6. Attach the header to the decoded body and advance the caller’s slice past the PDU.

new() is Default::default() plus the PDU type, family and length, so a new PDU is always valid to send.

Derived fields and update rules

The values of some fields are determined by the value of others: a count by the length of the associated list, a record length by its contents, or a flag by whether an optional field is present. Users should never have to set these, so each one has a deku update rule:

#[deku(update = "self.supplies.len()")]
pub number_of_supply_types: u8,
padding: u16,
#[deku(count = "number_of_supply_types")]
pub supplies: Vec<SupplyQuantity>,
  • update says how to compute the field when encoding.
  • count says how many items to read when decoding.

When a record inside a list has its own derived fields, the list’s count field runs the record’s update rules too, using wire::update_each:

#[deku(update = "crate::wire::update_each(&mut self.systems)?")]
pub number_of_systems: u8,

update_each updates every record and returns the list’s length, so one rule covers both jobs.

Other field patterns

SituationPatternExample
PaddingA private field named padding, padding2 and so on, with the width the standard givesCollisionPdu
Optional field controlled by a flagOption<T> with #[deku(cond = "…")], plus an update rule that sets the flagTimeSpacePositionInformationPdu
A 16- or 32-bit count read from the wireAdd assert = "crate::wire::fits_in_pdu(*count)"AggregateStatePdu
Variable-length record with a length fieldUse the wire helpers padded_record_length, record_fields_len and write_padded_fieldsAttribute
A layout attributes can’t describeCustom reader and writer functions on the fieldMinefieldDataPdu, IFFPdu
A record that needs a fully hand-written codecImplement DekuReader, DekuWriter and DekuUpdate yourself, then call impl_deku_default_endian!GridAxisDescriptor

Enumerations

The enumerations and bit layouts in siso take three forms:

  • Ordinary enums derive FromPrimitive and get their deku code from impl_deku_enum!(Name, u8, from_u8). The macro is hand-written rather than derived because deku’s derived reader for the largest enums, which have thousands of variants, needs megabytes of stack in debug builds.
  • Bit flags use the bitflags! macro, with impl_deku_bitflags! for encoding. Unknown bits are kept, so flags from newer revisions round-trip unchanged.
  • Bit records with enumerated or multi-bit fields, such as siso::bit_records::ComponentVisualDamageStatus, keep the wire value in a private raw field with a getter and setter for each field. Bit 0 is the least significant bit, and unused bits are kept as received. PduStatus and the appearance views work the same way.

Updating Enumerations covers how to change them.

What is public and what is not

The public API is the PDU and record structs, the constants, the siso enumerations and bit layouts, the Pdu, StandardPdu, and LiveEntityPdu traits, and DISError. Everything that names a deku type is internal: the wire module, impl_pdu!, pdu_tests! and impl_deku_default_endian! are all private to the crate, and DISError::WireFormat wraps deku’s error in the opaque WireFormatError variant.

This keeps deku, which hasn’t reached 1.0, out of the crate’s stable API, so the crate can upgrade deku without a breaking release. Keep it that way:

  • Don’t add a public function, trait method, or From impl that takes or returns a deku type. Convert deku errors with DISError::from_wire, which is pub(crate).
  • Public encoding and decoding go through Vec<u8> and &[u8], not through deku’s readers and writers or another crate’s buffer types.

The structs still implement deku’s DekuRead and DekuWrite because they’re derived. Those impls are visible in the API documentation, but they aren’t part of the stable API, and users shouldn’t call them.

Rules the code follows

This crate denies clippy’s pedantic and nursery groups, plus a set of lints that rule out panics. These are configured in Cargo.toml, and they shape how the code is written:

  • No panics on any input. No unwrap, expect, panic!, unreachable!, or todo! outside tests. Errors are propagated up to the caller as DISError.
  • No indexing. Use .get() instead of [i], and .get(..n) instead of slicing.
  • No unchecked arithmetic. Use checked_* or saturating_* methods instead of +, -, and *.
  • No as casts. Use From and TryFrom so that a value that does not fit is an error instead of being truncated. Generated code that needs as allows it within that scope.
  • No trust of count values from the wire. A count field in a received PDU can say anything, especially if the PDU was constructed with a separate crate/library. Check it against the PDU size limit before allocating, with fits_in_pdu or wire::read_n, so a malformed/malicious PDU cannot make a receiver allocate an unreasonable amount of memory.
  • Keep encoding and decoding symmetric. Every field read must be written the same way. The round-trip tests check this for every PDU.

Testing Strategy

A DIS codec has two separate jobs: its encoder and decoder must agree with each other, and both must agree with the standard and with other DIS implementations. The current tests cover the first objective well. This page describes them, then the tests needed for the second objective.

What the tests cover today

Run everything with cargo test.

PDU tests

Every PDU has a pdu_tests! entry at the bottom of its module, which generates these tests:

TestChecks
decodes_as_any_pduAnyPdu::deserialize decodes the PDU as its own type and encodes it to the same bytes.
new_sets_pdu_typenew() sets the PDU type in the header.
new_sets_default_lengthnew() sets the header length to the expected default size.
serialized_length_matches_headerThe encoded size equals the header’s Length field.
round_trip_is_byte_identicalEncoding, decoding and encoding again produces identical bytes and an identical header.
rejects_wrong_pdu_typeDecoding a different PDU type as this one fails.

The default length test is the only one that checks the crate against the standard, and only for an empty PDU. Its expected size should be worked out from the standard by hand.

Enumeration tests

siso/enums/tests.rs checks that every enumeration encodes to the right number and that undefined numbers are rejected. 8- and 16-bit enums are tested with every possible value. 32-bit enums are tested at every defined value, the values next to them, and a few far-off ones.

Unit tests

A few modules, including pdu_header.rs and constants.rs have their own unit tests for specific behavior such as get_pdu_type.

What round-trip tests cannot catch

A round-trip test passes whenever the encoder and decoder agree, even if both are wrong. If a record has a padding field that is 16 bits instead of 8, the encoder writes one extra octet, the decoder reads one extra octet, and the round trip passes. Only another DIS implementation would notice the error.

Every problem listed in Conformance Notes is of this kind, and all of them pass the current tests.

Golden-byte tests

A golden-byte test compares the crate’s output with bytes that came from outside the crate; that is, written out by hand from the standard’s field tables, or captured from another DIS implementation.

Put them in tests/golden.rs. Write each fixture as hex, laid out one field per line with a comment, so a reviewer can check it against the standard line by line:

#![allow(clippy::unwrap_used, reason = "test helpers")]

use open_dis_rust::{
    Pdu,
    records::{EntityIdentifier, SimulationAddress, Timestamp},
    simulation_management::AcknowledgePdu,
    siso::enums::{AcknowledgeFlag, AcknowledgeResponseFlag},
};

const ACKNOWLEDGE: &str = "
    07 01 0F 05   00 00 00 00   00 20 00 00   # header: v7, exercise 1, type 15, family 5, timestamp 0, length 32
    00 01 00 01 00 00                         # originating entity 1:1:0
    00 01 00 02 00 00                         # receiving entity 1:2:0
    00 01                                     # acknowledge flag: Create Entity
    00 01                                     # response flag: Able to Comply
    00 00 00 2A                               # request ID 42
";

/// Parses a fixture: hex digits, with whitespace and `# comments` ignored.
fn fixture(s: &str) -> Vec<u8> {
    let digits: Vec<u8> = s
        .lines()
        .flat_map(|line| line.split('#').next().unwrap().bytes())
        .filter(|b| !b.is_ascii_whitespace())
        .collect();
    digits
        .chunks(2)
        .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
        .collect()
}

#[test]
fn acknowledge_encodes_to_golden_bytes() {
    let mut pdu = AcknowledgePdu::new();
    pdu.header_mut().timestamp = Timestamp::from_raw(0); // fixed, so the bytes are repeatable
    pdu.originating_entity_id = EntityIdentifier::new(SimulationAddress::new(1, 1), 0);
    pdu.receiving_entity_id = EntityIdentifier::new(SimulationAddress::new(1, 2), 0);
    pdu.acknowledge_flag = AcknowledgeFlag::CreateEntity;
    pdu.response_flag = AcknowledgeResponseFlag::AbleToComply;
    pdu.request_id = 42;

    assert_eq!(pdu.to_bytes().unwrap(), fixture(ACKNOWLEDGE));
}

#[test]
fn acknowledge_decodes_from_golden_bytes() {
    let bytes = fixture(ACKNOWLEDGE);
    let pdu = AcknowledgePdu::deserialize(&mut bytes.as_slice()).unwrap();
    assert_eq!(
        pdu.receiving_entity_id,
        EntityIdentifier::new(SimulationAddress::new(1, 2), 0)
    );
    assert_eq!(pdu.response_flag, AcknowledgeResponseFlag::AbleToComply);
    assert_eq!(pdu.request_id, 42);
}

Test both directions for each fixture. Encoding checks that the crate writes exactly these bytes. Decoding checks that it reads the right values from them.

Set the timestamp to a fixed value, such as 0, before encoding. Otherwise, the bytes change on every run.

Where fixtures come from

In order of preference:

  1. Captures from other implementations, such as OpenDIS for Java, C++ or Python, or a commercial tool. These test real interoperability. Save the PDU’s bytes from a Wireshark capture (right-click the DIS layer, then Copy -> …as a Hex Stream) and note where it came from in a comment.
  2. Hand-written from the standard, as in the example above. Fill every field with a different, recognizable value, so that a field in the wrong place shows up clearly.
  3. Never from open-dis-rust itself. A fixture produced by the encoder under test only checks that the encoder hasn’t changed.

Prioritize golden tests for PDUs with variable-length records, padding inside lists, or length fields measured in bits or 32-bit words. Those are where the current bugs are.

Fuzzing

Decoding must never panic no matter what bytes arrive. The crate’s lints rule out most panics, but fuzzing checks for the rest along with unbounded memory use. cargo-fuzz works well for this. A useful target decodes arbitrary bytes as each PDU type and, when decoding succeeds, checks that encoding the result reproduces the input:

#![no_main]
use libfuzzer_sys::fuzz_target;
use open_dis_rust::{Pdu, entity_information::EntityStatePdu};

fuzz_target!(|data: &[u8]| {
    let mut input = data;
    if let Ok(mut pdu) = EntityStatePdu::deserialize(&mut input) {
        let used = data.len() - input.len();
        let bytes = pdu.to_bytes().expect("a decoded PDU must re-encode");
        assert_eq!(bytes, data[..used], "re-encoding must reproduce the input");
    }
});

Checking against Wireshark

Wireshark’s DIS dissector is an independent implementation of the standard, and its command-line version, tshark, can run in CI. Write the crate’s PDUs to a .pcap file in a test, then run tshark -r out.pcap -V and fail if it reports any packet as malformed. This catches layout errors in PDUs that don’t have golden-byte tests yet.

Continuous integration

CI runs on every pull request and push to main. It currently:

  • runs cargo test on nightly Rust
  • builds on stable and beta
  • runs clippy and uploads the results to GitHub code scanning

Before you push, run the same checks locally:

cargo fmt --check
cargo clippy --all-targets
cargo test
cargo build --examples
mdbook build book

Improvements the CI would benefit from:

  • Run the tests on stable, the toolchain users build with, as well as nightly.
  • Fail the build on clippy warnings. The clippy step currently has continue-on-error: true, so the strict lints in Cargo.toml aren’t enforced.
  • Check formatting with cargo fmt --check.
  • Build the examples and the book, so the Quickstart code and the book’s code samples will not fall out of date.

Updating Enumerations

The enumerations in src/siso/enums.rs come from SISO-REF-010 which SISO revises regularly. The crate currently follows SISO-REF-010-2023. This page covers the conventions for enumerations and how to move the crate to a new revision.

Enumerations explains what SISO-REF-010 is and how users see these types.

Conventions

Every enumeration in enums.rs follows the same pattern. If modifying or updating to a new SISO revision, please adhere to this existing pattern so that the file stays consistent and could be regenerated by a script later.

Ordinary enums

// SISO-REF-010-2023 RepairResponseRepairResult [UID 65]
#[derive(Copy, Clone, Debug, Default, FromPrimitive, PartialEq, Eq)]
pub enum RepairResponseRepairResult {
    #[default]
    Other = 0,
    RepairEnded = 1,
    InvalidRepair = 2,
    RepairInterrupted = 3,
    ServiceCanceledByTheSupplier = 4,
}

impl_deku_enum!(RepairResponseRepairResult, u8, from_u8);
  • Comment line. The SISO-REF-010 revision, the table name and its UID. The UID is how anyone can find the table in SISO-REF-010.
  • Name. The table name in upper camel case, with spaces and punctuation removed. Variant names follow the same rule, from each row’s description.
  • Values. Give every variant an explicit value. Do not allow for values to be determined implicitly.
  • Default. Mark the variant for value 0, usually Other or NoStatement, with #[default]. If 0 isn’t defined, use the most neutral value.
  • impl_deku_enum!. The second argument is the field’s width on the wire, as given by SISO-REF-010: u8, u16 or u32. The third is the matching FromPrimitive method: from_u8, from_u16 or from_u32. A wrong width shifts every field after it.

Bit flags

Tables whose values are bits that can be combined use bitflags! instead. These, and the hand-written bit layouts with multi-bit fields, live in src/siso/bit_records.rs and src/siso/appearance.rs, not in enums.rs, so regenerating enums.rs will not overwrite them:

// SISO-REF-010-2023 FrozenBehavior [UID 68]
bitflags! {
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    pub struct FrozenBehavior: u8 {
        const RunSimulationClock = 1 << 0;
        const TransmitUpdates = 1 << 1;
        const ProcessUpdates = 1 << 2;
    }
}

impl_deku_bitflags!(FrozenBehavior, u8);

PDU Status fields

The enums for the PDU Status record’s bit fields, such as LVCIndicator, are packed into PduStatus by its accessors, which match on every variant. Adding a variant to one of them is a compile error until the matching accessor handles it.

Deprecated values

When SISO deprecates a value, keep the variant and mark it:

#[deprecated(note = "Deprecated in SISO-REF-010-2023")]
SerbiaandMontenegro_ = 240,

NEVER remove or renumber a variant, even a deprecated one. Old recordings and older simulators still send those values, and the crate needs to be able to decode them.

Moving to a new revision

1. Get the new revision

Download the new SISO-REF-010 from the SISO website. Along with the PDF, SISO publishes a machine-readable XML edition, which is much easier to compare between revisions.

2. Find what changed

Compare the XML of the new revision with the current one, and list the tables that changed. For each one, note any new values, deprecated values and renamed descriptions. Also note any tables that are new in this revision.

3. Update the enums

For each changed table:

  • New values: add variants with explicit values in numeric order.
  • Newly deprecated values: add #[deprecated(note = "Deprecated in SISO-REF-010-YYYY")].
  • Renamed descriptions: keep the old variant name, because renaming a variant breaks users’ code. If the new name is much clearer, add it as an associated constant instead, and leave the old variant as it is:
  impl Country {
      #[allow(non_upper_case_globals)]
      pub const NewName: Self = Self::OldName;
  }
  • New tables: add a new enum following the conventions above.

4. Update the tests

src/siso/enums/tests.rs has one line per enum in deku_matches_from_primitive_for_every_enum. Add a line for every new enum:

check_u8::<RepairResponseRepairResult>(RepairResponseRepairResult::from_u8);

check_u8 and check_u16 test every possible value. check_u32 can’t, so it takes a list of the defined values, which you must update whenever you add values to a 32-bit enum:

check_u32::<EntityCapabilities>(
    &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    EntityCapabilities::from_u32,
);

5. Update the revision everywhere

Replace the old revision with the new one in

  • the comment line above every enum in enums.rs
  • the Enumerations page in this book
  • README.md where the revision is mentioned

Leave the revision in existing #[deprecated] notes as it is. Those record when each value was deprecated.

Get In Touch

open-dis-rust is maintained by volunteers in their spare time. Everything happens on GitHub, so whatever you need, start there. Please use the channel that fits your request. That way it reaches the right place, and other users can find the answer later.

I want to…Go here
Ask a question or get help using the crateGitHub Discussions
Report a bug or a PDU / data type / enumeration that doesn’t match the standardBug report
Suggest a new feature or API changeFeature request
Report a mistake in this book or the API docsDocumentation issue
Report a security vulnerabilityPrivate security advisory. Please don’t open a public issue for security vulnerabilities.

Before you open an issue

  • Search first. Check open and closed issues and Discussions. Somebody may already have run into the same problem.
  • Check that you are using the latest release. Run cargo update -p open-dis-rust and try again. It is possible your issue has already been addressed in a new update.
  • Check the API documentation. Most questions about a specific type or method could be answered there.

Reporting a bug

A good report allows a maintainer to reproduce the problem without guessing. Please include:

  • The open-dis-rust version (from Cargo.lock) and your Rust version (rustc --version).
  • The PDU type, record, or enumeration involved.
  • What you expected vs. what happened, including the full DISError message if there is one.
  • The smallest code that shows the problem, if you are able to trim it down.

Encoding and interoperability problems

If a PDU will not decode, or another DIS application cannot read what open-dis-rust sends, the raw bytes are by far the most useful thing you can attach:

  • A packet capture (.pcap or .pcapng) from Wireshark, trimmed to the PDUs in question, or a hex dump of the datagram.
  • The other application involved and its version.
  • If you have it, the section or table of IEEE 1278.1-2012 that you think the crate gets wrong.

Please remove anything sensitive from captures before attaching them, such as exercise data, IP addresses, or real-world locations. Also, NEVER post anything CUI or classified. Doing so is a violation of federal law and potentially a danger to the security of the United States (or whichever country controls the data).

Security issues

If you find a vulnerability such as a malformed PDU that crashes a receiver or uses unbounded memory, report it privately using GitHub’s private vulnerability reporting.

A maintainer will acknowledge your report within 5 days. We will work with you on a fix and agree on a disclosure date before anything is made public. See SECURITY.md for which versions receive security fixes.

What to expect

This is a volunteer project, so response times vary. Most issues get a first reply within a week. If you post an issue and don’t get a response within a couple weeks, a polite follow-up comment is welcome. Pull requests that include tests, and bug reports with a capture attached, are usually handled fastest.

Everyone taking part is expected to follow the project’s Code of Conduct.

Maintainers

  • Cameron Howell (@crhowell3), creator and lead maintainer

Supporting the project

Contributing fixes, documentation, and packet captures from real exercises helps make this crate better.