Skip to main content

rustorb_dds_ffi/
lib.rs

1//! Stable `extern "C"` ABI of rustorb-dds.
2//!
3//! The C++ binding (`cpp/include/rustorb/dds`) and the Java binding
4//! (through the FFM API) are built on this crate; the Python binding uses
5//! PyO3 directly instead. The functions are declared, with the rules every
6//! caller follows (handles, errors, strings, streams), in
7//! `include/rustorb/dds.h`, whose names start with `rdds_`.
8//!
9//! - [`types`]: topic types, built the way DDS-XTypes 1.3 builds a
10//!   `DynamicType` (7.5.2.2), member by member.
11//! - [`stream`]: samples. The caller writes the values of a sample in the
12//!   order of its type into an output stream, and reads a sample from an
13//!   input stream in the same order; the library encodes and decodes them
14//!   (XCDR1 or XCDR2, the key hash) knowing the type. Generated code
15//!   therefore knows nothing of the encodings.
16//! - [`entity`]: the DCPS entities, their QoS and statuses.
17//! - [`condition`]: conditions and WaitSets.
18//!
19//! Failures return a DDS `ReturnCode_t` (DDS 1.4, 2.2.1.1) and leave a
20//! message for the thread ([`rdds_last_error_message`]). A Rust panic is
21//! caught at the boundary and returns `RETCODE_ERROR`.
22
23// Every function takes raw pointers from C; what they must point to is
24// documented once, in the header.
25#![allow(clippy::missing_safety_doc)]
26// The fields of the C structs are documented in the header too.
27#![allow(missing_docs)]
28
29pub mod condition;
30pub mod entity;
31pub mod listener;
32pub mod rpc;
33pub mod stream;
34pub mod types;
35
36use std::cell::RefCell;
37use std::ffi::{CStr, CString, c_char};
38use std::panic::{AssertUnwindSafe, catch_unwind};
39
40/// `rdds_status`: a DDS `ReturnCode_t`.
41pub type Status = i32;
42
43/// `RETCODE_OK`.
44pub const OK: Status = 0;
45/// `RETCODE_ERROR`.
46pub const ERROR: Status = 1;
47/// `RETCODE_UNSUPPORTED`.
48pub const UNSUPPORTED: Status = 2;
49/// `RETCODE_BAD_PARAMETER`.
50pub const BAD_PARAMETER: Status = 3;
51/// `RETCODE_PRECONDITION_NOT_MET`.
52pub const PRECONDITION_NOT_MET: Status = 4;
53/// `RETCODE_OUT_OF_RESOURCES`.
54pub const OUT_OF_RESOURCES: Status = 5;
55/// `RETCODE_ALREADY_DELETED`.
56pub const ALREADY_DELETED: Status = 9;
57/// `RETCODE_TIMEOUT`.
58pub const TIMEOUT: Status = 10;
59/// `RETCODE_NO_DATA`.
60pub const NO_DATA: Status = 11;
61
62/// The version of the ABI in the header (`RDDS_ABI_VERSION`).
63pub const ABI_VERSION: u32 = 1;
64
65/// `rdds_abi_version`: the ABI version of the library, to compare with
66/// `RDDS_ABI_VERSION` of the header the caller was built with.
67#[unsafe(no_mangle)]
68pub extern "C" fn rdds_abi_version() -> u32 {
69    ABI_VERSION
70}
71
72thread_local! {
73    static LAST_ERROR: RefCell<CString> = RefCell::new(CString::default());
74}
75
76/// `rdds_last_error_message`: the message of the last failure on this
77/// thread, valid until the next failure on the thread.
78#[unsafe(no_mangle)]
79pub extern "C" fn rdds_last_error_message() -> *const c_char {
80    LAST_ERROR.with(|e| e.borrow().as_ptr())
81}
82
83/// A failure: the code to return and the message to leave.
84#[derive(Debug)]
85pub(crate) struct Fail(pub Status, pub String);
86
87pub(crate) type Res<T = ()> = std::result::Result<T, Fail>;
88
89pub(crate) fn bad(msg: impl Into<String>) -> Fail {
90    Fail(BAD_PARAMETER, msg.into())
91}
92
93impl From<rustorb_dds::Error> for Fail {
94    fn from(e: rustorb_dds::Error) -> Fail {
95        use rustorb_dds::Error as E;
96        let code = match &e {
97            E::Serialize(_) | E::Dynamic(_) => BAD_PARAMETER,
98            E::AlreadyDeleted => ALREADY_DELETED,
99            E::OutOfResources => OUT_OF_RESOURCES,
100            E::Timeout => TIMEOUT,
101            E::PreconditionNotMet => PRECONDITION_NOT_MET,
102            E::Unsupported(_) => UNSUPPORTED,
103            _ => ERROR,
104        };
105        Fail(code, e.to_string())
106    }
107}
108
109impl From<rustorb_xtypes::Error> for Fail {
110    fn from(e: rustorb_xtypes::Error) -> Fail {
111        bad(e.to_string())
112    }
113}
114
115fn set_error(msg: &str) {
116    let c = CString::new(msg.replace('\0', " ")).unwrap_or_default();
117    LAST_ERROR.with(|e| *e.borrow_mut() = c);
118}
119
120/// Runs `f`, turning its failure or panic into a status.
121pub(crate) fn guard(f: impl FnOnce() -> Res) -> Status {
122    match catch_unwind(AssertUnwindSafe(f)) {
123        Ok(Ok(())) => OK,
124        Ok(Err(Fail(code, msg))) => {
125            set_error(&msg);
126            code
127        }
128        Err(p) => {
129            let msg = p
130                .downcast_ref::<&str>()
131                .map(|s| s.to_string())
132                .or_else(|| p.downcast_ref::<String>().cloned())
133                .unwrap_or_else(|| "panic".into());
134            set_error(&format!("internal error: {msg}"));
135            ERROR
136        }
137    }
138}
139
140/// Runs `f` for a value of a function that cannot fail, `default` after
141/// a panic.
142pub(crate) fn guard_value<T>(default: T, f: impl FnOnce() -> T) -> T {
143    catch_unwind(AssertUnwindSafe(f)).unwrap_or(default)
144}
145
146/// The object a handle points to; a failure for NULL.
147pub(crate) unsafe fn obj<'a, T>(p: *const T, what: &str) -> Res<&'a T> {
148    // SAFETY: the caller passes NULL or a live handle (the header).
149    unsafe { p.as_ref() }.ok_or_else(|| bad(format!("{what} is NULL")))
150}
151
152/// Stores `v` boxed in `*out`.
153pub(crate) unsafe fn put<T>(out: *mut *mut T, v: T) -> Res {
154    if out.is_null() {
155        return Err(bad("the output pointer is NULL"));
156    }
157    // SAFETY: `out` is valid for a write (the header).
158    unsafe { *out = Box::into_raw(Box::new(v)) };
159    Ok(())
160}
161
162/// Writes `v` to `*out`.
163pub(crate) unsafe fn set<T>(out: *mut T, v: T) -> Res {
164    if out.is_null() {
165        return Err(bad("the output pointer is NULL"));
166    }
167    // SAFETY: `out` is valid for a write (the header).
168    unsafe { out.write(v) };
169    Ok(())
170}
171
172/// A NUL-terminated UTF-8 string.
173pub(crate) unsafe fn cstr<'a>(p: *const c_char, what: &str) -> Res<&'a str> {
174    if p.is_null() {
175        return Err(bad(format!("{what} is NULL")));
176    }
177    // SAFETY: a NUL-terminated string (the header).
178    unsafe { CStr::from_ptr(p) }
179        .to_str()
180        .map_err(|_| bad(format!("{what} is not UTF-8")))
181}
182
183/// `n` items at `p` (NULL for none when `n` is 0).
184pub(crate) unsafe fn slice<'a, T>(p: *const T, n: usize) -> Res<&'a [T]> {
185    if n == 0 {
186        return Ok(&[]);
187    }
188    if p.is_null() {
189        return Err(bad("an array pointer is NULL"));
190    }
191    // SAFETY: `n` valid items (the header).
192    Ok(unsafe { std::slice::from_raw_parts(p, n) })
193}
194
195/// Frees a handle made by [`put`].
196pub(crate) unsafe fn release<T>(p: *mut T) {
197    if !p.is_null() {
198        let _ = catch_unwind(AssertUnwindSafe(|| {
199            // SAFETY: a handle this library made, released once.
200            drop(unsafe { Box::from_raw(p) })
201        }));
202    }
203}