cyclonedds 1.2.0

Safe Rust wrapper for Eclipse CycloneDDS
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
use crate::{
    error::check,
    qos::Qos,
    xtypes::{FindScope, TopicDescriptor, TypeInfo, TypeObject},
    DdsError, DdsResult, DdsType, UntypedTopic,
};
use cyclonedds_rust_sys::*;
use std::ffi::{c_char, CStr};

pub const DDS_MIN_PSEUDO_HANDLE: dds_entity_t = 0x7fff0000u32 as dds_entity_t;
pub const BUILTIN_TOPIC_DCPSPARTICIPANT: dds_entity_t = DDS_MIN_PSEUDO_HANDLE + 1;
pub const BUILTIN_TOPIC_DCPSTOPIC: dds_entity_t = DDS_MIN_PSEUDO_HANDLE + 2;
pub const BUILTIN_TOPIC_DCPSPUBLICATION: dds_entity_t = DDS_MIN_PSEUDO_HANDLE + 3;
pub const BUILTIN_TOPIC_DCPSSUBSCRIPTION: dds_entity_t = DDS_MIN_PSEUDO_HANDLE + 4;

fn dup_cstr(ptr: *const c_char) -> *mut c_char {
    if ptr.is_null() {
        std::ptr::null_mut()
    } else {
        unsafe { dds_string_dup(ptr) }
    }
}

#[repr(C)]
pub struct BuiltinParticipantSample {
    key: dds_guid_t,
    qos: *mut dds_qos_t,
}

unsafe impl Send for BuiltinParticipantSample {}

impl BuiltinParticipantSample {
    pub fn key(&self) -> dds_guid_t {
        self.key
    }

    pub fn qos(&self) -> DdsResult<Option<Qos>> {
        Qos::from_raw_clone(self.qos)
    }

    /// Returns the participant name if set (via the QoS entity_name policy).
    ///
    /// In CycloneDDS, the participant name is not a direct field of
    /// `dds_builtintopic_participant_t` but is carried as the entity name
    /// in the participant's QoS.
    pub fn participant_name(&self) -> Option<String> {
        self.qos()
            .ok()
            .flatten()
            .and_then(|q| q.entity_name().ok().flatten())
    }
}

impl Clone for BuiltinParticipantSample {
    fn clone(&self) -> Self {
        Self {
            key: self.key,
            qos: Qos::from_raw_clone(self.qos)
                .ok()
                .flatten()
                .map_or(std::ptr::null_mut(), |q| {
                    let ptr = q.as_ptr() as *mut dds_qos_t;
                    std::mem::forget(q);
                    ptr
                }),
        }
    }
}

impl Drop for BuiltinParticipantSample {
    fn drop(&mut self) {
        if !self.qos.is_null() {
            unsafe { dds_delete_qos(self.qos) };
        }
    }
}

impl DdsType for BuiltinParticipantSample {
    fn type_name() -> &'static str {
        "DCPSParticipant"
    }

    fn ops() -> Vec<u32> {
        Vec::new()
    }

    unsafe fn clone_out(ptr: *const Self) -> Self {
        let src = &*ptr;
        src.clone()
    }
}

#[repr(C)]
pub struct BuiltinTopicSample {
    key: dds_builtintopic_topic_key_t,
    topic_name: *mut c_char,
    type_name: *mut c_char,
    qos: *mut dds_qos_t,
}

unsafe impl Send for BuiltinTopicSample {}

impl BuiltinTopicSample {
    pub fn key(&self) -> dds_builtintopic_topic_key_t {
        self.key
    }

    pub fn topic_name(&self) -> String {
        if self.topic_name.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(self.topic_name) }
                .to_string_lossy()
                .into_owned()
        }
    }

    pub fn type_name_value(&self) -> String {
        if self.type_name.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(self.type_name) }
                .to_string_lossy()
                .into_owned()
        }
    }

    pub fn qos(&self) -> DdsResult<Option<Qos>> {
        Qos::from_raw_clone(self.qos)
    }

    pub fn find_topic(
        &self,
        participant: dds_entity_t,
        scope: FindScope,
        timeout: dds_duration_t,
    ) -> DdsResult<Option<UntypedTopic>> {
        let name = std::ffi::CString::new(self.topic_name())
            .map_err(|_| DdsError::BadParameter("topic name contains null".into()))?;
        let handle = unsafe {
            dds_find_topic(
                scope.as_raw(),
                participant,
                name.as_ptr(),
                std::ptr::null(),
                timeout,
            )
        };
        if handle == 0 {
            return Ok(None);
        }
        crate::error::check_entity(handle).map(|entity| Some(UntypedTopic::from_entity(entity)))
    }
}

impl Clone for BuiltinTopicSample {
    fn clone(&self) -> Self {
        Self {
            key: self.key,
            topic_name: dup_cstr(self.topic_name),
            type_name: dup_cstr(self.type_name),
            qos: Qos::from_raw_clone(self.qos)
                .ok()
                .flatten()
                .map_or(std::ptr::null_mut(), |q| {
                    let ptr = q.as_ptr() as *mut dds_qos_t;
                    std::mem::forget(q);
                    ptr
                }),
        }
    }
}

impl Drop for BuiltinTopicSample {
    fn drop(&mut self) {
        if !self.topic_name.is_null() {
            unsafe { dds_string_free(self.topic_name) };
        }
        if !self.type_name.is_null() {
            unsafe { dds_string_free(self.type_name) };
        }
        if !self.qos.is_null() {
            unsafe { dds_delete_qos(self.qos) };
        }
    }
}

impl DdsType for BuiltinTopicSample {
    fn type_name() -> &'static str {
        "DCPSTopic"
    }

    fn ops() -> Vec<u32> {
        Vec::new()
    }

    unsafe fn clone_out(ptr: *const Self) -> Self {
        let src = &*ptr;
        src.clone()
    }
}

impl std::fmt::Debug for BuiltinParticipantSample {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuiltinParticipantSample")
            .field("key", &self.key)
            .field("participant_name", &self.participant_name())
            .finish()
    }
}

impl std::fmt::Debug for BuiltinTopicSample {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuiltinTopicSample")
            .field("topic_name", &self.topic_name())
            .field("type_name", &self.type_name_value())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::CString;

    #[test]
    fn builtin_topic_sample_clone_preserves_strings_and_qos() {
        let qos = Qos::builder()
            .reliable()
            .entity_name("builtin-topic")
            .build()
            .unwrap();
        let topic_name = CString::new("topic-a").unwrap();
        let type_name = CString::new("type-a").unwrap();

        let sample = BuiltinTopicSample {
            key: dds_builtintopic_topic_key_t { d: [1; 16] },
            topic_name: unsafe { dds_string_dup(topic_name.as_ptr()) },
            type_name: unsafe { dds_string_dup(type_name.as_ptr()) },
            qos: {
                let ptr = qos.as_ptr() as *mut dds_qos_t;
                std::mem::forget(qos);
                ptr
            },
        };

        let cloned = sample.clone();
        assert_eq!(cloned.topic_name(), "topic-a");
        assert_eq!(cloned.type_name_value(), "type-a");
        let cloned_qos = cloned.qos().unwrap().unwrap();
        assert_eq!(cloned_qos.entity_name().unwrap().unwrap(), "builtin-topic");
    }

    #[test]
    fn builtin_participant_sample_clone_preserves_qos() {
        let qos = Qos::builder()
            .entity_name("builtin-participant")
            .build()
            .unwrap();
        let sample = BuiltinParticipantSample {
            key: dds_guid_t { v: [9; 16] },
            qos: {
                let ptr = qos.as_ptr() as *mut dds_qos_t;
                std::mem::forget(qos);
                ptr
            },
        };

        let cloned = sample.clone();
        let cloned_qos = cloned.qos().unwrap().unwrap();
        assert_eq!(
            cloned_qos.entity_name().unwrap().unwrap(),
            "builtin-participant"
        );
        assert_eq!(cloned.key().v, [9; 16]);
    }
}

#[repr(C)]
pub struct BuiltinEndpointSample {
    key: dds_guid_t,
    participant_key: dds_guid_t,
    participant_instance_handle: dds_instance_handle_t,
    topic_name: *mut c_char,
    type_name: *mut c_char,
    qos: *mut dds_qos_t,
}

unsafe impl Send for BuiltinEndpointSample {}

impl BuiltinEndpointSample {
    fn as_native_ptr(&self) -> *mut dds_builtintopic_endpoint_t {
        self as *const Self as *mut dds_builtintopic_endpoint_t
    }

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

    pub fn participant_key(&self) -> dds_guid_t {
        self.participant_key
    }

    pub fn participant_instance_handle(&self) -> dds_instance_handle_t {
        self.participant_instance_handle
    }

    pub fn topic_name(&self) -> String {
        if self.topic_name.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(self.topic_name) }
                .to_string_lossy()
                .into_owned()
        }
    }

    pub fn type_name_value(&self) -> String {
        if self.type_name.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(self.type_name) }
                .to_string_lossy()
                .into_owned()
        }
    }

    /// Alias for [`type_name_value()`](Self::type_name_value) for ergonomic API
    /// consistency with the cyclonedds-python binding.
    pub fn type_name(&self) -> String {
        self.type_name_value()
    }

    pub fn qos(&self) -> DdsResult<Option<Qos>> {
        Qos::from_raw_clone(self.qos)
    }

    pub fn type_info(&self) -> DdsResult<TypeInfo> {
        let mut ptr = std::ptr::null();
        unsafe {
            check(dds_builtintopic_get_endpoint_type_info(
                self.as_native_ptr(),
                &mut ptr,
            ))?;
        }
        if ptr.is_null() {
            return Err(DdsError::Other(
                "CycloneDDS returned null endpoint typeinfo".into(),
            ));
        }
        Ok(TypeInfo::from_raw(ptr.cast_mut()))
    }

    pub fn create_topic_descriptor(
        &self,
        participant: dds_entity_t,
        scope: FindScope,
        timeout: dds_duration_t,
    ) -> DdsResult<TopicDescriptor> {
        self.type_info()?
            .create_topic_descriptor(participant, scope, timeout)
    }

    pub fn create_topic(
        &self,
        participant: dds_entity_t,
        scope: FindScope,
        timeout: dds_duration_t,
    ) -> DdsResult<UntypedTopic> {
        let descriptor = self.create_topic_descriptor(participant, scope, timeout)?;
        descriptor.create_topic(participant, &self.topic_name())
    }

    pub fn create_topic_with_qos(
        &self,
        participant: dds_entity_t,
        scope: FindScope,
        timeout: dds_duration_t,
        qos: &Qos,
    ) -> DdsResult<UntypedTopic> {
        let descriptor = self.create_topic_descriptor(participant, scope, timeout)?;
        descriptor.create_topic_with_qos(participant, &self.topic_name(), qos)
    }

    pub fn find_topic(
        &self,
        participant: dds_entity_t,
        scope: FindScope,
        timeout: dds_duration_t,
    ) -> DdsResult<Option<UntypedTopic>> {
        let type_info = self.type_info()?;
        let name = std::ffi::CString::new(self.topic_name())
            .map_err(|_| DdsError::BadParameter("topic name contains null".into()))?;
        let handle = unsafe {
            dds_find_topic(
                scope.as_raw(),
                participant,
                name.as_ptr(),
                type_info.as_ptr(),
                timeout,
            )
        };
        if handle == 0 {
            return Ok(None);
        }
        crate::error::check_entity(handle).map(|entity| Some(UntypedTopic::from_entity(entity)))
    }

    pub fn minimal_type_object(
        &self,
        participant: dds_entity_t,
        timeout: dds_duration_t,
    ) -> DdsResult<Option<TypeObject>> {
        self.type_info()?.minimal_type_object(participant, timeout)
    }

    pub fn complete_type_object(
        &self,
        participant: dds_entity_t,
        timeout: dds_duration_t,
    ) -> DdsResult<Option<TypeObject>> {
        self.type_info()?.complete_type_object(participant, timeout)
    }
}

impl Clone for BuiltinEndpointSample {
    fn clone(&self) -> Self {
        Self {
            key: self.key,
            participant_key: self.participant_key,
            participant_instance_handle: self.participant_instance_handle,
            topic_name: dup_cstr(self.topic_name),
            type_name: dup_cstr(self.type_name),
            qos: Qos::from_raw_clone(self.qos)
                .ok()
                .flatten()
                .map_or(std::ptr::null_mut(), |q| {
                    let ptr = q.as_ptr() as *mut dds_qos_t;
                    std::mem::forget(q);
                    ptr
                }),
        }
    }
}

impl Drop for BuiltinEndpointSample {
    fn drop(&mut self) {
        if !self.topic_name.is_null() {
            unsafe { dds_string_free(self.topic_name) };
        }
        if !self.type_name.is_null() {
            unsafe { dds_string_free(self.type_name) };
        }
        if !self.qos.is_null() {
            unsafe { dds_delete_qos(self.qos) };
        }
    }
}

impl DdsType for BuiltinEndpointSample {
    fn type_name() -> &'static str {
        "BuiltinEndpointSample"
    }

    fn ops() -> Vec<u32> {
        Vec::new()
    }

    unsafe fn clone_out(ptr: *const Self) -> Self {
        let src = &*ptr;
        src.clone()
    }
}

impl std::fmt::Debug for BuiltinEndpointSample {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuiltinEndpointSample")
            .field("topic_name", &self.topic_name())
            .field("type_name", &self.type_name_value())
            .finish()
    }
}

#[cfg(test)]
mod endpoint_tests {
    use super::*;
    use std::ffi::CString;

    #[test]
    fn builtin_endpoint_sample_clone_preserves_strings_and_qos() {
        let qos = Qos::builder()
            .reliable()
            .entity_name("builtin-endpoint")
            .build()
            .unwrap();
        let topic_name = CString::new("topic-endpoint").unwrap();
        let type_name = CString::new("type-endpoint").unwrap();

        let sample = BuiltinEndpointSample {
            key: dds_guid_t { v: [1; 16] },
            participant_key: dds_guid_t { v: [2; 16] },
            participant_instance_handle: 42,
            topic_name: unsafe { dds_string_dup(topic_name.as_ptr()) },
            type_name: unsafe { dds_string_dup(type_name.as_ptr()) },
            qos: {
                let ptr = qos.as_ptr() as *mut dds_qos_t;
                std::mem::forget(qos);
                ptr
            },
        };

        let cloned = sample.clone();
        assert_eq!(cloned.topic_name(), "topic-endpoint");
        assert_eq!(cloned.type_name_value(), "type-endpoint");
        assert_eq!(cloned.participant_instance_handle(), 42);
        let cloned_qos = cloned.qos().unwrap().unwrap();
        assert_eq!(
            cloned_qos.entity_name().unwrap().unwrap(),
            "builtin-endpoint"
        );
    }
}