Skip to main content

rustorb_dds_ffi/
entity.rs

1//! The DCPS entities (`rdds_participant`, `rdds_topic`,
2//! `rdds_publisher`, `rdds_subscriber`, `rdds_writer`, `rdds_reader`),
3//! their QoS, statuses and listeners, and the samples a reader returns
4//! (`rdds_samples`).
5
6use std::ffi::{c_char, c_void};
7use std::time::Duration;
8
9use rustorb_dds::{
10    ContentFilteredTopic, DataReader, DataReaderListener, DataReaderQos, DataWriter,
11    DataWriterListener, DataWriterQos, DeadlineMissedStatus, DomainParticipant, DurabilityKind,
12    DurabilityService, DynamicData, DynamicType, Guid, History, IncompatibleQosStatus,
13    InconsistentTopicStatus, InstanceHandle, InstanceState, InstanceStateMask, Liveliness,
14    LivelinessChangedStatus, LivelinessKind, LivelinessLostStatus, MatchedStatus,
15    ParticipantConfig, Publisher, PublisherQos, Reliability, ReliabilityKind, ResourceLimits,
16    Sample, SampleLostStatus, SampleRejectedReason, SampleRejectedStatus, SampleState,
17    SampleStateMask, StateFilter, StatusMask, Subscriber, SubscriberQos, Time, Topic,
18    TypeConsistency, TypeConsistencyKind, ViewState, ViewStateMask, data_representation,
19};
20
21use crate::condition::RddsCondition;
22use crate::stream::{In, Out, from_data, to_data};
23use crate::{Res, Status, TIMEOUT, bad, cstr, guard, guard_value, obj, put, release, set, slice};
24
25// ---------- plain values --------------------------------------------------
26
27/// `rdds_duration` (DDS `Duration_t`).
28#[repr(C)]
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct RddsDuration {
31    pub sec: i32,
32    pub nanosec: u32,
33}
34
35/// `DURATION_INFINITE_SEC` and `DURATION_INFINITE_NSEC`.
36pub const DURATION_INFINITE: RddsDuration = RddsDuration {
37    sec: 0x7fff_ffff,
38    nanosec: 0x7fff_ffff,
39};
40
41impl RddsDuration {
42    fn to_std(self) -> Res<Option<Duration>> {
43        if self == DURATION_INFINITE {
44            return Ok(None);
45        }
46        if self.sec < 0 || self.nanosec >= 1_000_000_000 {
47            return Err(bad("a duration out of range"));
48        }
49        Ok(Some(Duration::new(self.sec as u64, self.nanosec)))
50    }
51
52    pub(crate) fn finite(self) -> Res<Duration> {
53        // An infinite wait is as long as anybody waits.
54        Ok(self
55            .to_std()?
56            .unwrap_or(Duration::from_secs(u32::MAX.into())))
57    }
58
59    fn of(d: Option<Duration>) -> RddsDuration {
60        match d {
61            None => DURATION_INFINITE,
62            Some(d) => RddsDuration {
63                sec: d.as_secs().min(0x7fff_fffe) as i32,
64                nanosec: d.subsec_nanos(),
65            },
66        }
67    }
68}
69
70/// `rdds_time` (DDS `Time_t`): since 1970.
71#[repr(C)]
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct RddsTime {
74    pub sec: i32,
75    pub nanosec: u32,
76}
77
78/// `TIME_INVALID`.
79pub const TIME_INVALID: RddsTime = RddsTime {
80    sec: -1,
81    nanosec: 0xffff_ffff,
82};
83
84impl RddsTime {
85    fn to_rtps(self) -> Res<Time> {
86        if self.sec < 0 || self.nanosec >= 1_000_000_000 {
87            return Err(bad("a timestamp out of range"));
88        }
89        Ok(Time {
90            seconds: self.sec as u32,
91            fraction: ((u64::from(self.nanosec) << 32) / 1_000_000_000) as u32,
92        })
93    }
94
95    fn of(t: Option<Time>) -> RddsTime {
96        match t {
97            None => TIME_INVALID,
98            Some(t) => RddsTime {
99                sec: t.seconds.min(0x7fff_ffff) as i32,
100                // Rounded up, so that a time to_rtps made comes back
101                // to the same nanosecond.
102                nanosec: (((u64::from(t.fraction) * 1_000_000_000) + 0xffff_ffff) >> 32)
103                    .min(999_999_999) as u32,
104            },
105        }
106    }
107}
108
109unsafe fn timestamp(t: *const RddsTime) -> Res<Time> {
110    match unsafe { t.as_ref() } {
111        None => Ok(Time::now()),
112        Some(t) => t.to_rtps(),
113    }
114}
115
116/// `rdds_guid`.
117#[repr(C)]
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119pub struct RddsGuid {
120    pub value: [u8; 16],
121}
122
123impl RddsGuid {
124    pub(crate) fn of(g: Option<Guid>) -> RddsGuid {
125        RddsGuid {
126            value: g.map_or([0; 16], Guid::to_bytes),
127        }
128    }
129}
130
131/// `rdds_instance_handle`: zeros for `HANDLE_NIL`.
132#[repr(C)]
133#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub struct RddsInstanceHandle {
135    pub value: [u8; 16],
136}
137
138impl RddsInstanceHandle {
139    fn of(h: Option<InstanceHandle>) -> RddsInstanceHandle {
140        RddsInstanceHandle {
141            value: h.map_or([0; 16], |h| h.0),
142        }
143    }
144}
145
146// ---------- QoS -----------------------------------------------------------
147
148/// `RDDS_LENGTH_UNLIMITED`.
149pub const LENGTH_UNLIMITED: i32 = -1;
150
151/// `rdds_writer_qos`.
152#[repr(C)]
153#[derive(Debug, Clone, Copy)]
154pub struct RddsWriterQos {
155    /// `RDDS_BEST_EFFORT_RELIABILITY_QOS` (0) or
156    /// `RDDS_RELIABLE_RELIABILITY_QOS` (1).
157    pub reliability_kind: i32,
158    pub max_blocking_time: RddsDuration,
159    /// `RDDS_KEEP_LAST_HISTORY_QOS` (0) or `RDDS_KEEP_ALL_HISTORY_QOS` (1).
160    pub history_kind: i32,
161    pub history_depth: i32,
162    pub max_samples: i32,
163    pub max_instances: i32,
164    pub max_samples_per_instance: i32,
165    /// `RDDS_VOLATILE_DURABILITY_QOS` (0) ... `RDDS_PERSISTENT_DURABILITY_QOS` (3).
166    pub durability_kind: i32,
167    pub deadline_period: RddsDuration,
168    /// `RDDS_AUTOMATIC_LIVELINESS_QOS` (0) ... `RDDS_MANUAL_BY_TOPIC_LIVELINESS_QOS` (2).
169    pub liveliness_kind: i32,
170    pub lease_duration: RddsDuration,
171    pub user_data: *const u8,
172    pub user_data_len: usize,
173    /// Data representation ids (`XCDR_DATA_REPRESENTATION` 0,
174    /// `XCDR2_DATA_REPRESENTATION` 2); the first is written. None for
175    /// the default (XCDR).
176    pub data_representation: *const i16,
177    pub data_representation_len: usize,
178    pub autodispose_unregistered_instances: bool,
179    /// DURABILITY_SERVICE, of a TRANSIENT or PERSISTENT writer.
180    pub service_cleanup_delay: RddsDuration,
181    pub service_history_kind: i32,
182    pub service_history_depth: i32,
183    pub service_max_samples: i32,
184    pub service_max_instances: i32,
185    pub service_max_samples_per_instance: i32,
186}
187
188/// `rdds_reader_qos`.
189#[repr(C)]
190#[derive(Debug, Clone, Copy)]
191pub struct RddsReaderQos {
192    pub reliability_kind: i32,
193    pub max_blocking_time: RddsDuration,
194    pub history_kind: i32,
195    pub history_depth: i32,
196    pub max_samples: i32,
197    pub max_instances: i32,
198    pub max_samples_per_instance: i32,
199    pub durability_kind: i32,
200    pub deadline_period: RddsDuration,
201    pub liveliness_kind: i32,
202    pub lease_duration: RddsDuration,
203    pub user_data: *const u8,
204    pub user_data_len: usize,
205    pub data_representation: *const i16,
206    pub data_representation_len: usize,
207    /// `RDDS_DISALLOW_TYPE_COERCION` (0) or `RDDS_ALLOW_TYPE_COERCION` (1).
208    pub type_consistency_kind: i32,
209    pub ignore_sequence_bounds: bool,
210    pub ignore_string_bounds: bool,
211    pub ignore_member_names: bool,
212    pub prevent_type_widening: bool,
213    pub force_type_validation: bool,
214}
215
216/// `rdds_publisher_qos` and `rdds_subscriber_qos`: the PARTITION names.
217#[repr(C)]
218#[derive(Debug, Clone, Copy)]
219pub struct RddsGroupQos {
220    pub partition: *const *const c_char,
221    pub partition_len: usize,
222}
223
224/// `rdds_participant_qos`.
225#[repr(C)]
226#[derive(Debug, Clone, Copy)]
227pub struct RddsParticipantQos {
228    pub user_data: *const u8,
229    pub user_data_len: usize,
230    pub property: *const RddsProperty,
231    pub property_len: usize,
232}
233
234/// `rdds_property`.
235#[repr(C)]
236#[derive(Debug, Clone, Copy)]
237pub struct RddsProperty {
238    pub name: *const c_char,
239    pub value: *const c_char,
240}
241
242static XCDR_BOTH: [i16; 2] = [data_representation::XCDR, data_representation::XCDR2];
243
244struct Common {
245    reliability: Reliability,
246    history: History,
247    resource_limits: ResourceLimits,
248    durability: DurabilityKind,
249    deadline: Option<Duration>,
250    liveliness: Liveliness,
251    user_data: Vec<u8>,
252    data_representation: Vec<i16>,
253}
254
255fn limit(v: i32) -> Res<Option<usize>> {
256    match v {
257        LENGTH_UNLIMITED => Ok(None),
258        v if v > 0 => Ok(Some(v as usize)),
259        _ => Err(bad(format!("a resource limit of {v}"))),
260    }
261}
262
263fn unlimited(v: Option<usize>) -> i32 {
264    v.map_or(LENGTH_UNLIMITED, |v| v.min(i32::MAX as usize) as i32)
265}
266
267fn history(kind: i32, depth: i32) -> Res<History> {
268    match kind {
269        0 if depth > 0 => Ok(History::KeepLast(depth as usize)),
270        0 => Err(bad("a KEEP_LAST history of depth below 1")),
271        1 => Ok(History::KeepAll),
272        k => Err(bad(format!("unknown history kind {k}"))),
273    }
274}
275
276#[allow(clippy::too_many_arguments)]
277unsafe fn common(
278    reliability_kind: i32,
279    max_blocking_time: RddsDuration,
280    history_kind: i32,
281    history_depth: i32,
282    limits: [i32; 3],
283    durability_kind: i32,
284    deadline: RddsDuration,
285    liveliness_kind: i32,
286    lease_duration: RddsDuration,
287    user_data: (*const u8, usize),
288    representation: (*const i16, usize),
289) -> Res<Common> {
290    let kind = match reliability_kind {
291        0 => ReliabilityKind::BestEffort,
292        1 => ReliabilityKind::Reliable,
293        k => return Err(bad(format!("unknown reliability kind {k}"))),
294    };
295    let reliability = Reliability {
296        kind,
297        max_blocking_time: max_blocking_time.finite()?,
298    };
299    let history = history(history_kind, history_depth)?;
300    let durability = match durability_kind {
301        0 => DurabilityKind::Volatile,
302        1 => DurabilityKind::TransientLocal,
303        2 => DurabilityKind::Transient,
304        3 => DurabilityKind::Persistent,
305        k => return Err(bad(format!("unknown durability kind {k}"))),
306    };
307    let kind = match liveliness_kind {
308        0 => LivelinessKind::Automatic,
309        1 => LivelinessKind::ManualByParticipant,
310        2 => LivelinessKind::ManualByTopic,
311        k => return Err(bad(format!("unknown liveliness kind {k}"))),
312    };
313    Ok(Common {
314        reliability,
315        history,
316        resource_limits: ResourceLimits {
317            max_samples: limit(limits[0])?,
318            max_instances: limit(limits[1])?,
319            max_samples_per_instance: limit(limits[2])?,
320        },
321        durability,
322        deadline: deadline.to_std()?,
323        liveliness: Liveliness {
324            kind,
325            lease_duration: lease_duration.to_std()?,
326        },
327        user_data: unsafe { slice(user_data.0, user_data.1) }?.to_vec(),
328        data_representation: unsafe { slice(representation.0, representation.1) }?.to_vec(),
329    })
330}
331
332pub(crate) unsafe fn writer_qos(q: *const RddsWriterQos) -> Res<DataWriterQos> {
333    let Some(q) = (unsafe { q.as_ref() }) else {
334        return Ok(DataWriterQos::default());
335    };
336    let c = unsafe {
337        common(
338            q.reliability_kind,
339            q.max_blocking_time,
340            q.history_kind,
341            q.history_depth,
342            [q.max_samples, q.max_instances, q.max_samples_per_instance],
343            q.durability_kind,
344            q.deadline_period,
345            q.liveliness_kind,
346            q.lease_duration,
347            (q.user_data, q.user_data_len),
348            (q.data_representation, q.data_representation_len),
349        )
350    }?;
351    let mut qos = DataWriterQos {
352        reliability: c.reliability,
353        history: c.history,
354        resource_limits: c.resource_limits,
355        durability: c.durability,
356        deadline: c.deadline,
357        liveliness: c.liveliness,
358        user_data: c.user_data,
359        data_representation: c.data_representation,
360        ..DataWriterQos::default()
361    };
362    qos.writer_data_lifecycle.autodispose_unregistered_instances =
363        q.autodispose_unregistered_instances;
364    qos.durability_service = DurabilityService {
365        service_cleanup_delay: q.service_cleanup_delay.finite()?,
366        history: history(q.service_history_kind, q.service_history_depth)?,
367        resource_limits: ResourceLimits {
368            max_samples: limit(q.service_max_samples)?,
369            max_instances: limit(q.service_max_instances)?,
370            max_samples_per_instance: limit(q.service_max_samples_per_instance)?,
371        },
372    };
373    Ok(qos)
374}
375
376pub(crate) unsafe fn reader_qos(q: *const RddsReaderQos) -> Res<DataReaderQos> {
377    let Some(q) = (unsafe { q.as_ref() }) else {
378        return Ok(DataReaderQos::default());
379    };
380    let c = unsafe {
381        common(
382            q.reliability_kind,
383            q.max_blocking_time,
384            q.history_kind,
385            q.history_depth,
386            [q.max_samples, q.max_instances, q.max_samples_per_instance],
387            q.durability_kind,
388            q.deadline_period,
389            q.liveliness_kind,
390            q.lease_duration,
391            (q.user_data, q.user_data_len),
392            (q.data_representation, q.data_representation_len),
393        )
394    }?;
395    let kind = match q.type_consistency_kind {
396        0 => TypeConsistencyKind::DisallowTypeCoercion,
397        1 => TypeConsistencyKind::AllowTypeCoercion,
398        k => return Err(bad(format!("unknown type consistency kind {k}"))),
399    };
400    let mut qos = DataReaderQos {
401        reliability: c.reliability,
402        history: c.history,
403        resource_limits: c.resource_limits,
404        durability: c.durability,
405        deadline: c.deadline,
406        liveliness: c.liveliness,
407        user_data: c.user_data,
408        type_consistency: TypeConsistency {
409            kind,
410            ignore_sequence_bounds: q.ignore_sequence_bounds,
411            ignore_string_bounds: q.ignore_string_bounds,
412            ignore_member_names: q.ignore_member_names,
413            prevent_type_widening: q.prevent_type_widening,
414            force_type_validation: q.force_type_validation,
415        },
416        ..DataReaderQos::default()
417    };
418    if !c.data_representation.is_empty() {
419        qos.data_representation = c.data_representation;
420    }
421    Ok(qos)
422}
423
424unsafe fn partition(q: *const RddsGroupQos) -> Res<Vec<String>> {
425    let Some(q) = (unsafe { q.as_ref() }) else {
426        return Ok(Vec::new());
427    };
428    unsafe { slice(q.partition, q.partition_len) }?
429        .iter()
430        .map(|p| Ok(unsafe { cstr(*p, "a partition name") }?.to_owned()))
431        .collect()
432}
433
434fn history_parts(h: History) -> (i32, i32) {
435    match h {
436        History::KeepLast(n) => (0, n.min(i32::MAX as usize) as i32),
437        History::KeepAll => (1, 1),
438    }
439}
440
441fn durability_kind(d: DurabilityKind) -> i32 {
442    match d {
443        DurabilityKind::Volatile => 0,
444        DurabilityKind::TransientLocal => 1,
445        DurabilityKind::Transient => 2,
446        DurabilityKind::Persistent => 3,
447    }
448}
449
450fn liveliness_kind(k: LivelinessKind) -> i32 {
451    match k {
452        LivelinessKind::Automatic => 0,
453        LivelinessKind::ManualByParticipant => 1,
454        LivelinessKind::ManualByTopic => 2,
455    }
456}
457
458fn reliability_kind(k: ReliabilityKind) -> i32 {
459    match k {
460        ReliabilityKind::BestEffort => 0,
461        ReliabilityKind::Reliable => 1,
462    }
463}
464
465/// `rdds_writer_qos_default`: the default writer QoS.
466#[unsafe(no_mangle)]
467pub unsafe extern "C" fn rdds_writer_qos_default(out: *mut RddsWriterQos) -> Status {
468    guard(|| {
469        let d = DataWriterQos::default();
470        let (history_kind, history_depth) = history_parts(d.history);
471        let ds = d.durability_service;
472        let (service_history_kind, service_history_depth) = history_parts(ds.history);
473        let q = RddsWriterQos {
474            reliability_kind: reliability_kind(d.reliability.kind),
475            max_blocking_time: RddsDuration::of(Some(d.reliability.max_blocking_time)),
476            history_kind,
477            history_depth,
478            max_samples: unlimited(d.resource_limits.max_samples),
479            max_instances: unlimited(d.resource_limits.max_instances),
480            max_samples_per_instance: unlimited(d.resource_limits.max_samples_per_instance),
481            durability_kind: durability_kind(d.durability),
482            deadline_period: RddsDuration::of(d.deadline),
483            liveliness_kind: liveliness_kind(d.liveliness.kind),
484            lease_duration: RddsDuration::of(d.liveliness.lease_duration),
485            user_data: std::ptr::null(),
486            user_data_len: 0,
487            data_representation: std::ptr::null(),
488            data_representation_len: 0,
489            autodispose_unregistered_instances: d
490                .writer_data_lifecycle
491                .autodispose_unregistered_instances,
492            service_cleanup_delay: RddsDuration::of(Some(ds.service_cleanup_delay)),
493            service_history_kind,
494            service_history_depth,
495            service_max_samples: unlimited(ds.resource_limits.max_samples),
496            service_max_instances: unlimited(ds.resource_limits.max_instances),
497            service_max_samples_per_instance: unlimited(
498                ds.resource_limits.max_samples_per_instance,
499            ),
500        };
501        unsafe { set(out, q) }
502    })
503}
504
505/// `rdds_reader_qos_default`: the default reader QoS.
506#[unsafe(no_mangle)]
507pub unsafe extern "C" fn rdds_reader_qos_default(out: *mut RddsReaderQos) -> Status {
508    guard(|| {
509        let d = DataReaderQos::default();
510        let (history_kind, history_depth) = history_parts(d.history);
511        let tc = d.type_consistency;
512        let q = RddsReaderQos {
513            reliability_kind: reliability_kind(d.reliability.kind),
514            max_blocking_time: RddsDuration::of(Some(d.reliability.max_blocking_time)),
515            history_kind,
516            history_depth,
517            max_samples: unlimited(d.resource_limits.max_samples),
518            max_instances: unlimited(d.resource_limits.max_instances),
519            max_samples_per_instance: unlimited(d.resource_limits.max_samples_per_instance),
520            durability_kind: durability_kind(d.durability),
521            deadline_period: RddsDuration::of(d.deadline),
522            liveliness_kind: liveliness_kind(d.liveliness.kind),
523            lease_duration: RddsDuration::of(d.liveliness.lease_duration),
524            user_data: std::ptr::null(),
525            user_data_len: 0,
526            data_representation: XCDR_BOTH.as_ptr(),
527            data_representation_len: XCDR_BOTH.len(),
528            type_consistency_kind: match tc.kind {
529                TypeConsistencyKind::DisallowTypeCoercion => 0,
530                _ => 1,
531            },
532            ignore_sequence_bounds: tc.ignore_sequence_bounds,
533            ignore_string_bounds: tc.ignore_string_bounds,
534            ignore_member_names: tc.ignore_member_names,
535            prevent_type_widening: tc.prevent_type_widening,
536            force_type_validation: tc.force_type_validation,
537        };
538        unsafe { set(out, q) }
539    })
540}
541
542// ---------- statuses ------------------------------------------------------
543
544/// `rdds_matched_status` (publication or subscription matched).
545#[repr(C)]
546#[derive(Debug, Clone, Copy, Default)]
547pub struct RddsMatchedStatus {
548    pub total_count: i32,
549    pub total_count_change: i32,
550    pub current_count: i32,
551    pub current_count_change: i32,
552    pub last_handle: RddsGuid,
553}
554
555impl From<MatchedStatus> for RddsMatchedStatus {
556    fn from(s: MatchedStatus) -> Self {
557        RddsMatchedStatus {
558            total_count: s.total_count as i32,
559            total_count_change: s.total_count_change as i32,
560            current_count: s.current_count as i32,
561            current_count_change: s.current_count_change,
562            last_handle: RddsGuid::of(s.last_handle),
563        }
564    }
565}
566
567/// `rdds_qos_policy_count`.
568#[repr(C)]
569#[derive(Debug, Clone, Copy, Default)]
570pub struct RddsQosPolicyCount {
571    pub policy_id: i32,
572    pub count: i32,
573}
574
575/// The most policies an incompatible-QoS status lists.
576pub const MAX_POLICIES: usize = 32;
577
578/// `rdds_incompatible_qos_status` (offered or requested).
579#[repr(C)]
580#[derive(Debug, Clone, Copy, Default)]
581pub struct RddsIncompatibleQosStatus {
582    pub total_count: i32,
583    pub total_count_change: i32,
584    pub last_policy_id: i32,
585    pub policies_len: u32,
586    pub policies: [RddsQosPolicyCount; MAX_POLICIES],
587}
588
589impl From<IncompatibleQosStatus> for RddsIncompatibleQosStatus {
590    fn from(s: IncompatibleQosStatus) -> Self {
591        let mut out = RddsIncompatibleQosStatus {
592            total_count: s.total_count as i32,
593            total_count_change: s.total_count_change as i32,
594            last_policy_id: s.last_policy_id.map_or(0, |p| p.0 as i32),
595            ..Default::default()
596        };
597        for (slot, p) in out.policies.iter_mut().zip(&s.policies) {
598            *slot = RddsQosPolicyCount {
599                policy_id: p.policy_id.0 as i32,
600                count: p.count as i32,
601            };
602            out.policies_len += 1;
603        }
604        out
605    }
606}
607
608/// `rdds_liveliness_changed_status`.
609#[repr(C)]
610#[derive(Debug, Clone, Copy, Default)]
611pub struct RddsLivelinessChangedStatus {
612    pub alive_count: i32,
613    pub not_alive_count: i32,
614    pub alive_count_change: i32,
615    pub not_alive_count_change: i32,
616    pub last_publication_handle: RddsGuid,
617}
618
619impl From<LivelinessChangedStatus> for RddsLivelinessChangedStatus {
620    fn from(s: LivelinessChangedStatus) -> Self {
621        RddsLivelinessChangedStatus {
622            alive_count: s.alive_count as i32,
623            not_alive_count: s.not_alive_count as i32,
624            alive_count_change: s.alive_count_change,
625            not_alive_count_change: s.not_alive_count_change,
626            last_publication_handle: RddsGuid::of(s.last_publication_handle),
627        }
628    }
629}
630
631/// `rdds_count_status`: LIVELINESS_LOST, SAMPLE_LOST and
632/// INCONSISTENT_TOPIC, which are only counts.
633#[repr(C)]
634#[derive(Debug, Clone, Copy, Default)]
635pub struct RddsCountStatus {
636    pub total_count: i32,
637    pub total_count_change: i32,
638}
639
640impl From<LivelinessLostStatus> for RddsCountStatus {
641    fn from(s: LivelinessLostStatus) -> Self {
642        RddsCountStatus {
643            total_count: s.total_count as i32,
644            total_count_change: s.total_count_change as i32,
645        }
646    }
647}
648
649impl From<SampleLostStatus> for RddsCountStatus {
650    fn from(s: SampleLostStatus) -> Self {
651        RddsCountStatus {
652            total_count: s.total_count as i32,
653            total_count_change: s.total_count_change as i32,
654        }
655    }
656}
657
658impl From<InconsistentTopicStatus> for RddsCountStatus {
659    fn from(s: InconsistentTopicStatus) -> Self {
660        RddsCountStatus {
661            total_count: s.total_count as i32,
662            total_count_change: s.total_count_change as i32,
663        }
664    }
665}
666
667/// `rdds_deadline_missed_status` (offered or requested).
668#[repr(C)]
669#[derive(Debug, Clone, Copy, Default)]
670pub struct RddsDeadlineMissedStatus {
671    pub total_count: i32,
672    pub total_count_change: i32,
673    pub last_instance_handle: RddsInstanceHandle,
674}
675
676impl From<DeadlineMissedStatus> for RddsDeadlineMissedStatus {
677    fn from(s: DeadlineMissedStatus) -> Self {
678        RddsDeadlineMissedStatus {
679            total_count: s.total_count as i32,
680            total_count_change: s.total_count_change as i32,
681            last_instance_handle: RddsInstanceHandle::of(s.last_instance_handle),
682        }
683    }
684}
685
686/// `rdds_sample_rejected_status`.
687#[repr(C)]
688#[derive(Debug, Clone, Copy, Default)]
689pub struct RddsSampleRejectedStatus {
690    pub total_count: i32,
691    pub total_count_change: i32,
692    /// `NOT_REJECTED` (0), `REJECTED_BY_INSTANCES_LIMIT` (1),
693    /// `REJECTED_BY_SAMPLES_LIMIT` (2),
694    /// `REJECTED_BY_SAMPLES_PER_INSTANCE_LIMIT` (3).
695    pub last_reason: i32,
696    pub last_instance_handle: RddsInstanceHandle,
697}
698
699impl From<SampleRejectedStatus> for RddsSampleRejectedStatus {
700    fn from(s: SampleRejectedStatus) -> Self {
701        RddsSampleRejectedStatus {
702            total_count: s.total_count as i32,
703            total_count_change: s.total_count_change as i32,
704            last_reason: match s.last_reason {
705                None => 0,
706                Some(SampleRejectedReason::InstancesLimit) => 1,
707                Some(SampleRejectedReason::SamplesLimit) => 2,
708                Some(SampleRejectedReason::SamplesPerInstanceLimit) => 3,
709            },
710            last_instance_handle: RddsInstanceHandle::of(s.last_instance_handle),
711        }
712    }
713}
714
715// ---------- listeners -----------------------------------------------------
716
717/// `rdds_writer_listener`: functions (any may be NULL) called with
718/// `self` on a thread of the participant; `release`, if not NULL, when
719/// the listener is replaced or the writer is released.
720#[repr(C)]
721#[derive(Debug, Clone, Copy)]
722pub struct RddsWriterListener {
723    pub self_: *mut c_void,
724    pub on_offered_deadline_missed:
725        Option<unsafe extern "C" fn(*mut c_void, *const RddsDeadlineMissedStatus)>,
726    pub on_offered_incompatible_qos:
727        Option<unsafe extern "C" fn(*mut c_void, *const RddsIncompatibleQosStatus)>,
728    pub on_liveliness_lost: Option<unsafe extern "C" fn(*mut c_void, *const RddsCountStatus)>,
729    pub on_publication_matched: Option<unsafe extern "C" fn(*mut c_void, *const RddsMatchedStatus)>,
730    pub release: Option<unsafe extern "C" fn(*mut c_void)>,
731}
732
733/// `rdds_reader_listener`.
734#[repr(C)]
735#[derive(Debug, Clone, Copy)]
736pub struct RddsReaderListener {
737    pub self_: *mut c_void,
738    pub on_requested_deadline_missed:
739        Option<unsafe extern "C" fn(*mut c_void, *const RddsDeadlineMissedStatus)>,
740    pub on_requested_incompatible_qos:
741        Option<unsafe extern "C" fn(*mut c_void, *const RddsIncompatibleQosStatus)>,
742    pub on_sample_rejected:
743        Option<unsafe extern "C" fn(*mut c_void, *const RddsSampleRejectedStatus)>,
744    pub on_liveliness_changed:
745        Option<unsafe extern "C" fn(*mut c_void, *const RddsLivelinessChangedStatus)>,
746    pub on_data_available: Option<unsafe extern "C" fn(*mut c_void)>,
747    pub on_subscription_matched:
748        Option<unsafe extern "C" fn(*mut c_void, *const RddsMatchedStatus)>,
749    pub on_sample_lost: Option<unsafe extern "C" fn(*mut c_void, *const RddsCountStatus)>,
750    pub release: Option<unsafe extern "C" fn(*mut c_void)>,
751}
752
753struct WriterCallbacks(RddsWriterListener);
754struct ReaderCallbacks(RddsReaderListener);
755
756// SAFETY: the caller's functions may be called from any thread (the
757// header says so of listeners).
758unsafe impl Send for WriterCallbacks {}
759unsafe impl Sync for WriterCallbacks {}
760unsafe impl Send for ReaderCallbacks {}
761unsafe impl Sync for ReaderCallbacks {}
762
763impl Drop for WriterCallbacks {
764    fn drop(&mut self) {
765        if let Some(f) = self.0.release {
766            unsafe { f(self.0.self_) }
767        }
768    }
769}
770
771impl Drop for ReaderCallbacks {
772    fn drop(&mut self) {
773        if let Some(f) = self.0.release {
774            unsafe { f(self.0.self_) }
775        }
776    }
777}
778
779macro_rules! call {
780    ($l:expr, $f:ident, $s:expr) => {
781        if let Some(f) = $l.$f {
782            let s = $s;
783            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe {
784                f($l.self_, &s)
785            }));
786        }
787    };
788}
789
790impl DataWriterListener<DynamicData> for WriterCallbacks {
791    fn on_publication_matched(&self, _: &DataWriter<DynamicData>, s: MatchedStatus) {
792        call!(self.0, on_publication_matched, RddsMatchedStatus::from(s));
793    }
794    fn on_liveliness_lost(&self, _: &DataWriter<DynamicData>, s: LivelinessLostStatus) {
795        call!(self.0, on_liveliness_lost, RddsCountStatus::from(s));
796    }
797    fn on_offered_deadline_missed(&self, _: &DataWriter<DynamicData>, s: DeadlineMissedStatus) {
798        call!(
799            self.0,
800            on_offered_deadline_missed,
801            RddsDeadlineMissedStatus::from(s)
802        );
803    }
804    fn on_offered_incompatible_qos(&self, _: &DataWriter<DynamicData>, s: IncompatibleQosStatus) {
805        call!(
806            self.0,
807            on_offered_incompatible_qos,
808            RddsIncompatibleQosStatus::from(s)
809        );
810    }
811}
812
813impl DataReaderListener<DynamicData> for ReaderCallbacks {
814    fn on_data_available(&self, _: &DataReader<DynamicData>) {
815        if let Some(f) = self.0.on_data_available {
816            let _ = std::panic::catch_unwind(|| unsafe { f(self.0.self_) });
817        }
818    }
819    fn on_subscription_matched(&self, _: &DataReader<DynamicData>, s: MatchedStatus) {
820        call!(self.0, on_subscription_matched, RddsMatchedStatus::from(s));
821    }
822    fn on_liveliness_changed(&self, _: &DataReader<DynamicData>, s: LivelinessChangedStatus) {
823        call!(
824            self.0,
825            on_liveliness_changed,
826            RddsLivelinessChangedStatus::from(s)
827        );
828    }
829    fn on_requested_deadline_missed(&self, _: &DataReader<DynamicData>, s: DeadlineMissedStatus) {
830        call!(
831            self.0,
832            on_requested_deadline_missed,
833            RddsDeadlineMissedStatus::from(s)
834        );
835    }
836    fn on_requested_incompatible_qos(&self, _: &DataReader<DynamicData>, s: IncompatibleQosStatus) {
837        call!(
838            self.0,
839            on_requested_incompatible_qos,
840            RddsIncompatibleQosStatus::from(s)
841        );
842    }
843    fn on_sample_rejected(&self, _: &DataReader<DynamicData>, s: SampleRejectedStatus) {
844        call!(
845            self.0,
846            on_sample_rejected,
847            RddsSampleRejectedStatus::from(s)
848        );
849    }
850    fn on_sample_lost(&self, _: &DataReader<DynamicData>, s: SampleLostStatus) {
851        call!(self.0, on_sample_lost, RddsCountStatus::from(s));
852    }
853}
854
855// ---------- entities ------------------------------------------------------
856
857/// `rdds_topic`.
858#[derive(Debug)]
859pub struct RddsTopic {
860    pub(crate) topic: Topic<DynamicData>,
861    pub(crate) ty: DynamicType,
862}
863
864/// `rdds_writer`.
865#[derive(Debug)]
866pub struct RddsWriter {
867    pub(crate) inner: DataWriter<DynamicData>,
868    ty: DynamicType,
869}
870
871/// `rdds_reader`.
872#[derive(Debug)]
873pub struct RddsReader {
874    pub(crate) inner: DataReader<DynamicData>,
875    ty: DynamicType,
876}
877
878/// `RDDS_PARTICIPANT_LOCALHOST`: only the loopback interface (tests).
879pub const PARTICIPANT_LOCALHOST: u32 = 1;
880
881/// `rdds_participant_new`: joins `domain_id`; `qos` NULL for the default.
882#[unsafe(no_mangle)]
883pub unsafe extern "C" fn rdds_participant_new(
884    domain_id: u32,
885    qos: *const RddsParticipantQos,
886    flags: u32,
887    out: *mut *mut DomainParticipant,
888) -> Status {
889    guard(|| {
890        let mut config = if flags & PARTICIPANT_LOCALHOST != 0 {
891            ParticipantConfig::localhost(domain_id)
892        } else {
893            ParticipantConfig::new(domain_id)
894        };
895        if let Some(q) = unsafe { qos.as_ref() } {
896            config.user_data = unsafe { slice(q.user_data, q.user_data_len) }?.to_vec();
897            let mut props = Vec::new();
898            for p in unsafe { slice(q.property, q.property_len) }? {
899                props.push((unsafe { cstr(p.name, "a property name") }?, unsafe {
900                    cstr(p.value, "a property value")
901                }?));
902            }
903            config.set_properties(props)?;
904        }
905        let p = DomainParticipant::with_config(config)?;
906        unsafe { put(out, p) }
907    })
908}
909
910/// `rdds_participant_release`: deletes the participant (its entities
911/// stop working).
912#[unsafe(no_mangle)]
913pub unsafe extern "C" fn rdds_participant_release(p: *mut DomainParticipant) {
914    unsafe { release(p) }
915}
916
917/// `rdds_participant_domain_id`.
918#[unsafe(no_mangle)]
919pub unsafe extern "C" fn rdds_participant_domain_id(p: *const DomainParticipant) -> u32 {
920    guard_value(0, || unsafe { p.as_ref() }.map_or(0, |p| p.domain_id()))
921}
922
923/// `rdds_participant_guid`.
924#[unsafe(no_mangle)]
925pub unsafe extern "C" fn rdds_participant_guid(
926    p: *const DomainParticipant,
927    out: *mut RddsGuid,
928) -> Status {
929    guard(|| {
930        let p = unsafe { obj(p, "the participant") }?;
931        unsafe { set(out, RddsGuid::of(Some(p.guid()))) }
932    })
933}
934
935/// `rdds_participant_assert_liveliness`.
936#[unsafe(no_mangle)]
937pub unsafe extern "C" fn rdds_participant_assert_liveliness(p: *const DomainParticipant) -> Status {
938    guard(|| Ok(unsafe { obj(p, "the participant") }?.assert_liveliness()?))
939}
940
941/// `rdds_participant_discovered_participants`: how many other
942/// participants are known.
943#[unsafe(no_mangle)]
944pub unsafe extern "C" fn rdds_participant_discovered_participants(
945    p: *const DomainParticipant,
946) -> usize {
947    guard_value(0, || {
948        unsafe { p.as_ref() }.map_or(0, |p| p.discovered_participants().len())
949    })
950}
951
952/// `rdds_participant_create_topic`: a topic of `type`, registered under
953/// its name.
954#[unsafe(no_mangle)]
955pub unsafe extern "C" fn rdds_participant_create_topic(
956    p: *const DomainParticipant,
957    name: *const c_char,
958    ty: *const DynamicType,
959    out: *mut *mut RddsTopic,
960) -> Status {
961    guard(|| {
962        let p = unsafe { obj(p, "the participant") }?;
963        let name = unsafe { cstr(name, "the topic name") }?;
964        let ty = unsafe { obj(ty, "the type") }?.clone();
965        let topic = p.create_dynamic_topic(name, &ty)?;
966        unsafe { put(out, RddsTopic { topic, ty }) }
967    })
968}
969
970/// `rdds_topic_release`.
971#[unsafe(no_mangle)]
972pub unsafe extern "C" fn rdds_topic_release(t: *mut RddsTopic) {
973    unsafe { release(t) }
974}
975
976/// `rdds_topic_inconsistent_topic_status`.
977#[unsafe(no_mangle)]
978pub unsafe extern "C" fn rdds_topic_inconsistent_topic_status(
979    t: *const RddsTopic,
980    out: *mut RddsCountStatus,
981) -> Status {
982    guard(|| {
983        let t = unsafe { obj(t, "the topic") }?;
984        unsafe { set(out, t.topic.inconsistent_topic_status().into()) }
985    })
986}
987
988/// `rdds_cftopic`: a content filtered topic, and its type.
989#[derive(Debug)]
990pub struct RddsCfTopic {
991    topic: ContentFilteredTopic<DynamicData>,
992    ty: DynamicType,
993}
994
995/// `n` C strings at `v`.
996unsafe fn strings(v: *const *const c_char, n: usize, what: &str) -> Res<Vec<String>> {
997    unsafe { slice(v, n) }?
998        .iter()
999        .map(|p| Ok(unsafe { cstr(*p, what) }?.to_owned()))
1000        .collect()
1001}
1002
1003/// `rdds_participant_create_contentfilteredtopic`: a content filtered
1004/// topic named `name` of `related`, with the filter `expression`
1005/// (DDS 1.4, Annex B) and `n` parameters at `parameters`.
1006#[unsafe(no_mangle)]
1007pub unsafe extern "C" fn rdds_participant_create_contentfilteredtopic(
1008    p: *const DomainParticipant,
1009    name: *const c_char,
1010    related: *const RddsTopic,
1011    expression: *const c_char,
1012    parameters: *const *const c_char,
1013    n: usize,
1014    out: *mut *mut RddsCfTopic,
1015) -> Status {
1016    guard(|| {
1017        let p = unsafe { obj(p, "the participant") }?;
1018        let name = unsafe { cstr(name, "the topic name") }?;
1019        let related = unsafe { obj(related, "the related topic") }?;
1020        let expression = unsafe { cstr(expression, "the filter expression") }?;
1021        let parameters = unsafe { strings(parameters, n, "an expression parameter") }?;
1022        let topic = p.create_contentfilteredtopic(name, &related.topic, expression, &parameters)?;
1023        unsafe {
1024            put(
1025                out,
1026                RddsCfTopic {
1027                    topic,
1028                    ty: related.ty.clone(),
1029                },
1030            )
1031        }
1032    })
1033}
1034
1035/// `rdds_cftopic_release`.
1036#[unsafe(no_mangle)]
1037pub unsafe extern "C" fn rdds_cftopic_release(t: *mut RddsCfTopic) {
1038    unsafe { release(t) }
1039}
1040
1041/// `rdds_cftopic_set_expression_parameters`.
1042#[unsafe(no_mangle)]
1043pub unsafe extern "C" fn rdds_cftopic_set_expression_parameters(
1044    t: *const RddsCfTopic,
1045    parameters: *const *const c_char,
1046    n: usize,
1047) -> Status {
1048    guard(|| {
1049        let t = unsafe { obj(t, "the topic") }?;
1050        let parameters = unsafe { strings(parameters, n, "an expression parameter") }?;
1051        t.topic.set_expression_parameters(&parameters)?;
1052        Ok(())
1053    })
1054}
1055
1056/// `rdds_participant_create_publisher`: `qos` NULL for the default.
1057#[unsafe(no_mangle)]
1058pub unsafe extern "C" fn rdds_participant_create_publisher(
1059    p: *const DomainParticipant,
1060    qos: *const RddsGroupQos,
1061    out: *mut *mut Publisher,
1062) -> Status {
1063    guard(|| {
1064        let p = unsafe { obj(p, "the participant") }?;
1065        let qos = PublisherQos {
1066            partition: unsafe { partition(qos) }?,
1067        };
1068        unsafe { put(out, p.create_publisher_with_qos(qos)?) }
1069    })
1070}
1071
1072/// `rdds_publisher_release`.
1073#[unsafe(no_mangle)]
1074pub unsafe extern "C" fn rdds_publisher_release(p: *mut Publisher) {
1075    unsafe { release(p) }
1076}
1077
1078/// `rdds_participant_create_subscriber`.
1079#[unsafe(no_mangle)]
1080pub unsafe extern "C" fn rdds_participant_create_subscriber(
1081    p: *const DomainParticipant,
1082    qos: *const RddsGroupQos,
1083    out: *mut *mut Subscriber,
1084) -> Status {
1085    guard(|| {
1086        let p = unsafe { obj(p, "the participant") }?;
1087        let qos = SubscriberQos {
1088            partition: unsafe { partition(qos) }?,
1089        };
1090        unsafe { put(out, p.create_subscriber_with_qos(qos)?) }
1091    })
1092}
1093
1094/// `rdds_subscriber_release`.
1095#[unsafe(no_mangle)]
1096pub unsafe extern "C" fn rdds_subscriber_release(s: *mut Subscriber) {
1097    unsafe { release(s) }
1098}
1099
1100// ---------- writer --------------------------------------------------------
1101
1102/// `rdds_publisher_create_writer`: `qos` NULL for the default; the
1103/// `listener`, if not NULL, is set before the writer is matched.
1104#[unsafe(no_mangle)]
1105pub unsafe extern "C" fn rdds_publisher_create_writer(
1106    p: *const Publisher,
1107    topic: *const RddsTopic,
1108    qos: *const RddsWriterQos,
1109    listener: *const RddsWriterListener,
1110    mask: u32,
1111    out: *mut *mut RddsWriter,
1112) -> Status {
1113    guard(|| {
1114        let p = unsafe { obj(p, "the publisher") }?;
1115        let t = unsafe { obj(topic, "the topic") }?;
1116        let qos = unsafe { writer_qos(qos) }?;
1117        let inner = match unsafe { listener.as_ref() } {
1118            None => p.create_datawriter_with_qos(&t.topic, qos)?,
1119            Some(l) => p.create_datawriter_with_listener(
1120                &t.topic,
1121                qos,
1122                WriterCallbacks(*l),
1123                StatusMask(mask),
1124            )?,
1125        };
1126        unsafe {
1127            put(
1128                out,
1129                RddsWriter {
1130                    inner,
1131                    ty: t.ty.clone(),
1132                },
1133            )
1134        }
1135    })
1136}
1137
1138/// `rdds_writer_release`: deletes the writer.
1139#[unsafe(no_mangle)]
1140pub unsafe extern "C" fn rdds_writer_release(w: *mut RddsWriter) {
1141    unsafe { release(w) }
1142}
1143
1144unsafe fn writer_sample<'a>(
1145    w: *const RddsWriter,
1146    sample: *const Out,
1147) -> Res<(&'a RddsWriter, DynamicData)> {
1148    let w = unsafe { obj(w, "the writer") }?;
1149    let s = unsafe { obj(sample, "the sample") }?;
1150    let d = to_data(&w.ty, s)?;
1151    Ok((w, d))
1152}
1153
1154/// `rdds_writer_guid`.
1155#[unsafe(no_mangle)]
1156pub unsafe extern "C" fn rdds_writer_guid(w: *const RddsWriter, out: *mut RddsGuid) -> Status {
1157    guard(|| {
1158        let w = unsafe { obj(w, "the writer") }?;
1159        unsafe { set(out, RddsGuid::of(Some(w.inner.guid()))) }
1160    })
1161}
1162
1163/// `rdds_writer_write`: `timestamp` NULL for now.
1164#[unsafe(no_mangle)]
1165pub unsafe extern "C" fn rdds_writer_write(
1166    w: *const RddsWriter,
1167    sample: *const Out,
1168    timestamp_: *const RddsTime,
1169) -> Status {
1170    guard(|| {
1171        let (w, d) = unsafe { writer_sample(w, sample) }?;
1172        let t = unsafe { timestamp(timestamp_) }?;
1173        Ok(w.inner.write_w_timestamp(&d, t)?)
1174    })
1175}
1176
1177/// `rdds_writer_register_instance`.
1178#[unsafe(no_mangle)]
1179pub unsafe extern "C" fn rdds_writer_register_instance(
1180    w: *const RddsWriter,
1181    sample: *const Out,
1182    out: *mut RddsInstanceHandle,
1183) -> Status {
1184    guard(|| {
1185        let (w, d) = unsafe { writer_sample(w, sample) }?;
1186        let h = w.inner.register_instance(&d)?;
1187        unsafe { set(out, RddsInstanceHandle::of(Some(h))) }
1188    })
1189}
1190
1191/// `rdds_writer_unregister_instance`.
1192#[unsafe(no_mangle)]
1193pub unsafe extern "C" fn rdds_writer_unregister_instance(
1194    w: *const RddsWriter,
1195    sample: *const Out,
1196    timestamp_: *const RddsTime,
1197) -> Status {
1198    guard(|| {
1199        let (w, d) = unsafe { writer_sample(w, sample) }?;
1200        let t = unsafe { timestamp(timestamp_) }?;
1201        Ok(w.inner.unregister_instance_w_timestamp(&d, t)?)
1202    })
1203}
1204
1205/// `rdds_writer_dispose`.
1206#[unsafe(no_mangle)]
1207pub unsafe extern "C" fn rdds_writer_dispose(
1208    w: *const RddsWriter,
1209    sample: *const Out,
1210    timestamp_: *const RddsTime,
1211) -> Status {
1212    guard(|| {
1213        let (w, d) = unsafe { writer_sample(w, sample) }?;
1214        let t = unsafe { timestamp(timestamp_) }?;
1215        Ok(w.inner.dispose_w_timestamp(&d, t)?)
1216    })
1217}
1218
1219/// `rdds_writer_lookup_instance`: `HANDLE_NIL` when it is not known.
1220#[unsafe(no_mangle)]
1221pub unsafe extern "C" fn rdds_writer_lookup_instance(
1222    w: *const RddsWriter,
1223    sample: *const Out,
1224    out: *mut RddsInstanceHandle,
1225) -> Status {
1226    guard(|| {
1227        let (w, d) = unsafe { writer_sample(w, sample) }?;
1228        unsafe { set(out, RddsInstanceHandle::of(w.inner.lookup_instance(&d))) }
1229    })
1230}
1231
1232/// `rdds_writer_wait_for_acknowledgments`.
1233#[unsafe(no_mangle)]
1234pub unsafe extern "C" fn rdds_writer_wait_for_acknowledgments(
1235    w: *const RddsWriter,
1236    max_wait: RddsDuration,
1237) -> Status {
1238    guard(|| {
1239        let w = unsafe { obj(w, "the writer") }?;
1240        Ok(w.inner.wait_for_acknowledgments(max_wait.finite()?)?)
1241    })
1242}
1243
1244/// `rdds_writer_wait_for_subscriptions`: until `count` readers match,
1245/// or `RETCODE_TIMEOUT`.
1246#[unsafe(no_mangle)]
1247pub unsafe extern "C" fn rdds_writer_wait_for_subscriptions(
1248    w: *const RddsWriter,
1249    count: usize,
1250    timeout: RddsDuration,
1251) -> Status {
1252    guard(|| {
1253        let w = unsafe { obj(w, "the writer") }?;
1254        if w.inner.wait_for_subscriptions(count, timeout.finite()?) {
1255            Ok(())
1256        } else {
1257            Err(crate::Fail(TIMEOUT, "no subscriptions in time".into()))
1258        }
1259    })
1260}
1261
1262/// Copies `v` into the caller's array of `cap`, the count into `*len`.
1263unsafe fn guids(v: Vec<Guid>, buf: *mut RddsGuid, cap: usize, len: *mut usize) -> Res {
1264    for (i, g) in v.iter().take(cap).enumerate() {
1265        // SAFETY: room for `cap` (the header).
1266        unsafe { buf.add(i).write(RddsGuid::of(Some(*g))) };
1267    }
1268    unsafe { set(len, v.len()) }
1269}
1270
1271/// `rdds_writer_matched_subscriptions`: up to `cap` into `buf`, and how
1272/// many there are into `*len`.
1273#[unsafe(no_mangle)]
1274pub unsafe extern "C" fn rdds_writer_matched_subscriptions(
1275    w: *const RddsWriter,
1276    buf: *mut RddsGuid,
1277    cap: usize,
1278    len: *mut usize,
1279) -> Status {
1280    guard(|| {
1281        let w = unsafe { obj(w, "the writer") }?;
1282        unsafe { guids(w.inner.matched_subscriptions(), buf, cap, len) }
1283    })
1284}
1285
1286/// `rdds_writer_assert_liveliness`.
1287#[unsafe(no_mangle)]
1288pub unsafe extern "C" fn rdds_writer_assert_liveliness(w: *const RddsWriter) -> Status {
1289    guard(|| Ok(unsafe { obj(w, "the writer") }?.inner.assert_liveliness()?))
1290}
1291
1292macro_rules! status_getter {
1293    ($($name:ident, $handle:ty, $what:literal, $method:ident, $out:ty;)*) => {$(
1294        #[doc = concat!("`", stringify!($name), "`: reads and resets the change counts.")]
1295        #[unsafe(no_mangle)]
1296        pub unsafe extern "C" fn $name(e: *const $handle, out: *mut $out) -> Status {
1297            guard(|| {
1298                let e = unsafe { obj(e, $what) }?;
1299                unsafe { set(out, <$out>::from(e.inner.$method())) }
1300            })
1301        }
1302    )*};
1303}
1304
1305status_getter! {
1306    rdds_writer_publication_matched_status, RddsWriter, "the writer", publication_matched_status, RddsMatchedStatus;
1307    rdds_writer_offered_incompatible_qos_status, RddsWriter, "the writer", offered_incompatible_qos_status, RddsIncompatibleQosStatus;
1308    rdds_writer_liveliness_lost_status, RddsWriter, "the writer", liveliness_lost_status, RddsCountStatus;
1309    rdds_writer_offered_deadline_missed_status, RddsWriter, "the writer", offered_deadline_missed_status, RddsDeadlineMissedStatus;
1310    rdds_reader_subscription_matched_status, RddsReader, "the reader", subscription_matched_status, RddsMatchedStatus;
1311    rdds_reader_requested_incompatible_qos_status, RddsReader, "the reader", requested_incompatible_qos_status, RddsIncompatibleQosStatus;
1312    rdds_reader_liveliness_changed_status, RddsReader, "the reader", liveliness_changed_status, RddsLivelinessChangedStatus;
1313    rdds_reader_requested_deadline_missed_status, RddsReader, "the reader", requested_deadline_missed_status, RddsDeadlineMissedStatus;
1314    rdds_reader_sample_lost_status, RddsReader, "the reader", sample_lost_status, RddsCountStatus;
1315    rdds_reader_sample_rejected_status, RddsReader, "the reader", sample_rejected_status, RddsSampleRejectedStatus;
1316}
1317
1318/// `rdds_writer_status_changes`: the mask of the statuses that changed.
1319#[unsafe(no_mangle)]
1320pub unsafe extern "C" fn rdds_writer_status_changes(w: *const RddsWriter) -> u32 {
1321    guard_value(0, || {
1322        unsafe { w.as_ref() }.map_or(0, |w| w.inner.status_changes().0)
1323    })
1324}
1325
1326/// `rdds_writer_status_condition`.
1327#[unsafe(no_mangle)]
1328pub unsafe extern "C" fn rdds_writer_status_condition(
1329    w: *const RddsWriter,
1330    out: *mut *mut RddsCondition,
1331) -> Status {
1332    guard(|| {
1333        let w = unsafe { obj(w, "the writer") }?;
1334        unsafe { put(out, RddsCondition::from(w.inner.status_condition())) }
1335    })
1336}
1337
1338/// `rdds_writer_set_listener`: NULL clears it.
1339#[unsafe(no_mangle)]
1340pub unsafe extern "C" fn rdds_writer_set_listener(
1341    w: *const RddsWriter,
1342    listener: *const RddsWriterListener,
1343    mask: u32,
1344) -> Status {
1345    guard(|| {
1346        let w = unsafe { obj(w, "the writer") }?;
1347        match unsafe { listener.as_ref() } {
1348            None => w.inner.clear_listener(),
1349            Some(l) => w.inner.set_listener(WriterCallbacks(*l), StatusMask(mask)),
1350        }
1351        Ok(())
1352    })
1353}
1354
1355// ---------- reader --------------------------------------------------------
1356
1357/// `rdds_subscriber_create_reader`.
1358#[unsafe(no_mangle)]
1359pub unsafe extern "C" fn rdds_subscriber_create_reader(
1360    s: *const Subscriber,
1361    topic: *const RddsTopic,
1362    qos: *const RddsReaderQos,
1363    listener: *const RddsReaderListener,
1364    mask: u32,
1365    out: *mut *mut RddsReader,
1366) -> Status {
1367    guard(|| {
1368        let s = unsafe { obj(s, "the subscriber") }?;
1369        let t = unsafe { obj(topic, "the topic") }?;
1370        let qos = unsafe { reader_qos(qos) }?;
1371        let inner = match unsafe { listener.as_ref() } {
1372            None => s.create_datareader_with_qos(&t.topic, qos)?,
1373            Some(l) => s.create_datareader_with_listener(
1374                &t.topic,
1375                qos,
1376                ReaderCallbacks(*l),
1377                StatusMask(mask),
1378            )?,
1379        };
1380        unsafe {
1381            put(
1382                out,
1383                RddsReader {
1384                    inner,
1385                    ty: t.ty.clone(),
1386                },
1387            )
1388        }
1389    })
1390}
1391
1392/// `rdds_subscriber_create_filtered_reader`: a reader of a content
1393/// filtered topic.
1394#[unsafe(no_mangle)]
1395pub unsafe extern "C" fn rdds_subscriber_create_filtered_reader(
1396    s: *const Subscriber,
1397    topic: *const RddsCfTopic,
1398    qos: *const RddsReaderQos,
1399    listener: *const RddsReaderListener,
1400    mask: u32,
1401    out: *mut *mut RddsReader,
1402) -> Status {
1403    guard(|| {
1404        let s = unsafe { obj(s, "the subscriber") }?;
1405        let t = unsafe { obj(topic, "the topic") }?;
1406        let qos = unsafe { reader_qos(qos) }?;
1407        let inner = match unsafe { listener.as_ref() } {
1408            None => s.create_datareader_with_qos(&t.topic, qos)?,
1409            Some(l) => s.create_datareader_with_listener(
1410                &t.topic,
1411                qos,
1412                ReaderCallbacks(*l),
1413                StatusMask(mask),
1414            )?,
1415        };
1416        unsafe {
1417            put(
1418                out,
1419                RddsReader {
1420                    inner,
1421                    ty: t.ty.clone(),
1422                },
1423            )
1424        }
1425    })
1426}
1427
1428/// `rdds_reader_release`: deletes the reader.
1429#[unsafe(no_mangle)]
1430pub unsafe extern "C" fn rdds_reader_release(r: *mut RddsReader) {
1431    unsafe { release(r) }
1432}
1433
1434/// `rdds_reader_guid`.
1435#[unsafe(no_mangle)]
1436pub unsafe extern "C" fn rdds_reader_guid(r: *const RddsReader, out: *mut RddsGuid) -> Status {
1437    guard(|| {
1438        let r = unsafe { obj(r, "the reader") }?;
1439        unsafe { set(out, RddsGuid::of(Some(r.inner.guid()))) }
1440    })
1441}
1442
1443/// `rdds_sample_info`.
1444#[repr(C)]
1445#[derive(Debug, Clone, Copy)]
1446pub struct RddsSampleInfo {
1447    /// `READ_SAMPLE_STATE` (1) or `NOT_READ_SAMPLE_STATE` (2).
1448    pub sample_state: u32,
1449    /// `NEW_VIEW_STATE` (1) or `NOT_NEW_VIEW_STATE` (2).
1450    pub view_state: u32,
1451    /// `ALIVE_INSTANCE_STATE` (1), `NOT_ALIVE_DISPOSED_INSTANCE_STATE`
1452    /// (2) or `NOT_ALIVE_NO_WRITERS_INSTANCE_STATE` (4).
1453    pub instance_state: u32,
1454    pub disposed_generation_count: i32,
1455    pub no_writers_generation_count: i32,
1456    pub sample_rank: i32,
1457    pub generation_rank: i32,
1458    pub absolute_generation_rank: i32,
1459    pub source_timestamp: RddsTime,
1460    pub instance_handle: RddsInstanceHandle,
1461    pub publication_handle: RddsGuid,
1462    pub sequence_number: i64,
1463    pub valid_data: bool,
1464}
1465
1466/// `rdds_samples`: what a read or take returned.
1467#[derive(Debug)]
1468pub struct RddsSamples(Vec<Sample<DynamicData>>);
1469
1470impl RddsSamples {
1471    pub(crate) fn sample(&self, i: usize) -> Res<&Sample<DynamicData>> {
1472        self.0.get(i).ok_or_else(|| bad("no such sample"))
1473    }
1474}
1475
1476/// `RDDS_SELECT_ANY`, `RDDS_SELECT_INSTANCE`, `RDDS_SELECT_NEXT_INSTANCE`.
1477pub const SELECT_ANY: i32 = 0;
1478/// See [`SELECT_ANY`].
1479pub const SELECT_INSTANCE: i32 = 1;
1480/// See [`SELECT_ANY`].
1481pub const SELECT_NEXT_INSTANCE: i32 = 2;
1482
1483fn filter(sample_states: u32, view_states: u32, instance_states: u32) -> Res<StateFilter> {
1484    let mut f = StateFilter::ANY;
1485    let mut s = None;
1486    for (bit, m) in [(1, SampleStateMask::READ), (2, SampleStateMask::NOT_READ)] {
1487        if sample_states & bit != 0 {
1488            s = Some(s.map_or(m, |x| x | m));
1489        }
1490    }
1491    f.sample_states = s.ok_or_else(|| bad("no sample state selected"))?;
1492    let mut v = None;
1493    for (bit, m) in [(1, ViewStateMask::NEW), (2, ViewStateMask::NOT_NEW)] {
1494        if view_states & bit != 0 {
1495            v = Some(v.map_or(m, |x| x | m));
1496        }
1497    }
1498    f.view_states = v.ok_or_else(|| bad("no view state selected"))?;
1499    let mut i = None;
1500    for (bit, m) in [
1501        (1, InstanceStateMask::ALIVE),
1502        (2, InstanceStateMask::NOT_ALIVE_DISPOSED),
1503        (4, InstanceStateMask::NOT_ALIVE_NO_WRITERS),
1504    ] {
1505        if instance_states & bit != 0 {
1506            i = Some(i.map_or(m, |x| x | m));
1507        }
1508    }
1509    f.instance_states = i.ok_or_else(|| bad("no instance state selected"))?;
1510    Ok(f)
1511}
1512
1513/// The `max_samples` of a read or take: `RDDS_LENGTH_UNLIMITED` (-1) or
1514/// a number.
1515fn max(max_samples: i32) -> Res<usize> {
1516    match max_samples {
1517        -1 => Ok(usize::MAX),
1518        n if n >= 0 => Ok(n as usize),
1519        n => Err(bad(format!("max_samples {n}"))),
1520    }
1521}
1522
1523/// `rdds_reader_select`: reads (or takes, with `take`) the samples in
1524/// the states of the masks (`RDDS_ANY_*_STATE` for any); with
1525/// `RDDS_SELECT_INSTANCE`, those of `*instance` only (the masks then
1526/// ignored); with `RDDS_SELECT_NEXT_INSTANCE`, those of the instance
1527/// after `*instance` (`HANDLE_NIL` or NULL for the first). At most
1528/// `max_samples` samples (`RDDS_LENGTH_UNLIMITED` for any number), the
1529/// first to arrive. An empty result is `RETCODE_OK` with no samples.
1530#[allow(clippy::too_many_arguments)]
1531#[unsafe(no_mangle)]
1532pub unsafe extern "C" fn rdds_reader_select(
1533    r: *const RddsReader,
1534    take: bool,
1535    max_samples: i32,
1536    sample_states: u32,
1537    view_states: u32,
1538    instance_states: u32,
1539    mode: i32,
1540    instance: *const RddsInstanceHandle,
1541    out: *mut *mut RddsSamples,
1542) -> Status {
1543    guard(|| {
1544        let r = unsafe { obj(r, "the reader") }?;
1545        let r = r.inner.max_samples(max(max_samples)?);
1546        let handle = unsafe { instance.as_ref() }
1547            .map(|h| InstanceHandle(h.value))
1548            .filter(|h| h.0 != [0; 16]);
1549        let v = match mode {
1550            SELECT_ANY => {
1551                let f = filter(sample_states, view_states, instance_states)?;
1552                if take { r.take_with(f) } else { r.read_with(f) }
1553            }
1554            SELECT_INSTANCE => {
1555                let h = handle.ok_or_else(|| bad("no instance given"))?;
1556                if take {
1557                    r.take_instance(h)
1558                } else {
1559                    r.read_instance(h)
1560                }
1561            }
1562            SELECT_NEXT_INSTANCE => {
1563                let f = filter(sample_states, view_states, instance_states)?;
1564                if take {
1565                    r.take_next_instance(handle, f)
1566                } else {
1567                    r.read_next_instance(handle, f)
1568                }
1569            }
1570            m => return Err(bad(format!("unknown selection {m}"))),
1571        };
1572        unsafe { put(out, RddsSamples(v)) }
1573    })
1574}
1575
1576/// `rdds_reader_select_w_condition`: the samples a read condition of
1577/// this reader selects, at most `max_samples`.
1578#[unsafe(no_mangle)]
1579pub unsafe extern "C" fn rdds_reader_select_w_condition(
1580    r: *const RddsReader,
1581    take: bool,
1582    max_samples: i32,
1583    condition: *const RddsCondition,
1584    out: *mut *mut RddsSamples,
1585) -> Status {
1586    guard(|| {
1587        let r = unsafe { obj(r, "the reader") }?;
1588        let c = unsafe { obj(condition, "the condition") }?;
1589        let rustorb_dds::Condition::Read(c) = &c.0 else {
1590            return Err(bad("not a read condition"));
1591        };
1592        let r = r.inner.max_samples(max(max_samples)?);
1593        let v = if take {
1594            r.take_w_condition(c)?
1595        } else {
1596            r.read_w_condition(c)?
1597        };
1598        unsafe { put(out, RddsSamples(v)) }
1599    })
1600}
1601
1602/// `rdds_samples_count`.
1603#[unsafe(no_mangle)]
1604pub unsafe extern "C" fn rdds_samples_count(s: *const RddsSamples) -> usize {
1605    unsafe { s.as_ref() }.map_or(0, |s| s.0.len())
1606}
1607
1608/// `rdds_samples_info`: the information of sample `i`.
1609#[unsafe(no_mangle)]
1610pub unsafe extern "C" fn rdds_samples_info(
1611    s: *const RddsSamples,
1612    i: usize,
1613    out: *mut RddsSampleInfo,
1614) -> Status {
1615    guard(|| {
1616        let s = unsafe { obj(s, "the samples") }?;
1617        let x = s.0.get(i).ok_or_else(|| bad("no such sample"))?;
1618        let info = &x.info;
1619        let v = RddsSampleInfo {
1620            sample_state: match info.sample_state {
1621                SampleState::Read => 1,
1622                SampleState::NotRead => 2,
1623            },
1624            view_state: match info.view_state {
1625                ViewState::New => 1,
1626                ViewState::NotNew => 2,
1627            },
1628            instance_state: match info.instance_state {
1629                InstanceState::Alive => 1,
1630                InstanceState::NotAliveDisposed => 2,
1631                InstanceState::NotAliveNoWriters => 4,
1632            },
1633            disposed_generation_count: info.disposed_generation_count as i32,
1634            no_writers_generation_count: info.no_writers_generation_count as i32,
1635            sample_rank: info.sample_rank as i32,
1636            generation_rank: info.generation_rank as i32,
1637            absolute_generation_rank: info.absolute_generation_rank as i32,
1638            source_timestamp: RddsTime::of(info.source_timestamp),
1639            instance_handle: RddsInstanceHandle::of(Some(info.instance_handle)),
1640            publication_handle: RddsGuid::of(Some(info.writer)),
1641            sequence_number: info.sequence_number.0,
1642            valid_data: info.valid_data,
1643        };
1644        unsafe { set(out, v) }
1645    })
1646}
1647
1648/// `rdds_samples_data`: an input stream of sample `i`'s values, released
1649/// by the caller; `RETCODE_NO_DATA` for a sample without data.
1650#[unsafe(no_mangle)]
1651pub unsafe extern "C" fn rdds_samples_data(
1652    s: *const RddsSamples,
1653    i: usize,
1654    out: *mut *mut In,
1655) -> Status {
1656    guard(|| {
1657        let s = unsafe { obj(s, "the samples") }?;
1658        let x = s.0.get(i).ok_or_else(|| bad("no such sample"))?;
1659        let d = x
1660            .data
1661            .as_ref()
1662            .ok_or_else(|| crate::Fail(crate::NO_DATA, "the sample has no data".into()))?;
1663        unsafe { put(out, from_data(d)?) }
1664    })
1665}
1666
1667/// `rdds_samples_release`.
1668#[unsafe(no_mangle)]
1669pub unsafe extern "C" fn rdds_samples_release(s: *mut RddsSamples) {
1670    unsafe { release(s) }
1671}
1672
1673/// `rdds_reader_lookup_instance`.
1674#[unsafe(no_mangle)]
1675pub unsafe extern "C" fn rdds_reader_lookup_instance(
1676    r: *const RddsReader,
1677    sample: *const Out,
1678    out: *mut RddsInstanceHandle,
1679) -> Status {
1680    guard(|| {
1681        let r = unsafe { obj(r, "the reader") }?;
1682        let s = unsafe { obj(sample, "the sample") }?;
1683        let d = to_data(&r.ty, s)?;
1684        unsafe { set(out, RddsInstanceHandle::of(r.inner.lookup_instance(&d))) }
1685    })
1686}
1687
1688/// `rdds_reader_get_key_value`: a sample with the key of an instance
1689/// (the other members default), or `RETCODE_BAD_PARAMETER` for an
1690/// unknown instance.
1691#[unsafe(no_mangle)]
1692pub unsafe extern "C" fn rdds_reader_get_key_value(
1693    r: *const RddsReader,
1694    instance: RddsInstanceHandle,
1695    out: *mut *mut In,
1696) -> Status {
1697    guard(|| {
1698        let r = unsafe { obj(r, "the reader") }?;
1699        let d = r
1700            .inner
1701            .get_key_value(InstanceHandle(instance.value))
1702            .ok_or_else(|| bad("unknown instance"))?;
1703        unsafe { put(out, from_data(&d)?) }
1704    })
1705}
1706
1707/// `rdds_reader_wait_for_data`: until a sample is there, or
1708/// `RETCODE_TIMEOUT`.
1709#[unsafe(no_mangle)]
1710pub unsafe extern "C" fn rdds_reader_wait_for_data(
1711    r: *const RddsReader,
1712    timeout: RddsDuration,
1713) -> Status {
1714    guard(|| {
1715        let r = unsafe { obj(r, "the reader") }?;
1716        if r.inner.wait_for_data(timeout.finite()?) {
1717            Ok(())
1718        } else {
1719            Err(crate::Fail(TIMEOUT, "no data in time".into()))
1720        }
1721    })
1722}
1723
1724/// `rdds_reader_wait_for_publications`.
1725#[unsafe(no_mangle)]
1726pub unsafe extern "C" fn rdds_reader_wait_for_publications(
1727    r: *const RddsReader,
1728    count: usize,
1729    timeout: RddsDuration,
1730) -> Status {
1731    guard(|| {
1732        let r = unsafe { obj(r, "the reader") }?;
1733        if r.inner.wait_for_publications(count, timeout.finite()?) {
1734            Ok(())
1735        } else {
1736            Err(crate::Fail(TIMEOUT, "no publications in time".into()))
1737        }
1738    })
1739}
1740
1741/// `rdds_reader_matched_publications`.
1742#[unsafe(no_mangle)]
1743pub unsafe extern "C" fn rdds_reader_matched_publications(
1744    r: *const RddsReader,
1745    buf: *mut RddsGuid,
1746    cap: usize,
1747    len: *mut usize,
1748) -> Status {
1749    guard(|| {
1750        let r = unsafe { obj(r, "the reader") }?;
1751        unsafe { guids(r.inner.matched_publications(), buf, cap, len) }
1752    })
1753}
1754
1755/// `rdds_reader_status_changes`.
1756#[unsafe(no_mangle)]
1757pub unsafe extern "C" fn rdds_reader_status_changes(r: *const RddsReader) -> u32 {
1758    guard_value(0, || {
1759        unsafe { r.as_ref() }.map_or(0, |r| r.inner.status_changes().0)
1760    })
1761}
1762
1763/// `rdds_reader_status_condition`.
1764#[unsafe(no_mangle)]
1765pub unsafe extern "C" fn rdds_reader_status_condition(
1766    r: *const RddsReader,
1767    out: *mut *mut RddsCondition,
1768) -> Status {
1769    guard(|| {
1770        let r = unsafe { obj(r, "the reader") }?;
1771        unsafe { put(out, RddsCondition::from(r.inner.status_condition())) }
1772    })
1773}
1774
1775/// `rdds_reader_create_readcondition`.
1776#[unsafe(no_mangle)]
1777pub unsafe extern "C" fn rdds_reader_create_readcondition(
1778    r: *const RddsReader,
1779    sample_states: u32,
1780    view_states: u32,
1781    instance_states: u32,
1782    out: *mut *mut RddsCondition,
1783) -> Status {
1784    guard(|| {
1785        let r = unsafe { obj(r, "the reader") }?;
1786        let f = filter(sample_states, view_states, instance_states)?;
1787        unsafe { put(out, RddsCondition::from(r.inner.create_readcondition(f))) }
1788    })
1789}
1790
1791/// `rdds_reader_set_listener`: NULL clears it.
1792#[unsafe(no_mangle)]
1793pub unsafe extern "C" fn rdds_reader_set_listener(
1794    r: *const RddsReader,
1795    listener: *const RddsReaderListener,
1796    mask: u32,
1797) -> Status {
1798    guard(|| {
1799        let r = unsafe { obj(r, "the reader") }?;
1800        match unsafe { listener.as_ref() } {
1801            None => r.inner.clear_listener(),
1802            Some(l) => r.inner.set_listener(ReaderCallbacks(*l), StatusMask(mask)),
1803        }
1804        Ok(())
1805    })
1806}