1use std::collections::{BTreeMap, BTreeSet};
6use std::fmt;
7use std::path::PathBuf;
8
9use bytes::Bytes;
10use microrti_core::{ExceptionKind, LogicalTime, RtiError, RtiResult, TimeKind};
11use microrti_proto as proto;
12
13use crate::handles::{
14 AttributeHandle, DimensionHandle, FederateHandle, InteractionClassHandle, MessageRetractionHandle,
15 ParameterHandle, RegionHandle,
16};
17use crate::wire::{FromWire, ToWire, WireCx, malformed};
18
19pub type FederateHandleSet = BTreeSet<FederateHandle>;
21pub type AttributeHandleSet = BTreeSet<AttributeHandle>;
23pub type InteractionClassHandleSet = BTreeSet<InteractionClassHandle>;
25pub type DimensionHandleSet = BTreeSet<DimensionHandle>;
27pub type RegionHandleSet = BTreeSet<RegionHandle>;
29pub type AttributeHandleValueMap = BTreeMap<AttributeHandle, Bytes>;
31pub type ParameterHandleValueMap = BTreeMap<ParameterHandle, Bytes>;
33pub type AttributeSetRegionSetPairList = Vec<AttributeSetRegionSetPair>;
35pub type ConveyedRegion = BTreeMap<DimensionHandle, RangeBounds>;
37pub type ConveyedRegionSet = BTreeSet<ConveyedRegion>;
39
40macro_rules! wire_enums {
41 ($(
42 $(#[$doc:meta])*
43 $name:ident { $( $(#[$vdoc:meta])* $variant:ident ),+ $(,)? }
44 )+) => {$(
45 $(#[$doc])*
46 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
47 pub enum $name {
48 $( $(#[$vdoc])* $variant, )+
49 }
50
51 impl $name {
52 pub const ALL: &'static [$name] = &[$($name::$variant),+];
54
55 pub(crate) fn to_i32(self) -> i32 {
56 match self {
57 $($name::$variant => proto::$name::$variant as i32,)+
58 }
59 }
60
61 pub(crate) fn from_i32(value: i32) -> RtiResult<Self> {
62 match proto::$name::try_from(value) {
63 $(Ok(proto::$name::$variant) => Ok($name::$variant),)+
64 Err(_) => Err(malformed(format!(concat!("unknown ", stringify!($name), " value {}"), value))),
65 }
66 }
67 }
68
69 impl ToWire<i32> for $name {
70 fn to_wire(self, _: &WireCx) -> RtiResult<i32> {
71 Ok(self.to_i32())
72 }
73 }
74
75 impl FromWire<i32> for $name {
76 fn from_wire(wire: i32, _: &WireCx) -> RtiResult<Self> {
77 Self::from_i32(wire)
78 }
79 }
80 )+};
81}
82
83wire_enums! {
84 CallbackModel {
86 Evoked,
88 Immediate,
90 }
91
92 AdditionalSettingsResultCode {
94 SettingsIgnored,
96 SettingsFailedToParse,
98 SettingsApplied,
100 }
101
102 ResignAction {
104 UnconditionallyDivestAttributes,
106 DeleteObjects,
108 CancelPendingOwnershipAcquisitions,
110 DeleteObjectsThenDivest,
112 CancelThenDeleteThenDivest,
114 NoAction,
116 }
117
118 SynchronizationPointFailureReason {
120 SynchronizationPointLabelNotUnique,
122 SynchronizationSetMemberNotJoined,
124 }
125
126 SaveFailureReason {
128 RtiUnableToSave,
130 FederateReportedFailureDuringSave,
132 FederateResignedDuringSave,
134 RtiDetectedFailureDuringSave,
136 SaveTimeCannotBeHonored,
138 SaveAborted,
140 }
141
142 RestoreFailureReason {
144 RtiUnableToRestore,
146 FederateReportedFailureDuringRestore,
148 FederateResignedDuringRestore,
150 RtiDetectedFailureDuringRestore,
152 RestoreAborted,
154 }
155
156 SaveStatus {
158 NoSaveInProgress,
160 FederateInstructedToSave,
162 FederateSaving,
164 FederateWaitingForFederationToSave,
166 }
167
168 RestoreStatus {
170 NoRestoreInProgress,
172 FederateRestoreRequestPending,
174 FederateWaitingForRestoreToBegin,
176 FederatePreparedToRestore,
178 FederateRestoring,
180 FederateWaitingForFederationToRestore,
182 }
183
184 OrderType {
186 Receive,
188 Timestamp,
190 }
191
192 ServiceGroup {
194 FederationManagement,
196 DeclarationManagement,
198 ObjectManagement,
200 OwnershipManagement,
202 TimeManagement,
204 DataDistributionManagement,
206 SupportServices,
208 }
209}
210
211impl TryFrom<i32> for CallbackModel {
214 type Error = RtiError;
215
216 fn try_from(value: i32) -> RtiResult<Self> {
217 Self::from_i32(value).map_err(|_| {
218 RtiError::new(
219 ExceptionKind::UnsupportedCallbackModel,
220 format!("callback model {value} is not supported"),
221 )
222 })
223 }
224}
225
226#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
228pub struct RangeBounds {
229 pub lower: u32,
231 pub upper: u32,
233}
234
235impl RangeBounds {
236 pub const fn new(lower: u32, upper: u32) -> Self {
238 Self { lower, upper }
239 }
240}
241
242#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
244pub struct AttributeSetRegionSetPair {
245 pub attributes: AttributeHandleSet,
247 pub regions: RegionHandleSet,
249}
250
251impl AttributeSetRegionSetPair {
252 pub fn new(attributes: AttributeHandleSet, regions: RegionHandleSet) -> Self {
254 Self { attributes, regions }
255 }
256}
257
258#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
260pub struct RtiConfiguration {
261 configuration_name: String,
262 rti_address: String,
263 additional_settings: String,
264}
265
266impl RtiConfiguration {
267 pub fn new() -> Self {
269 Self::default()
270 }
271
272 pub fn with_configuration_name(mut self, configuration_name: impl Into<String>) -> Self {
274 self.configuration_name = configuration_name.into();
275 self
276 }
277
278 pub fn with_rti_address(mut self, rti_address: impl Into<String>) -> Self {
281 self.rti_address = rti_address.into();
282 self
283 }
284
285 pub fn with_additional_settings(mut self, additional_settings: impl Into<String>) -> Self {
288 self.additional_settings = additional_settings.into();
289 self
290 }
291
292 pub fn configuration_name(&self) -> &str {
294 &self.configuration_name
295 }
296
297 pub fn rti_address(&self) -> &str {
299 &self.rti_address
300 }
301
302 pub fn additional_settings(&self) -> &str {
304 &self.additional_settings
305 }
306}
307
308#[derive(Clone, Debug, PartialEq, Eq, Hash)]
310pub struct ConfigurationResult {
311 pub configuration_used: bool,
313 pub address_used: bool,
315 pub additional_settings_result_code: AdditionalSettingsResultCode,
317 pub message: String,
319}
320
321#[derive(Clone, PartialEq, Eq, Hash)]
323pub struct Credentials {
324 credentials_type: String,
325 data: Bytes,
326}
327
328impl Credentials {
329 pub const NO_CREDENTIALS: &'static str = "HLAnoCredentials";
331 pub const PLAIN_TEXT_PASSWORD: &'static str = "HLAplainTextPassword";
333
334 pub fn new(credentials_type: impl Into<String>, data: impl Into<Bytes>) -> Self {
336 Self { credentials_type: credentials_type.into(), data: data.into() }
337 }
338
339 pub fn no_credentials() -> Self {
341 Self::new(Self::NO_CREDENTIALS, Bytes::new())
342 }
343
344 pub fn plain_text_password(password: &str) -> Self {
346 Self::new(Self::PLAIN_TEXT_PASSWORD, encode_hla_unicode_string(password))
347 }
348
349 pub fn credentials_type(&self) -> &str {
351 &self.credentials_type
352 }
353
354 pub fn data(&self) -> &[u8] {
356 &self.data
357 }
358
359 pub(crate) fn data_bytes(&self) -> Bytes {
360 self.data.clone()
361 }
362}
363
364impl fmt::Debug for Credentials {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 f.debug_struct("Credentials")
368 .field("credentials_type", &self.credentials_type)
369 .field("data_length", &self.data.len())
370 .finish()
371 }
372}
373
374pub fn encode_hla_unicode_string(text: &str) -> Bytes {
377 let units: Vec<u16> = text.encode_utf16().collect();
378 let mut encoded = Vec::with_capacity(4 + 2 * units.len());
379 encoded.extend_from_slice(&u32::try_from(units.len()).unwrap_or(u32::MAX).to_be_bytes());
380 for unit in units {
381 encoded.extend_from_slice(&unit.to_be_bytes());
382 }
383 Bytes::from(encoded)
384}
385
386pub fn decode_hla_unicode_string(encoded: &[u8]) -> RtiResult<String> {
389 let could_not_decode =
390 |what: &str| RtiError::new(ExceptionKind::CouldNotDecode, format!("HLAunicodeString: {what}"));
391 let (count, units) =
392 encoded.split_first_chunk::<4>().ok_or_else(|| could_not_decode("missing length"))?;
393 let count = u32::from_be_bytes(*count) as usize;
394 if units.len() != count.saturating_mul(2) {
395 return Err(could_not_decode("length does not match the data"));
396 }
397 let units: Vec<u16> = units.as_chunks::<2>().0.iter().map(|pair| u16::from_be_bytes(*pair)).collect();
398 String::from_utf16(&units).map_err(|_| could_not_decode("invalid UTF-16"))
399}
400
401#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
403pub struct FederationExecutionInformation {
404 pub federation_execution_name: String,
406 pub logical_time_implementation_name: String,
408}
409
410#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
412pub struct FederationExecutionMemberInformation {
413 pub federate_name: String,
415 pub federate_type: String,
417}
418
419#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
421pub struct FederateHandleSaveStatusPair {
422 pub federate: FederateHandle,
424 pub save_status: SaveStatus,
426}
427
428#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
430pub struct FederateRestoreStatus {
431 pub pre_restore_handle: FederateHandle,
433 pub post_restore_handle: Option<FederateHandle>,
436 pub restore_status: RestoreStatus,
438}
439
440#[derive(Clone, Debug, PartialEq, Eq, Hash)]
443pub struct MessageRetractionReturn {
444 pub handle: Option<MessageRetractionHandle>,
446}
447
448impl MessageRetractionReturn {
449 pub fn retraction_handle_is_valid(&self) -> bool {
451 self.handle.is_some()
452 }
453}
454
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457pub struct TimeQueryReturn {
458 pub time: Option<LogicalTime>,
460}
461
462impl TimeQueryReturn {
463 pub fn time_is_valid(&self) -> bool {
465 self.time.is_some()
466 }
467}
468
469#[derive(Clone, Debug, PartialEq, Eq, Hash)]
474pub struct SupplementalReflectInfo {
475 pub producing_federate: FederateHandle,
477 pub sent_regions: Option<ConveyedRegionSet>,
479}
480
481#[derive(Clone, Debug, PartialEq, Eq, Hash)]
485pub struct SupplementalReceiveInfo {
486 pub producing_federate: FederateHandle,
488 pub sent_regions: Option<ConveyedRegionSet>,
490}
491
492#[derive(Clone, Debug, PartialEq, Eq, Hash)]
494pub struct JoinResult {
495 pub federate_handle: FederateHandle,
497 pub logical_time_implementation_name: String,
499 pub time_kind: TimeKind,
501}
502
503#[derive(Clone, Debug, PartialEq, Eq, Hash)]
505pub enum FomModule {
506 File(PathBuf),
508 Content {
510 name: String,
512 content: Bytes,
514 },
515 Compressed(Bytes),
517 Url(String),
519}
520
521impl FomModule {
522 pub fn file(path: impl Into<PathBuf>) -> Self {
524 FomModule::File(path.into())
525 }
526
527 pub fn content(name: impl Into<String>, content: impl Into<Bytes>) -> Self {
529 FomModule::Content { name: name.into(), content: content.into() }
530 }
531
532 pub fn compressed(archive: impl Into<Bytes>) -> Self {
534 FomModule::Compressed(archive.into())
535 }
536
537 pub fn url(url: impl Into<String>) -> Self {
539 FomModule::Url(url.into())
540 }
541
542 pub(crate) fn to_proto(&self, unreadable: ExceptionKind) -> RtiResult<proto::FomModule> {
545 use proto::fom_module::FomModule as Wire;
546 let module = match self {
547 FomModule::File(path) => {
548 let content = std::fs::read(path)
549 .map_err(|error| RtiError::new(unreadable, format!("{}: {error}", path.display())))?;
550 let name = match path.file_name() {
551 Some(name) => name.to_string_lossy().into_owned(),
552 None => path.display().to_string(),
553 };
554 Wire::File(proto::FileFomModule { name, content: Bytes::from(content) })
555 }
556 FomModule::Content { name, content } => {
557 Wire::File(proto::FileFomModule { name: name.clone(), content: content.clone() })
558 }
559 FomModule::Compressed(archive) => Wire::CompressedModule(archive.clone()),
560 FomModule::Url(url) => Wire::Url(url.clone()),
561 };
562 Ok(proto::FomModule { fom_module: Some(module) })
563 }
564}