Skip to main content

open_dis_rust/
records.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::fmt;
8use std::time::{Duration, SystemTime, UNIX_EPOCH};
9
10use deku::{
11    DekuError, DekuReader, DekuUpdate, DekuWriter,
12    ctx::Endian,
13    no_std_io::{Read, Seek, Write},
14    reader::Reader,
15    writer::Writer,
16};
17use num_traits::FromPrimitive;
18
19use crate::siso::appearance::ObjectStateAppearanceGeneral;
20use crate::siso::bit_records::ComponentVisualDamageStatus;
21use crate::siso::enums::{
22    ActiveInterrogationIndicator, AggregateStateAggregateKind, ArticulatedPartsTypeClass,
23    ArticulatedPartsTypeMetric, AttachedPartDetachedIndicator, BeamStatusBeamState,
24    ComponentDamageStatus, ComponentIdentification, ComponentVisualSmokeColor, Country,
25    CoupledExtensionIndicator, DEPrecisionAimpointBeamSpotType, DetonationTypeIndicator,
26    EEAttributeStateIndicator, EmitterName, EmitterSystemFunction,
27    EntityAssociationAssociationStatus, EntityAssociationAssociationType,
28    EntityAssociationGroupMemberType, EntityAssociationPhysicalAssociationType,
29    EntityAssociationPhysicalConnectionType, EntityKind, EntityMarkingCharacterSet,
30    EntityOwnershipStatus, EntityVPRecordChangeIndicator, EnvironmentalProcessRecordType,
31    ExplosiveMaterialCategories, FireTypeIndicator, ForceId, FuelLocation, FuelMeasurementUnits,
32    GridAxisDescriptorAxisType, GriddedDataDataRepresentation, GriddedDataSampleType,
33    IFFApplicableModes, IFFSimulationMode, IFFSystemMode, IFFSystemName, IFFSystemType,
34    IOCommsNodeRecordCommsNodeType, IOEffectsRecordIOEffect, IOEffectsRecordIOLinkType,
35    IOEffectsRecordIOProcess, IOEffectsRecordIOStatus, IntercomAttachedIndicator,
36    IntercomControlRecordType, IsPartOfStationName, LVCIndicator, MinefieldSensorTypesFLIR,
37    MinefieldSensorTypesLaser, MinefieldSensorTypesMagnetic, MinefieldSensorTypesMultispectral,
38    MinefieldSensorTypesOptical, MinefieldSensorTypesPhysical, MinefieldSensorTypesRADAR,
39    MinefieldSensorTypesSONAR, MinefieldStateProtocolMode, MunitionDescriptorFuse,
40    MunitionDescriptorWarhead, MunitionExpendableStatus, OtherKinds, PduStatusIFFSimulationMode,
41    PduType, ProtocolFamily, ProtocolVersion, RadioAttachedIndicator, SensorOnOffStatus,
42    SensorTypeSource, SeparationVPPreEntityIndicator, SeparationVPReasonforSeparation,
43    ServiceRequestServiceTypeRequested, SupplyFuelType, TransferredEntityIndicator,
44    TransmitterAntennaPatternReferenceSystem, TransmitterMajorModulation,
45    TransmitterModulationTypeSystem, TransponderInterrogatorIndicator,
46    UAAcousticEmitterSystemFunction, UAAcousticSystemName, UAActiveEmissionParameterIndex,
47    UAScanPattern, VariableRecordTypes,
48};
49use crate::wire;
50
51#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
52#[deku(
53    endian = "endian",
54    ctx = "endian: deku::ctx::Endian",
55    ctx_default = "deku::ctx::Endian::Big"
56)]
57/// Implemented according to IEEE 1278.1-2012 §6.2.2
58pub struct AcousticEmitterSystem {
59    pub acoustic_name: UAAcousticSystemName,
60    pub acoustic_function: UAAcousticEmitterSystemFunction,
61    pub acoustic_id: u8,
62}
63
64impl AcousticEmitterSystem {
65    #[must_use]
66    pub const fn new(
67        acoustic_name: UAAcousticSystemName,
68        acoustic_function: UAAcousticEmitterSystemFunction,
69        acoustic_id: u8,
70    ) -> Self {
71        Self {
72            acoustic_name,
73            acoustic_function,
74            acoustic_id,
75        }
76    }
77}
78
79/// Implemented according to IEEE 1278.1-2012 §6.2.3
80#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
81#[deku(
82    endian = "endian",
83    ctx = "endian: deku::ctx::Endian",
84    ctx_default = "deku::ctx::Endian::Big"
85)]
86pub struct AggregateIdentifier {
87    pub simulation_address: SimulationAddress,
88    pub aggregate_id: u16,
89}
90
91impl AggregateIdentifier {
92    #[must_use]
93    pub const fn new(simulation_address: SimulationAddress, aggregate_id: u16) -> Self {
94        Self {
95            simulation_address,
96            aggregate_id,
97        }
98    }
99}
100
101/// Implemented according to IEEE 1278.1-2012 §6.2.4
102#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
103#[deku(
104    endian = "endian",
105    ctx = "endian: deku::ctx::Endian",
106    ctx_default = "deku::ctx::Endian::Big"
107)]
108pub struct AggregateMarking {
109    pub character_set: EntityMarkingCharacterSet,
110    pub characters: [u8; 31],
111}
112
113impl AggregateMarking {
114    #[must_use]
115    pub const fn new(character_set: EntityMarkingCharacterSet, characters: [u8; 31]) -> Self {
116        Self {
117            character_set,
118            characters,
119        }
120    }
121}
122
123/// Implemented according to IEEE 1278.1-2012 §6.2.5
124#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
125#[deku(
126    endian = "endian",
127    ctx = "endian: deku::ctx::Endian",
128    ctx_default = "deku::ctx::Endian::Big"
129)]
130pub struct AggregateType {
131    pub aggregate_kind: AggregateStateAggregateKind,
132    pub domain: OtherKinds,
133    pub country: Country,
134    pub category: u8,
135    pub subcategory: u8,
136    pub specific: u8,
137    pub extra: u8,
138}
139
140impl AggregateType {
141    #[must_use]
142    pub const fn new() -> Self {
143        Self {
144            aggregate_kind: AggregateStateAggregateKind::Other,
145            domain: OtherKinds::Other,
146            country: Country::Other,
147            category: 0,
148            subcategory: 0,
149            specific: 0,
150            extra: 0,
151        }
152    }
153}
154
155/// Implemented according to IEEE 1278.1-2012 §6.2.6
156#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
157#[deku(
158    endian = "endian",
159    ctx = "endian: deku::ctx::Endian",
160    ctx_default = "deku::ctx::Endian::Big"
161)]
162pub struct Angle(f32);
163
164/// Implemented according to IEEE 1278.1-2012 §6.2.7
165/// For all fields, assume right-hand rule for directionality
166#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
167#[deku(
168    endian = "endian",
169    ctx = "endian: deku::ctx::Endian",
170    ctx_default = "deku::ctx::Endian::Big"
171)]
172pub struct AngularVelocityVector {
173    /// The angular velocity in radians/second about the entity's X-axis
174    pub rate_about_x_axis: f32,
175    /// The angular velocity in radians/second about the entity's Y-axis
176    pub rate_about_y_axis: f32,
177    /// The angular velocity in radians/second about the entity's Z-axis
178    pub rate_about_z_axis: f32,
179}
180
181impl AngularVelocityVector {
182    /// Create a new `AngularVelocity` struct with existing values
183    #[must_use]
184    pub fn new() -> Self {
185        Self::default()
186    }
187}
188
189/// Implemented according to IEEE 1278.1-2012 §6.2.8.2
190#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
191#[deku(
192    endian = "endian",
193    ctx = "endian: deku::ctx::Endian",
194    ctx_default = "deku::ctx::Endian::Big"
195)]
196pub struct BeamAntennaPattern {
197    pub beam_direction: EulerAngles,
198    pub azimuth_beamwidth: f32,
199    pub elevation_beamwidth: f32,
200    pub reference_system: TransmitterAntennaPatternReferenceSystem,
201    padding: u8,
202    padding2: u16,
203    pub ez: f32,
204    pub ex: f32,
205    pub phase: f32,
206    padding3: u32,
207}
208
209/// Implemented according to IEEE 1278.1-2012 §6.2.9
210#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
211#[deku(
212    endian = "endian",
213    ctx = "endian: deku::ctx::Endian",
214    ctx_default = "deku::ctx::Endian::Big"
215)]
216pub struct Association {
217    /// Indicates the type of association
218    pub association_type: EntityAssociationAssociationType,
219    /// Padding field
220    padding: u8,
221    /// Identifies the associated entity
222    associated_entity_id: EntityIdentifier,
223    /// Specifies the associated location in world coordinates
224    associated_location_in_world_coordinates: WorldCoordinates,
225}
226
227impl Association {
228    /// Create a new `Association` struct with existing values
229    #[must_use]
230    pub fn new() -> Self {
231        Self::default()
232    }
233}
234
235/// Implemented according to IEEE 1278.1-2012 §6.2.10
236#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
237#[deku(
238    endian = "endian",
239    ctx = "endian: deku::ctx::Endian",
240    ctx_default = "deku::ctx::Endian::Big"
241)]
242pub struct Attribute {
243    pub record_type: u32,
244    #[deku(
245        update = "crate::wire::padded_record_length(self.record_specific_fields.len())?",
246        assert = "crate::wire::valid_record_length(*record_length)"
247    )]
248    pub record_length: u16,
249    /// Everything after the record length. When decoded, this includes the
250    /// padding to the 64-bit boundary; when encoded, padding is added to
251    /// reach it.
252    #[deku(
253        count = "crate::wire::record_fields_len(*record_length)",
254        writer = "crate::wire::write_padded_fields(deku::writer, record_specific_fields)"
255    )]
256    pub record_specific_fields: Vec<u8>,
257}
258
259impl Attribute {
260    #[must_use]
261    pub const fn new() -> Self {
262        Self {
263            record_type: 0u32,
264            record_length: 0u16,
265            record_specific_fields: vec![],
266        }
267    }
268}
269
270/// Implemented according to IEEE 1278.1-2012 §6.2.11
271#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
272#[deku(
273    endian = "endian",
274    ctx = "endian: deku::ctx::Endian",
275    ctx_default = "deku::ctx::Endian::Big"
276)]
277pub struct BeamData {
278    pub beam_azimuth_center: f32,
279    pub beam_azimuth_sweep: f32,
280    pub beam_elevation_center: f32,
281    pub beam_elevation_sweep: f32,
282    pub beam_sweep_sync: f32,
283}
284
285impl BeamData {
286    #[must_use]
287    pub const fn new(
288        beam_azimuth_center: f32,
289        beam_azimuth_sweep: f32,
290        beam_elevation_center: f32,
291        beam_elevation_sweep: f32,
292        beam_sweep_sync: f32,
293    ) -> Self {
294        Self {
295            beam_azimuth_center,
296            beam_azimuth_sweep,
297            beam_elevation_center,
298            beam_elevation_sweep,
299            beam_sweep_sync,
300        }
301    }
302}
303
304/// Implemented according to IEEE 1278.1-2012 §6.2.12
305#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
306#[deku(
307    endian = "endian",
308    ctx = "endian: deku::ctx::Endian",
309    ctx_default = "deku::ctx::Endian::Big"
310)]
311pub struct BeamStatus {
312    raw: u8,
313}
314
315impl BeamStatus {
316    const BEAM_STATE: u8 = 0b0000_0001;
317
318    /// A Beam Status record with the given state and the padding bits clear.
319    #[must_use]
320    pub const fn new(beam_state: BeamStatusBeamState) -> Self {
321        let mut status = Self { raw: 0 };
322        status.set_beam_state(beam_state);
323        status
324    }
325
326    /// Whether the beam is active or deactivated
327    #[must_use]
328    pub const fn beam_state(self) -> BeamStatusBeamState {
329        if self.raw & Self::BEAM_STATE == 0 {
330            BeamStatusBeamState::Active
331        } else {
332            BeamStatusBeamState::Deactivated
333        }
334    }
335
336    /// Sets the Beam State bit, leaving the padding bits as they are
337    pub const fn set_beam_state(&mut self, beam_state: BeamStatusBeamState) {
338        self.raw = match beam_state {
339            BeamStatusBeamState::Active => self.raw & !Self::BEAM_STATE,
340            BeamStatusBeamState::Deactivated => self.raw | Self::BEAM_STATE,
341        };
342    }
343
344    /// A Beam Status record from its wire octet. The padding bits are kept so
345    /// a decoded record encodes back to the same octet
346    #[must_use]
347    pub const fn from_raw(raw: u8) -> Self {
348        Self { raw }
349    }
350
351    /// The record's wire octet
352    #[must_use]
353    pub const fn to_raw(self) -> u8 {
354        self.raw
355    }
356}
357
358/// Implemented according to IEEE 1278.1-2012 §6.2.13 & §B.2.4
359#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
360#[deku(
361    endian = "endian",
362    ctx = "endian: deku::ctx::Endian",
363    ctx_default = "deku::ctx::Endian::Big"
364)]
365pub struct ChangeOptions {
366    raw: u8,
367}
368
369impl ChangeOptions {
370    /// Change Indicator (bit 0): `true` when this is the entity's first IFF PDU, its data
371    /// changed since the last one, or it's the first heartbeat after a PDU that had this
372    /// bit set. Every system type implements it.
373    #[must_use]
374    pub const fn initial_report_or_change(self) -> bool {
375        self.raw & (1 << 0) != 0
376    }
377
378    /// Sets bit 0. See [`initial_report_or_change`](Self::initial_report_or_change).
379    pub const fn set_initial_report_or_change(&mut self, value: bool) {
380        if value {
381            self.raw |= 1 << 0;
382        } else {
383            self.raw &= !(1 << 0);
384        }
385    }
386
387    /// System-Specific Field 1 (bit 1). Its meaning depends on the system type: for
388    /// a system with a Mode 4 capability, it's the Alternate Mode 4 Indicator; `true`
389    /// when present. Systems that don't implement it set this to `false`.
390    #[must_use]
391    pub const fn system_specific_1(self) -> bool {
392        self.raw & (1 << 1) != 0
393    }
394
395    /// Sets bit 1. See [`system_specific_1`](Self::system_specific_1).
396    pub const fn set_system_specific_1(&mut self, value: bool) {
397        if value {
398            self.raw |= 1 << 1;
399        } else {
400            self.raw &= !(1 << 1);
401        }
402    }
403
404    /// System-Specific Field 2 (bit 2). Its meaning depends on the system type: for
405    /// a system with a Mode C capability, it's the Alternate Mode C Indicator; `true`
406    /// when present. Systems that don't implement it set this to `false`.
407    #[must_use]
408    pub const fn system_specific_2(self) -> bool {
409        self.raw & (1 << 2) != 0
410    }
411
412    /// Sets bit 2. See [`system_specific_2`](Self::system_specific_2).
413    pub const fn set_system_specific_2(&mut self, value: bool) {
414        if value {
415            self.raw |= 1 << 2;
416        } else {
417            self.raw &= !(1 << 2);
418        }
419    }
420
421    /// Heartbeat Indicator (bit 3): `true` when this IFF PDU is a heartbeat. Optional for
422    /// system types 1 to 5, required for the rest.
423    #[must_use]
424    pub const fn heartbeat(self) -> bool {
425        self.raw & (1 << 3) != 0
426    }
427
428    /// Sets bit 3. See [`heartbeat`](Self::heartbeat).
429    pub const fn set_heartbeat(&mut self, value: bool) {
430        if value {
431            self.raw |= 1 << 3;
432        } else {
433            self.raw &= !(1 << 3);
434        }
435    }
436
437    const TRANSPONDER_INTERROGATOR: u8 = 1 << 4;
438    const SIMULATION_MODE: u8 = 1 << 5;
439
440    /// Transponder/Interrogator Indicator (bit 4) \[UID 337\]. Optional for system types
441    /// 1 to 5, required for the rest. A combined system can be either, so the system type
442    /// and name along do not say which.
443    #[must_use]
444    pub const fn transponder_interrogator(self) -> TransponderInterrogatorIndicator {
445        if self.raw & Self::TRANSPONDER_INTERROGATOR == 0 {
446            TransponderInterrogatorIndicator::Transponder
447        } else {
448            TransponderInterrogatorIndicator::Interrogator
449        }
450    }
451
452    /// Sets bit 4. See [`transponder_interrogator`](Self::transponder_interrogator).
453    pub const fn set_transponder_interrogator(&mut self, value: TransponderInterrogatorIndicator) {
454        self.raw = match value {
455            TransponderInterrogatorIndicator::Transponder => {
456                self.raw & !Self::TRANSPONDER_INTERROGATOR
457            }
458            TransponderInterrogatorIndicator::Interrogator => {
459                self.raw | Self::TRANSPONDER_INTERROGATOR
460            }
461        };
462    }
463
464    /// Simulation Mode (bit 5) \[UID 338\]: Regeneration or Interactive. Every system type
465    /// implements it.
466    #[must_use]
467    pub const fn simulation_mode(self) -> IFFSimulationMode {
468        if self.raw & Self::SIMULATION_MODE == 0 {
469            IFFSimulationMode::Regeneration
470        } else {
471            IFFSimulationMode::Interactive
472        }
473    }
474
475    /// Sets bit 5. See [`simulation_mode`](Self::simulation_mode).
476    pub const fn set_simulation_mode(&mut self, value: IFFSimulationMode) {
477        self.raw = match value {
478            IFFSimulationMode::Regeneration => self.raw & !Self::SIMULATION_MODE,
479            IFFSimulationMode::Interactive => self.raw | Self::SIMULATION_MODE,
480        }
481    }
482
483    /// Interactive Capable (bit 6): `true` when the IFF system is capable of the
484    /// Interactive simulation mode.
485    #[must_use]
486    pub const fn interactive_capable(self) -> bool {
487        self.raw & (1 << 6) != 0
488    }
489
490    /// Sets bit 6. See [`interactive_capable`](Self::interactive_capable).
491    pub const fn set_interactive_capable(&mut self, value: bool) {
492        if value {
493            self.raw |= 1 << 6;
494        } else {
495            self.raw &= !(1 << 6);
496        }
497    }
498
499    /// Test Mode (bit 7): `true` when the IFF system is in equipment test mode.
500    #[must_use]
501    pub const fn test_mode(self) -> bool {
502        self.raw & (1 << 7) != 0
503    }
504
505    /// Sets bit 7. See [`test_mode`](Self::test_mode).
506    pub const fn set_test_mode(&mut self, value: bool) {
507        if value {
508            self.raw |= 1 << 7;
509        } else {
510            self.raw &= !(1 << 7);
511        }
512    }
513
514    /// A Change/Options record from its wire octet.
515    #[must_use]
516    pub const fn from_raw(raw: u8) -> Self {
517        Self { raw }
518    }
519
520    /// The record's wire octet.
521    #[must_use]
522    pub const fn to_raw(self) -> u8 {
523        self.raw
524    }
525}
526
527/// Implemented according to IEEE 1278.1-2012 §6.2.14
528#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
529#[deku(
530    endian = "endian",
531    ctx = "endian: deku::ctx::Endian",
532    ctx_default = "deku::ctx::Endian::Big"
533)]
534pub struct ClockTime {
535    /// The hours since 0000h 1 January 1970 UTC (The Epoch)
536    pub hour: u32,
537    /// Time past the hour indicated in the hour field
538    pub time_past_hour: Timestamp,
539}
540
541impl ClockTime {
542    #[must_use]
543    pub const fn new(hour: u32, time_past_hour: Timestamp) -> Self {
544        Self {
545            hour,
546            time_past_hour,
547        }
548    }
549
550    /// The current UTC time, from the system clock, with an absolute timestamp
551    #[must_use]
552    pub fn now() -> Self {
553        let since_epoch = SystemTime::now()
554            .duration_since(UNIX_EPOCH)
555            .unwrap_or_default();
556        let hour = u32::try_from(since_epoch.as_secs() / 3600).unwrap_or(u32::MAX);
557        Self::new(hour, Timestamp::absolute(since_epoch))
558    }
559}
560
561/// Implemented according to IEEE 1278.1-2012 §6.2.15
562#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
563#[deku(
564    endian = "endian",
565    ctx = "endian: deku::ctx::Endian",
566    ctx_default = "deku::ctx::Endian::Big"
567)]
568pub struct DirectedEnergyDamage {
569    pub record_type: u32,
570    pub record_length: u16,
571    padding: u16,
572    pub damage_location: Vector,
573    pub damage_diameter: f32,
574    pub temperature: f32,
575    pub component_identification: ComponentIdentification,
576    pub component_damage_status: ComponentDamageStatus,
577    pub component_visual_damage_status: ComponentVisualDamageStatus,
578    pub component_visual_smoke_color: ComponentVisualSmokeColor,
579    pub fire_event_id: EventIdentifier,
580    padding2: u16,
581}
582
583impl DirectedEnergyDamage {
584    #[must_use]
585    #[allow(clippy::too_many_arguments)]
586    pub const fn new(
587        damage_location: Vector,
588        damage_diameter: f32,
589        temperature: f32,
590        component_identification: ComponentIdentification,
591        component_damage_status: ComponentDamageStatus,
592        component_visual_damage_status: ComponentVisualDamageStatus,
593        component_visual_smoke_color: ComponentVisualSmokeColor,
594        fire_event_id: EventIdentifier,
595    ) -> Self {
596        Self {
597            record_type: 4500,
598            record_length: 40,
599            padding: 0_u16,
600            damage_location,
601            damage_diameter,
602            temperature,
603            component_identification,
604            component_damage_status,
605            component_visual_damage_status,
606            component_visual_smoke_color,
607            fire_event_id,
608            padding2: 0_u16,
609        }
610    }
611}
612
613/// Implemented according to IEEE 1278.1-2012 §6.2.16
614#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
615#[deku(
616    endian = "endian",
617    ctx = "endian: deku::ctx::Endian",
618    ctx_default = "deku::ctx::Endian::Big"
619)]
620pub struct DataFilter {
621    raw: u32,
622}
623
624impl DataFilter {
625    /// Ground Burial Depth Offet (bit 0).
626    #[must_use]
627    pub const fn ground_burial_depth_offset(self) -> bool {
628        self.raw & (1 << 0) != 0
629    }
630
631    /// Sets bit 0. See [`ground_burial_depth_offset`](Self::ground_burial_depth_offset).
632    pub const fn set_ground_burial_depth_offset(&mut self, value: bool) {
633        if value {
634            self.raw |= 1 << 0;
635        } else {
636            self.raw &= !(1 << 0);
637        }
638    }
639
640    /// Water Burial Depth Offset (bit 1).
641    #[must_use]
642    pub const fn water_burial_depth_offset(self) -> bool {
643        self.raw & (1 << 1) != 0
644    }
645
646    /// Sets bit 1. See [`water_burial_depth_offset`](Self::water_burial_depth_offset).
647    pub const fn set_water_burial_depth_offset(&mut self, value: bool) {
648        if value {
649            self.raw |= 1 << 1;
650        } else {
651            self.raw &= !(1 << 1);
652        }
653    }
654
655    /// Snow Burial Depth Offset (bit 2).
656    #[must_use]
657    pub const fn snow_burial_depth_offset(self) -> bool {
658        self.raw & (1 << 2) != 0
659    }
660
661    /// Sets bit 2. See [`snow_burial_depth_offset`](Self::snow_burial_depth_offset).
662    pub const fn set_snow_burial_depth_offset(&mut self, value: bool) {
663        if value {
664            self.raw |= 1 << 2;
665        } else {
666            self.raw &= !(1 << 2);
667        }
668    }
669
670    /// Mine Orientation (bit 3).
671    #[must_use]
672    pub const fn mine_orientation(self) -> bool {
673        self.raw & (1 << 3) != 0
674    }
675
676    /// Sets bit 3. See [`mine_orientation`](Self::mine_orientation).
677    pub const fn set_mine_orientation(&mut self, value: bool) {
678        if value {
679            self.raw |= 1 << 3;
680        } else {
681            self.raw &= !(1 << 3);
682        }
683    }
684
685    /// Thermal Contrast (bit 4).
686    #[must_use]
687    pub const fn thermal_contrast(self) -> bool {
688        self.raw & (1 << 4) != 0
689    }
690
691    /// Sets bit 4. See [`thermal_contrast`](Self::thermal_contrast).
692    pub const fn set_thermal_contrast(&mut self, value: bool) {
693        if value {
694            self.raw |= 1 << 4;
695        } else {
696            self.raw &= !(1 << 4);
697        }
698    }
699
700    /// Reflectance (bit 5).
701    #[must_use]
702    pub const fn reflectance(self) -> bool {
703        self.raw & (1 << 5) != 0
704    }
705
706    /// Sets bit 5. See [`reflectance`](Self::reflectance).
707    pub const fn set_reflectance(&mut self, value: bool) {
708        if value {
709            self.raw |= 1 << 5;
710        } else {
711            self.raw &= !(1 << 5);
712        }
713    }
714
715    /// Mine Emplacement Time (bit 6).
716    #[must_use]
717    pub const fn mine_emplacement_time(self) -> bool {
718        self.raw & (1 << 6) != 0
719    }
720
721    /// Sets bit 6. See [`mine_emplacement_time`](Self::mine_emplacement_time).
722    pub const fn set_mine_emplacement_time(&mut self, value: bool) {
723        if value {
724            self.raw |= 1 << 6;
725        } else {
726            self.raw &= !(1 << 6);
727        }
728    }
729
730    /// Trip/Detonation Wire (bit 7).
731    #[must_use]
732    pub const fn trip_detonation_wire(self) -> bool {
733        self.raw & (1 << 7) != 0
734    }
735
736    /// Sets bit 7. See [`trip_detonation_wire`](Self::trip_detonation_wire).
737    pub const fn set_trip_detonation_wire(&mut self, value: bool) {
738        if value {
739            self.raw |= 1 << 7;
740        } else {
741            self.raw &= !(1 << 7);
742        }
743    }
744
745    /// Fusing (bit 8).
746    #[must_use]
747    pub const fn fusing(self) -> bool {
748        self.raw & (1 << 8) != 0
749    }
750
751    /// Sets bit 8. See [`fusing`](Self::fusing).
752    pub const fn set_fusing(&mut self, value: bool) {
753        if value {
754            self.raw |= 1 << 8;
755        } else {
756            self.raw &= !(1 << 8);
757        }
758    }
759
760    /// Scalar Detection Coefficient (bit 9).
761    #[must_use]
762    pub const fn scalar_detection_coefficient(self) -> bool {
763        self.raw & (1 << 9) != 0
764    }
765
766    /// Sets bit 9. See [`scalar_detection_coefficient`](Self::scalar_detection_coefficient).
767    pub const fn set_scalar_detection_coefficient(&mut self, value: bool) {
768        if value {
769            self.raw |= 1 << 9;
770        } else {
771            self.raw &= !(1 << 9);
772        }
773    }
774
775    /// Paint Scheme (bit 10).
776    #[must_use]
777    pub const fn paint_scheme(self) -> bool {
778        self.raw & (1 << 10) != 0
779    }
780
781    /// Sets bit 10. See [`paint_scheme`](Self::paint_scheme).
782    pub const fn set_paint_scheme(&mut self, value: bool) {
783        if value {
784            self.raw |= 1 << 10;
785        } else {
786            self.raw &= !(1 << 10);
787        }
788    }
789
790    /// A Data Filter record from its wire octets.
791    #[must_use]
792    pub const fn from_raw(raw: u32) -> Self {
793        Self { raw }
794    }
795
796    /// The record's wire octets.
797    #[must_use]
798    pub const fn to_raw(self) -> u32 {
799        self.raw
800    }
801}
802
803/// Implemented according to IEEE 1278.1-2012 §6.2.17
804#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
805#[deku(
806    endian = "endian",
807    ctx = "endian: deku::ctx::Endian",
808    ctx_default = "deku::ctx::Endian::Big"
809)]
810pub struct DataQueryDatumSpecification {
811    #[deku(
812        update = "self.fixed_datums.len()",
813        assert = "crate::wire::fits_in_pdu(*number_of_fixed_datums)"
814    )]
815    pub number_of_fixed_datums: u32,
816    #[deku(
817        update = "self.variable_datums.len()",
818        assert = "crate::wire::fits_in_pdu(*number_of_variable_datums)"
819    )]
820    pub number_of_variable_datums: u32,
821    #[deku(count = "number_of_fixed_datums")]
822    pub fixed_datums: Vec<VariableRecordTypes>,
823    #[deku(count = "number_of_variable_datums")]
824    pub variable_datums: Vec<VariableRecordTypes>,
825}
826
827impl DataQueryDatumSpecification {
828    #[must_use]
829    pub const fn new() -> Self {
830        Self {
831            number_of_fixed_datums: 0,
832            number_of_variable_datums: 0,
833            fixed_datums: Vec::new(),
834            variable_datums: Vec::new(),
835        }
836    }
837}
838
839/// Implemented according to IEEE 1278.1-2012 §6.2.18
840#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
841#[deku(
842    endian = "endian",
843    ctx = "endian: deku::ctx::Endian",
844    ctx_default = "deku::ctx::Endian::Big"
845)]
846pub struct DatumSpecification {
847    #[deku(
848        update = "self.fixed_datum_records.len()",
849        assert = "crate::wire::fits_in_pdu(*number_of_fixed_datum_records)"
850    )]
851    pub number_of_fixed_datum_records: u32,
852    #[deku(
853        update = "self.variable_datum_records.len()",
854        assert = "crate::wire::fits_in_pdu(*number_of_variable_datum_records)"
855    )]
856    pub number_of_variable_datum_records: u32,
857    #[deku(count = "number_of_fixed_datum_records")]
858    pub fixed_datum_records: Vec<FixedDatumRecord>,
859    #[deku(count = "number_of_variable_datum_records")]
860    pub variable_datum_records: Vec<VariableDatumRecord>,
861}
862
863impl DatumSpecification {
864    #[must_use]
865    pub const fn new() -> Self {
866        Self {
867            number_of_fixed_datum_records: 0,
868            number_of_variable_datum_records: 0,
869            fixed_datum_records: Vec::new(),
870            variable_datum_records: Vec::new(),
871        }
872    }
873}
874
875/// Implemented according to IEEE 1278.1-2012 §6.2.19.2
876#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
877#[deku(
878    endian = "endian",
879    ctx = "endian: deku::ctx::Endian",
880    ctx_default = "deku::ctx::Endian::Big"
881)]
882pub struct MunitionDescriptor {
883    pub munition_type: EntityType,
884    pub warhead: MunitionDescriptorWarhead,
885    pub fuse: MunitionDescriptorFuse,
886    pub quantity: u16,
887    pub rate: u16,
888}
889
890/// Implemented according to IEEE 1278.1-2012 §6.2.19.3
891#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
892#[deku(
893    endian = "endian",
894    ctx = "endian: deku::ctx::Endian",
895    ctx_default = "deku::ctx::Endian::Big"
896)]
897pub struct ExplosionDescriptor {
898    pub exploding_object_type: EntityType,
899    pub explosive_material: ExplosiveMaterialCategories,
900    padding: u16,
901    pub explosive_force: f32,
902}
903
904/// Implemented according to IEEE 1278.1-2012 §6.2.20.2
905#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
906#[deku(
907    endian = "endian",
908    ctx = "endian: deku::ctx::Endian",
909    ctx_default = "deku::ctx::Endian::Big"
910)]
911pub struct DEAreaAimpoint {
912    pub record_type: u32,
913    /// The whole record in octets, a multiple of 8. `serialize` sets it
914    #[deku(update = "crate::wire::encoded_len(self)?")]
915    pub record_length: u16,
916    padding: u16,
917    #[deku(
918        update = "self.beam_antenna_pattern_records.len()",
919        assert = "crate::wire::fits_in_pdu(*beam_antenna_pattern_record_count)"
920    )]
921    pub beam_antenna_pattern_record_count: u16,
922    #[deku(
923        update = "self.de_target_energy_deposition_records.len()",
924        assert = "crate::wire::fits_in_pdu(*de_target_energy_deposition_record_count)"
925    )]
926    pub de_target_energy_deposition_record_count: u16,
927    #[deku(count = "beam_antenna_pattern_record_count")]
928    pub beam_antenna_pattern_records: Vec<BeamAntennaPattern>,
929    #[deku(count = "de_target_energy_deposition_record_count")]
930    pub de_target_energy_deposition_records: Vec<DETargetEnergyDeposition>,
931    /// Zero octets that end the record on a 64-bit boundary
932    #[deku(
933        count = "area_aimpoint_padding(usize::from(*beam_antenna_pattern_record_count), usize::from(*de_target_energy_deposition_record_count))",
934        writer = "crate::wire::write_zeros(deku::writer, area_aimpoint_padding(beam_antenna_pattern_records.len(), de_target_energy_deposition_records.len()))"
935    )]
936    padding2: Vec<u8>,
937}
938
939impl DEAreaAimpoint {
940    #[must_use]
941    pub fn new() -> Self {
942        Self {
943            record_type: 4001,
944            record_length: 16,
945            ..Default::default()
946        }
947    }
948}
949
950/// Padding that ends a DE Area Aimpoint record on a 64-bit boundary: its
951/// 12-octet header, 40-octet Beam Antenna Pattern records and 12-octet DE
952/// Target Energy Deposition records (Table 44).
953const fn area_aimpoint_padding(patterns: usize, depositions: usize) -> usize {
954    let length = 12_usize
955        .saturating_add(patterns.saturating_mul(40))
956        .saturating_add(depositions.saturating_mul(12));
957    crate::wire::padding_to(length, 8)
958}
959
960/// Implemented according to IEEE 1278.1-2012 §6.2.20.3
961#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
962#[deku(
963    endian = "endian",
964    ctx = "endian: deku::ctx::Endian",
965    ctx_default = "deku::ctx::Endian::Big"
966)]
967pub struct DEPrecisionAimpoint {
968    pub record_type: u32,
969    pub record_length: u16,
970    padding: u16,
971    pub target_spot_world_location: WorldCoordinates,
972    pub target_spot_entity_location: Vector,
973    pub target_spot_velocity: Vector,
974    pub target_spot_acceleration: Vector,
975    pub target_entity_id: EntityIdentifier,
976    pub target_component_identifier: u8,
977    pub beam_spot_type: DEPrecisionAimpointBeamSpotType,
978    pub beam_spot_cross_section_semi_major_axis: f32,
979    pub beam_spot_cross_section_semi_minor_axis: f32,
980    pub beam_spot_cross_section_orientation_angle: f32,
981    pub peak_irradiance: f32,
982    padding2: u32,
983}
984
985impl DEPrecisionAimpoint {
986    #[must_use]
987    pub fn new() -> Self {
988        Self {
989            record_type: 4000,
990            record_length: 96,
991            ..Default::default()
992        }
993    }
994}
995
996/// Implemented according to IEEE 1278.1-2012 §6.2.20.4
997#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
998#[deku(
999    endian = "endian",
1000    ctx = "endian: deku::ctx::Endian",
1001    ctx_default = "deku::ctx::Endian::Big"
1002)]
1003pub struct DETargetEnergyDeposition {
1004    pub target_entity_id: EntityIdentifier,
1005    padding: u16,
1006    pub peak_irradiance: f32,
1007}
1008
1009/// Implemented according to IEEE 1278.1-2012 §6.2.21.1
1010#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1011#[deku(
1012    endian = "endian",
1013    ctx = "endian: deku::ctx::Endian",
1014    ctx_default = "deku::ctx::Endian::Big"
1015)]
1016pub struct BlankingSectorAttribute {
1017    pub record_type: u32,
1018    pub record_length: u16,
1019    padding: u16,
1020    pub emitter_number: u8,
1021    pub beam_number: u8,
1022    pub state_indicator: EEAttributeStateIndicator,
1023    padding2: u8,
1024    pub left_azimuth: f32,
1025    pub right_azimuth: f32,
1026    pub lower_elevation: f32,
1027    pub upper_elevation: f32,
1028    pub residual_power: f32,
1029    padding3: u64,
1030}
1031
1032impl BlankingSectorAttribute {
1033    #[must_use]
1034    pub fn new() -> Self {
1035        Self {
1036            record_type: 3500,
1037            record_length: 40,
1038            ..Default::default()
1039        }
1040    }
1041}
1042
1043/// Implemented according to IEEE 1278.1-2012 §6.2.21.2
1044#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1045#[deku(
1046    endian = "endian",
1047    ctx = "endian: deku::ctx::Endian",
1048    ctx_default = "deku::ctx::Endian::Big"
1049)]
1050pub struct AngleDeceptionAttribute {
1051    pub record_type: u32,
1052    pub record_length: u16,
1053    padding: u16,
1054    pub emitter_number: u8,
1055    pub beam_number: u8,
1056    pub state_indicator: EEAttributeStateIndicator,
1057    padding2: u8,
1058    pub azimuth_offset: f32,
1059    pub azimuth_width: f32,
1060    pub azimuth_pull_rate: f32,
1061    pub azimuth_pull_acceleration: f32,
1062    pub elevation_offset: f32,
1063    pub elevation_width: f32,
1064    pub elevation_pull_rate: f32,
1065    pub elevation_pull_acceleration: f32,
1066    padding3: u32,
1067}
1068
1069impl AngleDeceptionAttribute {
1070    #[must_use]
1071    pub fn new() -> Self {
1072        Self {
1073            record_type: 3501,
1074            record_length: 48,
1075            ..Default::default()
1076        }
1077    }
1078}
1079
1080/// Implemented according to IEEE 1278.1-2012 §6.2.21.3
1081#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1082#[deku(
1083    endian = "endian",
1084    ctx = "endian: deku::ctx::Endian",
1085    ctx_default = "deku::ctx::Endian::Big"
1086)]
1087pub struct FalseTargetsAttribute {
1088    pub record_type: u32,
1089    pub record_length: u16,
1090    padding: u16,
1091    pub emitter_number: u8,
1092    pub beam_number: u8,
1093    pub state_indicator: EEAttributeStateIndicator,
1094    padding2: u8,
1095    padding3: u16,
1096    pub false_target_count: u16,
1097    pub walk_speed: f32,
1098    pub walk_acceleration: f32,
1099    pub maximum_walk_distance: f32,
1100    pub keep_time: f32,
1101    pub echo_spacing: f32,
1102    pub first_target_offset: f32,
1103}
1104
1105impl FalseTargetsAttribute {
1106    #[must_use]
1107    pub fn new() -> Self {
1108        Self {
1109            record_type: 3502,
1110            record_length: 40,
1111            ..Default::default()
1112        }
1113    }
1114}
1115
1116/// Implemented according to IEEE 1278.1-2012 §6.2.22
1117#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1118#[deku(
1119    endian = "endian",
1120    ctx = "endian: deku::ctx::Endian",
1121    ctx_default = "deku::ctx::Endian::Big"
1122)]
1123pub struct EEFundamentalParameterData {
1124    pub frequency: f32,
1125    pub frequency_range: f32,
1126    pub effective_radiated_power: f32,
1127    pub pulse_repetition_frequency: f32,
1128    pub pulse_width: f32,
1129}
1130
1131/// Implemented according to IEEE 1278.1-2012 §6.2.23
1132#[derive(Copy, Clone, Debug, deku::DekuRead, deku::DekuWrite)]
1133#[deku(
1134    endian = "endian",
1135    ctx = "endian: deku::ctx::Endian",
1136    ctx_default = "deku::ctx::Endian::Big"
1137)]
1138pub struct EmitterSystem {
1139    pub emitter_name: EmitterName,
1140    pub function: EmitterSystemFunction,
1141    pub emitter_id_number: u8,
1142}
1143
1144impl Default for EmitterSystem {
1145    fn default() -> Self {
1146        Self {
1147            emitter_name: EmitterName::default(),
1148            function: EmitterSystemFunction::Other,
1149            emitter_id_number: 0,
1150        }
1151    }
1152}
1153
1154impl EmitterSystem {
1155    #[must_use]
1156    pub const fn new(name: EmitterName, function: EmitterSystemFunction, id: u8) -> Self {
1157        Self {
1158            emitter_name: name,
1159            function,
1160            emitter_id_number: id,
1161        }
1162    }
1163}
1164
1165/// Implemented according to IEEE 1278.1-2012 §6.2.24
1166#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1167#[deku(
1168    endian = "endian",
1169    ctx = "endian: deku::ctx::Endian",
1170    ctx_default = "deku::ctx::Endian::Big"
1171)]
1172pub struct EngineFuel {
1173    pub fuel_quantity: u32,
1174    pub fuel_measurement_units: FuelMeasurementUnits,
1175    pub fuel_type: SupplyFuelType,
1176    pub fuel_location: FuelLocation,
1177    padding: u8,
1178}
1179
1180/// Implemented according to IEEE 1278.1-2012 §6.2.25
1181#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1182#[deku(
1183    endian = "endian",
1184    ctx = "endian: deku::ctx::Endian",
1185    ctx_default = "deku::ctx::Endian::Big"
1186)]
1187pub struct EngineFuelReload {
1188    pub standard_quantity: u32,
1189    pub maximum_quantity: u32,
1190    pub standard_quantity_reload_time: u32,
1191    pub maximum_quantity_reload_time: u32,
1192    pub fuel_measurement_units: FuelMeasurementUnits,
1193    pub fuel_type: SupplyFuelType,
1194    pub fuel_location: FuelLocation,
1195    padding: u8,
1196}
1197
1198/// Implemented according to IEEE 1278.1-2012 §6.2.26
1199#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
1200#[deku(
1201    endian = "endian",
1202    ctx = "endian: deku::ctx::Endian",
1203    ctx_default = "deku::ctx::Endian::Big"
1204)]
1205pub struct EntityAppearance(u32);
1206
1207impl EntityAppearance {
1208    /// The record from its 32-bit wire value.
1209    #[must_use]
1210    pub const fn from_raw(raw: u32) -> Self {
1211        Self(raw)
1212    }
1213
1214    /// The record's 32-bit wire value.
1215    #[must_use]
1216    pub const fn to_raw(self) -> u32 {
1217        self.0
1218    }
1219}
1220
1221impl From<u32> for EntityAppearance {
1222    fn from(raw: u32) -> Self {
1223        Self(raw)
1224    }
1225}
1226
1227impl From<EntityAppearance> for u32 {
1228    fn from(record: EntityAppearance) -> Self {
1229        record.0
1230    }
1231}
1232
1233/// Implemented according to IEEE 1278.1-2012 §6.2.27 & SISO-REF-010 v32 UID 55
1234#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
1235#[deku(
1236    endian = "endian",
1237    ctx = "endian: deku::ctx::Endian",
1238    ctx_default = "deku::ctx::Endian::Big"
1239)]
1240pub struct EntityCapabilities(u32);
1241
1242impl EntityCapabilities {
1243    /// The record from its 32-bit wire value.
1244    #[must_use]
1245    pub const fn from_raw(raw: u32) -> Self {
1246        Self(raw)
1247    }
1248
1249    /// The record's 32-bit wire value.
1250    #[must_use]
1251    pub const fn to_raw(self) -> u32 {
1252        self.0
1253    }
1254}
1255
1256impl From<u32> for EntityCapabilities {
1257    fn from(raw: u32) -> Self {
1258        Self(raw)
1259    }
1260}
1261
1262impl From<EntityCapabilities> for u32 {
1263    fn from(record: EntityCapabilities) -> Self {
1264        record.0
1265    }
1266}
1267
1268/// Implemented according to IEEE 1278.1-2012 §6.2.28
1269#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
1270#[deku(
1271    endian = "endian",
1272    ctx = "endian: deku::ctx::Endian",
1273    ctx_default = "deku::ctx::Endian::Big"
1274)]
1275pub struct EntityIdentifier {
1276    /// The simulation's designation associated with all object identifiers
1277    pub simulation_address: SimulationAddress,
1278    /// The unique identification number of the entity
1279    pub entity_id: u16,
1280}
1281
1282impl EntityIdentifier {
1283    #[must_use]
1284    pub const fn new(simulation_address: SimulationAddress, entity_id: u16) -> Self {
1285        Self {
1286            simulation_address,
1287            entity_id,
1288        }
1289    }
1290}
1291
1292/// Number of character octets in an Entity Marking record.
1293const MARKING_CHARACTERS: usize = 11;
1294
1295/// Implemented according to IEEE 1278.1-2012 §6.2.29
1296///
1297/// A character set (UID 45) and an 11-element character string in that
1298/// character set. The octets are kept as they are, so markings in any
1299/// character set can survive a round-trip unchanged. Use [`Self::from_ascii`] and
1300/// [`Self::as_ascii`] for ASCII markings
1301#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1302#[deku(
1303    endian = "endian",
1304    ctx = "endian: deku::ctx::Endian",
1305    ctx_default = "deku::ctx::Endian::Big"
1306)]
1307pub struct EntityMarking {
1308    pub entity_marking_character_set: EntityMarkingCharacterSet,
1309    pub characters: [u8; MARKING_CHARACTERS],
1310}
1311
1312impl EntityMarking {
1313    #[must_use]
1314    pub const fn new(
1315        entity_marking_character_set: EntityMarkingCharacterSet,
1316        characters: [u8; MARKING_CHARACTERS],
1317    ) -> Self {
1318        Self {
1319            entity_marking_character_set,
1320            characters,
1321        }
1322    }
1323
1324    /// An ASCII marking of up to 11 characters, zero-padded, or `None` if
1325    /// `text` is longer or is not ASCII
1326    #[must_use]
1327    pub fn from_ascii(text: &str) -> Option<Self> {
1328        if !text.is_ascii() || text.len() > MARKING_CHARACTERS {
1329            return None;
1330        }
1331
1332        let mut characters = [0u8; MARKING_CHARACTERS];
1333        for (slot, byte) in characters.iter_mut().zip(text.bytes()) {
1334            *slot = byte;
1335        }
1336        Some(Self::new(EntityMarkingCharacterSet::ASCII, characters))
1337    }
1338
1339    /// The marking as text, up to the first zero octet, when the character
1340    /// set is ASCII and the characters are as well; otherwise, `None`
1341    #[must_use]
1342    pub fn as_ascii(&self) -> Option<&str> {
1343        if self.entity_marking_character_set != EntityMarkingCharacterSet::ASCII {
1344            return None;
1345        }
1346
1347        let end = self
1348            .characters
1349            .iter()
1350            .position(|&octet| octet == 0)
1351            .unwrap_or(MARKING_CHARACTERS);
1352        let text = self.characters.get(..end)?;
1353
1354        if text.is_ascii() {
1355            std::str::from_utf8(text).ok()
1356        } else {
1357            None
1358        }
1359    }
1360}
1361
1362/// Implemented according to IEEE 1278.1-2012 §6.2.30
1363#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1364#[deku(
1365    endian = "endian",
1366    ctx = "endian: deku::ctx::Endian",
1367    ctx_default = "deku::ctx::Endian::Big"
1368)]
1369pub struct EntityType {
1370    pub kind: EntityKind,
1371    pub domain: u8,
1372    pub country: Country,
1373    pub category: u8,
1374    pub subcategory: u8,
1375    pub specific: u8,
1376    pub extra: u8,
1377}
1378
1379impl EntityType {
1380    #[must_use]
1381    pub const fn new(
1382        kind: EntityKind,
1383        domain: u8,
1384        country: Country,
1385        category: u8,
1386        subcategory: u8,
1387        specific: u8,
1388        extra: u8,
1389    ) -> Self {
1390        Self {
1391            kind,
1392            domain,
1393            country,
1394            category,
1395            subcategory,
1396            specific,
1397            extra,
1398        }
1399    }
1400}
1401
1402/// Implemented according to IEEE 1278.1-2012 §6.2.31
1403///
1404/// `geometry_or_state` holds the geometry or state record (§6.2.31.2 and
1405/// §6.2.31.3) as raw octets; its layout depends on `environment_type`
1406#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1407#[deku(
1408    endian = "endian",
1409    ctx = "endian: deku::ctx::Endian",
1410    ctx_default = "deku::ctx::Endian::Big"
1411)]
1412pub struct Environment {
1413    pub environment_type: EnvironmentalProcessRecordType,
1414    /// The whole record's length in bits, padding included: 64 + K + P.
1415    /// `serialize` sets it from `geometry_or_state`
1416    #[deku(
1417        update = "environment_length_bits(self.geometry_or_state.len())?",
1418        assert = "valid_environment_length(*length)"
1419    )]
1420    pub length: u16,
1421    pub index: u8,
1422    padding: u8,
1423    /// When decoded, this includes the padding to the 64-bit boundary; when
1424    /// encoded, padding is added to reach it
1425    #[deku(
1426        count = "usize::from(*length / 8).saturating_sub(8)",
1427        writer = "write_environment_fields(deku::writer, geometry_or_state)"
1428    )]
1429    pub geometry_or_state: Vec<u8>,
1430}
1431
1432impl Environment {
1433    #[must_use]
1434    pub fn new(
1435        environment_type: EnvironmentalProcessRecordType,
1436        index: u8,
1437        geometry_or_state: Vec<u8>,
1438    ) -> Self {
1439        let length = environment_length_bits(geometry_or_state.len()).unwrap_or(u16::MAX);
1440        Self {
1441            environment_type,
1442            length,
1443            index,
1444            padding: 0,
1445            geometry_or_state,
1446        }
1447    }
1448}
1449
1450/// An Environment record's Length for `fields` octets of geometry or state:
1451/// the 8-octet header plus the fields, padded to 64 bits, in bits (Table 57).
1452fn environment_length_bits(fields: usize) -> Result<u16, DekuError> {
1453    crate::wire::padded_record_length(fields.saturating_add(2))?
1454        .checked_mul(8)
1455        .and_then(|bits| u16::try_from(bits).ok())
1456        .ok_or_else(|| DekuError::Assertion("environment record is too long".into()))
1457}
1458
1459/// Writes the geometry or state octets and the padding to a 64-bit boundary.
1460/// The 8-octet header is already aligned, so only the fields need padding.
1461fn write_environment_fields<W: Write + Seek>(
1462    writer: &mut Writer<W>,
1463    fields: &[u8],
1464) -> Result<(), DekuError> {
1465    fields.to_writer(writer, ())?;
1466    crate::wire::write_zeros(writer, crate::wire::padding_to(fields.len(), 8))
1467}
1468
1469/// Whether a received Length is a whole number of 64-bit words, header
1470/// included.
1471const fn valid_environment_length(length_bits: u16) -> bool {
1472    length_bits >= 64 && length_bits % 64 == 0
1473}
1474
1475/// Implemented according to IEEE 1278.1-2012 §6.2.32
1476#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1477#[deku(
1478    endian = "endian",
1479    ctx = "endian: deku::ctx::Endian",
1480    ctx_default = "deku::ctx::Endian::Big"
1481)]
1482pub struct EulerAngles {
1483    /// Angle of rotation about the Z-axis
1484    pub psi: f32,
1485    /// Angle of rotation about the Y-axis
1486    pub theta: f32,
1487    /// Angle of rotation about the X-axis
1488    pub phi: f32,
1489}
1490
1491impl EulerAngles {
1492    #[must_use]
1493    #[allow(clippy::similar_names)]
1494    pub const fn new(psi: f32, theta: f32, phi: f32) -> Self {
1495        Self { psi, theta, phi }
1496    }
1497}
1498
1499/// Implemented according to IEEE 1278.1-2012 §6.2.33
1500#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1501#[deku(
1502    endian = "endian",
1503    ctx = "endian: deku::ctx::Endian",
1504    ctx_default = "deku::ctx::Endian::Big"
1505)]
1506pub struct EventIdentifier {
1507    pub simulation_address: SimulationAddress,
1508    pub event_number: u16,
1509}
1510
1511impl EventIdentifier {
1512    #[must_use]
1513    pub const fn new(simulation_address: SimulationAddress, event_number: u16) -> Self {
1514        Self {
1515            simulation_address,
1516            event_number,
1517        }
1518    }
1519}
1520
1521/// Implemented according to IEEE 1278.1-2012 §6.2.34
1522/// The exercise a PDU belongs to, from 1 to 255. Every participant in an exercise uses the same one.
1523///
1524/// The default is exercise 1.
1525#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
1526#[deku(
1527    endian = "endian",
1528    ctx = "endian: deku::ctx::Endian",
1529    ctx_default = "deku::ctx::Endian::Big"
1530)]
1531pub struct ExerciseIdentifier(u8);
1532
1533impl ExerciseIdentifier {
1534    /// The exercise with the given number.
1535    #[must_use]
1536    pub const fn new(id: u8) -> Self {
1537        Self(id)
1538    }
1539
1540    /// The exercise's number.
1541    #[must_use]
1542    pub const fn get(self) -> u8 {
1543        self.0
1544    }
1545}
1546
1547impl Default for ExerciseIdentifier {
1548    fn default() -> Self {
1549        Self(1)
1550    }
1551}
1552
1553impl From<u8> for ExerciseIdentifier {
1554    fn from(id: u8) -> Self {
1555        Self(id)
1556    }
1557}
1558
1559impl From<ExerciseIdentifier> for u8 {
1560    fn from(id: ExerciseIdentifier) -> Self {
1561        id.0
1562    }
1563}
1564
1565/// Implemented according to IEEE 1278.1-2012 §6.2.35
1566#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1567#[deku(
1568    endian = "endian",
1569    ctx = "endian: deku::ctx::Endian",
1570    ctx_default = "deku::ctx::Endian::Big"
1571)]
1572pub struct Expendable {
1573    pub expendable_type: EntityType,
1574    pub station_launcher: u32,
1575    pub quantity: u16,
1576    pub expendable_status: MunitionExpendableStatus,
1577    padding: u8,
1578}
1579
1580/// Implemented according to IEEE 1278.1-2012 §6.2.36
1581#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1582#[deku(
1583    endian = "endian",
1584    ctx = "endian: deku::ctx::Endian",
1585    ctx_default = "deku::ctx::Endian::Big"
1586)]
1587pub struct ExpendableReload {
1588    pub expendable_type: EntityType,
1589    pub station_launcher: u32,
1590    pub standard_quantity: u16,
1591    pub maximum_quantity: u16,
1592    pub standard_quantity_reload_time: u32,
1593    pub maximum_quantity_reload_time: u32,
1594}
1595
1596/// Implemented according to IEEE 1278.1-2012 §6.2.37
1597#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1598#[deku(
1599    endian = "endian",
1600    ctx = "endian: deku::ctx::Endian",
1601    ctx_default = "deku::ctx::Endian::Big"
1602)]
1603pub struct FixedDatumRecord {
1604    pub datum_id: u32,
1605    pub datum_value: u32,
1606}
1607
1608/// Implemented according to IEEE 1278.1-2012 §6.2.38
1609#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1610#[deku(
1611    endian = "endian",
1612    ctx = "endian: deku::ctx::Endian",
1613    ctx_default = "deku::ctx::Endian::Big"
1614)]
1615pub struct ForceIdentification(pub ForceId);
1616
1617/// Implemented according to IEEE 1278.1-2012 §6.2.39
1618#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1619#[deku(
1620    endian = "endian",
1621    ctx = "endian: deku::ctx::Endian",
1622    ctx_default = "deku::ctx::Endian::Big"
1623)]
1624pub struct FundamentalOperationalData {
1625    pub system_status: SystemStatus,
1626    pub data_field1: u8,
1627    pub information_layers: InformationLayers,
1628    pub data_field2: u8,
1629    pub parameter1: u16,
1630    pub parameter2: u16,
1631    pub parameter3: u16,
1632    pub parameter4: u16,
1633    pub parameter5: u16,
1634    pub parameter6: u16,
1635}
1636
1637/// The spacing of a grid axis, which decides the rest of the Grid Axis
1638/// Descriptor record.
1639#[derive(Clone, Debug, PartialEq)]
1640pub enum GridAxisType {
1641    /// Regular (fixed spacing) axis data (IEEE 1278.1-2012 Table 66).
1642    FixedSpacing {
1643        number_of_points_on_x_axis: u16,
1644        initial_index: u16,
1645    },
1646    /// Irregular (variable spacing) axis data (IEEE 1278.1-2012 Table 67).
1647    /// The number of points is `x_values.len()`; the record is padded to a
1648    /// 64-bit boundary on the wire.
1649    VariableSpacing {
1650        initial_index: u16,
1651        coordinate_scale_x: f64,
1652        coordinate_offset_x: f64,
1653        x_values: Vec<u16>,
1654    },
1655}
1656
1657impl Default for GridAxisType {
1658    fn default() -> Self {
1659        Self::FixedSpacing {
1660            number_of_points_on_x_axis: 0,
1661            initial_index: 0,
1662        }
1663    }
1664}
1665
1666impl GridAxisType {
1667    /// The axis type this spacing is sent as.
1668    #[must_use]
1669    pub const fn axis_type(&self) -> GridAxisDescriptorAxisType {
1670        match self {
1671            Self::FixedSpacing { .. } => GridAxisDescriptorAxisType::RegularAxis,
1672            Self::VariableSpacing { .. } => GridAxisDescriptorAxisType::IrregularAxis,
1673        }
1674    }
1675}
1676
1677/// Implemented according to IEEE 1278.1-2012 §6.2.40
1678///
1679/// `axis_type` follows `data`: it is set from `data` when decoding and by
1680/// `serialize`, and the encoded axis type always matches `data`.
1681#[derive(Clone, Debug, Default)]
1682pub struct GridAxisDescriptor {
1683    pub domain_initial: f64,
1684    pub domain_final: f64,
1685    pub domain_points: u16,
1686    pub interleaf_factor: u8,
1687    pub axis_type: GridAxisDescriptorAxisType,
1688    pub data: GridAxisType,
1689}
1690
1691impl GridAxisDescriptor {
1692    #[must_use]
1693    pub const fn new(
1694        domain_initial: f64,
1695        domain_final: f64,
1696        domain_points: u16,
1697        interleaf_factor: u8,
1698        axis_type: GridAxisDescriptorAxisType,
1699        data: GridAxisType,
1700    ) -> Self {
1701        Self {
1702            domain_initial,
1703            domain_final,
1704            domain_points,
1705            interleaf_factor,
1706            axis_type,
1707            data,
1708        }
1709    }
1710}
1711
1712impl DekuReader<'_, Endian> for GridAxisDescriptor {
1713    fn from_reader_with_ctx<R: Read + Seek>(
1714        reader: &mut Reader<R>,
1715        endian: Endian,
1716    ) -> Result<Self, DekuError> {
1717        let domain_initial = f64::from_reader_with_ctx(reader, endian)?;
1718        let domain_final = f64::from_reader_with_ctx(reader, endian)?;
1719        let domain_points = u16::from_reader_with_ctx(reader, endian)?;
1720        let interleaf_factor = u8::from_reader_with_ctx(reader, endian)?;
1721        let axis_type = GridAxisDescriptorAxisType::from_reader_with_ctx(reader, endian)?;
1722        let number_of_points = u16::from_reader_with_ctx(reader, endian)?;
1723        let initial_index = u16::from_reader_with_ctx(reader, endian)?;
1724        let data = match axis_type {
1725            GridAxisDescriptorAxisType::RegularAxis => GridAxisType::FixedSpacing {
1726                number_of_points_on_x_axis: number_of_points,
1727                initial_index,
1728            },
1729            GridAxisDescriptorAxisType::IrregularAxis => {
1730                let coordinate_scale_x = f64::from_reader_with_ctx(reader, endian)?;
1731                let coordinate_offset_x = f64::from_reader_with_ctx(reader, endian)?;
1732                let x_values = wire::read_n(reader, usize::from(number_of_points), endian)?;
1733                wire::skip(reader, x_values_padding(x_values.len()))?;
1734                GridAxisType::VariableSpacing {
1735                    initial_index,
1736                    coordinate_scale_x,
1737                    coordinate_offset_x,
1738                    x_values,
1739                }
1740            }
1741        };
1742        Ok(Self {
1743            domain_initial,
1744            domain_final,
1745            domain_points,
1746            interleaf_factor,
1747            axis_type,
1748            data,
1749        })
1750    }
1751}
1752
1753impl DekuWriter<Endian> for GridAxisDescriptor {
1754    fn to_writer<W: Write + Seek>(
1755        &self,
1756        writer: &mut Writer<W>,
1757        endian: Endian,
1758    ) -> Result<(), DekuError> {
1759        self.domain_initial.to_writer(writer, endian)?;
1760        self.domain_final.to_writer(writer, endian)?;
1761        self.domain_points.to_writer(writer, endian)?;
1762        self.interleaf_factor.to_writer(writer, endian)?;
1763        self.data.axis_type().to_writer(writer, endian)?;
1764        match &self.data {
1765            GridAxisType::FixedSpacing {
1766                number_of_points_on_x_axis,
1767                initial_index,
1768            } => {
1769                number_of_points_on_x_axis.to_writer(writer, endian)?;
1770                initial_index.to_writer(writer, endian)
1771            }
1772            GridAxisType::VariableSpacing {
1773                initial_index,
1774                coordinate_scale_x,
1775                coordinate_offset_x,
1776                x_values,
1777            } => {
1778                let points = u16::try_from(x_values.len()).map_err(|_| {
1779                    DekuError::Assertion("grid axis has more than 65,535 points".into())
1780                })?;
1781                points.to_writer(writer, endian)?;
1782                initial_index.to_writer(writer, endian)?;
1783                coordinate_scale_x.to_writer(writer, endian)?;
1784                coordinate_offset_x.to_writer(writer, endian)?;
1785                x_values.to_writer(writer, endian)?;
1786                wire::write_zeros(writer, x_values_padding(x_values.len()))
1787            }
1788        }
1789    }
1790}
1791
1792impl DekuUpdate for GridAxisDescriptor {
1793    fn update(&mut self) -> Result<(), DekuError> {
1794        self.axis_type = self.data.axis_type();
1795        Ok(())
1796    }
1797}
1798
1799crate::wire::impl_deku_default_endian!(GridAxisDescriptor);
1800
1801/// Padding after `points` 16-bit x values, to a 64-bit boundary. The rest of
1802/// the irregular-axis record is 40 octets, already a multiple of 8.
1803const fn x_values_padding(points: usize) -> usize {
1804    wire::padding_to(points.saturating_mul(2), 8)
1805}
1806
1807/// The values of a Grid Data record, by data representation. The number of
1808/// values is `data_values.len()`.
1809#[derive(Clone, Debug, PartialEq)]
1810pub enum DataRepresentationType {
1811    /// Representation type 0 (IEEE 1278.1-2012 Table 68): octets, padded to
1812    /// a 16-bit boundary on the wire.
1813    Type0 { data_values: Vec<u8> },
1814    /// Representation type 1 (Table 69): scaled 16-bit values, padded to a
1815    /// 32-bit boundary on the wire.
1816    Type1 {
1817        field_scale: f32,
1818        field_offset: f32,
1819        data_values: Vec<u16>,
1820    },
1821    /// Representation type 2 (Table 70): 32-bit floating point values.
1822    Type2 { data_values: Vec<f32> },
1823}
1824
1825impl Default for DataRepresentationType {
1826    fn default() -> Self {
1827        Self::Type0 {
1828            data_values: Vec::new(),
1829        }
1830    }
1831}
1832
1833impl DataRepresentationType {
1834    /// The data representation these values are sent as.
1835    #[must_use]
1836    pub const fn data_representation(&self) -> GriddedDataDataRepresentation {
1837        match self {
1838            Self::Type0 { .. } => GriddedDataDataRepresentation::Type0,
1839            Self::Type1 { .. } => GriddedDataDataRepresentation::Type1,
1840            Self::Type2 { .. } => GriddedDataDataRepresentation::Type2,
1841        }
1842    }
1843}
1844
1845/// Implemented according to IEEE 1278.1-2012 §6.2.41
1846///
1847/// `data_representation` follows `data`: it is set from `data` when
1848/// decoding and by `serialize`, and the encoded representation always
1849/// matches `data`.
1850#[derive(Clone, Debug, Default)]
1851pub struct GridData {
1852    /// SISO-REF-010 UID 246, a 16-bit enumeration.
1853    pub sample_type: GriddedDataSampleType,
1854    pub data_representation: GriddedDataDataRepresentation,
1855    pub data: DataRepresentationType,
1856}
1857
1858impl GridData {
1859    #[must_use]
1860    pub const fn new(
1861        sample_type: GriddedDataSampleType,
1862        data_representation: GriddedDataDataRepresentation,
1863        data: DataRepresentationType,
1864    ) -> Self {
1865        Self {
1866            sample_type,
1867            data_representation,
1868            data,
1869        }
1870    }
1871}
1872
1873impl DekuReader<'_, Endian> for GridData {
1874    fn from_reader_with_ctx<R: Read + Seek>(
1875        reader: &mut Reader<R>,
1876        endian: Endian,
1877    ) -> Result<Self, DekuError> {
1878        let sample_type =
1879            GriddedDataSampleType::from_u16(u16::from_reader_with_ctx(reader, endian)?)
1880                .unwrap_or_default();
1881        let representation = u16::from_reader_with_ctx(reader, endian)?;
1882        let data_representation = GriddedDataDataRepresentation::from_u16(representation)
1883            .ok_or_else(|| {
1884                DekuError::Parse(
1885                    format!(
1886                        "{representation} is not a defined GriddedDataDataRepresentation value"
1887                    )
1888                    .into(),
1889                )
1890            })?;
1891        let data = match data_representation {
1892            GriddedDataDataRepresentation::Type0 => {
1893                let count = u16::from_reader_with_ctx(reader, endian)?;
1894                let data_values: Vec<u8> = wire::read_n(reader, usize::from(count), endian)?;
1895                wire::skip(reader, wire::padding_to(data_values.len(), 2))?;
1896                DataRepresentationType::Type0 { data_values }
1897            }
1898            GriddedDataDataRepresentation::Type1 => {
1899                let field_scale = f32::from_reader_with_ctx(reader, endian)?;
1900                let field_offset = f32::from_reader_with_ctx(reader, endian)?;
1901                let count = u16::from_reader_with_ctx(reader, endian)?;
1902                let data_values: Vec<u16> = wire::read_n(reader, usize::from(count), endian)?;
1903                wire::skip(reader, type_1_padding(data_values.len()))?;
1904                DataRepresentationType::Type1 {
1905                    field_scale,
1906                    field_offset,
1907                    data_values,
1908                }
1909            }
1910            GriddedDataDataRepresentation::Type2 => {
1911                let count = u16::from_reader_with_ctx(reader, endian)?;
1912                wire::skip(reader, 2)?;
1913                let data_values = wire::read_n(reader, usize::from(count), endian)?;
1914                DataRepresentationType::Type2 { data_values }
1915            }
1916        };
1917        Ok(Self {
1918            sample_type,
1919            data_representation,
1920            data,
1921        })
1922    }
1923}
1924
1925impl DekuWriter<Endian> for GridData {
1926    fn to_writer<W: Write + Seek>(
1927        &self,
1928        writer: &mut Writer<W>,
1929        endian: Endian,
1930    ) -> Result<(), DekuError> {
1931        self.sample_type.to_writer(writer, endian)?;
1932        // Lossless: a fieldless enum whose values all fit in 16 bits.
1933        #[allow(clippy::as_conversions)]
1934        let representation = u16::from(self.data.data_representation() as u8);
1935        representation.to_writer(writer, endian)?;
1936        match &self.data {
1937            DataRepresentationType::Type0 { data_values } => {
1938                value_count(data_values.len())?.to_writer(writer, endian)?;
1939                data_values.to_writer(writer, endian)?;
1940                wire::write_zeros(writer, wire::padding_to(data_values.len(), 2))
1941            }
1942            DataRepresentationType::Type1 {
1943                field_scale,
1944                field_offset,
1945                data_values,
1946            } => {
1947                field_scale.to_writer(writer, endian)?;
1948                field_offset.to_writer(writer, endian)?;
1949                value_count(data_values.len())?.to_writer(writer, endian)?;
1950                data_values.to_writer(writer, endian)?;
1951                wire::write_zeros(writer, type_1_padding(data_values.len()))
1952            }
1953            DataRepresentationType::Type2 { data_values } => {
1954                value_count(data_values.len())?.to_writer(writer, endian)?;
1955                wire::write_zeros(writer, 2)?;
1956                data_values.to_writer(writer, endian)
1957            }
1958        }
1959    }
1960}
1961
1962impl DekuUpdate for GridData {
1963    fn update(&mut self) -> Result<(), DekuError> {
1964        self.data_representation = self.data.data_representation();
1965        Ok(())
1966    }
1967}
1968
1969crate::wire::impl_deku_default_endian!(GridData);
1970
1971fn value_count(len: usize) -> Result<u16, DekuError> {
1972    u16::try_from(len)
1973        .map_err(|_| DekuError::Assertion("grid data record has more than 65,535 values".into()))
1974}
1975
1976/// Padding after `count` 16-bit values in a type 1 record: the record is 14
1977/// octets plus the values, padded to a 32-bit boundary.
1978const fn type_1_padding(count: usize) -> usize {
1979    wire::padding_to(count.saturating_mul(2).saturating_add(14), 4)
1980}
1981
1982/// Implemented according to IEEE 1278.1-2012 §6.2.42
1983#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
1984#[deku(
1985    endian = "endian",
1986    ctx = "endian: deku::ctx::Endian",
1987    ctx_default = "deku::ctx::Endian::Big"
1988)]
1989pub struct GroupIdentifier {
1990    pub simulation_address: SimulationAddress,
1991    pub group_number: u16,
1992}
1993
1994/// IFF Data record: a variable-length record in an IFF PDU layer, padded to a 32-bit
1995/// boundary. Its record-specific fields include the padding as received.
1996#[derive(Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
1997#[deku(
1998    endian = "endian",
1999    ctx = "endian: deku::ctx::Endian",
2000    ctx_default = "deku::ctx::Endian::Big"
2001)]
2002pub struct IFFDataRecord {
2003    pub record_type: VariableRecordTypes,
2004    #[deku(
2005        update = "crate::wire::padded_record_length_to(self.record_specific_fields.len(), 4)?",
2006        assert = "crate::wire::valid_aligned_record_length(*record_length, 4)"
2007    )]
2008    pub record_length: u16,
2009    #[deku(
2010        count = "crate::wire::record_fields_len(*record_length)",
2011        writer = "crate::wire::write_padded_fields_to(deku::writer, record_specific_fields, 4)"
2012    )]
2013    pub record_specific_fields: Vec<u8>,
2014}
2015
2016/// Implemented according to IEEE 1278.1-2012 §6.2.43
2017#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2018#[deku(
2019    endian = "endian",
2020    ctx = "endian: deku::ctx::Endian",
2021    ctx_default = "deku::ctx::Endian::Big"
2022)]
2023pub struct IFFDataSpecification {
2024    #[deku(
2025        update = "self.iff_data_records.len()",
2026        assert = "crate::wire::fits_in_pdu(*number_of_iff_data_records)"
2027    )]
2028    pub number_of_iff_data_records: u16,
2029    #[deku(count = "number_of_iff_data_records")]
2030    pub iff_data_records: Vec<IFFDataRecord>,
2031}
2032
2033/// Implemented according to IEEE 1278.1-2012 §6.2.44
2034#[derive(Copy, Clone, Debug, Default, PartialEq, deku::DekuRead, deku::DekuWrite)]
2035#[deku(
2036    endian = "endian",
2037    ctx = "endian: deku::ctx::Endian",
2038    ctx_default = "deku::ctx::Endian::Big"
2039)]
2040pub struct IFFFundamentalParameterData {
2041    /// Effective radiated power, in dBm
2042    pub erp: f32,
2043    /// Frequency, in hertz
2044    pub frequency: f32,
2045    /// Pulse group repetition frequency, in hertz
2046    pub pgrf: f32,
2047    /// Pulse width, in microseconds
2048    pub pulse_width: f32,
2049    /// Number of pulses in a burst
2050    pub burst_length: u32,
2051    /// Which modes the parameters apply to \[UID 339\]
2052    pub applicable_modes: IFFApplicableModes,
2053    /// System-specific data
2054    pub system_specific_data: [u8; 3],
2055}
2056
2057impl IFFFundamentalParameterData {
2058    #[must_use]
2059    pub const fn new(
2060        erp: f32,
2061        frequency: f32,
2062        pgrf: f32,
2063        pulse_width: f32,
2064        burst_length: u32,
2065        applicable_modes: IFFApplicableModes,
2066        system_specific_data: [u8; 3],
2067    ) -> Self {
2068        Self {
2069            erp,
2070            frequency,
2071            pgrf,
2072            pulse_width,
2073            burst_length,
2074            applicable_modes,
2075            system_specific_data,
2076        }
2077    }
2078}
2079
2080bitflags::bitflags! {
2081    /// Implemented according to IEEE 1278.1-2012 §6.2.45
2082    #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
2083    pub struct InformationLayers: u8 {
2084        const LAYER_1 = 1 << 1;
2085        const LAYER_2 = 1 << 2;
2086        const LAYER_3 = 1 << 3;
2087        const LAYER_4 = 1 << 4;
2088        const LAYER_5 = 1 << 5;
2089        const LAYER_6 = 1 << 6;
2090        const LAYER_7 = 1 << 7;
2091    }
2092}
2093
2094crate::wire::impl_deku_bitflags!(InformationLayers, u8);
2095
2096impl InformationLayers {
2097    #[must_use]
2098    pub const fn layer(number: u8) -> Option<Self> {
2099        match number {
2100            1..=7 => Some(Self::from_bits_retain(1 << number)),
2101            _ => None,
2102        }
2103    }
2104}
2105
2106/// Implemented according to IEEE 1278.1-2012 §6.2.46
2107///
2108/// `record_length` is the length of `record_specific_fields` in octets, not
2109/// counting the record type, the length itself or the padding. On the wire,
2110/// the record is padded to a 32-bit boundary.
2111#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2112#[deku(
2113    endian = "endian",
2114    ctx = "endian: deku::ctx::Endian",
2115    ctx_default = "deku::ctx::Endian::Big"
2116)]
2117pub struct IntercomCommunicationsParameters {
2118    pub record_type: IntercomControlRecordType,
2119    /// `serialize` sets this from `record_specific_fields`.
2120    #[deku(
2121        update = "self.record_specific_fields.len()",
2122        assert = "crate::wire::fits_in_pdu(*record_length)"
2123    )]
2124    pub record_length: u16,
2125    /// Exactly `record_length` octets without the padding
2126    #[deku(
2127        reader = "read_intercom_fields(deku::reader, *record_length)",
2128        writer = "write_intercom_fields(deku::writer, record_specific_fields)"
2129    )]
2130    pub record_specific_fields: Vec<u8>,
2131}
2132
2133impl IntercomCommunicationsParameters {
2134    #[must_use]
2135    pub fn new(record_type: IntercomControlRecordType, record_specific_fields: Vec<u8>) -> Self {
2136        Self {
2137            record_type,
2138            record_length: u16::try_from(record_specific_fields.len()).unwrap_or(u16::MAX),
2139            record_specific_fields,
2140        }
2141    }
2142}
2143
2144/// Reads an Intercom Communications Parameters record's `length` octets of
2145/// fields and skips its padding to a 32-bit boundary (§6.2.46, Table 75).
2146fn read_intercom_fields<R: Read + Seek>(
2147    reader: &mut Reader<R>,
2148    length: u16,
2149) -> Result<Vec<u8>, DekuError> {
2150    let length = usize::from(length);
2151    let fields = crate::wire::read_n(reader, length, Endian::Big)?;
2152    crate::wire::skip(reader, crate::wire::padding_to(length, 4))?;
2153    Ok(fields)
2154}
2155
2156fn write_intercom_fields<W: Write + Seek>(
2157    writer: &mut Writer<W>,
2158    fields: &[u8],
2159) -> Result<(), DekuError> {
2160    fields.to_writer(writer, ())?;
2161    crate::wire::write_zeros(writer, crate::wire::padding_to(fields.len(), 4))
2162}
2163
2164/// Implemented according to IEEE 1278.1-2012 §6.2.47
2165#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2166#[deku(
2167    endian = "endian",
2168    ctx = "endian: deku::ctx::Endian",
2169    ctx_default = "deku::ctx::Endian::Big"
2170)]
2171pub struct IntercomIdentifier {
2172    pub intercom_reference_id: EntityIdentifier,
2173    pub intercom_number: u16,
2174}
2175
2176impl IntercomIdentifier {
2177    #[must_use]
2178    pub const fn new(intercom_reference_id: EntityIdentifier, intercom_number: u16) -> Self {
2179        Self {
2180            intercom_reference_id,
2181            intercom_number,
2182        }
2183    }
2184}
2185
2186/// Implemented according to IEEE 1278.1-2012 §6.2.48.2
2187#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2188#[deku(
2189    endian = "endian",
2190    ctx = "endian: deku::ctx::Endian",
2191    ctx_default = "deku::ctx::Endian::Big"
2192)]
2193pub struct IOCommunicationsNode {
2194    pub record_type: u32,
2195    pub record_length: u16,
2196    pub communications_node_type: IOCommsNodeRecordCommsNodeType,
2197    padding: u8,
2198    pub communications_node_id: CommunicationsNodeID,
2199}
2200
2201impl IOCommunicationsNode {
2202    #[must_use]
2203    pub fn new() -> Self {
2204        Self {
2205            record_type: 5501,
2206            record_length: 16,
2207            communications_node_type: IOCommsNodeRecordCommsNodeType::default(),
2208            padding: 0u8,
2209            communications_node_id: CommunicationsNodeID::default(),
2210        }
2211    }
2212}
2213
2214/// Implemented according to IEEE 1278.1-2012 §6.2.48.3
2215#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2216#[deku(
2217    endian = "endian",
2218    ctx = "endian: deku::ctx::Endian",
2219    ctx_default = "deku::ctx::Endian::Big"
2220)]
2221pub struct IOEffect {
2222    pub record_type: u32,
2223    pub record_length: u16,
2224    pub io_status: IOEffectsRecordIOStatus,
2225    pub io_link_type: IOEffectsRecordIOLinkType,
2226    pub io_effect: IOEffectsRecordIOEffect,
2227    pub io_effect_duty_cycle: u8,
2228    pub io_effect_duration: u16,
2229    pub io_process: IOEffectsRecordIOProcess,
2230    padding: u16,
2231}
2232
2233impl IOEffect {
2234    #[must_use]
2235    pub fn new() -> Self {
2236        Self {
2237            record_type: 5500,
2238            record_length: 16,
2239            ..Default::default()
2240        }
2241    }
2242}
2243
2244/// Implemented according to IEEE 1278.1-2012 §6.2.48.4
2245#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2246#[deku(
2247    endian = "endian",
2248    ctx = "endian: deku::ctx::Endian",
2249    ctx_default = "deku::ctx::Endian::Big"
2250)]
2251pub struct CommunicationsNodeID {
2252    pub entity_id: EntityIdentifier,
2253    pub element_id: u16,
2254}
2255
2256/// Implemented according to IEEE 1278.1-2012 §6.2.49
2257#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
2258#[deku(
2259    endian = "endian",
2260    ctx = "endian: deku::ctx::Endian",
2261    ctx_default = "deku::ctx::Endian::Big"
2262)]
2263pub struct JammingTechnique {
2264    pub kind: u8,
2265    pub category: u8,
2266    pub subcategory: u8,
2267    pub specific: u8,
2268}
2269
2270impl JammingTechnique {
2271    #[must_use]
2272    pub const fn new(kind: u8, category: u8, subcategory: u8, specific: u8) -> Self {
2273        Self {
2274            kind,
2275            category,
2276            subcategory,
2277            specific,
2278        }
2279    }
2280
2281    /// The technique's name as defined in SISO-REF-010, or `None` if the code is not
2282    /// in the table.
2283    #[must_use]
2284    pub fn name(self) -> Option<&'static str> {
2285        NAMES
2286            .iter()
2287            .find(|(technique, _)| *technique == self)
2288            .map(|&(_, name)| name)
2289    }
2290
2291    /// Whether this technique is `parent` or falls under it in the hierarchy.
2292    ///
2293    /// Every level that `parent` specifies must match; the levels it leaves as 0
2294    /// match anything. So every noise technique is within [`NOISE`](Self::NOISE)
2295    /// and [`CLICK`](Self::CLICK) is within [`BARRAGE_NOISE`](Self::BARRAGE_NOISE).
2296    #[must_use]
2297    pub const fn is_within(self, parent: Self) -> bool {
2298        const fn level_matches(level: u8, parent: u8) -> bool {
2299            parent == 0 || level == parent
2300        }
2301
2302        self.kind == parent.kind
2303            && level_matches(self.category, parent.category)
2304            && level_matches(self.subcategory, parent.subcategory)
2305            && level_matches(self.specific, parent.specific)
2306    }
2307}
2308
2309/// Every technique in SISO-REF-010-2023 Jamming Technique [UID 284], with its name.
2310const NAMES: [(JammingTechnique, &str); 134] = [
2311    (JammingTechnique::new(1, 0, 0, 0), "Noise"),
2312    (
2313        JammingTechnique::new(1, 5, 0, 0),
2314        "Amplitude Modulation (AM) Noise",
2315    ),
2316    (JammingTechnique::new(1, 10, 0, 0), "Barrage Noise"),
2317    (JammingTechnique::new(1, 10, 5, 0), "Click"),
2318    (JammingTechnique::new(1, 10, 10, 0), "Source Noise"),
2319    (JammingTechnique::new(1, 15, 0, 0), "Bistatic Clutter"),
2320    (JammingTechnique::new(1, 20, 0, 0), "Comb"),
2321    (
2322        JammingTechnique::new(1, 25, 0, 0),
2323        "Cooperative Blinked Noise (CBN)",
2324    ),
2325    (JammingTechnique::new(1, 30, 0, 0), "Doppler Noise"),
2326    (
2327        JammingTechnique::new(1, 35, 0, 0),
2328        "Frequency Modulation (FM) by Noise",
2329    ),
2330    (JammingTechnique::new(1, 40, 0, 0), "Impulse Noise"),
2331    (JammingTechnique::new(1, 45, 0, 0), "Partial Band"),
2332    (JammingTechnique::new(1, 50, 0, 0), "Pseudorandom AM"),
2333    (JammingTechnique::new(1, 55, 0, 0), "Pulse Noise"),
2334    (
2335        JammingTechnique::new(1, 60, 0, 0),
2336        "Quasi-Noise (aka Pseudorandom)",
2337    ),
2338    (
2339        JammingTechnique::new(1, 65, 0, 0),
2340        "Range Bin Masking (RBM) (aka Cover Pulse)",
2341    ),
2342    (
2343        JammingTechnique::new(1, 65, 5, 0),
2344        "Range Bin Masking with Velocity Bin Masking",
2345    ),
2346    (JammingTechnique::new(1, 70, 0, 0), "Repeater Noise"),
2347    (
2348        JammingTechnique::new(1, 70, 5, 0),
2349        "Narrowband Repeater Noise",
2350    ),
2351    (
2352        JammingTechnique::new(1, 70, 10, 0),
2353        "Wide Band Repeater Noise",
2354    ),
2355    (JammingTechnique::new(1, 75, 0, 0), "Spot Noise"),
2356    (
2357        JammingTechnique::new(1, 75, 5, 0),
2358        "Automatic Spot Noise (ASJ)",
2359    ),
2360    (JammingTechnique::new(1, 75, 10, 0), "Blinking Spot Noise"),
2361    (JammingTechnique::new(1, 75, 15, 0), "Burst Spot Noise"),
2362    (JammingTechnique::new(1, 75, 20, 0), "Doppler Spot Noise"),
2363    (JammingTechnique::new(1, 75, 25, 0), "Skirt Frequency"),
2364    (
2365        JammingTechnique::new(1, 80, 0, 0),
2366        "Swept Noise (aka Swept Spot Noise, Sweep)",
2367    ),
2368    (JammingTechnique::new(1, 80, 5, 0), "Frequency Swept"),
2369    (JammingTechnique::new(1, 80, 10, 0), "Swept AM"),
2370    (
2371        JammingTechnique::new(1, 85, 0, 0),
2372        "Velocity Bin Masking (VBM)",
2373    ),
2374    (JammingTechnique::new(2, 0, 0, 0), "Deception"),
2375    (JammingTechnique::new(2, 5, 0, 0), "Analyzer"),
2376    (JammingTechnique::new(2, 10, 0, 0), "Angle"),
2377    (JammingTechnique::new(2, 10, 5, 0), "Angle Gate Walk-Off"),
2378    (
2379        JammingTechnique::new(2, 10, 10, 0),
2380        "Cooperative Angle (CAJ)",
2381    ),
2382    (JammingTechnique::new(2, 10, 15, 0), "Cross-Eye"),
2383    (JammingTechnique::new(2, 10, 20, 0), "Cross-Polarization"),
2384    (JammingTechnique::new(2, 10, 25, 0), "Delta"),
2385    (
2386        JammingTechnique::new(2, 10, 30, 0),
2387        "Inverse Gain (aka Inverse Amplitude)",
2388    ),
2389    (JammingTechnique::new(2, 10, 35, 0), "Sea-Bounced"),
2390    (
2391        JammingTechnique::new(2, 10, 40, 0),
2392        "Swept Square Wave (SSW)",
2393    ),
2394    (JammingTechnique::new(2, 10, 45, 0), "Terrain Bounce"),
2395    (JammingTechnique::new(2, 15, 0, 0), "Angle and Gate Stealer"),
2396    (
2397        JammingTechnique::new(2, 15, 5, 0),
2398        "Cross-Polarization and Range Gate Pull-Off (RGPO)",
2399    ),
2400    (
2401        JammingTechnique::new(2, 15, 10, 0),
2402        "Cross-Polarization and Velocity Gate Pull-Off (VGPO)",
2403    ),
2404    (
2405        JammingTechnique::new(2, 15, 15, 0),
2406        "Cross-Polarization, RGPO and VGPO",
2407    ),
2408    (JammingTechnique::new(2, 15, 20, 0), "Inverse Gain and RGPO"),
2409    (
2410        JammingTechnique::new(2, 15, 25, 0),
2411        "Inverse Gain and RGPO and VGPO",
2412    ),
2413    (JammingTechnique::new(2, 15, 30, 0), "Inverse Gain and VGPO"),
2414    (JammingTechnique::new(2, 15, 35, 0), "RGPO and SSW"),
2415    (JammingTechnique::new(2, 15, 40, 0), "SSW and VGPO"),
2416    (JammingTechnique::new(2, 20, 0, 0), "Angle and False Target"),
2417    (
2418        JammingTechnique::new(2, 20, 5, 0),
2419        "Angle and Velocity False Targets (VFT)",
2420    ),
2421    (JammingTechnique::new(2, 20, 5, 5), "Inverse Gain and VFT"),
2422    (JammingTechnique::new(2, 20, 5, 10), "SSW and VFT"),
2423    (
2424        JammingTechnique::new(2, 20, 10, 0),
2425        "Range False Targets (RFT) and Inverse Gain",
2426    ),
2427    (JammingTechnique::new(2, 20, 15, 0), "RFT and SSW"),
2428    (
2429        JammingTechnique::new(2, 25, 0, 0),
2430        "Angle and Random Range Programs (RANRAP)",
2431    ),
2432    (JammingTechnique::new(2, 25, 5, 0), "RANRAP and SSW"),
2433    (JammingTechnique::new(2, 30, 0, 0), "Angle and Velocity"),
2434    (JammingTechnique::new(2, 30, 5, 0), "Inverse Gain and VBM"),
2435    (JammingTechnique::new(2, 30, 10, 0), "SSW and VBM"),
2436    (
2437        JammingTechnique::new(2, 35, 0, 0),
2438        "Automatic Gain Control (AGC)",
2439    ),
2440    (JammingTechnique::new(2, 40, 0, 0), "AGC and Gate Stealer"),
2441    (JammingTechnique::new(2, 40, 5, 0), "AGC and RGPO"),
2442    (JammingTechnique::new(2, 40, 10, 0), "AGC and VGPO"),
2443    (JammingTechnique::new(2, 40, 15, 0), "AGC and RGPO and VGPO"),
2444    (JammingTechnique::new(2, 45, 0, 0), "Colinear"),
2445    (
2446        JammingTechnique::new(2, 50, 0, 0),
2447        "Constant False Alarm Rate",
2448    ),
2449    (JammingTechnique::new(2, 55, 0, 0), "Double Cross"),
2450    (JammingTechnique::new(2, 60, 0, 0), "Down Link"),
2451    (JammingTechnique::new(2, 65, 0, 0), "False Target"),
2452    (JammingTechnique::new(2, 65, 5, 0), "Coherent False Targets"),
2453    (
2454        JammingTechnique::new(2, 65, 10, 0),
2455        "False Doppler Target (FDT)",
2456    ),
2457    (
2458        JammingTechnique::new(2, 65, 15, 0),
2459        "Multiple False Targets",
2460    ),
2461    (
2462        JammingTechnique::new(2, 65, 20, 0),
2463        "Range False Targets (RFT)",
2464    ),
2465    (JammingTechnique::new(2, 65, 25, 0), "Transponder"),
2466    (
2467        JammingTechnique::new(2, 65, 30, 0),
2468        "Velocity False Targets (VFT)",
2469    ),
2470    (JammingTechnique::new(2, 70, 0, 0), "Figure Eight"),
2471    (JammingTechnique::new(2, 75, 0, 0), "Gate Stealer"),
2472    (
2473        JammingTechnique::new(2, 75, 5, 0),
2474        "Chirp Gate Stealer (CGS)",
2475    ),
2476    (
2477        JammingTechnique::new(2, 75, 10, 0),
2478        "Range Gate Pull-Off (RGPO)",
2479    ),
2480    (JammingTechnique::new(2, 75, 15, 0), "RGPO and VGPO"),
2481    (
2482        JammingTechnique::new(2, 75, 20, 0),
2483        "VGPO (aka Velocity Gate Stealer, VGS)",
2484    ),
2485    (
2486        JammingTechnique::new(2, 80, 0, 0),
2487        "Gate Stealer and Repeater",
2488    ),
2489    (
2490        JammingTechnique::new(2, 80, 5, 0),
2491        "Repeater Swept Amplitude Modulation (RSAM) and VGPO",
2492    ),
2493    (JammingTechnique::new(2, 85, 0, 0), "Glint Enhance"),
2494    (JammingTechnique::new(2, 90, 0, 0), "Image Frequency"),
2495    (
2496        JammingTechnique::new(2, 95, 0, 0),
2497        "Jittered Pulse Repetition Frequency",
2498    ),
2499    (JammingTechnique::new(2, 100, 0, 0), "Jittered Pulse Width"),
2500    (
2501        JammingTechnique::new(2, 105, 0, 0),
2502        "Pseudorandom Noise (PRN)",
2503    ),
2504    (JammingTechnique::new(2, 110, 0, 0), "Pulse"),
2505    (
2506        JammingTechnique::new(2, 115, 0, 0),
2507        "Pulse Compression Deception",
2508    ),
2509    (
2510        JammingTechnique::new(2, 120, 0, 0),
2511        "Random Range Programs (RANRAP)",
2512    ),
2513    (JammingTechnique::new(2, 125, 0, 0), "Refraction"),
2514    (JammingTechnique::new(2, 130, 0, 0), "Repeater"),
2515    (
2516        JammingTechnique::new(2, 130, 5, 0),
2517        "Continuous Wave Repeater",
2518    ),
2519    (JammingTechnique::new(2, 130, 10, 0), "Repeater Noise"),
2520    (
2521        JammingTechnique::new(2, 130, 15, 0),
2522        "Multiple Frequency Repeater (MFR)",
2523    ),
2524    (
2525        JammingTechnique::new(2, 130, 20, 0),
2526        "Narrow Band Repeater Noise (NBRN)",
2527    ),
2528    (JammingTechnique::new(2, 130, 25, 0), "Random Doppler (RD)"),
2529    (
2530        JammingTechnique::new(2, 130, 30, 0),
2531        "Repeater Digital Radio Frequency Memory (DRFM)",
2532    ),
2533    (JammingTechnique::new(2, 130, 30, 1), "DRFM Level A"),
2534    (JammingTechnique::new(2, 130, 30, 2), "DRFM Level B"),
2535    (JammingTechnique::new(2, 130, 30, 3), "DRFM Level C"),
2536    (JammingTechnique::new(2, 130, 30, 4), "DRFM Level D"),
2537    (JammingTechnique::new(2, 130, 30, 5), "DRFM Level E"),
2538    (
2539        JammingTechnique::new(2, 130, 35, 0),
2540        "Repeater Swept Amplitude Modulation (RSAM)",
2541    ),
2542    (JammingTechnique::new(2, 135, 0, 0), "Scintillation"),
2543    (JammingTechnique::new(2, 140, 0, 0), "Serrodyne"),
2544    (JammingTechnique::new(2, 145, 0, 0), "Velocity"),
2545    (JammingTechnique::new(3, 0, 0, 0), "Deception and Noise"),
2546    (JammingTechnique::new(3, 5, 0, 0), "Angle and Noise"),
2547    (JammingTechnique::new(3, 5, 5, 0), "Angle and Barrage"),
2548    (
2549        JammingTechnique::new(3, 5, 5, 5),
2550        "Barrage and Inverse Gain",
2551    ),
2552    (JammingTechnique::new(3, 5, 5, 10), "Barrage and SSW"),
2553    (JammingTechnique::new(3, 10, 0, 0), "Angle and FM by Noise"),
2554    (
2555        JammingTechnique::new(3, 10, 5, 0),
2556        "FM by Noise and Inverse Gain",
2557    ),
2558    (JammingTechnique::new(3, 10, 10, 0), "FM by Noise and SSW"),
2559    (
2560        JammingTechnique::new(3, 15, 0, 0),
2561        "Angle and Pseudorandom AM",
2562    ),
2563    (
2564        JammingTechnique::new(3, 15, 5, 0),
2565        "Inverse Gain and Pseudorandom AM",
2566    ),
2567    (
2568        JammingTechnique::new(3, 15, 10, 0),
2569        "Pseudorandom AM and SSW",
2570    ),
2571    (JammingTechnique::new(3, 20, 0, 0), "Angle and Spot"),
2572    (
2573        JammingTechnique::new(3, 20, 5, 0),
2574        "Inverse Gain and Low Level Noise",
2575    ),
2576    (
2577        JammingTechnique::new(3, 20, 10, 0),
2578        "Inverse Gain and Spot Noise",
2579    ),
2580    (JammingTechnique::new(3, 20, 15, 0), "Spot and SSW"),
2581    (JammingTechnique::new(3, 25, 0, 0), "Gate Stealer and Noise"),
2582    (JammingTechnique::new(3, 25, 5, 0), "Noise and RGPO"),
2583    (
2584        JammingTechnique::new(3, 25, 5, 5),
2585        "Low Level Noise and RGPO",
2586    ),
2587    (JammingTechnique::new(3, 25, 10, 0), "Noise and VGPO"),
2588    (
2589        JammingTechnique::new(3, 25, 10, 5),
2590        "Low Level Noise and VGPO",
2591    ),
2592    (
2593        JammingTechnique::new(3, 30, 0, 0),
2594        "False Target Deception and Swept Noise",
2595    ),
2596    (JammingTechnique::new(4, 0, 0, 0), "Special"),
2597    (JammingTechnique::new(4, 1, 0, 0), "Super Jam"),
2598];
2599
2600/// Formats the code in SISO-REF-010's dotted form, without trailing zero levels,
2601/// followed by the name when it's known: for example `1.10.5 Click`.
2602impl fmt::Display for JammingTechnique {
2603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2604        let levels = [self.kind, self.category, self.subcategory, self.specific];
2605        let shown = levels
2606            .iter()
2607            .rposition(|&level| level != 0)
2608            .map_or(1, |last| last.saturating_add(1));
2609        for (i, level) in levels.iter().take(shown).enumerate() {
2610            if i > 0 {
2611                f.write_str(".")?;
2612            }
2613            write!(f, "{level}")?;
2614        }
2615        if let Some(name) = self.name() {
2616            write!(f, " {name}")?;
2617        }
2618        Ok(())
2619    }
2620}
2621
2622/// The techniques defined in SISO-REF-010-2023 Jamming Technique [UID 284].
2623impl JammingTechnique {
2624    /// `1` Noise.
2625    pub const NOISE: Self = Self::new(1, 0, 0, 0);
2626    /// `1.5` Amplitude Modulation (AM) Noise, under Noise.
2627    pub const AMPLITUDE_MODULATION_NOISE: Self = Self::new(1, 5, 0, 0);
2628    /// `1.10` Barrage Noise, under Noise.
2629    pub const BARRAGE_NOISE: Self = Self::new(1, 10, 0, 0);
2630    /// `1.10.5` Click, under Noise → Barrage Noise.
2631    pub const CLICK: Self = Self::new(1, 10, 5, 0);
2632    /// `1.10.10` Source Noise, under Noise → Barrage Noise.
2633    pub const SOURCE_NOISE: Self = Self::new(1, 10, 10, 0);
2634    /// `1.15` Bistatic Clutter, under Noise.
2635    pub const BISTATIC_CLUTTER: Self = Self::new(1, 15, 0, 0);
2636    /// `1.20` Comb, under Noise.
2637    pub const COMB: Self = Self::new(1, 20, 0, 0);
2638    /// `1.25` Cooperative Blinked Noise (CBN), under Noise.
2639    pub const COOPERATIVE_BLINKED_NOISE: Self = Self::new(1, 25, 0, 0);
2640    /// `1.30` Doppler Noise, under Noise.
2641    pub const DOPPLER_NOISE: Self = Self::new(1, 30, 0, 0);
2642    /// `1.35` Frequency Modulation (FM) by Noise, under Noise.
2643    pub const FREQUENCY_MODULATION_BY_NOISE: Self = Self::new(1, 35, 0, 0);
2644    /// `1.40` Impulse Noise, under Noise.
2645    pub const IMPULSE_NOISE: Self = Self::new(1, 40, 0, 0);
2646    /// `1.45` Partial Band, under Noise.
2647    pub const PARTIAL_BAND: Self = Self::new(1, 45, 0, 0);
2648    /// `1.50` Pseudorandom AM, under Noise.
2649    pub const PSEUDORANDOM_AM: Self = Self::new(1, 50, 0, 0);
2650    /// `1.55` Pulse Noise, under Noise.
2651    pub const PULSE_NOISE: Self = Self::new(1, 55, 0, 0);
2652    /// `1.60` Quasi-Noise (aka Pseudorandom), under Noise.
2653    pub const QUASI_NOISE: Self = Self::new(1, 60, 0, 0);
2654    /// `1.65` Range Bin Masking (RBM) (aka Cover Pulse), under Noise.
2655    pub const RANGE_BIN_MASKING: Self = Self::new(1, 65, 0, 0);
2656    /// `1.65.5` Range Bin Masking with Velocity Bin Masking, under Noise → Range Bin Masking (RBM) (aka Cover Pulse).
2657    pub const RANGE_BIN_MASKING_WITH_VELOCITY_BIN_MASKING: Self = Self::new(1, 65, 5, 0);
2658    /// `1.70` Repeater Noise, under Noise.
2659    pub const NOISE_REPEATER_NOISE: Self = Self::new(1, 70, 0, 0);
2660    /// `1.70.5` Narrowband Repeater Noise, under Noise → Repeater Noise.
2661    pub const NARROWBAND_REPEATER_NOISE: Self = Self::new(1, 70, 5, 0);
2662    /// `1.70.10` Wide Band Repeater Noise, under Noise → Repeater Noise.
2663    pub const WIDE_BAND_REPEATER_NOISE: Self = Self::new(1, 70, 10, 0);
2664    /// `1.75` Spot Noise, under Noise.
2665    pub const SPOT_NOISE: Self = Self::new(1, 75, 0, 0);
2666    /// `1.75.5` Automatic Spot Noise (ASJ), under Noise → Spot Noise.
2667    pub const AUTOMATIC_SPOT_NOISE: Self = Self::new(1, 75, 5, 0);
2668    /// `1.75.10` Blinking Spot Noise, under Noise → Spot Noise.
2669    pub const BLINKING_SPOT_NOISE: Self = Self::new(1, 75, 10, 0);
2670    /// `1.75.15` Burst Spot Noise, under Noise → Spot Noise.
2671    pub const BURST_SPOT_NOISE: Self = Self::new(1, 75, 15, 0);
2672    /// `1.75.20` Doppler Spot Noise, under Noise → Spot Noise.
2673    pub const DOPPLER_SPOT_NOISE: Self = Self::new(1, 75, 20, 0);
2674    /// `1.75.25` Skirt Frequency, under Noise → Spot Noise.
2675    pub const SKIRT_FREQUENCY: Self = Self::new(1, 75, 25, 0);
2676    /// `1.80` Swept Noise (aka Swept Spot Noise, Sweep), under Noise.
2677    pub const SWEPT_NOISE: Self = Self::new(1, 80, 0, 0);
2678    /// `1.80.5` Frequency Swept, under Noise → Swept Noise (aka Swept Spot Noise, Sweep).
2679    pub const FREQUENCY_SWEPT: Self = Self::new(1, 80, 5, 0);
2680    /// `1.80.10` Swept AM, under Noise → Swept Noise (aka Swept Spot Noise, Sweep).
2681    pub const SWEPT_AM: Self = Self::new(1, 80, 10, 0);
2682    /// `1.85` Velocity Bin Masking (VBM), under Noise.
2683    pub const VELOCITY_BIN_MASKING: Self = Self::new(1, 85, 0, 0);
2684    /// `2` Deception.
2685    pub const DECEPTION: Self = Self::new(2, 0, 0, 0);
2686    /// `2.5` Analyzer, under Deception.
2687    pub const ANALYZER: Self = Self::new(2, 5, 0, 0);
2688    /// `2.10` Angle, under Deception.
2689    pub const ANGLE: Self = Self::new(2, 10, 0, 0);
2690    /// `2.10.5` Angle Gate Walk-Off, under Deception → Angle.
2691    pub const ANGLE_GATE_WALK_OFF: Self = Self::new(2, 10, 5, 0);
2692    /// `2.10.10` Cooperative Angle (CAJ), under Deception → Angle.
2693    pub const COOPERATIVE_ANGLE: Self = Self::new(2, 10, 10, 0);
2694    /// `2.10.15` Cross-Eye, under Deception → Angle.
2695    pub const CROSS_EYE: Self = Self::new(2, 10, 15, 0);
2696    /// `2.10.20` Cross-Polarization, under Deception → Angle.
2697    pub const CROSS_POLARIZATION: Self = Self::new(2, 10, 20, 0);
2698    /// `2.10.25` Delta, under Deception → Angle.
2699    pub const DELTA: Self = Self::new(2, 10, 25, 0);
2700    /// `2.10.30` Inverse Gain (aka Inverse Amplitude), under Deception → Angle.
2701    pub const INVERSE_GAIN: Self = Self::new(2, 10, 30, 0);
2702    /// `2.10.35` Sea-Bounced, under Deception → Angle.
2703    pub const SEA_BOUNCED: Self = Self::new(2, 10, 35, 0);
2704    /// `2.10.40` Swept Square Wave (SSW), under Deception → Angle.
2705    pub const SWEPT_SQUARE_WAVE: Self = Self::new(2, 10, 40, 0);
2706    /// `2.10.45` Terrain Bounce, under Deception → Angle.
2707    pub const TERRAIN_BOUNCE: Self = Self::new(2, 10, 45, 0);
2708    /// `2.15` Angle and Gate Stealer, under Deception.
2709    pub const ANGLE_AND_GATE_STEALER: Self = Self::new(2, 15, 0, 0);
2710    /// `2.15.5` Cross-Polarization and Range Gate Pull-Off (RGPO), under Deception → Angle and Gate Stealer.
2711    pub const CROSS_POLARIZATION_AND_RANGE_GATE_PULL_OFF: Self = Self::new(2, 15, 5, 0);
2712    /// `2.15.10` Cross-Polarization and Velocity Gate Pull-Off (VGPO), under Deception → Angle and Gate Stealer.
2713    pub const CROSS_POLARIZATION_AND_VELOCITY_GATE_PULL_OFF: Self = Self::new(2, 15, 10, 0);
2714    /// `2.15.15` Cross-Polarization, RGPO and VGPO, under Deception → Angle and Gate Stealer.
2715    pub const CROSS_POLARIZATION_RGPO_AND_VGPO: Self = Self::new(2, 15, 15, 0);
2716    /// `2.15.20` Inverse Gain and RGPO, under Deception → Angle and Gate Stealer.
2717    pub const INVERSE_GAIN_AND_RGPO: Self = Self::new(2, 15, 20, 0);
2718    /// `2.15.25` Inverse Gain and RGPO and VGPO, under Deception → Angle and Gate Stealer.
2719    pub const INVERSE_GAIN_AND_RGPO_AND_VGPO: Self = Self::new(2, 15, 25, 0);
2720    /// `2.15.30` Inverse Gain and VGPO, under Deception → Angle and Gate Stealer.
2721    pub const INVERSE_GAIN_AND_VGPO: Self = Self::new(2, 15, 30, 0);
2722    /// `2.15.35` RGPO and SSW, under Deception → Angle and Gate Stealer.
2723    pub const RGPO_AND_SSW: Self = Self::new(2, 15, 35, 0);
2724    /// `2.15.40` SSW and VGPO, under Deception → Angle and Gate Stealer.
2725    pub const SSW_AND_VGPO: Self = Self::new(2, 15, 40, 0);
2726    /// `2.20` Angle and False Target, under Deception.
2727    pub const ANGLE_AND_FALSE_TARGET: Self = Self::new(2, 20, 0, 0);
2728    /// `2.20.5` Angle and Velocity False Targets (VFT), under Deception → Angle and False Target.
2729    pub const ANGLE_AND_VELOCITY_FALSE_TARGETS: Self = Self::new(2, 20, 5, 0);
2730    /// `2.20.5.5` Inverse Gain and VFT, under Deception → Angle and False Target → Angle and Velocity False Targets (VFT).
2731    pub const INVERSE_GAIN_AND_VFT: Self = Self::new(2, 20, 5, 5);
2732    /// `2.20.5.10` SSW and VFT, under Deception → Angle and False Target → Angle and Velocity False Targets (VFT).
2733    pub const SSW_AND_VFT: Self = Self::new(2, 20, 5, 10);
2734    /// `2.20.10` Range False Targets (RFT) and Inverse Gain, under Deception → Angle and False Target.
2735    pub const RANGE_FALSE_TARGETS_AND_INVERSE_GAIN: Self = Self::new(2, 20, 10, 0);
2736    /// `2.20.15` RFT and SSW, under Deception → Angle and False Target.
2737    pub const RFT_AND_SSW: Self = Self::new(2, 20, 15, 0);
2738    /// `2.25` Angle and Random Range Programs (RANRAP), under Deception.
2739    pub const ANGLE_AND_RANDOM_RANGE_PROGRAMS: Self = Self::new(2, 25, 0, 0);
2740    /// `2.25.5` RANRAP and SSW, under Deception → Angle and Random Range Programs (RANRAP).
2741    pub const RANRAP_AND_SSW: Self = Self::new(2, 25, 5, 0);
2742    /// `2.30` Angle and Velocity, under Deception.
2743    pub const ANGLE_AND_VELOCITY: Self = Self::new(2, 30, 0, 0);
2744    /// `2.30.5` Inverse Gain and VBM, under Deception → Angle and Velocity.
2745    pub const INVERSE_GAIN_AND_VBM: Self = Self::new(2, 30, 5, 0);
2746    /// `2.30.10` SSW and VBM, under Deception → Angle and Velocity.
2747    pub const SSW_AND_VBM: Self = Self::new(2, 30, 10, 0);
2748    /// `2.35` Automatic Gain Control (AGC), under Deception.
2749    pub const AUTOMATIC_GAIN_CONTROL: Self = Self::new(2, 35, 0, 0);
2750    /// `2.40` AGC and Gate Stealer, under Deception.
2751    pub const AGC_AND_GATE_STEALER: Self = Self::new(2, 40, 0, 0);
2752    /// `2.40.5` AGC and RGPO, under Deception → AGC and Gate Stealer.
2753    pub const AGC_AND_RGPO: Self = Self::new(2, 40, 5, 0);
2754    /// `2.40.10` AGC and VGPO, under Deception → AGC and Gate Stealer.
2755    pub const AGC_AND_VGPO: Self = Self::new(2, 40, 10, 0);
2756    /// `2.40.15` AGC and RGPO and VGPO, under Deception → AGC and Gate Stealer.
2757    pub const AGC_AND_RGPO_AND_VGPO: Self = Self::new(2, 40, 15, 0);
2758    /// `2.45` Colinear, under Deception.
2759    pub const COLINEAR: Self = Self::new(2, 45, 0, 0);
2760    /// `2.50` Constant False Alarm Rate, under Deception.
2761    pub const CONSTANT_FALSE_ALARM_RATE: Self = Self::new(2, 50, 0, 0);
2762    /// `2.55` Double Cross, under Deception.
2763    pub const DOUBLE_CROSS: Self = Self::new(2, 55, 0, 0);
2764    /// `2.60` Down Link, under Deception.
2765    pub const DOWN_LINK: Self = Self::new(2, 60, 0, 0);
2766    /// `2.65` False Target, under Deception.
2767    pub const FALSE_TARGET: Self = Self::new(2, 65, 0, 0);
2768    /// `2.65.5` Coherent False Targets, under Deception → False Target.
2769    pub const COHERENT_FALSE_TARGETS: Self = Self::new(2, 65, 5, 0);
2770    /// `2.65.10` False Doppler Target (FDT), under Deception → False Target.
2771    pub const FALSE_DOPPLER_TARGET: Self = Self::new(2, 65, 10, 0);
2772    /// `2.65.15` Multiple False Targets, under Deception → False Target.
2773    pub const MULTIPLE_FALSE_TARGETS: Self = Self::new(2, 65, 15, 0);
2774    /// `2.65.20` Range False Targets (RFT), under Deception → False Target.
2775    pub const RANGE_FALSE_TARGETS: Self = Self::new(2, 65, 20, 0);
2776    /// `2.65.25` Transponder, under Deception → False Target.
2777    pub const TRANSPONDER: Self = Self::new(2, 65, 25, 0);
2778    /// `2.65.30` Velocity False Targets (VFT), under Deception → False Target.
2779    pub const VELOCITY_FALSE_TARGETS: Self = Self::new(2, 65, 30, 0);
2780    /// `2.70` Figure Eight, under Deception.
2781    pub const FIGURE_EIGHT: Self = Self::new(2, 70, 0, 0);
2782    /// `2.75` Gate Stealer, under Deception.
2783    pub const GATE_STEALER: Self = Self::new(2, 75, 0, 0);
2784    /// `2.75.5` Chirp Gate Stealer (CGS), under Deception → Gate Stealer.
2785    pub const CHIRP_GATE_STEALER: Self = Self::new(2, 75, 5, 0);
2786    /// `2.75.10` Range Gate Pull-Off (RGPO), under Deception → Gate Stealer.
2787    pub const RANGE_GATE_PULL_OFF: Self = Self::new(2, 75, 10, 0);
2788    /// `2.75.15` RGPO and VGPO, under Deception → Gate Stealer.
2789    pub const RGPO_AND_VGPO: Self = Self::new(2, 75, 15, 0);
2790    /// `2.75.20` VGPO (aka Velocity Gate Stealer, VGS), under Deception → Gate Stealer.
2791    pub const VGPO: Self = Self::new(2, 75, 20, 0);
2792    /// `2.80` Gate Stealer and Repeater, under Deception.
2793    pub const GATE_STEALER_AND_REPEATER: Self = Self::new(2, 80, 0, 0);
2794    /// `2.80.5` Repeater Swept Amplitude Modulation (RSAM) and VGPO, under Deception → Gate Stealer and Repeater.
2795    pub const REPEATER_SWEPT_AMPLITUDE_MODULATION_AND_VGPO: Self = Self::new(2, 80, 5, 0);
2796    /// `2.85` Glint Enhance, under Deception.
2797    pub const GLINT_ENHANCE: Self = Self::new(2, 85, 0, 0);
2798    /// `2.90` Image Frequency, under Deception.
2799    pub const IMAGE_FREQUENCY: Self = Self::new(2, 90, 0, 0);
2800    /// `2.95` Jittered Pulse Repetition Frequency, under Deception.
2801    pub const JITTERED_PULSE_REPETITION_FREQUENCY: Self = Self::new(2, 95, 0, 0);
2802    /// `2.100` Jittered Pulse Width, under Deception.
2803    pub const JITTERED_PULSE_WIDTH: Self = Self::new(2, 100, 0, 0);
2804    /// `2.105` Pseudorandom Noise (PRN), under Deception.
2805    pub const PSEUDORANDOM_NOISE: Self = Self::new(2, 105, 0, 0);
2806    /// `2.110` Pulse, under Deception.
2807    pub const PULSE: Self = Self::new(2, 110, 0, 0);
2808    /// `2.115` Pulse Compression Deception, under Deception.
2809    pub const PULSE_COMPRESSION_DECEPTION: Self = Self::new(2, 115, 0, 0);
2810    /// `2.120` Random Range Programs (RANRAP), under Deception.
2811    pub const RANDOM_RANGE_PROGRAMS: Self = Self::new(2, 120, 0, 0);
2812    /// `2.125` Refraction, under Deception.
2813    pub const REFRACTION: Self = Self::new(2, 125, 0, 0);
2814    /// `2.130` Repeater, under Deception.
2815    pub const REPEATER: Self = Self::new(2, 130, 0, 0);
2816    /// `2.130.5` Continuous Wave Repeater, under Deception → Repeater.
2817    pub const CONTINUOUS_WAVE_REPEATER: Self = Self::new(2, 130, 5, 0);
2818    /// `2.130.10` Repeater Noise, under Deception → Repeater.
2819    pub const DECEPTION_REPEATER_NOISE: Self = Self::new(2, 130, 10, 0);
2820    /// `2.130.15` Multiple Frequency Repeater (MFR), under Deception → Repeater.
2821    pub const MULTIPLE_FREQUENCY_REPEATER: Self = Self::new(2, 130, 15, 0);
2822    /// `2.130.20` Narrow Band Repeater Noise (NBRN), under Deception → Repeater.
2823    pub const NARROW_BAND_REPEATER_NOISE: Self = Self::new(2, 130, 20, 0);
2824    /// `2.130.25` Random Doppler (RD), under Deception → Repeater.
2825    pub const RANDOM_DOPPLER: Self = Self::new(2, 130, 25, 0);
2826    /// `2.130.30` Repeater Digital Radio Frequency Memory (DRFM), under Deception → Repeater.
2827    pub const REPEATER_DIGITAL_RADIO_FREQUENCY_MEMORY: Self = Self::new(2, 130, 30, 0);
2828    /// `2.130.30.1` DRFM Level A, under Deception → Repeater → Repeater Digital Radio Frequency Memory (DRFM).
2829    pub const DRFM_LEVEL_A: Self = Self::new(2, 130, 30, 1);
2830    /// `2.130.30.2` DRFM Level B, under Deception → Repeater → Repeater Digital Radio Frequency Memory (DRFM).
2831    pub const DRFM_LEVEL_B: Self = Self::new(2, 130, 30, 2);
2832    /// `2.130.30.3` DRFM Level C, under Deception → Repeater → Repeater Digital Radio Frequency Memory (DRFM).
2833    pub const DRFM_LEVEL_C: Self = Self::new(2, 130, 30, 3);
2834    /// `2.130.30.4` DRFM Level D, under Deception → Repeater → Repeater Digital Radio Frequency Memory (DRFM).
2835    pub const DRFM_LEVEL_D: Self = Self::new(2, 130, 30, 4);
2836    /// `2.130.30.5` DRFM Level E, under Deception → Repeater → Repeater Digital Radio Frequency Memory (DRFM).
2837    pub const DRFM_LEVEL_E: Self = Self::new(2, 130, 30, 5);
2838    /// `2.130.35` Repeater Swept Amplitude Modulation (RSAM), under Deception → Repeater.
2839    pub const REPEATER_SWEPT_AMPLITUDE_MODULATION: Self = Self::new(2, 130, 35, 0);
2840    /// `2.135` Scintillation, under Deception.
2841    pub const SCINTILLATION: Self = Self::new(2, 135, 0, 0);
2842    /// `2.140` Serrodyne, under Deception.
2843    pub const SERRODYNE: Self = Self::new(2, 140, 0, 0);
2844    /// `2.145` Velocity, under Deception.
2845    pub const VELOCITY: Self = Self::new(2, 145, 0, 0);
2846    /// `3` Deception and Noise.
2847    pub const DECEPTION_AND_NOISE: Self = Self::new(3, 0, 0, 0);
2848    /// `3.5` Angle and Noise, under Deception and Noise.
2849    pub const ANGLE_AND_NOISE: Self = Self::new(3, 5, 0, 0);
2850    /// `3.5.5` Angle and Barrage, under Deception and Noise → Angle and Noise.
2851    pub const ANGLE_AND_BARRAGE: Self = Self::new(3, 5, 5, 0);
2852    /// `3.5.5.5` Barrage and Inverse Gain, under Deception and Noise → Angle and Noise → Angle and Barrage.
2853    pub const BARRAGE_AND_INVERSE_GAIN: Self = Self::new(3, 5, 5, 5);
2854    /// `3.5.5.10` Barrage and SSW, under Deception and Noise → Angle and Noise → Angle and Barrage.
2855    pub const BARRAGE_AND_SSW: Self = Self::new(3, 5, 5, 10);
2856    /// `3.10` Angle and FM by Noise, under Deception and Noise.
2857    pub const ANGLE_AND_FM_BY_NOISE: Self = Self::new(3, 10, 0, 0);
2858    /// `3.10.5` FM by Noise and Inverse Gain, under Deception and Noise → Angle and FM by Noise.
2859    pub const FM_BY_NOISE_AND_INVERSE_GAIN: Self = Self::new(3, 10, 5, 0);
2860    /// `3.10.10` FM by Noise and SSW, under Deception and Noise → Angle and FM by Noise.
2861    pub const FM_BY_NOISE_AND_SSW: Self = Self::new(3, 10, 10, 0);
2862    /// `3.15` Angle and Pseudorandom AM, under Deception and Noise.
2863    pub const ANGLE_AND_PSEUDORANDOM_AM: Self = Self::new(3, 15, 0, 0);
2864    /// `3.15.5` Inverse Gain and Pseudorandom AM, under Deception and Noise → Angle and Pseudorandom AM.
2865    pub const INVERSE_GAIN_AND_PSEUDORANDOM_AM: Self = Self::new(3, 15, 5, 0);
2866    /// `3.15.10` Pseudorandom AM and SSW, under Deception and Noise → Angle and Pseudorandom AM.
2867    pub const PSEUDORANDOM_AM_AND_SSW: Self = Self::new(3, 15, 10, 0);
2868    /// `3.20` Angle and Spot, under Deception and Noise.
2869    pub const ANGLE_AND_SPOT: Self = Self::new(3, 20, 0, 0);
2870    /// `3.20.5` Inverse Gain and Low Level Noise, under Deception and Noise → Angle and Spot.
2871    pub const INVERSE_GAIN_AND_LOW_LEVEL_NOISE: Self = Self::new(3, 20, 5, 0);
2872    /// `3.20.10` Inverse Gain and Spot Noise, under Deception and Noise → Angle and Spot.
2873    pub const INVERSE_GAIN_AND_SPOT_NOISE: Self = Self::new(3, 20, 10, 0);
2874    /// `3.20.15` Spot and SSW, under Deception and Noise → Angle and Spot.
2875    pub const SPOT_AND_SSW: Self = Self::new(3, 20, 15, 0);
2876    /// `3.25` Gate Stealer and Noise, under Deception and Noise.
2877    pub const GATE_STEALER_AND_NOISE: Self = Self::new(3, 25, 0, 0);
2878    /// `3.25.5` Noise and RGPO, under Deception and Noise → Gate Stealer and Noise.
2879    pub const NOISE_AND_RGPO: Self = Self::new(3, 25, 5, 0);
2880    /// `3.25.5.5` Low Level Noise and RGPO, under Deception and Noise → Gate Stealer and Noise → Noise and RGPO.
2881    pub const LOW_LEVEL_NOISE_AND_RGPO: Self = Self::new(3, 25, 5, 5);
2882    /// `3.25.10` Noise and VGPO, under Deception and Noise → Gate Stealer and Noise.
2883    pub const NOISE_AND_VGPO: Self = Self::new(3, 25, 10, 0);
2884    /// `3.25.10.5` Low Level Noise and VGPO, under Deception and Noise → Gate Stealer and Noise → Noise and VGPO.
2885    pub const LOW_LEVEL_NOISE_AND_VGPO: Self = Self::new(3, 25, 10, 5);
2886    /// `3.30` False Target Deception and Swept Noise, under Deception and Noise.
2887    pub const FALSE_TARGET_DECEPTION_AND_SWEPT_NOISE: Self = Self::new(3, 30, 0, 0);
2888    /// `4` Special.
2889    pub const SPECIAL: Self = Self::new(4, 0, 0, 0);
2890    /// `4.1` Super Jam, under Special.
2891    pub const SUPER_JAM: Self = Self::new(4, 1, 0, 0);
2892}
2893
2894/// Implemented according to IEEE 1278.1-2012 §6.2.50
2895#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2896#[deku(
2897    endian = "endian",
2898    ctx = "endian: deku::ctx::Endian",
2899    ctx_default = "deku::ctx::Endian::Big"
2900)]
2901pub struct LaunchedMunition {
2902    pub fire_event_id: EventIdentifier,
2903    padding: u16,
2904    pub firing_entity_id: EntityIdentifier,
2905    padding2: u16,
2906    pub targeting_entity_id: EntityIdentifier,
2907    padding3: u16,
2908    pub target_location_in_world_coordinates: WorldCoordinates,
2909}
2910
2911impl LaunchedMunition {
2912    #[must_use]
2913    pub fn new() -> Self {
2914        Self {
2915            fire_event_id: EventIdentifier::default(),
2916            padding: 0u16,
2917            firing_entity_id: EntityIdentifier::default(),
2918            padding2: 0u16,
2919            targeting_entity_id: EntityIdentifier::default(),
2920            padding3: 0u16,
2921            target_location_in_world_coordinates: WorldCoordinates::default(),
2922        }
2923    }
2924}
2925
2926/// Implemented according to IEEE 1278.1-2012 §6.2.51
2927#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2928#[deku(
2929    endian = "endian",
2930    ctx = "endian: deku::ctx::Endian",
2931    ctx_default = "deku::ctx::Endian::Big"
2932)]
2933pub struct LayerHeader {
2934    pub layer_number: u8,
2935    pub layer_specific_information: u8,
2936    pub length: u16,
2937}
2938
2939impl LayerHeader {
2940    #[must_use]
2941    pub const fn new(layer_number: u8, layer_specific_information: u8, length: u16) -> Self {
2942        Self {
2943            layer_number,
2944            layer_specific_information,
2945            length,
2946        }
2947    }
2948}
2949
2950/// Implemented according to IEEE 1278.1-2012 §6.2.52
2951#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
2952#[deku(
2953    endian = "endian",
2954    ctx = "endian: deku::ctx::Endian",
2955    ctx_default = "deku::ctx::Endian::Big"
2956)]
2957pub struct LinearSegmentParameter {
2958    pub segment_number: u8,
2959    pub segment_modification: u8,
2960    pub general_segment_appearance: ObjectStateAppearanceGeneral,
2961    pub specific_segment_appearance: u32,
2962    pub segment_location: WorldCoordinates,
2963    pub segment_orientation: EulerAngles,
2964    pub segment_length: f32,
2965    pub segment_width: f32,
2966    pub segment_height: f32,
2967    pub segment_depth: f32,
2968    padding: u32,
2969}
2970
2971impl LinearSegmentParameter {
2972    #[must_use]
2973    #[allow(clippy::too_many_arguments)]
2974    pub const fn new(
2975        segment_number: u8,
2976        segment_modification: u8,
2977        general_segment_appearance: ObjectStateAppearanceGeneral,
2978        specific_segment_appearance: u32,
2979        segment_location: WorldCoordinates,
2980        segment_orientation: EulerAngles,
2981        segment_length: f32,
2982        segment_width: f32,
2983        segment_height: f32,
2984        segment_depth: f32,
2985    ) -> Self {
2986        Self {
2987            segment_number,
2988            segment_modification,
2989            general_segment_appearance,
2990            specific_segment_appearance,
2991            segment_location,
2992            segment_orientation,
2993            segment_length,
2994            segment_width,
2995            segment_height,
2996            segment_depth,
2997            padding: 0_u32,
2998        }
2999    }
3000}
3001
3002/// Implemented according to IEEE 1278.1-2012 §6.2.53
3003#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3004#[deku(
3005    endian = "endian",
3006    ctx = "endian: deku::ctx::Endian",
3007    ctx_default = "deku::ctx::Endian::Big"
3008)]
3009pub struct LiveEntityIdentifier {
3010    pub live_simulation_address: LiveSimulationAddress,
3011    pub entity_number: u16,
3012}
3013
3014/// Implemented according to IEEE 1278.1-2012 §6.2.54
3015#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3016#[deku(
3017    endian = "endian",
3018    ctx = "endian: deku::ctx::Endian",
3019    ctx_default = "deku::ctx::Endian::Big"
3020)]
3021pub struct LiveSimulationAddress {
3022    pub live_site_number: u8,
3023    pub live_application_number: u8,
3024}
3025
3026/// Implemented according to IEEE 1278.1-2012 §6.2.55
3027#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3028#[deku(
3029    endian = "endian",
3030    ctx = "endian: deku::ctx::Endian",
3031    ctx_default = "deku::ctx::Endian::Big"
3032)]
3033pub struct MineEntityIdentifier {
3034    pub simulation_address: SimulationAddress,
3035    pub mine_entity_number: u16,
3036}
3037
3038/// Implemented according to IEEE 1278.1-2012 §6.2.56
3039#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3040#[deku(
3041    endian = "endian",
3042    ctx = "endian: deku::ctx::Endian",
3043    ctx_default = "deku::ctx::Endian::Big"
3044)]
3045pub struct MinefieldIdentifier {
3046    pub simulation_address: SimulationAddress,
3047    pub minefield_number: u16,
3048}
3049
3050impl MinefieldIdentifier {
3051    #[must_use]
3052    pub const fn new(simulation_address: SimulationAddress, minefield_number: u16) -> Self {
3053        Self {
3054            simulation_address,
3055            minefield_number,
3056        }
3057    }
3058}
3059
3060/// Implemented according to IEEE 1278.1-2012 §6.2.57
3061#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3062pub enum MinefieldSensorType {
3063    Other(u16),
3064    Optical(MinefieldSensorTypesOptical),
3065    Flir(MinefieldSensorTypesFLIR),
3066    Radar(MinefieldSensorTypesRADAR),
3067    Magnetic(MinefieldSensorTypesMagnetic),
3068    Laser(MinefieldSensorTypesLaser),
3069    Sonar(MinefieldSensorTypesSONAR),
3070    Physical(MinefieldSensorTypesPhysical),
3071    Multispectral(MinefieldSensorTypesMultispectral),
3072}
3073
3074/// Implemented according to IEEE 1278.1-2012 §6.2.58
3075#[derive(Clone, Debug, Default)]
3076pub struct ModulationParameters {
3077    pub record_specific_fields: Vec<u8>,
3078}
3079
3080impl ModulationParameters {
3081    #[must_use]
3082    pub const fn new() -> Self {
3083        Self {
3084            record_specific_fields: Vec::new(),
3085        }
3086    }
3087}
3088
3089/// Implemented according to IEEE 1278.1-2012 §6.2.59
3090#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3091#[deku(
3092    endian = "endian",
3093    ctx = "endian: deku::ctx::Endian",
3094    ctx_default = "deku::ctx::Endian::Big"
3095)]
3096pub struct ModulationType {
3097    pub spread_spectrum: u16,
3098    pub major_modulation: TransmitterMajorModulation,
3099    pub detail: u16,
3100    pub radio_system: TransmitterModulationTypeSystem,
3101}
3102
3103impl ModulationType {
3104    #[must_use]
3105    pub const fn new(
3106        spread_spectrum: u16,
3107        major_modulation: TransmitterMajorModulation,
3108        detail: u16,
3109        radio_system: TransmitterModulationTypeSystem,
3110    ) -> Self {
3111        Self {
3112            spread_spectrum,
3113            major_modulation,
3114            detail,
3115            radio_system,
3116        }
3117    }
3118}
3119
3120/// Implemented according to IEEE 1278.1-2012 §6.2.60
3121#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3122#[deku(
3123    endian = "endian",
3124    ctx = "endian: deku::ctx::Endian",
3125    ctx_default = "deku::ctx::Endian::Big"
3126)]
3127pub struct Munition {
3128    pub munition_type: EntityType,
3129    pub station_launcher: u32,
3130    pub quantity: u16,
3131    pub munition_status: u8,
3132    padding: u8,
3133}
3134
3135/// Implemented according to IEEE 1278.1-2012 §6.2.61
3136#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3137#[deku(
3138    endian = "endian",
3139    ctx = "endian: deku::ctx::Endian",
3140    ctx_default = "deku::ctx::Endian::Big"
3141)]
3142pub struct MunitionReload {
3143    pub munition_type: EntityType,
3144    pub station_launcher: u32,
3145    pub standard_quantity: u16,
3146    pub maximum_quantity: u16,
3147    pub standard_quantity_reload_time: u32,
3148    pub maximum_quantity_reload_time: u32,
3149}
3150
3151/// Implemented according to IEEE 1278.1-2012 §6.2.62
3152#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
3153#[deku(
3154    endian = "endian",
3155    ctx = "endian: deku::ctx::Endian",
3156    ctx_default = "deku::ctx::Endian::Big"
3157)]
3158pub struct NamedLocationIdentification {
3159    pub station_name: u16,
3160    pub station_number: u16,
3161}
3162
3163impl NamedLocationIdentification {
3164    #[must_use]
3165    pub const fn new(station_name: u16, station_number: u16) -> Self {
3166        Self {
3167            station_name,
3168            station_number,
3169        }
3170    }
3171}
3172
3173/// Implemented according to IEEE 1278.1-2012 §6.2.63
3174#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3175#[deku(
3176    endian = "endian",
3177    ctx = "endian: deku::ctx::Endian",
3178    ctx_default = "deku::ctx::Endian::Big"
3179)]
3180pub struct ObjectIdentifier {
3181    pub simulation_address: SimulationAddress,
3182    pub object_number: u16,
3183}
3184
3185impl ObjectIdentifier {
3186    #[must_use]
3187    pub fn new() -> Self {
3188        Self::default()
3189    }
3190}
3191
3192/// Implemented according to IEEE 1278.1-2012 §6.2.64
3193#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3194#[deku(
3195    endian = "endian",
3196    ctx = "endian: deku::ctx::Endian",
3197    ctx_default = "deku::ctx::Endian::Big"
3198)]
3199pub struct ObjectType {
3200    pub domain: u8,
3201    pub object_kind: u8,
3202    pub category: u8,
3203    pub subcategory: u8,
3204}
3205
3206impl ObjectType {
3207    #[must_use]
3208    pub const fn new(domain: u8, object_kind: u8, category: u8, subcategory: u8) -> Self {
3209        Self {
3210            domain,
3211            object_kind,
3212            category,
3213            subcategory,
3214        }
3215    }
3216}
3217
3218/// Implemented according to IEEE 1278.1-2012 §6.2.65
3219#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3220#[deku(
3221    endian = "endian",
3222    ctx = "endian: deku::ctx::Endian",
3223    ctx_default = "deku::ctx::Endian::Big"
3224)]
3225pub struct OwnershipStatus {
3226    pub entity_id: EntityIdentifier,
3227    pub ownership_status: EntityOwnershipStatus,
3228    padding: u8,
3229}
3230
3231/// Implemented according to IEEE 1278.1-2012 §6.2.66
3232#[derive(Copy, Clone, Debug, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
3233#[deku(
3234    endian = "endian",
3235    ctx = "endian: deku::ctx::Endian",
3236    ctx_default = "deku::ctx::Endian::Big"
3237)]
3238pub struct PduHeader {
3239    /// The version of the protocol
3240    pub protocol_version: ProtocolVersion,
3241    /// Exercise ID
3242    pub exercise_id: ExerciseIdentifier,
3243    /// Type of PDU, set from the PDU when it's encoded. Read it with
3244    /// [`pdu_type`](Self::pdu_type).
3245    pub(crate) pdu_type: PduType,
3246    /// Protocol family, set from the PDU when it's encoded. Read it with
3247    /// [`protocol_family`](Self::protocol_family).
3248    pub(crate) protocol_family: ProtocolFamily,
3249    /// When the data in the PDU was valid. New headers use [`Timestamp::now`].
3250    pub timestamp: Timestamp,
3251    /// Length of the PDU in octets, header included, set when it's encoded. Read it
3252    /// with [`length`](Self::length).
3253    pub(crate) length: u16,
3254    /// PDU status record
3255    pub pdu_status: PduStatus,
3256    /// Padding
3257    padding: u8,
3258}
3259
3260impl PduHeader {
3261    /// A header for the given exercise, timestamped now. The PDU type, protocol
3262    /// family and length are set when the PDU is encoded.
3263    #[must_use]
3264    pub fn new(exercise_id: ExerciseIdentifier) -> Self {
3265        Self {
3266            exercise_id,
3267            ..Self::default()
3268        }
3269    }
3270
3271    /// The PDU type, set from the PDU when it is encoded
3272    #[must_use]
3273    pub const fn pdu_type(&self) -> PduType {
3274        self.pdu_type
3275    }
3276
3277    /// The protocol family, set from the PDU when it is encoded
3278    #[must_use]
3279    pub const fn protocol_family(&self) -> ProtocolFamily {
3280        self.protocol_family
3281    }
3282
3283    /// The PDU's length in octets, header included, set when it is encoded
3284    #[must_use]
3285    pub const fn length(&self) -> u16 {
3286        self.length
3287    }
3288
3289    /// Encodes the header alone and appends it to `buf`
3290    pub fn serialize(&self, buf: &mut Vec<u8>) {
3291        let _ = crate::wire::write(self, buf);
3292    }
3293
3294    /// Decodes a header from the front of `buf`, advancing `buf` past it. Pass it to
3295    /// [`Pdu::deserialize_without_header`](crate::Pdu::deserialize_without_header)
3296    /// to decode the body of the PDU
3297    ///
3298    /// # Errors
3299    ///
3300    /// Will return a `DISError` if `buf` does not start with a valid header.
3301    pub fn deserialize(buf: &mut &[u8]) -> Result<Self, crate::DISError> {
3302        crate::wire::read(buf).map_err(crate::DISError::from_wire)
3303    }
3304
3305    /// Looks at the PDU type from a raw byte buffer.
3306    /// Only deserializes the 12-byte header.
3307    #[must_use]
3308    pub fn get_pdu_type(bytes: &[u8]) -> Option<PduType> {
3309        let mut buf = bytes.get(..crate::constants::PDU_HEADER_SIZE)?;
3310        Self::deserialize(&mut buf)
3311            .ok()
3312            .map(|header| header.pdu_type)
3313    }
3314}
3315
3316impl crate::pdu::DerivedFields for PduHeader {
3317    #[cfg(test)]
3318    fn length(&self) -> u16 {
3319        self.length
3320    }
3321
3322    fn set_pdu_type(&mut self, value: PduType) {
3323        self.pdu_type = value;
3324    }
3325
3326    fn set_protocol_family(&mut self, value: ProtocolFamily) {
3327        self.protocol_family = value;
3328    }
3329
3330    fn set_length(&mut self, value: u16) {
3331        self.length = value;
3332    }
3333}
3334
3335impl Default for PduHeader {
3336    fn default() -> Self {
3337        Self {
3338            protocol_version: ProtocolVersion::IEEE1278_1_2012,
3339            exercise_id: ExerciseIdentifier::default(),
3340            pdu_type: PduType::default(),
3341            protocol_family: ProtocolFamily::default(),
3342            timestamp: Timestamp::now(),
3343            length: 0,
3344            pdu_status: PduStatus::default(),
3345            padding: 0,
3346        }
3347    }
3348}
3349
3350/// Implemented according to IEEE 1278.1-2012 §6.2.67
3351#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
3352#[deku(
3353    endian = "endian",
3354    ctx = "endian: deku::ctx::Endian",
3355    ctx_default = "deku::ctx::Endian::Big"
3356)]
3357pub struct PduStatus {
3358    raw: u8,
3359}
3360
3361impl PduStatus {
3362    const TEI: u8 = 0b0000_0001;
3363    const LVC: u8 = 0b0000_0110;
3364    const CEI: u8 = 0b0000_1000;
3365    const BIT_4: u8 = 0b0001_0000;
3366    const BIT_5: u8 = 0b0010_0000;
3367    const BITS_4_5: u8 = Self::BIT_4 | Self::BIT_5;
3368
3369    /// Creates a PDU Status record with every field set to zero
3370    #[must_use]
3371    pub const fn new() -> Self {
3372        Self { raw: 0 }
3373    }
3374
3375    /// PDU Status record from its wire octet
3376    #[must_use]
3377    pub const fn from_raw(raw: u8) -> Self {
3378        Self { raw }
3379    }
3380
3381    /// The wire octet itself
3382    #[must_use]
3383    pub const fn to_raw(self) -> u8 {
3384        self.raw
3385    }
3386
3387    /// Replaces the bits in `mask` with `value`
3388    const fn set_bits(&mut self, mask: u8, value: u8) {
3389        self.raw = (self.raw & !mask) | (value & mask);
3390    }
3391
3392    /// Transferred Entity Indicator (bit 0) \[UID 301\]: whether a simulation other than
3393    /// the one in the PDU's primary Entity ID owns the entity
3394    #[must_use]
3395    pub const fn tei(self) -> TransferredEntityIndicator {
3396        if self.raw & Self::TEI == 0 {
3397            TransferredEntityIndicator::NoDifference
3398        } else {
3399            TransferredEntityIndicator::Difference
3400        }
3401    }
3402
3403    /// Sets bit 0. See [`tei`](Self::tei).
3404    pub const fn set_tei(&mut self, tei: TransferredEntityIndicator) {
3405        let value = match tei {
3406            TransferredEntityIndicator::NoDifference => 0,
3407            TransferredEntityIndicator::Difference => Self::TEI,
3408        };
3409        self.set_bits(Self::TEI, value);
3410    }
3411
3412    /// LVC Indicator (bits 1 and 2) \[UID 302\]: whether the PDU's data relates to a
3413    /// live, virtual or constructive entity.
3414    #[must_use]
3415    pub const fn lvc(self) -> LVCIndicator {
3416        match (self.raw & Self::LVC) >> 1 {
3417            0 => LVCIndicator::NoStatement,
3418            1 => LVCIndicator::Live,
3419            2 => LVCIndicator::Virtual,
3420            _ => LVCIndicator::Constructive,
3421        }
3422    }
3423
3424    /// Sets bits 1 and 2. See [`lvc`](Self::lvc).
3425    pub const fn set_lvc(&mut self, lvc: LVCIndicator) {
3426        let value = match lvc {
3427            LVCIndicator::NoStatement => 0,
3428            LVCIndicator::Live => 1,
3429            LVCIndicator::Virtual => 2,
3430            LVCIndicator::Constructive => 3,
3431        };
3432        self.set_bits(Self::LVC, value << 1);
3433    }
3434
3435    /// Coupled Extension Indicator (bit 3) \[UID 303\]: whether the PDU is coupled with
3436    /// an Attribute PDU.
3437    #[must_use]
3438    pub const fn cei(self) -> CoupledExtensionIndicator {
3439        if self.raw & Self::CEI == 0 {
3440            CoupledExtensionIndicator::NotCoupled
3441        } else {
3442            CoupledExtensionIndicator::Coupled
3443        }
3444    }
3445
3446    /// Sets bit 3. See [`cei`](Self::cei).
3447    pub const fn set_cei(&mut self, cei: CoupledExtensionIndicator) {
3448        let value = match cei {
3449            CoupledExtensionIndicator::NotCoupled => 0,
3450            CoupledExtensionIndicator::Coupled => Self::CEI,
3451        };
3452        self.set_bits(Self::CEI, value);
3453    }
3454
3455    /// Fire Type Indicator (bit 4) \[UID 304\], for the Fire PDU: whether a munition or
3456    /// an expendable was fired.
3457    #[must_use]
3458    pub const fn fti(self) -> FireTypeIndicator {
3459        if self.raw & Self::BIT_4 == 0 {
3460            FireTypeIndicator::Munition
3461        } else {
3462            FireTypeIndicator::Expendable
3463        }
3464    }
3465
3466    /// Sets bit 4, leaving bit 5 as it is. See [`fti`](Self::fti).
3467    pub const fn set_fti(&mut self, fti: FireTypeIndicator) {
3468        let value = match fti {
3469            FireTypeIndicator::Munition => 0,
3470            FireTypeIndicator::Expendable => Self::BIT_4,
3471        };
3472        self.set_bits(Self::BIT_4, value);
3473    }
3474
3475    /// Detonation Type Indicator (bits 4 and 5) \[UID 305\], for the Detonation PDU:
3476    /// what detonated. `None` if the bits hold 3, which isn't defined.
3477    #[must_use]
3478    pub const fn dti(self) -> Option<DetonationTypeIndicator> {
3479        match (self.raw & Self::BITS_4_5) >> 4 {
3480            0 => Some(DetonationTypeIndicator::Munition),
3481            1 => Some(DetonationTypeIndicator::Expendable),
3482            2 => Some(DetonationTypeIndicator::NonMunitionExplosion),
3483            _ => None,
3484        }
3485    }
3486
3487    /// Sets bits 4 and 5. See [`dti`](Self::dti).
3488    pub const fn set_dti(&mut self, dti: DetonationTypeIndicator) {
3489        let value = match dti {
3490            DetonationTypeIndicator::Munition => 0,
3491            DetonationTypeIndicator::Expendable => 1,
3492            DetonationTypeIndicator::NonMunitionExplosion => 2,
3493        };
3494        self.set_bits(Self::BITS_4_5, value << 4);
3495    }
3496
3497    /// Radio Attached Indicator (bits 4 and 5) \[UID 306\], for the Transmitter, Signal
3498    /// and Receiver PDUs: whether the radio is attached to an entity or object. `None` if
3499    /// the bits hold 3, which isn't defined.
3500    #[must_use]
3501    pub const fn rai(self) -> Option<RadioAttachedIndicator> {
3502        match (self.raw & Self::BITS_4_5) >> 4 {
3503            0 => Some(RadioAttachedIndicator::NoStatement),
3504            1 => Some(RadioAttachedIndicator::Unattached),
3505            2 => Some(RadioAttachedIndicator::Attached),
3506            _ => None,
3507        }
3508    }
3509
3510    /// Sets bits 4 and 5. See [`rai`](Self::rai).
3511    pub const fn set_rai(&mut self, rai: RadioAttachedIndicator) {
3512        let value = match rai {
3513            RadioAttachedIndicator::NoStatement => 0,
3514            RadioAttachedIndicator::Unattached => 1,
3515            RadioAttachedIndicator::Attached => 2,
3516        };
3517        self.set_bits(Self::BITS_4_5, value << 4);
3518    }
3519
3520    /// Intercom Attached Indicator (bits 4 and 5) \[UID 307\], for the Intercom Signal
3521    /// and Intercom Control PDUs: whether the intercom is attached to an entity or object.
3522    /// `None` if the bits hold 3, which isn't defined.
3523    #[must_use]
3524    pub const fn iai(self) -> Option<IntercomAttachedIndicator> {
3525        match (self.raw & Self::BITS_4_5) >> 4 {
3526            0 => Some(IntercomAttachedIndicator::NoStatement),
3527            1 => Some(IntercomAttachedIndicator::Unattached),
3528            2 => Some(IntercomAttachedIndicator::Attached),
3529            _ => None,
3530        }
3531    }
3532
3533    /// Sets bits 4 and 5. See [`iai`](Self::iai).
3534    pub const fn set_iai(&mut self, iai: IntercomAttachedIndicator) {
3535        let value = match iai {
3536            IntercomAttachedIndicator::NoStatement => 0,
3537            IntercomAttachedIndicator::Unattached => 1,
3538            IntercomAttachedIndicator::Attached => 2,
3539        };
3540        self.set_bits(Self::BITS_4_5, value << 4);
3541    }
3542
3543    /// IFF Simulation Mode (bit 4) \[UID 308\], for the IFF PDU. It matches the
3544    /// Simulation Mode in the PDU's [`ChangeOptions`] record.
3545    #[must_use]
3546    pub const fn ism(self) -> PduStatusIFFSimulationMode {
3547        if self.raw & Self::BIT_4 == 0 {
3548            PduStatusIFFSimulationMode::Regeneration
3549        } else {
3550            PduStatusIFFSimulationMode::Interactive
3551        }
3552    }
3553
3554    /// Sets bit 4, leaving bit 5 as it is. See [`ism`](Self::ism).
3555    pub const fn set_ism(&mut self, ism: PduStatusIFFSimulationMode) {
3556        let value = match ism {
3557            PduStatusIFFSimulationMode::Regeneration => 0,
3558            PduStatusIFFSimulationMode::Interactive => Self::BIT_4,
3559        };
3560        self.set_bits(Self::BIT_4, value);
3561    }
3562
3563    /// Active Interrogation Indicator (bit 5) \[UID 389\], for the IFF PDU: whether the
3564    /// PDU is an active interrogation by an interrogator in Regeneration mode.
3565    #[must_use]
3566    pub const fn aii(self) -> ActiveInterrogationIndicator {
3567        if self.raw & Self::BIT_5 == 0 {
3568            ActiveInterrogationIndicator::NotActive
3569        } else {
3570            ActiveInterrogationIndicator::Active
3571        }
3572    }
3573
3574    /// Sets bit 5, leaving bit 4 as it is. See [`aii`](Self::aii).
3575    pub const fn set_aii(&mut self, aii: ActiveInterrogationIndicator) {
3576        let value = match aii {
3577            ActiveInterrogationIndicator::NotActive => 0,
3578            ActiveInterrogationIndicator::Active => Self::BIT_5,
3579        };
3580        self.set_bits(Self::BIT_5, value);
3581    }
3582}
3583
3584/// Implemented according to IEEE 1278.1-2012 §6.2.68
3585#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3586#[deku(
3587    endian = "endian",
3588    ctx = "endian: deku::ctx::Endian",
3589    ctx_default = "deku::ctx::Endian::Big"
3590)]
3591pub struct PropulsionSystemData {
3592    pub power_setting: f32,
3593    pub engine_rpm: f32,
3594}
3595
3596impl PropulsionSystemData {
3597    #[must_use]
3598    pub const fn new(power_setting: f32, engine_rpm: f32) -> Self {
3599        Self {
3600            power_setting,
3601            engine_rpm,
3602        }
3603    }
3604}
3605
3606/// Implemented according to IEEE 1278.1-2012 §6.2.69
3607#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3608#[deku(
3609    endian = "endian",
3610    ctx = "endian: deku::ctx::Endian",
3611    ctx_default = "deku::ctx::Endian::Big"
3612)]
3613pub struct ProtocolMode {
3614    raw: u16,
3615}
3616
3617impl ProtocolMode {
3618    const SHIFT: u16 = 14;
3619    const MODE: u16 = 0b11 << Self::SHIFT;
3620
3621    /// A Protocol Mode record with the given mode and the padding bits clear.
3622    #[must_use]
3623    pub const fn new(mode: MinefieldStateProtocolMode) -> Self {
3624        let mut record = Self { raw: 0 };
3625        record.set_mode(mode);
3626        record
3627    }
3628
3629    /// The protocol mode, or `None` if bits 14 and 15 hold 2 or 3, which UID 336
3630    /// does not define.
3631    #[must_use]
3632    pub const fn mode(self) -> Option<MinefieldStateProtocolMode> {
3633        match (self.raw & Self::MODE) >> Self::SHIFT {
3634            0 => Some(MinefieldStateProtocolMode::HeartbeatMode),
3635            1 => Some(MinefieldStateProtocolMode::QRPMode),
3636            _ => None,
3637        }
3638    }
3639
3640    /// Sets bits 14 and 15, leaving the padding bits as they are.
3641    pub const fn set_mode(&mut self, mode: MinefieldStateProtocolMode) {
3642        let value: u16 = match mode {
3643            MinefieldStateProtocolMode::HeartbeatMode => 0,
3644            MinefieldStateProtocolMode::QRPMode => 1,
3645        };
3646        self.raw = (self.raw & !Self::MODE) | (value << Self::SHIFT);
3647    }
3648
3649    /// A Protocol Mode record from its 16-bit wire value. Every bit is kept.
3650    #[must_use]
3651    pub const fn from_raw(raw: u16) -> Self {
3652        Self { raw }
3653    }
3654
3655    /// The record's 16-bit wire value
3656    #[must_use]
3657    pub const fn to_raw(self) -> u16 {
3658        self.raw
3659    }
3660}
3661
3662impl From<MinefieldStateProtocolMode> for ProtocolMode {
3663    fn from(mode: MinefieldStateProtocolMode) -> Self {
3664        Self::new(mode)
3665    }
3666}
3667
3668/// Implemented according to IEEE 1278.1-2012 §6.2.70
3669#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3670#[deku(
3671    endian = "endian",
3672    ctx = "endian: deku::ctx::Endian",
3673    ctx_default = "deku::ctx::Endian::Big"
3674)]
3675pub struct RadioIdentifier {
3676    pub radio_reference_id: SimulationIdentifier,
3677    pub radio_number: u16,
3678}
3679
3680/// Implemented according to IEEE 1278.1-2012 §6.2.71
3681#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3682#[deku(
3683    endian = "endian",
3684    ctx = "endian: deku::ctx::Endian",
3685    ctx_default = "deku::ctx::Endian::Big"
3686)]
3687pub struct RadioType {
3688    pub entity_kind: EntityKind,
3689    pub domain: u8,
3690    pub country: Country,
3691    pub category: u8,
3692    pub subcategory: u8,
3693    pub specific: u8,
3694    pub extra: u8,
3695}
3696
3697/// Implemented according to IEEE 1278.1-2012 §6.2.72
3698#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3699#[deku(
3700    endian = "endian",
3701    ctx = "endian: deku::ctx::Endian",
3702    ctx_default = "deku::ctx::Endian::Big"
3703)]
3704pub struct RecordQuerySpecification {
3705    #[deku(assert = "crate::wire::fits_in_pdu(*number_of_records)")]
3706    pub number_of_records: u32,
3707    #[deku(count = "number_of_records")]
3708    pub record_ids: Vec<VariableRecordTypes>,
3709}
3710
3711/// One record set in a [`RecordSpecification`]: its record ID,
3712/// serial number, and `record_count` values of `record_length` octets each.
3713#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3714#[deku(
3715    endian = "endian",
3716    ctx = "endian: deku::ctx::Endian",
3717    ctx_default = "deku::ctx::Endian::Big"
3718)]
3719pub struct RecordSpecificationElement {
3720    pub record_id: u32,
3721    pub record_set_serial_number: u32,
3722    pub record_length: u16,
3723    #[deku(assert = "crate::wire::fits_in_pdu(values_len(*record_length, *record_count))")]
3724    pub record_count: u16,
3725    /// Exactly `record_length * record_count` octets; encoding fails otherwise.
3726    #[deku(
3727        count = "values_len(*record_length, *record_count)",
3728        assert = "record_values.len() == values_len(*record_length, *record_count)"
3729    )]
3730    pub record_values: Vec<u8>,
3731}
3732
3733impl RecordSpecificationElement {
3734    #[must_use]
3735    pub const fn new(
3736        record_id: u32,
3737        record_set_serial_number: u32,
3738        record_length: u16,
3739        record_count: u16,
3740        record_values: Vec<u8>,
3741    ) -> Self {
3742        Self {
3743            record_id,
3744            record_set_serial_number,
3745            record_length,
3746            record_count,
3747            record_values,
3748        }
3749    }
3750}
3751
3752/// The number of octets in `record_values`: `record_length * record_count`.
3753/// Cannot overflow: two 16-bit values multiply to at most 32 bits.
3754fn values_len(record_length: u16, record_count: u16) -> usize {
3755    usize::from(record_length).saturating_mul(usize::from(record_count))
3756}
3757
3758/// Implemented according to IEEE 1278.1-2012 §6.2.73
3759#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3760#[deku(
3761    endian = "endian",
3762    ctx = "endian: deku::ctx::Endian",
3763    ctx_default = "deku::ctx::Endian::Big"
3764)]
3765pub struct RecordSpecification {
3766    #[deku(
3767        update = "crate::wire::update_each(&mut self.record_sets)?",
3768        assert = "crate::wire::fits_in_pdu(*number_of_record_sets)"
3769    )]
3770    pub number_of_record_sets: u32,
3771    #[deku(count = "number_of_record_sets")]
3772    pub record_sets: Vec<RecordSpecificationElement>,
3773}
3774
3775impl RecordSpecification {
3776    #[must_use]
3777    pub const fn new(
3778        number_of_record_sets: u32,
3779        record_sets: Vec<RecordSpecificationElement>,
3780    ) -> Self {
3781        Self {
3782            number_of_record_sets,
3783            record_sets,
3784        }
3785    }
3786}
3787
3788/// Implemented according to IEEE 1278.1-2012 §6.2.74
3789#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3790#[deku(
3791    endian = "endian",
3792    ctx = "endian: deku::ctx::Endian",
3793    ctx_default = "deku::ctx::Endian::Big"
3794)]
3795pub struct Relationship {
3796    pub nature: u16,
3797    pub position: u16,
3798}
3799
3800impl Relationship {
3801    #[must_use]
3802    pub const fn new(nature: u16, position: u16) -> Self {
3803        Self { nature, position }
3804    }
3805}
3806
3807/// Implemented according to IEEE 1278.1-2012 §6.2.75
3808#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
3809#[deku(
3810    endian = "endian",
3811    ctx = "endian: deku::ctx::Endian",
3812    ctx_default = "deku::ctx::Endian::Big"
3813)]
3814pub struct RequestIdentifier(u32);
3815
3816impl RequestIdentifier {
3817    /// The request ID with the given value.
3818    #[must_use]
3819    pub const fn new(id: u32) -> Self {
3820        Self(id)
3821    }
3822
3823    /// The request ID's value.
3824    #[must_use]
3825    pub const fn get(self) -> u32 {
3826        self.0
3827    }
3828
3829    /// The ID for the next request. Wraps to 0 after `u32::MAX`.
3830    #[must_use]
3831    pub const fn next(self) -> Self {
3832        Self(self.0.wrapping_add(1))
3833    }
3834}
3835
3836impl From<u32> for RequestIdentifier {
3837    fn from(id: u32) -> Self {
3838        Self(id)
3839    }
3840}
3841
3842impl From<RequestIdentifier> for u32 {
3843    fn from(id: RequestIdentifier) -> Self {
3844        id.0
3845    }
3846}
3847
3848/// Implemented according to IEEE 1278.1-2012 §6.2.76
3849#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3850#[deku(
3851    endian = "endian",
3852    ctx = "endian: deku::ctx::Endian",
3853    ctx_default = "deku::ctx::Endian::Big"
3854)]
3855pub struct SecondaryOperationalData {
3856    pub operational_data1: u8,
3857    pub operational_data2: u8,
3858    pub number_of_iff_fundamental_parameter_records: u16,
3859}
3860
3861impl SecondaryOperationalData {
3862    #[must_use]
3863    pub const fn new(
3864        operational_data1: u8,
3865        operational_data2: u8,
3866        number_of_iff_fundamental_parameter_records: u16,
3867    ) -> Self {
3868        Self {
3869            operational_data1,
3870            operational_data2,
3871            number_of_iff_fundamental_parameter_records,
3872        }
3873    }
3874}
3875
3876/// Implemented according to IEEE 1278.1-2012 §6.2.77
3877#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3878#[deku(
3879    endian = "endian",
3880    ctx = "endian: deku::ctx::Endian",
3881    ctx_default = "deku::ctx::Endian::Big"
3882)]
3883pub struct Sensor {
3884    pub sensor_type_source: SensorTypeSource,
3885    pub sensor_on_off_status: SensorOnOffStatus,
3886    pub sensor_type: u16,
3887    pub station: u32,
3888    pub quantity: u16,
3889    padding: u16,
3890}
3891
3892/// Implemented according to IEEE 1278.1-2012 §6.2.78
3893#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
3894#[deku(
3895    endian = "endian",
3896    ctx = "endian: deku::ctx::Endian",
3897    ctx_default = "deku::ctx::Endian::Big"
3898)]
3899pub struct Service(pub ServiceRequestServiceTypeRequested);
3900
3901/// Implemented according to IEEE 1278.1-2012 §6.2.79
3902#[derive(Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
3903#[deku(
3904    endian = "endian",
3905    ctx = "endian: deku::ctx::Endian",
3906    ctx_default = "deku::ctx::Endian::Big"
3907)]
3908pub struct SilentEntitySystem {
3909    pub number_of_entities: u16,
3910    #[deku(
3911        update = "self.entity_appearances.len()",
3912        assert = "crate::wire::fits_in_pdu(*number_of_appearance_records)"
3913    )]
3914    pub number_of_appearance_records: u16,
3915    pub entity_type: EntityType,
3916    #[deku(count = "number_of_appearance_records")]
3917    pub entity_appearances: Vec<EntityAppearance>,
3918}
3919
3920/// Implemented according to IEEE 1278.1-2012 §6.2.80
3921#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
3922#[deku(
3923    endian = "endian",
3924    ctx = "endian: deku::ctx::Endian",
3925    ctx_default = "deku::ctx::Endian::Big"
3926)]
3927pub struct SimulationAddress {
3928    /// Identification number representing the site, which may be a facility,
3929    /// installation, organizational unit, or a geographical location. Valid
3930    /// site ID values range from 1 to 65,534
3931    pub site_id: u16,
3932    /// Identification number representing the software program that is used to
3933    /// generate and process distributed simulation data. Valid application ID
3934    /// values range from 1 to 65,534
3935    pub application_id: u16,
3936}
3937
3938impl Default for SimulationAddress {
3939    fn default() -> Self {
3940        Self {
3941            site_id: 1,
3942            application_id: 1,
3943        }
3944    }
3945}
3946
3947impl SimulationAddress {
3948    #[must_use]
3949    pub const fn new(site_id: u16, application_id: u16) -> Self {
3950        Self {
3951            site_id,
3952            application_id,
3953        }
3954    }
3955}
3956
3957/// Implemented according to IEEE 1278.1-2012 §6.2.81
3958#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
3959#[deku(
3960    endian = "endian",
3961    ctx = "endian: deku::ctx::Endian",
3962    ctx_default = "deku::ctx::Endian::Big"
3963)]
3964pub struct SimulationIdentifier {
3965    pub simulation_address: SimulationAddress,
3966    pub reference_number: u16,
3967}
3968
3969impl SimulationIdentifier {
3970    #[must_use]
3971    pub fn new() -> Self {
3972        Self {
3973            simulation_address: SimulationAddress::default(),
3974            reference_number: 0u16,
3975        }
3976    }
3977}
3978
3979/// Originating or receiving ID of a SIMAN or SIMAN-R PDU
3980#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
3981pub enum SimulationManagementId {
3982    Simulation(SimulationAddress),
3983    Entity(EntityIdentifier),
3984}
3985
3986impl SimulationManagementId {
3987    /// The simulation address, whichever kind of identifier this is.
3988    #[must_use]
3989    pub const fn simulation_address(self) -> SimulationAddress {
3990        match self {
3991            Self::Simulation(address) => address,
3992            Self::Entity(id) => id.simulation_address,
3993        }
3994    }
3995}
3996
3997impl DekuReader<'_, Endian> for SimulationManagementId {
3998    fn from_reader_with_ctx<R: Read + Seek>(
3999        reader: &mut Reader<R>,
4000        endian: Endian,
4001    ) -> Result<Self, DekuError> {
4002        let id = EntityIdentifier::from_reader_with_ctx(reader, endian)?;
4003        Ok(if id.entity_id == 0 {
4004            Self::Simulation(id.simulation_address)
4005        } else {
4006            Self::Entity(id)
4007        })
4008    }
4009}
4010
4011impl DekuWriter<Endian> for SimulationManagementId {
4012    fn to_writer<W: Write + Seek>(
4013        &self,
4014        writer: &mut Writer<W>,
4015        endian: Endian,
4016    ) -> Result<(), DekuError> {
4017        let id = match *self {
4018            Self::Simulation(simulation_address) => EntityIdentifier {
4019                simulation_address,
4020                entity_id: 0,
4021            },
4022            Self::Entity(id) => id,
4023        };
4024        id.to_writer(writer, endian)
4025    }
4026}
4027
4028/// Implemented according to IEEE 1278.1-2012 §6.2.82
4029#[derive(Copy, Clone, Debug, deku::DekuRead, deku::DekuWrite)]
4030#[deku(
4031    endian = "endian",
4032    ctx = "endian: deku::ctx::Endian",
4033    ctx_default = "deku::ctx::Endian::Big"
4034)]
4035pub struct SimulationManagementPduHeader {
4036    pub pdu_header: PduHeader,
4037    pub originating_id: SimulationManagementId,
4038    pub receiving_id: SimulationManagementId,
4039}
4040
4041/// Standard Variable record. `record_length` is the whole record in octets,
4042/// a multiple of 8.
4043#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4044#[deku(
4045    endian = "endian",
4046    ctx = "endian: deku::ctx::Endian",
4047    ctx_default = "deku::ctx::Endian::Big"
4048)]
4049pub struct StandardVariableRecord {
4050    pub record_type: u32,
4051    #[deku(
4052        update = "crate::wire::padded_record_length(self.record_specific_fields.len())?",
4053        assert = "crate::wire::valid_record_length(*record_length)"
4054    )]
4055    pub record_length: u16,
4056    /// Everything after the record length. When decoded, this includes the
4057    /// padding to the 64-bit boundary; when encoded, padding is added to
4058    /// reach it.
4059    #[deku(
4060        count = "crate::wire::record_fields_len(*record_length)",
4061        writer = "crate::wire::write_padded_fields(deku::writer, record_specific_fields)"
4062    )]
4063    pub record_specific_fields: Vec<u8>,
4064}
4065
4066impl StandardVariableRecord {
4067    #[must_use]
4068    pub const fn new(
4069        record_type: u32,
4070        record_length: u16,
4071        record_specific_fields: Vec<u8>,
4072    ) -> Self {
4073        Self {
4074            record_type,
4075            record_length,
4076            record_specific_fields,
4077        }
4078    }
4079
4080    /// Encodes a typed record as a Standard Variable record
4081    ///
4082    /// `record` must begin with its own 32-bit record type and 16-bit record
4083    /// length, as [`DirectedEnergyDamage`], [`DEPrecisionAimpoint`] and
4084    /// [`IOEffect`] do, and its record length must be its encoded size.
4085    ///
4086    /// # Errors
4087    ///
4088    /// Will return `DISError` if `record` can't be encoded, or its record
4089    /// length doesn't match its encoded size.
4090    pub fn from_record<T: DekuWriter<()>>(record: &T) -> crate::DISResult<Self> {
4091        let mut octets = Vec::new();
4092        crate::wire::write(record, &mut octets).map_err(crate::DISError::from_wire)?;
4093        let mut rest = octets.as_slice();
4094        let standard: Self = crate::wire::read(&mut rest).map_err(crate::DISError::from_wire)?;
4095        if !rest.is_empty() {
4096            return Err(crate::DISError::from_wire(DekuError::Assertion(
4097                "the record's length doesn't match its encoded size".into(),
4098            )));
4099        }
4100        Ok(standard)
4101    }
4102
4103    /// Decodes this record as a typed record, such as [`DirectedEnergyDamage`]
4104    ///
4105    /// Check `record_type` first to pick the type.
4106    ///
4107    /// # Errors
4108    ///
4109    /// Will return `DISError` if the record's octets aren't a valid `T`.
4110    pub fn to_record<T: for<'a> DekuReader<'a, ()>>(&self) -> crate::DISResult<T> {
4111        let mut octets = Vec::new();
4112        crate::wire::write(self, &mut octets).map_err(crate::DISError::from_wire)?;
4113        crate::wire::read(&mut octets.as_slice()).map_err(crate::DISError::from_wire)
4114    }
4115}
4116
4117/// Implemented according to IEEE 1278.1-2012 §6.2.83
4118#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4119#[deku(
4120    endian = "endian",
4121    ctx = "endian: deku::ctx::Endian",
4122    ctx_default = "deku::ctx::Endian::Big"
4123)]
4124pub struct StandardVariableSpecification {
4125    #[deku(
4126        update = "crate::wire::update_each(&mut self.standard_variable_records)?",
4127        assert = "crate::wire::fits_in_pdu(*number_of_standard_variable_records)"
4128    )]
4129    pub number_of_standard_variable_records: u16,
4130    #[deku(count = "number_of_standard_variable_records")]
4131    pub standard_variable_records: Vec<StandardVariableRecord>,
4132}
4133
4134impl StandardVariableSpecification {
4135    #[must_use]
4136    pub const fn new(
4137        number_of_standard_variable_records: u16,
4138        standard_variable_records: Vec<StandardVariableRecord>,
4139    ) -> Self {
4140        Self {
4141            number_of_standard_variable_records,
4142            standard_variable_records,
4143        }
4144    }
4145}
4146
4147/// Implemented according to IEEE 1278.1-2012 §6.2.84
4148#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4149#[deku(
4150    endian = "endian",
4151    ctx = "endian: deku::ctx::Endian",
4152    ctx_default = "deku::ctx::Endian::Big"
4153)]
4154pub struct StorageFuel {
4155    pub fuel_quantity: u32,
4156    pub fuel_measurement_units: FuelMeasurementUnits,
4157    pub fuel_type: SupplyFuelType,
4158    pub fuel_location: FuelLocation,
4159    padding: u8,
4160}
4161
4162/// Implemented according to IEEE 1278.1-2012 §6.2.85
4163#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4164#[deku(
4165    endian = "endian",
4166    ctx = "endian: deku::ctx::Endian",
4167    ctx_default = "deku::ctx::Endian::Big"
4168)]
4169pub struct StorageFuelReload {
4170    pub standard_quantity: u32,
4171    pub maximum_quantity: u32,
4172    pub standard_quantity_reload_time: u32,
4173    pub maximum_quantity_reload_time: u32,
4174    pub fuel_measurement_units: FuelMeasurementUnits,
4175    pub fuel_type: SupplyFuelType,
4176    pub fuel_location: FuelLocation,
4177    padding: u8,
4178}
4179
4180/// Implemented according to IEEE 1278.1-2012 §6.2.86
4181#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4182#[deku(
4183    endian = "endian",
4184    ctx = "endian: deku::ctx::Endian",
4185    ctx_default = "deku::ctx::Endian::Big"
4186)]
4187pub struct SupplyQuantity {
4188    pub supply_type: EntityType,
4189    pub quantity: f32,
4190}
4191
4192impl SupplyQuantity {
4193    #[must_use]
4194    pub const fn new(supply_type: EntityType, quantity: f32) -> Self {
4195        Self {
4196            supply_type,
4197            quantity,
4198        }
4199    }
4200}
4201
4202/// Implemented according to IEEE 1278.1-2012 §6.2.87
4203#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4204#[deku(
4205    endian = "endian",
4206    ctx = "endian: deku::ctx::Endian",
4207    ctx_default = "deku::ctx::Endian::Big"
4208)]
4209pub struct SystemIdentifier {
4210    pub system_type: IFFSystemType,
4211    pub system_name: IFFSystemName,
4212    pub system_mode: IFFSystemMode,
4213    pub change_options: ChangeOptions,
4214}
4215
4216impl SystemIdentifier {
4217    #[must_use]
4218    pub const fn new(
4219        system_type: IFFSystemType,
4220        system_name: IFFSystemName,
4221        system_mode: IFFSystemMode,
4222        change_options: ChangeOptions,
4223    ) -> Self {
4224        Self {
4225            system_type,
4226            system_name,
4227            system_mode,
4228            change_options,
4229        }
4230    }
4231}
4232
4233/// Timestamp ticks in one hour: bits 31 to 1 count units of 3600/2^31 seconds
4234const TICKS_PER_HOUR: u128 = 1 << 31;
4235const NANOS_PER_HOUR: u128 = 3_600_000_000_000;
4236const SECONDS_PER_HOUR: u64 = 3600;
4237const ABSOLUTE_BIT: u32 = 1;
4238
4239/// Implemented according to IEEE 1278.1-2012 §6.2.88
4240/// A DIS timestamp, as carried in every PDU header and in [`ClockTime`] records.
4241///
4242/// A timestamp counts the time since the start of the current hour in units of
4243/// about 1.676 microseconds.
4244///
4245/// Because the count restarts every hour, timestamps can't be ordered by
4246/// comparing them directly. Use [`duration_since`](Self::duration_since), which
4247/// allows for the hour wrapping around.
4248///
4249/// ```
4250/// use std::time::Duration;
4251/// use open_dis_rust::records::Timestamp;
4252///
4253/// let start = Timestamp::absolute(Duration::from_secs(3599)); // 59:59
4254/// let later = Timestamp::absolute(Duration::from_secs(1));    // 00:01, in the next hour
4255/// // Accurate to within a tick, about 1.7 µs.
4256/// assert_eq!(later.duration_since(start).as_secs_f64().round(), 2.0);
4257/// assert!(later.is_absolute());
4258/// ```
4259///
4260/// [`ClockTime`]: crate::records::ClockTime
4261#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
4262#[deku(
4263    endian = "endian",
4264    ctx = "endian: deku::ctx::Endian",
4265    ctx_default = "deku::ctx::Endian::Big"
4266)]
4267pub struct Timestamp {
4268    raw: u32,
4269}
4270
4271impl Timestamp {
4272    /// An absolute timestamp for the current time from the system clock
4273    ///
4274    /// The result is only as accurate as the system clock, so sync it with
4275    /// something like NTP before other simulators compare their timestamps
4276    /// with yours.
4277    #[must_use]
4278    pub fn now() -> Self {
4279        let since_epoch = SystemTime::now()
4280            .duration_since(UNIX_EPOCH)
4281            .unwrap_or_default();
4282        Self::absolute(since_epoch)
4283    }
4284
4285    /// An absolute timestamp for the given time past the hour, in UTC.
4286    ///
4287    /// Whole hours are discarded, so a time since midnight, or since the Unix
4288    /// epoch, gives the same result as the time since the start of its hour.
4289    #[must_use]
4290    pub fn absolute(time_past_hour: Duration) -> Self {
4291        Self {
4292            raw: Self::ticks(time_past_hour) << 1 | ABSOLUTE_BIT,
4293        }
4294    }
4295
4296    /// A relative timestamp for the given time on the simulation's own clock, for
4297    /// example the time since the simulation started.
4298    ///
4299    /// Whole hours are discarded, as for [`absolute`](Self::absolute).
4300    #[must_use]
4301    pub fn relative(time: Duration) -> Self {
4302        Self {
4303            raw: Self::ticks(time) << 1,
4304        }
4305    }
4306
4307    /// A timestamp from its 32-bit wire value.
4308    #[must_use]
4309    pub const fn from_raw(raw: u32) -> Self {
4310        Self { raw }
4311    }
4312
4313    /// The timestamp's 32-bit wire value.
4314    #[must_use]
4315    pub const fn to_raw(self) -> u32 {
4316        self.raw
4317    }
4318
4319    /// Whether the timestamp is absolute (measured against UTC) rather than relative.
4320    #[must_use]
4321    pub const fn is_absolute(self) -> bool {
4322        self.raw & ABSOLUTE_BIT == ABSOLUTE_BIT
4323    }
4324
4325    /// The time since the start of the hour that the timestamp gives.
4326    #[must_use]
4327    pub fn time_past_hour(self) -> Duration {
4328        Self::duration(self.raw >> 1)
4329    }
4330
4331    /// How long after `earlier` this timestamp is, allowing for the hour wrapping
4332    /// around.
4333    ///
4334    /// The result is always less than an hour. A timestamp from 59:59, compared
4335    /// with one from 00:01, is 2 seconds earlier, not 59 minutes and 58 seconds
4336    /// later. Like every timestamp, it's accurate to within about 1.7 µs, so a
4337    /// whole number of seconds can come out a fraction of a microsecond short.
4338    ///
4339    /// If `earlier` is actually slightly *after* this timestamp, for example
4340    /// because the sender's clock runs fast, the result is just under an hour.
4341    /// Treat results above about 30 minutes as meaning `earlier` is in the future.
4342    ///
4343    /// Only compare timestamps of the same kind: absolute with absolute, or
4344    /// relative with relative from the same simulation.
4345    #[must_use]
4346    pub fn duration_since(self, earlier: Self) -> Duration {
4347        let ticks = (self.raw >> 1).wrapping_sub(earlier.raw >> 1) & (u32::MAX >> 1);
4348        Self::duration(ticks)
4349    }
4350
4351    /// Converts a duration to the nearest tick since the start of its hour. Always
4352    /// below 2³¹: a time that rounds up to the next hour becomes tick 0
4353    fn ticks(time: Duration) -> u32 {
4354        let past_hour = time.as_nanos().checked_rem(NANOS_PER_HOUR).unwrap_or(0);
4355        let ticks = past_hour
4356            .saturating_mul(TICKS_PER_HOUR)
4357            .saturating_add(NANOS_PER_HOUR / 2)
4358            .checked_div(NANOS_PER_HOUR)
4359            .unwrap_or(0)
4360            .checked_rem(TICKS_PER_HOUR)
4361            .unwrap_or(0);
4362        u32::try_from(ticks).unwrap_or(0)
4363    }
4364
4365    /// Converts ticks to a duration. `ticks` is below 2³¹, so this never overflows.
4366    fn duration(ticks: u32) -> Duration {
4367        // 3600 s / 2³¹ per tick: whole seconds first, then the remainder in nanoseconds
4368        let total = u64::from(ticks).saturating_mul(SECONDS_PER_HOUR);
4369        let seconds = total >> 31;
4370        let remainder = total & ((1 << 31) - 1);
4371        // Round to the nearest nanosecond. `Duration::new` carries 10⁹ nanoseconds
4372        // into the seconds
4373        let nanos = remainder
4374            .saturating_mul(1_000_000_000)
4375            .saturating_add(1 << 30)
4376            >> 31;
4377        Duration::new(seconds, u32::try_from(nanos).unwrap_or(0))
4378    }
4379}
4380
4381impl From<Timestamp> for u32 {
4382    fn from(timestamp: Timestamp) -> Self {
4383        timestamp.raw
4384    }
4385}
4386
4387impl fmt::Debug for Timestamp {
4388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4389        f.debug_struct("Timestamp")
4390            .field("time_past_hour", &self.time_past_hour())
4391            .field("absolute", &self.is_absolute())
4392            .finish()
4393    }
4394}
4395
4396/// Formats the time past the hour as minutes and seconds, to the nearest microsecond,
4397/// followed by `abs` or `rel`: for example `35:26.232076 abs`. A timestamp's
4398/// resolution is about 1.676 µs, so the last digit isn't always exact.
4399impl fmt::Display for Timestamp {
4400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4401        // Round to the nearest microsecond, but never up to 60:00
4402        let micros = self
4403            .time_past_hour()
4404            .as_nanos()
4405            .saturating_add(500)
4406            .checked_div(1000)
4407            .unwrap_or(0)
4408            .min(3_599_999_999);
4409        let seconds = micros / 1_000_000;
4410        write!(
4411            f,
4412            "{:02}:{:02}.{:06} {}",
4413            seconds / 60,
4414            seconds % 60,
4415            micros % 1_000_000,
4416            if self.is_absolute() { "abs" } else { "rel" }
4417        )
4418    }
4419}
4420
4421/// Implemented according to IEEE 1278.1-2012 §6.2.89
4422#[derive(Copy, Clone, Default, Debug, deku::DekuRead, deku::DekuWrite)]
4423#[deku(
4424    endian = "endian",
4425    ctx = "endian: deku::ctx::Endian",
4426    ctx_default = "deku::ctx::Endian::Big"
4427)]
4428pub struct TotalRecordSets {
4429    pub total_record_sets: u16,
4430    padding: u16,
4431}
4432
4433/// Implemented according to IEEE 1278.1-2012 §6.2.90
4434#[derive(Copy, Clone, Default, Debug, deku::DekuRead, deku::DekuWrite)]
4435#[deku(
4436    endian = "endian",
4437    ctx = "endian: deku::ctx::Endian",
4438    ctx_default = "deku::ctx::Endian::Big"
4439)]
4440pub struct TrackJamData {
4441    pub entity_id: EntityIdentifier,
4442    pub emitter_number: u8,
4443    pub beam_number: u8,
4444}
4445
4446/// Implemented according to IEEE 1278.1-2012 §6.2.91
4447#[derive(Copy, Clone, Default, Debug, deku::DekuRead, deku::DekuWrite)]
4448#[deku(
4449    endian = "endian",
4450    ctx = "endian: deku::ctx::Endian",
4451    ctx_default = "deku::ctx::Endian::Big"
4452)]
4453pub struct UAFundamentalParameterData {
4454    pub active_emission_parameter_index_filename: UAActiveEmissionParameterIndex,
4455    pub scan_pattern: UAScanPattern,
4456    pub beam_center_azimuth: f32,
4457    pub azimuthal_beamwidth: f32,
4458    pub beam_center_de: f32,
4459    pub de_beamwidth: f32,
4460}
4461
4462/// Implemented according to IEEE 1278.1-2012 §6.2.92
4463#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4464#[deku(
4465    endian = "endian",
4466    ctx = "endian: deku::ctx::Endian",
4467    ctx_default = "deku::ctx::Endian::Big"
4468)]
4469pub struct UnattachedIdentifier {
4470    pub simulation_address: SimulationAddress,
4471    pub reference_number: u16,
4472}
4473
4474impl UnattachedIdentifier {
4475    #[must_use]
4476    pub const fn new(simulation_address: SimulationAddress, reference_number: u16) -> Self {
4477        Self {
4478            simulation_address,
4479            reference_number,
4480        }
4481    }
4482}
4483
4484/// Implemented according to IEEE 1278.1-2012 §6.2.93
4485/// Variable Datum record: an ID, a length in bits, then the value, padded with
4486/// zeros to a 64-bit boundary.
4487///
4488/// `value` holds the value's octets, `ceil(length_bits / 8)` of them; the
4489/// padding is added when encoding and skipped when decoding.
4490#[derive(Debug, Clone, Default, deku::DekuRead, deku::DekuWrite)]
4491#[deku(
4492    endian = "endian",
4493    ctx = "endian: deku::ctx::Endian",
4494    ctx_default = "deku::ctx::Endian::Big"
4495)]
4496pub struct VariableDatumRecord {
4497    pub datum_id: u32,
4498    #[deku(assert = "wire::fits_in_pdu(value_len(*length_bits))")]
4499    pub length_bits: u32,
4500    /// Encoding fails unless this holds exactly `ceil(length_bits / 8)` octets.
4501    #[deku(
4502        reader = "read_value(deku::reader, *length_bits)",
4503        writer = "write_value(deku::writer, value, *length_bits)"
4504    )]
4505    pub value: Vec<u8>,
4506}
4507
4508/// Octets needed to hold `length_bits` bits.
4509fn value_len(length_bits: u32) -> usize {
4510    usize::try_from(length_bits.div_ceil(8)).unwrap_or(usize::MAX)
4511}
4512
4513/// Zero octets after the value, to reach the next 64-bit boundary.
4514fn padding_len(length_bits: u32) -> usize {
4515    let padded = usize::try_from(length_bits.div_ceil(64))
4516        .unwrap_or(usize::MAX)
4517        .saturating_mul(8);
4518    padded.saturating_sub(value_len(length_bits))
4519}
4520
4521/// Read the value's octets, then skip its padding.
4522fn read_value<R: Read + Seek>(
4523    reader: &mut Reader<R>,
4524    length_bits: u32,
4525) -> Result<Vec<u8>, DekuError> {
4526    let mut value = vec![0; value_len(length_bits)];
4527    for octet in &mut value {
4528        *octet = u8::from_reader_with_ctx(reader, ())?;
4529    }
4530    for _ in 0..padding_len(length_bits) {
4531        u8::from_reader_with_ctx(reader, ())?;
4532    }
4533    Ok(value)
4534}
4535
4536/// Write the value's octets, then zero padding to the 64-bit boundary.
4537fn write_value<W: Write + Seek>(
4538    writer: &mut Writer<W>,
4539    value: &[u8],
4540    length_bits: u32,
4541) -> Result<(), DekuError> {
4542    if value.len() != value_len(length_bits) {
4543        return Err(DekuError::Assertion(
4544            format!(
4545                "VariableDatumRecord: {length_bits} bits needs {} octets, but value has {}",
4546                value_len(length_bits),
4547                value.len()
4548            )
4549            .into(),
4550        ));
4551    }
4552    value.to_writer(writer, ())?;
4553    vec![0u8; padding_len(length_bits)].to_writer(writer, ())
4554}
4555
4556/// Implemented according to IEEE 1278.1-2012 §6.2.94.1
4557///
4558/// A 128-bit record whose format depends on its Record Type (UID 56): one
4559/// variant per record type, holding the 120 bits of record-specific fields.
4560/// A Record Type the crate doesn't define decodes as [`Self::Other`], so it
4561/// round-trips unchanged.
4562#[derive(Copy, Clone, Debug, PartialEq, deku::DekuRead, deku::DekuWrite)]
4563#[deku(
4564    endian = "endian",
4565    ctx = "endian: deku::ctx::Endian",
4566    ctx_default = "deku::ctx::Endian::Big",
4567    id_type = "u8"
4568)]
4569pub enum VariableParameter {
4570    /// Record Type 0 (§6.2.94.2)
4571    #[deku(id = 0)]
4572    ArticulatedPart(ArticulatedPartVP),
4573    /// Record Type 1 (§6.2.94.3)
4574    #[deku(id = 1)]
4575    AttachedPart(AttachedPartVP),
4576    /// Record Type 2 (§6.2.94.6)
4577    #[deku(id = 2)]
4578    Separation(SeparationVP),
4579    /// Record Type 3 (§6.2.94.5)
4580    #[deku(id = 3)]
4581    EntityType(EntityTypeVP),
4582    /// Record Type 4 (§6.2.94.4)
4583    #[deku(id = 4)]
4584    EntityAssociation(EntityAssociationVP),
4585    /// Any other Record Type, with its record-specific fields as raw octets
4586    #[deku(id_pat = "_")]
4587    Other {
4588        record_type: u8,
4589        record_specific_fields: [u8; 15],
4590    },
4591}
4592
4593impl Default for VariableParameter {
4594    fn default() -> Self {
4595        Self::ArticulatedPart(ArticulatedPartVP::default())
4596    }
4597}
4598
4599impl VariableParameter {
4600    #[must_use]
4601    pub const fn record_type(&self) -> u8 {
4602        match self {
4603            Self::ArticulatedPart(_) => 0,
4604            Self::AttachedPart(_) => 1,
4605            Self::Separation(_) => 2,
4606            Self::EntityType(_) => 3,
4607            Self::EntityAssociation(_) => 4,
4608            Self::Other { record_type, .. } => *record_type,
4609        }
4610    }
4611}
4612
4613/// The low bits of an Articulated Part's Parameter Type that hold the Type
4614/// Metric: "The maximum value of the Type Metric shall be 31. The Type Class
4615/// value shall be a multiple of 32" (Annex I.2.2.4)
4616const TYPE_METRIC_MASK: u32 = 31;
4617
4618/// Implemented according to IEEE 1278.1-2012 §6.2.94.2 (Record Type 0)
4619#[derive(Copy, Clone, Debug, Default, PartialEq, deku::DekuRead, deku::DekuWrite)]
4620#[deku(
4621    endian = "endian",
4622    ctx = "endian: deku::ctx::Endian",
4623    ctx_default = "deku::ctx::Endian::Big"
4624)]
4625pub struct ArticulatedPartVP {
4626    pub change_indicator: u8,
4627    pub id_part_attached_to: u16,
4628    pub parameter_type: u32,
4629    pub parameter_value: f32,
4630    padding: u32,
4631}
4632
4633impl ArticulatedPartVP {
4634    #[must_use]
4635    pub const fn new(
4636        type_class: ArticulatedPartsTypeClass,
4637        type_metric: ArticulatedPartsTypeMetric,
4638        parameter_value: f32,
4639    ) -> Self {
4640        // Lossless: fieldless enums cast to the type their values fit in.
4641        #[allow(clippy::as_conversions)]
4642        let parameter_type = (type_class as u32).saturating_add(type_metric as u32);
4643        Self {
4644            change_indicator: 0,
4645            id_part_attached_to: 0,
4646            parameter_type,
4647            parameter_value,
4648            padding: 0,
4649        }
4650    }
4651
4652    /// The Type Class: `parameter_type` minus its Type Metric, if it's one
4653    /// the crate defines
4654    #[must_use]
4655    pub fn type_class(&self) -> Option<ArticulatedPartsTypeClass> {
4656        ArticulatedPartsTypeClass::from_u32(self.parameter_type & !TYPE_METRIC_MASK)
4657    }
4658
4659    /// The Type Metric: `parameter_type` modulo 32, if it's one the crate
4660    /// defines
4661    #[must_use]
4662    pub fn type_metric(&self) -> Option<ArticulatedPartsTypeMetric> {
4663        ArticulatedPartsTypeMetric::from_u32(self.parameter_type & TYPE_METRIC_MASK)
4664    }
4665}
4666
4667/// Implemented according to IEEE 1278.1-2012 §6.2.94.3 (Record Type 1)
4668///
4669/// `parameter_type` is the station the part is attached to (UID 57). Stations
4670/// are numbered within ranges such as
4671/// [`AttachedParts::FuselageStations`](crate::siso::enums::AttachedParts::FuselageStations), so
4672/// it is kept as a number.
4673#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
4674#[deku(
4675    endian = "endian",
4676    ctx = "endian: deku::ctx::Endian",
4677    ctx_default = "deku::ctx::Endian::Big"
4678)]
4679pub struct AttachedPartVP {
4680    pub detached_indicator: AttachedPartDetachedIndicator,
4681    /// The part this one is attached to, or 0 for the entity
4682    pub id_part_attached_to: u16,
4683    pub parameter_type: u32,
4684    pub attached_part_type: EntityType,
4685}
4686
4687/// Implemented according to IEEE 1278.1-2012 §6.2.94.6 (Record Type 2)
4688#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
4689#[deku(
4690    endian = "endian",
4691    ctx = "endian: deku::ctx::Endian",
4692    ctx_default = "deku::ctx::Endian::Big"
4693)]
4694pub struct SeparationVP {
4695    pub reason_for_separation: SeparationVPReasonforSeparation,
4696    pub pre_entity_indicator: SeparationVPPreEntityIndicator,
4697    padding: u8,
4698    pub parent_entity_id: EntityIdentifier,
4699    padding2: u16,
4700    pub station_location: NamedLocationIdentification,
4701}
4702
4703impl SeparationVP {
4704    #[must_use]
4705    pub const fn new(
4706        reason_for_separation: SeparationVPReasonforSeparation,
4707        pre_entity_indicator: SeparationVPPreEntityIndicator,
4708        parent_entity_id: EntityIdentifier,
4709        station_location: NamedLocationIdentification,
4710    ) -> Self {
4711        Self {
4712            reason_for_separation,
4713            pre_entity_indicator,
4714            padding: 0,
4715            parent_entity_id,
4716            padding2: 0,
4717            station_location,
4718        }
4719    }
4720}
4721
4722/// Implemented according to IEEE 1278.1-2012 §6.2.94.5 (Record Type 3)
4723#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
4724#[deku(
4725    endian = "endian",
4726    ctx = "endian: deku::ctx::Endian",
4727    ctx_default = "deku::ctx::Endian::Big"
4728)]
4729pub struct EntityTypeVP {
4730    pub change_indicator: EntityVPRecordChangeIndicator,
4731    pub entity_type: EntityType,
4732    padding: u16,
4733    padding2: u32,
4734}
4735
4736impl EntityTypeVP {
4737    #[must_use]
4738    pub const fn new(
4739        change_indicator: EntityVPRecordChangeIndicator,
4740        entity_type: EntityType,
4741    ) -> Self {
4742        Self {
4743            change_indicator,
4744            entity_type,
4745            padding: 0,
4746            padding2: 0,
4747        }
4748    }
4749}
4750
4751/// Implemented according to IEEE 1278.1-2012 §6.2.94.4 (Record Type 4)
4752#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, deku::DekuRead, deku::DekuWrite)]
4753#[deku(
4754    endian = "endian",
4755    ctx = "endian: deku::ctx::Endian",
4756    ctx_default = "deku::ctx::Endian::Big"
4757)]
4758pub struct EntityAssociationVP {
4759    pub change_indicator: EntityVPRecordChangeIndicator,
4760    pub association_status: EntityAssociationAssociationStatus,
4761    /// UID 323
4762    pub association_type: EntityAssociationPhysicalAssociationType,
4763    /// The associated entity, or an object (an Object Identifier has the
4764    /// same layout)
4765    pub entity_or_object_id: EntityIdentifier,
4766    pub own_station_location: IsPartOfStationName,
4767    pub physical_connection_type: EntityAssociationPhysicalConnectionType,
4768    pub group_member_type: EntityAssociationGroupMemberType,
4769    pub group_number: u16,
4770}
4771
4772/// Implemented according to IEEE 1278.1-2012 §6.2.95
4773/// `record_length` is the whole record in octets, a multiple of 8.
4774#[derive(Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4775#[deku(
4776    endian = "endian",
4777    ctx = "endian: deku::ctx::Endian",
4778    ctx_default = "deku::ctx::Endian::Big"
4779)]
4780pub struct VariableTransmitterParameters {
4781    /// SISO-REF-010 UID 66.
4782    pub record_type: VariableRecordTypes,
4783    #[deku(
4784        update = "crate::wire::padded_record_length(self.record_specific_fields.len())?",
4785        assert = "crate::wire::valid_record_length(*record_length)"
4786    )]
4787    pub record_length: u16,
4788    /// Everything after the record length. When decoded, this includes the
4789    /// padding to the 64-bit boundary; when encoded, padding is added to
4790    /// reach it.
4791    #[deku(
4792        count = "crate::wire::record_fields_len(*record_length)",
4793        writer = "crate::wire::write_padded_fields(deku::writer, record_specific_fields)"
4794    )]
4795    pub record_specific_fields: Vec<u8>,
4796}
4797
4798impl VariableTransmitterParameters {
4799    #[must_use]
4800    pub fn new() -> Self {
4801        Self::default()
4802    }
4803}
4804
4805/// Implemented according to IEEE 1278.1-2012 §6.2.96
4806#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4807#[deku(
4808    endian = "endian",
4809    ctx = "endian: deku::ctx::Endian",
4810    ctx_default = "deku::ctx::Endian::Big"
4811)]
4812pub struct Vector {
4813    pub first_vector_component: f32,
4814    pub second_vector_component: f32,
4815    pub third_vector_component: f32,
4816}
4817
4818impl Vector {
4819    #[must_use]
4820    pub const fn new(x: f32, y: f32, z: f32) -> Self {
4821        Self {
4822            first_vector_component: x,
4823            second_vector_component: y,
4824            third_vector_component: z,
4825        }
4826    }
4827}
4828
4829/// Implemented according to IEEE 1278.1-2012 §6.2.97
4830#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4831#[deku(
4832    endian = "endian",
4833    ctx = "endian: deku::ctx::Endian",
4834    ctx_default = "deku::ctx::Endian::Big"
4835)]
4836pub struct VectoringNozzleSystemData {
4837    pub horizontal_deflection_angle: f32,
4838    pub vertical_deflection_angle: f32,
4839}
4840
4841impl VectoringNozzleSystemData {
4842    #[must_use]
4843    pub const fn new(horizontal_deflection_angle: f32, vertical_deflection_angle: f32) -> Self {
4844        Self {
4845            horizontal_deflection_angle,
4846            vertical_deflection_angle,
4847        }
4848    }
4849}
4850
4851/// Implemented according to IEEE 1278.1-2012 §6.2.98
4852#[derive(Copy, Clone, Debug, Default, deku::DekuRead, deku::DekuWrite)]
4853#[deku(
4854    endian = "endian",
4855    ctx = "endian: deku::ctx::Endian",
4856    ctx_default = "deku::ctx::Endian::Big"
4857)]
4858pub struct WorldCoordinates {
4859    /// The coordinate value along the X-axis which passes through the prime meridian at the equator
4860    pub x_coordinate: f64,
4861    /// The coordinate value along the Y-axis which passes through 90°E longitude at the equator
4862    pub y_coordinate: f64,
4863    /// The coordinate value along the Z-axis which passes through the North Pole
4864    pub z_coordinate: f64,
4865}
4866
4867impl WorldCoordinates {
4868    #[must_use]
4869    pub const fn new(x_coordinate: f64, y_coordinate: f64, z_coordinate: f64) -> Self {
4870        Self {
4871            x_coordinate,
4872            y_coordinate,
4873            z_coordinate,
4874        }
4875    }
4876}
4877
4878/// Implemented according to IEEE 1278.1-2012 §B.2.52
4879/// The overall status of an IFF system
4880///
4881/// It is the first octet of the IFF PDU's [`FundamentalOperationalData`], and says
4882/// whether the system is on, which of the parameters 1 to 6 it has a component for, and
4883/// whether it is operational.
4884///
4885/// | Bit | Field | Lo | Hi |
4886/// | --- | --- | --- | --- |
4887/// | 0 | System On/Off Status | Off | On |
4888/// | 1-6 | Parameter 1-6 Capable | Capable | Not Capable |
4889/// | 7 | Operational Status | Operational | System Failed |
4890///
4891/// Bit 0 is the least significant bit. The accessors use `true` for On, Capable, and
4892/// Operational, so the capable and operational getters are `true` when their bit is 0.
4893/// The default record (which has every bit set to 0) is a system that is off,
4894/// capable for all six parameters, and operational.
4895///
4896/// ```
4897/// use open_dis_rust::records::SystemStatus;
4898///
4899/// let mut status = SystemStatus::new();
4900/// status.set_system_on(true);
4901/// status.set_parameter_6_capable(false);  // no component for Parameter 6
4902/// assert_eq!(status.to_raw(), 0b0100_0001);
4903/// assert!(status.is_operational());
4904/// ```
4905#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, deku::DekuRead, deku::DekuWrite)]
4906#[deku(
4907    endian = "endian",
4908    ctx = "endian: deku::ctx::Endian",
4909    ctx_default = "deku::ctx::Endian::Big"
4910)]
4911pub struct SystemStatus {
4912    raw: u8,
4913}
4914
4915impl SystemStatus {
4916    const SYSTEM_ON: u8 = 1 << 0;
4917    const PARAMETER_1_NOT_CAPABLE: u8 = 1 << 1;
4918    const PARAMETER_2_NOT_CAPABLE: u8 = 1 << 2;
4919    const PARAMETER_3_NOT_CAPABLE: u8 = 1 << 3;
4920    const PARAMETER_4_NOT_CAPABLE: u8 = 1 << 4;
4921    const PARAMETER_5_NOT_CAPABLE: u8 = 1 << 5;
4922    const PARAMETER_6_NOT_CAPABLE: u8 = 1 << 6;
4923    const SYSTEM_FAILED: u8 = 1 << 7;
4924
4925    /// Creates a System Status record with every field set to zero
4926    #[must_use]
4927    pub const fn new() -> Self {
4928        Self { raw: 0 }
4929    }
4930
4931    /// System Status record from its wire octet
4932    #[must_use]
4933    pub const fn from_raw(raw: u8) -> Self {
4934        Self { raw }
4935    }
4936
4937    /// The wire octet itself
4938    #[must_use]
4939    pub const fn to_raw(self) -> u8 {
4940        self.raw
4941    }
4942
4943    const fn set_bit(&mut self, bit: u8, set: bool) {
4944        self.raw = if set { self.raw | bit } else { self.raw & !bit };
4945    }
4946
4947    /// System On/Off Status (bit 0): whether the overall system is on
4948    #[must_use]
4949    pub const fn system_on(self) -> bool {
4950        self.raw & Self::SYSTEM_ON != 0
4951    }
4952
4953    /// Sets bit 0. See [`system_on`](Self::system_on)
4954    pub const fn set_system_on(&mut self, on: bool) {
4955        self.set_bit(Self::SYSTEM_ON, on);
4956    }
4957
4958    /// Whether a system component is defined for Parameter 1 of the Fundamental
4959    /// Operational Data record (bit 1). On the wire, Capable is 0 and Not Capable is 1
4960    #[must_use]
4961    pub const fn parameter_1_capable(self) -> bool {
4962        self.raw & Self::PARAMETER_1_NOT_CAPABLE == 0
4963    }
4964
4965    /// Sets bit 1. See [`parameter_1_capable`](Self::parameter_1_capable)
4966    pub const fn set_parameter_1_capable(&mut self, capable: bool) {
4967        self.set_bit(Self::PARAMETER_1_NOT_CAPABLE, !capable);
4968    }
4969
4970    /// Whether a system component is defined for Parameter 2 of the Fundamental
4971    /// Operational Data record (bit 2). On the wire, Capable is 0 and Not Capable is 1
4972    #[must_use]
4973    pub const fn parameter_2_capable(self) -> bool {
4974        self.raw & Self::PARAMETER_2_NOT_CAPABLE == 0
4975    }
4976
4977    /// Sets bit 2. See [`parameter_2_capable`](Self::parameter_2_capable)
4978    pub const fn set_parameter_2_capable(&mut self, capable: bool) {
4979        self.set_bit(Self::PARAMETER_2_NOT_CAPABLE, !capable);
4980    }
4981
4982    /// Whether a system component is defined for Parameter 3 of the Fundamental
4983    /// Operational Data record (bit 3). On the wire, Capable is 0 and Not Capable is 1
4984    #[must_use]
4985    pub const fn parameter_3_capable(self) -> bool {
4986        self.raw & Self::PARAMETER_3_NOT_CAPABLE == 0
4987    }
4988
4989    /// Sets bit 3. See [`parameter_3_capable`](Self::parameter_3_capable)
4990    pub const fn set_parameter_3_capable(&mut self, capable: bool) {
4991        self.set_bit(Self::PARAMETER_3_NOT_CAPABLE, !capable);
4992    }
4993
4994    /// Whether a system component is defined for Parameter 4 of the Fundamental
4995    /// Operational Data record (bit 4). On the wire, Capable is 0 and Not Capable is 1
4996    #[must_use]
4997    pub const fn parameter_4_capable(self) -> bool {
4998        self.raw & Self::PARAMETER_4_NOT_CAPABLE == 0
4999    }
5000
5001    /// Sets bit 4. See [`parameter_4_capable`](Self::parameter_4_capable)
5002    pub const fn set_parameter_4_capable(&mut self, capable: bool) {
5003        self.set_bit(Self::PARAMETER_4_NOT_CAPABLE, !capable);
5004    }
5005
5006    /// Whether a system component is defined for Parameter 5 of the Fundamental
5007    /// Operational Data record (bit 5). On the wire, Capable is 0 and Not Capable is 1
5008    #[must_use]
5009    pub const fn parameter_5_capable(self) -> bool {
5010        self.raw & Self::PARAMETER_5_NOT_CAPABLE == 0
5011    }
5012
5013    /// Sets bit 5. See [`parameter_5_capable`](Self::parameter_5_capable)
5014    pub const fn set_parameter_5_capable(&mut self, capable: bool) {
5015        self.set_bit(Self::PARAMETER_5_NOT_CAPABLE, !capable);
5016    }
5017
5018    /// Whether a system component is defined for Parameter 6 of the Fundamental
5019    /// Operational Data record (bit 6). On the wire, Capable is 0 and Not Capable is 1
5020    #[must_use]
5021    pub const fn parameter_6_capable(self) -> bool {
5022        self.raw & Self::PARAMETER_6_NOT_CAPABLE == 0
5023    }
5024
5025    /// Sets bit 6. See [`parameter_6_capable`](Self::parameter_6_capable)
5026    pub const fn set_parameter_6_capable(&mut self, capable: bool) {
5027        self.set_bit(Self::PARAMETER_6_NOT_CAPABLE, !capable);
5028    }
5029
5030    /// Operational Status (bit 7): `false` if the system has failed, which it reports when
5031    /// it cannot provide data for any of parameters 1 to 6 or the Modifier record.
5032    #[must_use]
5033    pub const fn is_operational(self) -> bool {
5034        self.raw & Self::SYSTEM_FAILED == 0
5035    }
5036
5037    /// Sets bit 7. See [`is_operational`](Self::is_operational)
5038    pub const fn set_operational(&mut self, operational: bool) {
5039        self.set_bit(Self::SYSTEM_FAILED, !operational);
5040    }
5041}
5042
5043impl fmt::Debug for SystemStatus {
5044    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5045        f.debug_struct("SystemStatus")
5046            .field("system_on", &self.system_on())
5047            .field("parameter_1_capable", &self.parameter_1_capable())
5048            .field("parameter_2_capable", &self.parameter_2_capable())
5049            .field("parameter_3_capable", &self.parameter_3_capable())
5050            .field("parameter_4_capable", &self.parameter_4_capable())
5051            .field("parameter_5_capable", &self.parameter_5_capable())
5052            .field("parameter_6_capable", &self.parameter_6_capable())
5053            .field("is_operational", &self.is_operational())
5054            .finish()
5055    }
5056}
5057
5058#[cfg(test)]
5059mod tests;