rustdds 0.11.8

Native Rust DDS implementation with RTPS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
use std::time::Instant;

use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use bytes::Bytes;
use speedy::{Readable, Writable};
use chrono::{DateTime, Utc};
use cdr_encoding_size::*;

use crate::{
  dds::{
    adapters::with_key::SerializerAdapter,
    participant::DomainParticipant,
    qos::{
      policy::{
        Deadline, DestinationOrder, Durability, History, LatencyBudget, Lifespan, Liveliness,
        Ownership, Presentation, Reliability, ResourceLimits, TimeBasedFilter,
      },
      HasQoSPolicy, QosPolicies,
    },
    topic::{Topic, TopicDescription},
    with_key::datawriter::DataWriter,
  },
  discovery::content_filter_property::ContentFilterProperty,
  messages::submessages::elements::{
    parameter::Parameter,
    parameter_list::{ParameterList, ParameterListable},
  },
  network::{constant::user_traffic_unicast_port, util::get_local_unicast_locators},
  rtps::{rtps_reader_proxy::RtpsReaderProxy, rtps_writer_proxy::RtpsWriterProxy},
  serialization::{
    pl_cdr_adapters::{
      PlCdrDeserialize, PlCdrDeserializeError, PlCdrSerialize, PlCdrSerializeError,
    },
    speedy_pl_cdr_helpers::*,
    RepresentationIdentifier,
  },
  structure::{
    entity::RTPSEntity,
    guid::{GuidPrefix, GUID},
    locator,
    locator::Locator,
    parameter_id::ParameterId,
  },
  Key, Keyed,
};
#[cfg(feature = "security")]
use crate::security::EndpointSecurityInfo;
#[cfg(not(feature = "security"))]
use crate::no_security::EndpointSecurityInfo;
#[cfg(test)]
use crate::structure::guid::EntityKind;

// We need a wrapper to distinguish between Participant and Endpoint GUIDs.
// They need to be distinguished, because the PL_CDR serialization is different:
// ParameterId is different.

#[allow(non_camel_case_types)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy, CdrEncodingSize, Hash, Serialize)]
pub struct Endpoint_GUID(pub GUID);

impl Key for Endpoint_GUID {}

impl PlCdrDeserialize for Endpoint_GUID {
  fn from_pl_cdr_bytes(
    input_bytes: &[u8],
    encoding: RepresentationIdentifier,
  ) -> Result<Self, PlCdrDeserializeError> {
    let ctx = pl_cdr_rep_id_to_speedy_d(encoding)?;
    let pl = ParameterList::read_from_buffer_with_ctx(ctx, input_bytes)?;
    let pl_map = pl.to_map();

    let guid: GUID = get_first_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_GUID,
      "Endpoint GUID",
    )?;

    Ok(Endpoint_GUID(guid))
  }
}

impl PlCdrSerialize for Endpoint_GUID {
  fn to_pl_cdr_bytes(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<Bytes, PlCdrSerializeError> {
    let mut pl = ParameterList::new();
    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;
    macro_rules! emit {
      ($pid:ident, $member:expr, $type:ty) => {
        pl.push(Parameter::new(ParameterId::$pid, {
          let m: &$type = $member;
          m.write_to_vec_with_ctx(ctx)?
        }))
      };
    }
    emit!(PID_ENDPOINT_GUID, &self.0, GUID);
    let bytes = pl.serialize_to_bytes(ctx)?;
    Ok(bytes)
  }
}

// Topic data contains all topic related
// (including reader and writer data structures for serialization and
// deserialization)

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReaderProxy {
  pub remote_reader_guid: GUID,
  pub expects_inline_qos: bool,
  pub unicast_locator_list: Vec<Locator>,
  pub multicast_locator_list: Vec<Locator>,
}

impl ReaderProxy {
  pub fn new(
    guid: GUID,
    expects_inline_qos: bool,
    unicast_locator_list: Vec<Locator>,
    multicast_locator_list: Vec<Locator>,
  ) -> Self {
    Self {
      remote_reader_guid: guid,
      expects_inline_qos,
      unicast_locator_list,
      multicast_locator_list,
    }
  }
}

impl From<RtpsReaderProxy> for ReaderProxy {
  fn from(rtps_reader_proxy: RtpsReaderProxy) -> Self {
    Self {
      remote_reader_guid: rtps_reader_proxy.remote_reader_guid,
      expects_inline_qos: rtps_reader_proxy.expects_inline_qos(),
      unicast_locator_list: rtps_reader_proxy.unicast_locator_list,
      multicast_locator_list: rtps_reader_proxy.multicast_locator_list,
    }
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// DDS SubscriptionBuiltinTopicData
/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubscriptionBuiltinTopicData {
  key: GUID,
  participant_key: Option<GUID>,
  pub topic_name: String,
  type_name: String,
  durability: Option<Durability>,
  deadline: Option<Deadline>,
  latency_budget: Option<LatencyBudget>,
  liveliness: Option<Liveliness>,
  reliability: Option<Reliability>,
  ownership: Option<Ownership>,
  destination_order: Option<DestinationOrder>,
  // pub user_data: Option<UserData>,
  time_based_filter: Option<TimeBasedFilter>,
  presentation: Option<Presentation>,
  // pub partition: Option<Partition>,
  // pub topic_data: Option<TopicData>,
  // pub group_data: Option<GroupData>,
  // pub durability_service: Option<DurabilityService>,
  lifespan: Option<Lifespan>,

  // From spec Remote Procedure Call over DDS:
  service_instance_name: Option<String>,
  related_datawriter_key: Option<GUID>,
  topic_aliases: Option<Vec<String>>, /* Option is a bit redundant, but it indicates if the
                                       * parameter was present or not */
  // DDS Security:
  #[cfg(feature = "security")]
  security_info: Option<EndpointSecurityInfo>,
}

impl SubscriptionBuiltinTopicData {
  pub fn new(
    key: GUID,
    participant_key: Option<GUID>,
    topic_name: String,
    type_name: String,
    qos: &QosPolicies,
    _security_info: Option<EndpointSecurityInfo>, // used only with security feature
  ) -> Self {
    #[cfg(not(feature = "security"))]
    let _dummy = _security_info; // avoid clippy warning

    let mut sbtd = Self {
      key,
      participant_key,
      topic_name,
      type_name,
      // QoS
      durability: None,
      deadline: None,
      latency_budget: None,
      liveliness: None,
      reliability: None,
      ownership: None,
      destination_order: None,
      time_based_filter: None,
      presentation: None,
      lifespan: None,
      // DDS-RPC
      // TODO: these are not implemented
      service_instance_name: None,  // Note: Not implemented
      related_datawriter_key: None, // Note: Not implemented
      topic_aliases: None,          // Note: Not implemented

      // DDS Security
      #[cfg(feature = "security")]
      security_info: _security_info,
    };

    sbtd.set_qos(qos);
    sbtd
  }

  pub fn key(&self) -> GUID {
    self.key
  }

  pub fn participant_key(&self) -> &Option<GUID> {
    &self.participant_key
  }

  pub fn topic_name(&self) -> &String {
    &self.topic_name
  }

  pub fn type_name(&self) -> &String {
    &self.type_name
  }

  #[cfg(feature = "security")]
  pub fn security_info(&self) -> &Option<EndpointSecurityInfo> {
    &self.security_info
  }

  pub fn set_qos(&mut self, qos: &QosPolicies) {
    self.durability = qos.durability;
    self.deadline = qos.deadline;
    self.latency_budget = qos.latency_budget;
    self.liveliness = qos.liveliness;
    self.reliability = qos.reliability;
    self.ownership = qos.ownership;
    self.destination_order = qos.destination_order;
    self.time_based_filter = qos.time_based_filter;
    self.presentation = qos.presentation;
    self.lifespan = qos.lifespan;
    // history does not exist
    // resource_limits does not exist
  }

  pub fn qos(&self) -> QosPolicies {
    QosPolicies {
      durability: self.durability,
      presentation: self.presentation,
      deadline: self.deadline,
      latency_budget: self.latency_budget,
      ownership: self.ownership,
      liveliness: self.liveliness,
      time_based_filter: self.time_based_filter,
      reliability: self.reliability,
      destination_order: self.destination_order,
      history: None, // SubscriptionBuiltinTopicData does not contain History QoS
      resource_limits: None, // nor Resource Limits, see Figure 8.30 in RTPS spec 2.5
      lifespan: self.lifespan,

      #[cfg(feature = "security")]
      property: None, // TODO: no property QoS?
    }
  }

  pub fn to_topic_data(&self) -> TopicBuiltinTopicData {
    // TODO: See the corresponding function in PublicationBuiltinTopicData
    TopicBuiltinTopicData::new(
      None,
      self.topic_name.clone(),
      self.type_name.clone(),
      &self.qos(),
    )
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredReaderData {
  pub reader_proxy: ReaderProxy,
  pub subscription_topic_data: SubscriptionBuiltinTopicData,
  pub content_filter: Option<ContentFilterProperty>,
}

impl DiscoveredReaderData {
  // This is for generating test data only
  #[cfg(test)]
  pub fn default(topic_name: String, type_name: String) -> Self {
    let rguid = GUID::dummy_test_guid(EntityKind::READER_WITH_KEY_BUILT_IN);
    let reader_proxy = ReaderProxy::new(rguid, false, vec![], vec![]);
    let subscription_topic_data = SubscriptionBuiltinTopicData::new(
      rguid,
      None,
      topic_name,
      type_name,
      &QosPolicies::builder().build(),
      None,
    );
    Self {
      reader_proxy,
      subscription_topic_data,
      content_filter: None,
    }
  }
}

impl Keyed for DiscoveredReaderData {
  type K = Endpoint_GUID;
  fn key(&self) -> Self::K {
    Endpoint_GUID(self.subscription_topic_data.key)
  }
}

impl PlCdrDeserialize for DiscoveredReaderData {
  fn from_pl_cdr_bytes(
    input_bytes: &[u8],
    encoding: RepresentationIdentifier,
  ) -> Result<Self, PlCdrDeserializeError> {
    let ctx = pl_cdr_rep_id_to_speedy_d(encoding)?;
    let pl = ParameterList::read_from_buffer_with_ctx(ctx, input_bytes)?;
    let pl_map = pl.to_map();

    let guid: GUID = get_first_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_GUID,
      "Endpoint GUID",
    )?;
    let participant_guid: Option<GUID> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_PARTICIPANT_GUID,
      "Participant GUID",
    )?;

    let expects_inline_qos : bool = // This one has default value false
      get_option_from_pl_map(&pl_map, ctx, ParameterId::PID_EXPECTS_INLINE_QOS, "Expects inline Qos")?
      .unwrap_or(false);

    let unicast_locator_list: Vec<Locator> = get_all_from_pl_map(
      &pl_map,
      &ctx,
      ParameterId::PID_UNICAST_LOCATOR,
      "unicast locators",
    )?;
    let multicast_locator_list: Vec<Locator> = get_all_from_pl_map(
      &pl_map,
      &ctx,
      ParameterId::PID_MULTICAST_LOCATOR,
      "multicast locators",
    )?;

    let topic_name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TOPIC_NAME, "topic name")?
      .into();
    let type_name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TYPE_NAME, "type name")?
      .into();

    let content_filter: Option<ContentFilterProperty> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_CONTENT_FILTER_PROPERTY,
      "content filter",
    )
    .map_err(|e| {
      warn!(
        "Content filter was: {:?}",
        pl_map.get(&ParameterId::PID_CONTENT_FILTER_PROPERTY)
      );
      e
    })?;

    #[cfg(not(feature = "security"))]
    let security_info = None;
    #[cfg(feature = "security")]
    let security_info: Option<EndpointSecurityInfo> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_SECURITY_INFO,
      "endpoint security info",
    )?;

    let qos = QosPolicies::from_parameter_list(ctx, &pl_map)?;

    Ok(DiscoveredReaderData {
      reader_proxy: ReaderProxy::new(
        guid,
        expects_inline_qos,
        unicast_locator_list,
        multicast_locator_list,
      ),
      subscription_topic_data: SubscriptionBuiltinTopicData::new(
        guid,
        participant_guid,
        topic_name,
        type_name,
        &qos,
        security_info,
      ),
      content_filter,
    })
  }
}

impl PlCdrSerialize for DiscoveredReaderData {
  fn to_pl_cdr_bytes(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<Bytes, PlCdrSerializeError> {
    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;
    let pl = self.to_parameter_list(encoding)?;
    let bytes = pl.serialize_to_bytes(ctx)?;
    Ok(bytes)
  }
}

impl ParameterListable for DiscoveredReaderData {
  fn to_parameter_list(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<ParameterList, PlCdrSerializeError> {
    let DiscoveredReaderData {
      reader_proxy:
        ReaderProxy {
          remote_reader_guid,
          expects_inline_qos,
          unicast_locator_list,
          multicast_locator_list,
        },
      subscription_topic_data:
        sbtd @ SubscriptionBuiltinTopicData {
          key,
          participant_key,
          topic_name,
          type_name,

          // QoS handled separately
          durability: _,
          deadline: _,
          latency_budget: _,
          liveliness: _,
          reliability: _,
          ownership: _,
          destination_order: _,
          time_based_filter: _,
          presentation: _,
          lifespan: _,

          service_instance_name,
          related_datawriter_key,
          topic_aliases,

          #[cfg(feature = "security")]
          security_info,
        },
      content_filter,
    } = self;

    let mut pl = ParameterList::new();
    let qos = sbtd.qos();

    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;

    macro_rules! emit {
      ($pid:ident, $member:expr, $type:ty) => {
        pl.push(Parameter::new(ParameterId::$pid, {
          let m: &$type = $member;
          m.write_to_vec_with_ctx(ctx)?
        }))
      };
    }
    macro_rules! emit_option {
      ($pid:ident, $member:expr, $type:ty) => {
        if let Some(m) = $member {
          emit!($pid, m, $type)
        }
      };
    }

    // ReaderProxy
    emit!(PID_EXPECTS_INLINE_QOS, expects_inline_qos, bool);

    // Note that this GUID can be in two places
    emit!(PID_ENDPOINT_GUID, remote_reader_guid, GUID);
    if remote_reader_guid != key {
      // sanity check
      warn!("DiscoveredReaderData: Inconsistent GUID: {remote_reader_guid:?} vs {key:?}");
    }

    for loc in unicast_locator_list {
      emit!(
        PID_UNICAST_LOCATOR,
        &locator::repr::Locator::from(*loc),
        locator::repr::Locator
      );
    }
    for loc in multicast_locator_list {
      emit!(
        PID_MULTICAST_LOCATOR,
        &locator::repr::Locator::from(*loc),
        locator::repr::Locator
      );
    }

    // SubscriptionBuiltinTopicData
    emit_option!(PID_PARTICIPANT_GUID, participant_key, GUID);
    emit!(PID_TOPIC_NAME, &topic_name.clone().into(), StringWithNul);
    emit!(PID_TYPE_NAME, &type_name.clone().into(), StringWithNul);
    pl.parameters.append(&mut qos.to_parameter_list(ctx)?);
    emit_option!(
      PID_SERVICE_INSTANCE_NAME,
      &service_instance_name.clone().map(|e| e.into()),
      StringWithNul
    );
    emit_option!(PID_RELATED_ENTITY_GUID, related_datawriter_key, GUID);
    // TODO: Should topic alias be on parameter with vector or multiple
    // parameters with one alias name each?
    for topic_alias in topic_aliases.as_ref().unwrap_or(&Vec::new()) {
      emit!(
        PID_TOPIC_ALIASES,
        &topic_alias.clone().into(),
        StringWithNul
      );
    }
    emit_option!(
      PID_CONTENT_FILTER_PROPERTY,
      content_filter,
      ContentFilterProperty
    );

    #[cfg(feature = "security")]
    emit_option!(
      PID_ENDPOINT_SECURITY_INFO,
      security_info,
      EndpointSecurityInfo
    );

    Ok(pl)
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriterProxy {
  pub remote_writer_guid: GUID,
  pub unicast_locator_list: Vec<Locator>,
  pub multicast_locator_list: Vec<Locator>,
  pub data_max_size_serialized: Option<u32>,
}

impl WriterProxy {
  pub fn new(
    guid: GUID,
    multicast_locator_list: Vec<Locator>,
    unicast_locator_list: Vec<Locator>,
  ) -> Self {
    Self {
      remote_writer_guid: guid,
      unicast_locator_list,
      multicast_locator_list,
      data_max_size_serialized: None,
    }
  }
}

impl From<RtpsWriterProxy> for WriterProxy {
  fn from(rtps_writer_proxy: RtpsWriterProxy) -> Self {
    WriterProxy {
      remote_writer_guid: rtps_writer_proxy.remote_writer_guid,
      unicast_locator_list: rtps_writer_proxy.unicast_locator_list,
      multicast_locator_list: rtps_writer_proxy.multicast_locator_list,
      data_max_size_serialized: None,
    }
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicationBuiltinTopicData {
  pub key: GUID, // endpoint GUID
  pub participant_key: Option<GUID>,
  pub topic_name: String, // TODO: Convert to method for symmetry with SubscriptionBuiltinTopicData
  pub type_name: String,
  pub durability: Option<Durability>,
  pub deadline: Option<Deadline>,
  pub latency_budget: Option<LatencyBudget>,
  pub liveliness: Option<Liveliness>,
  pub reliability: Option<Reliability>,
  pub lifespan: Option<Lifespan>,
  pub time_based_filter: Option<TimeBasedFilter>,
  pub ownership: Option<Ownership>,
  pub destination_order: Option<DestinationOrder>,
  pub presentation: Option<Presentation>,

  // From Remote Procedure Call over DDS:
  pub service_instance_name: Option<String>,
  pub related_datareader_key: Option<GUID>,
  pub topic_aliases: Option<Vec<String>>, /* Option is a bit redundant, but it indicates
                                           * if the parameter was present or not */
  // DDS Security:
  #[cfg(feature = "security")]
  pub security_info: Option<EndpointSecurityInfo>,
}

impl PublicationBuiltinTopicData {
  pub fn new(
    guid: GUID,
    participant_guid: Option<GUID>,
    topic_name: String,
    type_name: String,
    _security_info: Option<EndpointSecurityInfo>,
  ) -> Self {
    #[cfg(not(feature = "security"))]
    let _dummy = _security_info; // suppress clippy warning

    Self {
      key: guid,
      participant_key: participant_guid,
      topic_name,
      type_name,

      durability: None,
      deadline: None,
      latency_budget: None,
      liveliness: None,
      reliability: None,
      lifespan: None,
      time_based_filter: None,
      ownership: None,
      destination_order: None,
      presentation: None,

      service_instance_name: None,  // TODO: These are not supported/used
      related_datareader_key: None, // TODO
      topic_aliases: None,          // TODO

      #[cfg(feature = "security")]
      security_info: _security_info,
    }
  }

  pub fn new_with_qos(
    guid: GUID,
    participant_guid: Option<GUID>,
    topic_name: String,
    type_name: String,
    qos: &QosPolicies,
    security_info: Option<EndpointSecurityInfo>,
  ) -> Self {
    let mut s = Self::new(guid, participant_guid, topic_name, type_name, security_info);
    s.set_qos(qos);
    s
  }

  pub fn set_qos(&mut self, qos: &QosPolicies) {
    self.durability = qos.durability;
    self.deadline = qos.deadline;
    self.latency_budget = qos.latency_budget;
    self.liveliness = qos.liveliness;
    self.reliability = qos.reliability;
    self.lifespan = qos.lifespan;
    self.time_based_filter = qos.time_based_filter;
    self.ownership = qos.ownership;
    self.destination_order = qos.destination_order;
    self.presentation = qos.presentation;
  }

  pub fn qos(&self) -> QosPolicies {
    QosPolicies {
      durability: self.durability,
      presentation: self.presentation,
      deadline: self.deadline,
      latency_budget: self.latency_budget,
      ownership: self.ownership,
      liveliness: self.liveliness,
      time_based_filter: self.time_based_filter,
      reliability: self.reliability,
      destination_order: self.destination_order,
      history: None,         // PublicationBuiltinTopicData does not contain History QoS
      resource_limits: None, // nor Resource Limits, see Figure 8.30 in RTPS spec 2.5
      lifespan: self.lifespan,
      #[cfg(feature = "security")]
      property: None, // TODO: no property Qos?
    }
  }

  pub fn topic_name(&self) -> &String {
    &self.topic_name
  }

  pub fn to_topic_data(&self) -> TopicBuiltinTopicData {
    TopicBuiltinTopicData::new(
      None, // This would be topic GUID or BuiltinInTopicKey_t. What is it and who defines it?
      // According to various googled sources, it is either 3x u32 or 4x u32
      // or a GUID or a GuidPrefix. Does it even matter?
      // TODO: Find out.
      self.topic_name.clone(),
      self.type_name.clone(),
      &self.qos(),
    )
  }

  #[cfg(feature = "security")]
  pub fn security_info(&self) -> &Option<EndpointSecurityInfo> {
    &self.security_info
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredWriterData {
  pub last_updated: Instant, // last_updated is not serialized

  pub writer_proxy: WriterProxy,
  pub publication_topic_data: PublicationBuiltinTopicData,
}

impl Keyed for DiscoveredWriterData {
  type K = Endpoint_GUID;

  fn key(&self) -> Self::K {
    Endpoint_GUID(self.publication_topic_data.key)
  }
}

impl DiscoveredWriterData {
  pub fn new<D: Keyed, SA: SerializerAdapter<D>>(
    writer: &DataWriter<D, SA>,
    topic: &Topic,
    dp: &DomainParticipant,
    security_info: Option<EndpointSecurityInfo>,
  ) -> Self {
    let unicast_port = user_traffic_unicast_port(dp.domain_id(), dp.participant_id());
    let unicast_addresses = get_local_unicast_locators(unicast_port);
    // TODO: Why empty vector below? No multicast?
    let writer_proxy = WriterProxy::new(writer.guid(), vec![], unicast_addresses);
    let publication_topic_data = PublicationBuiltinTopicData::new_with_qos(
      writer.guid(),
      Some(dp.guid()),
      topic.name(),
      topic.get_type().name().to_string(),
      &writer.qos(),
      security_info,
    );

    Self {
      last_updated: Instant::now(),
      writer_proxy,
      publication_topic_data,
    }
  }
}

impl PlCdrDeserialize for DiscoveredWriterData {
  fn from_pl_cdr_bytes(
    input_bytes: &[u8],
    encoding: RepresentationIdentifier,
  ) -> Result<Self, PlCdrDeserializeError> {
    let ctx = pl_cdr_rep_id_to_speedy_d(encoding)?;
    let pl = ParameterList::read_from_buffer_with_ctx(ctx, input_bytes)?;
    let pl_map = pl.to_map();

    let guid: GUID = get_first_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_GUID,
      "Endpoint GUID",
    )?;
    let participant_guid: Option<GUID> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_PARTICIPANT_GUID,
      "Participant GUID",
    )?;

    let unicast_locator_list: Vec<Locator> = get_all_from_pl_map(
      &pl_map,
      &ctx,
      ParameterId::PID_UNICAST_LOCATOR,
      "unicast locators",
    )?;
    let multicast_locator_list: Vec<Locator> = get_all_from_pl_map(
      &pl_map,
      &ctx,
      ParameterId::PID_MULTICAST_LOCATOR,
      "multicast locators",
    )?;

    let topic_name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TOPIC_NAME, "topic name")?
      .into();
    let type_name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TYPE_NAME, "type name")?
      .into();

    let data_max_size_serialized: Option<u32> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_TYPE_MAX_SIZE_SERIALIZED,
      "Max size serialized",
    )?;

    #[cfg(feature = "security")]
    let security_info: Option<EndpointSecurityInfo> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_SECURITY_INFO,
      "endpoint security info",
    )?;

    #[cfg(not(feature = "security"))]
    let security_info: Option<EndpointSecurityInfo> = None;

    let qos = QosPolicies::from_parameter_list(ctx, &pl_map)?;

    Ok(DiscoveredWriterData {
      last_updated: Instant::now(),
      writer_proxy: WriterProxy {
        remote_writer_guid: guid,
        unicast_locator_list,
        multicast_locator_list,
        data_max_size_serialized,
      },
      publication_topic_data: PublicationBuiltinTopicData::new_with_qos(
        guid,
        participant_guid,
        topic_name,
        type_name,
        &qos,
        security_info,
      ),
    })
  }
}

impl PlCdrSerialize for DiscoveredWriterData {
  fn to_pl_cdr_bytes(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<Bytes, PlCdrSerializeError> {
    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;
    let pl = self.to_parameter_list(encoding)?;
    let bytes = pl.serialize_to_bytes(ctx)?;
    Ok(bytes)
  }
}

impl ParameterListable for DiscoveredWriterData {
  fn to_parameter_list(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<ParameterList, PlCdrSerializeError> {
    let DiscoveredWriterData {
      last_updated: _, // This is never serialized
      writer_proxy:
        WriterProxy {
          remote_writer_guid,
          unicast_locator_list,
          multicast_locator_list,
          data_max_size_serialized,
        },
      publication_topic_data:
        pbtd @ PublicationBuiltinTopicData {
          key,
          participant_key,
          topic_name,
          type_name,

          // QoS handled separately
          durability: _,
          deadline: _,
          latency_budget: _,
          liveliness: _,
          reliability: _,
          ownership: _,
          destination_order: _,
          time_based_filter: _,
          presentation: _,
          lifespan: _,

          service_instance_name,
          related_datareader_key,
          topic_aliases,
          #[cfg(feature = "security")]
          security_info,
        },
    } = self;

    let mut pl = ParameterList::new();
    let qos = pbtd.qos();

    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;

    macro_rules! emit {
      ($pid:ident, $member:expr, $type:ty) => {
        pl.push(Parameter::new(ParameterId::$pid, {
          let m: &$type = $member;
          m.write_to_vec_with_ctx(ctx)?
        }))
      };
    }
    macro_rules! emit_option {
      ($pid:ident, $member:expr, $type:ty) => {
        if let Some(m) = $member {
          emit!($pid, m, $type)
        }
      };
    }

    // ReaderProxy
    emit_option!(PID_TYPE_MAX_SIZE_SERIALIZED, data_max_size_serialized, u32);

    // Note that this GUID can be in two places
    emit!(PID_ENDPOINT_GUID, remote_writer_guid, GUID);
    if remote_writer_guid != key {
      // sanity check
      warn!("DiscoveredWriterData: Inconsistent GUID: {remote_writer_guid:?} vs {key:?}");
    }

    for loc in unicast_locator_list {
      emit!(
        PID_UNICAST_LOCATOR,
        &locator::repr::Locator::from(*loc),
        locator::repr::Locator
      );
    }
    for loc in multicast_locator_list {
      emit!(
        PID_MULTICAST_LOCATOR,
        &locator::repr::Locator::from(*loc),
        locator::repr::Locator
      );
    }

    // SubscriptionBuiltinTopicData
    emit_option!(PID_PARTICIPANT_GUID, participant_key, GUID);
    emit!(PID_TOPIC_NAME, &topic_name.clone().into(), StringWithNul);
    emit!(PID_TYPE_NAME, &type_name.clone().into(), StringWithNul);
    pl.parameters.append(&mut qos.to_parameter_list(ctx)?);
    emit_option!(
      PID_SERVICE_INSTANCE_NAME,
      &service_instance_name.clone().map(|e| e.into()),
      StringWithNul
    );
    emit_option!(PID_RELATED_ENTITY_GUID, related_datareader_key, GUID);
    // TODO: Should topic alias be on parameter with vector or multiple
    // parameters with one alias name each?
    for topic_alias in topic_aliases.as_ref().unwrap_or(&Vec::new()) {
      emit!(
        PID_TOPIC_ALIASES,
        &topic_alias.clone().into(),
        StringWithNul
      );
    }

    #[cfg(feature = "security")]
    emit_option!(
      PID_ENDPOINT_SECURITY_INFO,
      security_info,
      EndpointSecurityInfo
    );

    Ok(pl)
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

/// Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TopicBuiltinTopicData {
  pub key: Option<GUID>,
  pub name: String,
  pub type_name: String,
  pub durability: Option<Durability>,
  pub deadline: Option<Deadline>,
  pub latency_budget: Option<LatencyBudget>,
  pub liveliness: Option<Liveliness>,
  pub reliability: Option<Reliability>,
  pub lifespan: Option<Lifespan>,
  pub destination_order: Option<DestinationOrder>,
  pub presentation: Option<Presentation>,
  pub history: Option<History>,
  pub resource_limits: Option<ResourceLimits>,
  pub ownership: Option<Ownership>,
}

impl TopicBuiltinTopicData {
  pub fn new(key: Option<GUID>, name: String, type_name: String, qos: &QosPolicies) -> Self {
    Self {
      key,
      name,
      type_name,
      durability: qos.durability(),
      deadline: qos.deadline(),
      latency_budget: qos.latency_budget(),
      liveliness: qos.liveliness(),
      reliability: qos.reliability(),
      lifespan: qos.lifespan(),
      destination_order: qos.destination_order(),
      presentation: qos.presentation(),
      history: qos.history(),
      resource_limits: qos.resource_limits(),
      ownership: qos.ownership(),
    }
  }
}

impl HasQoSPolicy for TopicBuiltinTopicData {
  fn qos(&self) -> QosPolicies {
    QosPolicies {
      durability: self.durability,
      presentation: self.presentation,
      deadline: self.deadline,
      latency_budget: self.latency_budget,
      ownership: self.ownership,
      liveliness: self.liveliness,
      time_based_filter: None,
      reliability: self.reliability,
      destination_order: self.destination_order,
      history: self.history,
      resource_limits: self.resource_limits,
      lifespan: self.lifespan,
      #[cfg(feature = "security")]
      property: None, // TODO: no property Qos?
    }
  }
}

pub fn topics_inconsistent(t1: &TopicBuiltinTopicData, t2: &TopicBuiltinTopicData) -> bool {
  // We are not comparing Topic names, because consistency should only ever be
  // compared between descriptions of the same Topic.
  //
  // We are not comparing the key, becaues we have no idea what that even means.

  // Check for type name
  t1.type_name != t2.type_name

  // Check for QoS inconsistencies:

  // TODO: Is there any combination of Topic QoS settings that would make the
  // two definitions of the Topic definetely incompatible (inconsistent).
  // There are several QoS policies that must match between Reader and Writer,
  // but the spec seems to say nothing about Topics.
}

// =======================================================================
// =======================================================================
// =======================================================================

/// DDS Spec defined DiscoveredTopicData with extra updated time attribute.
///
/// Practically this is gotten from
/// [DomainParticipant](../participant/struct.DomainParticipant.html) during
/// runtime Type specified in RTPS v2.3 spec Figure 8.30
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DiscoveredTopicData {
  updated_time: DateTime<Utc>,
  pub topic_data: TopicBuiltinTopicData,
}

impl DiscoveredTopicData {
  pub fn new(updated_time: DateTime<Utc>, topic_data: TopicBuiltinTopicData) -> Self {
    Self {
      updated_time,
      topic_data,
    }
  }

  pub fn topic_name(&self) -> &String {
    &self.topic_data.name
  }

  pub fn type_name(&self) -> &String {
    &self.topic_data.type_name
  }
}

impl Keyed for DiscoveredTopicData {
  type K = Endpoint_GUID;

  fn key(&self) -> Self::K {
    Endpoint_GUID(match self.topic_data.key {
      Some(k) => k,
      None => GUID::GUID_UNKNOWN,
    })
  }
}

impl PlCdrDeserialize for DiscoveredTopicData {
  fn from_pl_cdr_bytes(
    input_bytes: &[u8],
    encoding: RepresentationIdentifier,
  ) -> Result<Self, PlCdrDeserializeError> {
    let ctx = pl_cdr_rep_id_to_speedy_d(encoding)?;
    let pl = ParameterList::read_from_buffer_with_ctx(ctx, input_bytes)?;
    let pl_map = pl.to_map();

    let key: Option<GUID> = get_option_from_pl_map(
      &pl_map,
      ctx,
      ParameterId::PID_ENDPOINT_GUID,
      "Endpoint GUID",
    )?;

    let name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TOPIC_NAME, "topic name")?
      .into();
    let type_name : String = // Note the serialized type is StringWithNul
      get_first_from_pl_map::< _ , StringWithNul>(&pl_map, ctx, ParameterId::PID_TYPE_NAME, "type name")?
      .into();

    let qos = QosPolicies::from_parameter_list(ctx, &pl_map)?;

    let topic_data = TopicBuiltinTopicData::new(key, name, type_name, &qos);

    Ok(DiscoveredTopicData {
      updated_time: Utc::now(),
      topic_data,
    })
  }
}

impl PlCdrSerialize for DiscoveredTopicData {
  fn to_pl_cdr_bytes(
    &self,
    encoding: RepresentationIdentifier,
  ) -> Result<Bytes, PlCdrSerializeError> {
    let DiscoveredTopicData {
      updated_time: _, // This is never serialized
      topic_data:
        td @ TopicBuiltinTopicData {
          key,
          name,
          type_name,

          // QoS handled separately
          durability: _,
          deadline: _,
          history: _,
          latency_budget: _,
          liveliness: _,
          reliability: _,
          ownership: _,
          destination_order: _,
          presentation: _,
          lifespan: _,
          resource_limits: _,
        },
    } = self;

    let mut pl = ParameterList::new();
    let qos = td.qos();

    let ctx = pl_cdr_rep_id_to_speedy(encoding)?;

    macro_rules! emit {
      ($pid:ident, $member:expr, $type:ty) => {
        pl.push(Parameter::new(ParameterId::$pid, {
          let m: &$type = $member;
          m.write_to_vec_with_ctx(ctx)?
        }))
      };
    }
    macro_rules! emit_option {
      ($pid:ident, $member:expr, $type:ty) => {
        if let Some(m) = $member {
          emit!($pid, m, $type)
        }
      };
    }

    // Also Topics have GUIDs, but apparently not mandatory?
    emit_option!(PID_ENDPOINT_GUID, key, GUID);
    emit!(PID_TOPIC_NAME, &name.clone().into(), StringWithNul);
    emit!(PID_TYPE_NAME, &type_name.clone().into(), StringWithNul);
    pl.parameters.append(&mut qos.to_parameter_list(ctx)?);

    let bytes = pl.serialize_to_bytes(ctx)?;
    Ok(bytes)
  }
}

// =======================================================================
// =======================================================================
// =======================================================================

#[derive(
  Copy, Clone, Debug, PartialOrd, PartialEq, Ord, Eq, Hash, Serialize, Deserialize, CdrEncodingSize,
)]
pub struct ParticipantMessageDataKind {
  value: [u8; 4],
}

impl ParticipantMessageDataKind {
  // This is defined in the spec, but currently unused.
  pub const UNKNOWN: Self = Self {
    value: [0x00, 0x00, 0x00, 0x00],
  };
  pub const AUTOMATIC_LIVELINESS_UPDATE: Self = Self {
    value: [0x00, 0x00, 0x00, 0x01],
  };
  pub const MANUAL_LIVELINESS_UPDATE: Self = Self {
    value: [0x00, 0x00, 0x00, 0x02],
  };
}

// =======================================================================
// =======================================================================
// =======================================================================

// This will be sent using ordinary CDR, not PL_CDR, so derive Serialize &
// Deserialize
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
pub struct ParticipantMessageData {
  pub guid: GuidPrefix,
  pub kind: ParticipantMessageDataKind,
  pub data: Vec<u8>, // normally this should be empty
}

impl Keyed for ParticipantMessageData {
  type K = ParticipantMessageDataKey;

  fn key(&self) -> Self::K {
    ParticipantMessageDataKey(self.guid, self.kind)
  }
}

#[derive(
  Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd, Serialize, Deserialize, CdrEncodingSize,
)]
pub struct ParticipantMessageDataKey(GuidPrefix, ParticipantMessageDataKind);

impl Key for ParticipantMessageDataKey {}

// =======================================================================
// =======================================================================
// =======================================================================

#[cfg(test)]
mod tests {
  use byteorder::LittleEndian;
  use log::info;
  use test_log::test; // to capture logging macros run by test cases

  use crate::{
    dds::adapters::no_key::{DeserializerAdapter, SerializerAdapter},
    rtps::Message,
    serialization::pl_cdr_adapters::*,
    test::test_data::{
      content_filter_data, publication_builtin_topic_data, reader_proxy_data,
      subscription_builtin_topic_data, topic_data, writer_proxy_data,
    },
  };
  use super::*;

  /* do not test separate ser/deser of components, as these are never seen on wire individually
    #[test]
    fn td_reader_proxy_ser_deser() {
      let reader_proxy = reader_proxy_data().unwrap();

      let sdata = to_bytes::<ReaderProxy, LittleEndian>(&reader_proxy).unwrap();
      let reader_proxy2: ReaderProxy =
        PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
      assert_eq!(reader_proxy, reader_proxy2);
      let sdata2 = to_bytes::<ReaderProxy, LittleEndian>(&reader_proxy2).unwrap();
      assert_eq!(sdata, sdata2);
    }

    #[test]
    fn td_writer_proxy_ser_deser() {
      let writer_proxy = writer_proxy_data().unwrap();

      let sdata = to_bytes::<WriterProxy, LittleEndian>(&writer_proxy).unwrap();
      let writer_proxy2: WriterProxy =
        PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
      assert_eq!(writer_proxy, writer_proxy2);
      let sdata2 = to_bytes::<WriterProxy, LittleEndian>(&writer_proxy2).unwrap();
      assert_eq!(sdata, sdata2);
    }

    #[test]
    fn td_subscription_builtin_topic_data_ser_deser() {
      let sub_topic_data = subscription_builtin_topic_data().unwrap();

      let sdata = to_bytes::<SubscriptionBuiltinTopicData, LittleEndian>(&sub_topic_data).unwrap();
      let sub_topic_data2: SubscriptionBuiltinTopicData =
        PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
      assert_eq!(sub_topic_data, sub_topic_data2);
      let sdata2 = to_bytes::<SubscriptionBuiltinTopicData, LittleEndian>(&sub_topic_data2).unwrap();
      assert_eq!(sdata, sdata2);
    }

    #[test]
    fn td_publication_builtin_topic_data_ser_deser() {
      let pub_topic_data = publication_builtin_topic_data().unwrap();

      let sdata = to_bytes::<PublicationBuiltinTopicData, LittleEndian>(&pub_topic_data).unwrap();
      let pub_topic_data2: PublicationBuiltinTopicData =
        PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
      assert_eq!(pub_topic_data, pub_topic_data2);
      let sdata2 = to_bytes::<PublicationBuiltinTopicData, LittleEndian>(&pub_topic_data2).unwrap();
      assert_eq!(sdata, sdata2);
    }
  */
  #[test]
  fn td_discovered_reader_data_ser_deser() {
    let mut reader_proxy = reader_proxy_data().unwrap();
    let sub_topic_data = subscription_builtin_topic_data().unwrap();
    reader_proxy.remote_reader_guid = sub_topic_data.key;
    let content_filter = content_filter_data().unwrap();

    let drd = DiscoveredReaderData {
      reader_proxy,
      subscription_topic_data: sub_topic_data,
      content_filter: Some(content_filter),
    };

    // serialize
    let sdata = drd
      .to_pl_cdr_bytes(RepresentationIdentifier::PL_CDR_LE)
      .unwrap();
    info!("td_discovered_reader_data_ser_deser serialized data is {sdata:x?}");
    // deserialize back
    let drd2: DiscoveredReaderData =
      PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE)
        .unwrap_or_else(|e| {
          println!("DiscoveredReaderData deserialize fail: {e:?}");
          panic!();
        });

    // check objects are equal
    assert_eq!(drd, drd2);
    let sdata2 =
      PlCdrSerializerAdapter::<DiscoveredReaderData, LittleEndian>::to_bytes(&drd2).unwrap();
    assert_eq!(sdata, sdata2);

    let raw_data = Bytes::from_static(&[
      0x52, 0x54, 0x50, 0x53, 0x02, 0x03, 0x00, 0x00, 0x39, 0xbc, 0xd6, 0xb1, 0x4f, 0xa2, 0x49,
      0x72, 0x81, 0x7d, 0xd4, 0x54, 0x09, 0x01, 0x08, 0x00, 0xa8, 0x3b, 0x56, 0x5f, 0xfa, 0xa6,
      0xa9, 0x75, 0x15, 0x05, 0xdc, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x04, 0xc7, 0x00,
      0x00, 0x04, 0xc2, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
      0x43, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x00, 0x10, 0x00, 0x39, 0xbc, 0xd6,
      0xb1, 0x4f, 0xa2, 0x49, 0x72, 0x81, 0x7d, 0xd4, 0x54, 0x00, 0x00, 0x01, 0xc1, 0x5a, 0x00,
      0x10, 0x00, 0x39, 0xbc, 0xd6, 0xb1, 0x4f, 0xa2, 0x49, 0x72, 0x81, 0x7d, 0xd4, 0x54, 0x4f,
      0xe7, 0xe7, 0x07, 0x2f, 0x00, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0xfd, 0x1c, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x50, 0x8e,
      0xc9, 0x2f, 0x00, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0xfd, 0x1c, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xa8, 0x45, 0x14, 0x2f,
      0x00, 0x18, 0x00, 0x01, 0x00, 0x00, 0x00, 0xfd, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xac, 0x11, 0x00, 0x01, 0x30, 0x00, 0x18,
      0x00, 0x01, 0x00, 0x00, 0x00, 0xe9, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xef, 0xff, 0x00, 0x01, 0x05, 0x00, 0x0c, 0x00, 0x07,
      0x00, 0x00, 0x00, 0x53, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x00, 0x07, 0x00, 0x0c, 0x00,
      0x07, 0x00, 0x00, 0x00, 0x53, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x00, 0x01, 0x00, 0x00,
      0x00,
    ]);

    let msg = Message::read_from_buffer(&raw_data).unwrap();
    info!("{msg:?}");
  }

  #[test]
  fn td_discovered_writer_data_ser_deser() {
    let mut writer_proxy = writer_proxy_data().unwrap();
    let pub_topic_data = publication_builtin_topic_data().unwrap();
    writer_proxy.remote_writer_guid = pub_topic_data.key;

    let dwd = DiscoveredWriterData {
      last_updated: Instant::now(),
      writer_proxy,
      publication_topic_data: pub_topic_data,
    };

    let sdata = dwd
      .to_pl_cdr_bytes(RepresentationIdentifier::PL_CDR_LE)
      .unwrap();
    let mut dwd2: DiscoveredWriterData =
      PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
    // last updated is not serialized thus copying value for correct result
    dwd2.last_updated = dwd.last_updated;

    info!("td_discovered_writer_data_ser_deser serialized data is {sdata:x?}");

    assert_eq!(dwd, dwd2);
    let sdata2 =
      PlCdrSerializerAdapter::<DiscoveredWriterData, LittleEndian>::to_bytes(&dwd2).unwrap();
    assert_eq!(sdata, sdata2);
  }

  // Do not test ser/deser. This is never seen on the wire out of
  // DiscoveredTopicData #[test]
  // fn td_topic_data_ser_deser() {
  //   let topic_data = topic_data().unwrap();

  //   let sdata = to_bytes::<TopicBuiltinTopicData,
  // LittleEndian>(&topic_data).unwrap();   let topic_data2:
  // TopicBuiltinTopicData =     PlCdrDeserializerAdapter::from_bytes(&sdata,
  // RepresentationIdentifier::PL_CDR_LE).unwrap();   assert_eq!(topic_data,
  // topic_data2);   let sdata2 = to_bytes::<TopicBuiltinTopicData,
  // LittleEndian>(&topic_data2).unwrap();   assert_eq!(sdata, sdata2);
  // }

  #[test]
  fn td_discovered_topic_data_ser_deser() {
    let topic_data = topic_data().unwrap();

    let dtd = DiscoveredTopicData::new(Utc::now(), topic_data);

    let sdata = dtd
      .to_pl_cdr_bytes(RepresentationIdentifier::PL_CDR_LE)
      .unwrap();
    let dtd2: DiscoveredTopicData =
      PlCdrDeserializerAdapter::from_bytes(&sdata, RepresentationIdentifier::PL_CDR_LE).unwrap();
    assert_eq!(dtd.topic_data, dtd2.topic_data);
    let sdata2 =
      PlCdrSerializerAdapter::<DiscoveredTopicData, LittleEndian>::to_bytes(&dtd2).unwrap();
    assert_eq!(sdata, sdata2);
  }

  // TODO: somehow get some actual bytes of ParticipantMessageData
  // #[test]
  // fn td_participant_message_data_ser_deser() {
  //   let mut pmd_file = File::open("participant_message_data.bin").unwrap();
  //   let mut buffer: [u8; 1024] = [0; 1024];
  //   let _len = pmd_file.read(&mut buffer).unwrap();

  //   let rpi = CDRDeserializerAdapter::<ParticipantMessageData>::from_bytes(
  //     &buffer,
  //     RepresentationIdentifier::CDR_LE,
  //   )
  //   .unwrap();

  //   let _data2 = to_bytes::<ParticipantMessageData,
  // LittleEndian>(&rpi).unwrap(); }
}