Skip to main content

rustorb_ffi/
value.rs

1//! Valuetypes on the `rorb_out` and `rorb_in` streams.
2//!
3//! The caller marshals the state of its own instances; these functions
4//! write and read what surrounds it (the value tag, the repository ids,
5//! chunks, end tags) and keep what sharing needs: an instance written
6//! twice in a message is sent as an indirection the second time (the
7//! caller names instances by a key), and the instances read are kept by
8//! slot, so that an indirection to one gives the same instance back.
9
10use std::ffi::{c_char, c_void};
11
12use std::sync::Arc;
13
14use rustorb_cdr::ValueHeader;
15use rustorb_core::TypeCode;
16
17use crate::host::{Host, Owned, Written, host_of};
18use crate::str_arg;
19use crate::stream::{RorbIn, RorbOut};
20
21/// `RORB_VALUE_NULL`, `RORB_VALUE_INDIRECTION`, `RORB_VALUE_NEW`.
22pub const VALUE_NULL: i32 = 0;
23pub const VALUE_INDIRECTION: i32 = 1;
24pub const VALUE_NEW: i32 = 2;
25
26/// Releases an instance stored with `rorb_in_set_value`.
27pub type ReleaseFn = Option<unsafe extern "C" fn(*mut c_void)>;
28
29/// An instance of the caller kept by an input stream.
30#[derive(Debug)]
31pub struct Held {
32    ptr: *mut c_void,
33    release: ReleaseFn,
34    /// The caller's key of the instance (`rorb_in_set_host_value`).
35    pub(crate) key: Option<u64>,
36    /// The core's reference, for an instance a core instance stands for.
37    _host: Option<Arc<Host>>,
38}
39
40impl Held {
41    /// The pointer and its release function, taken over from the stream.
42    pub(crate) fn take(&mut self) -> (*mut c_void, ReleaseFn) {
43        (self.ptr, self.release.take())
44    }
45}
46
47impl Drop for Held {
48    fn drop(&mut self) {
49        if let Some(release) = self.release {
50            unsafe { release(self.ptr) };
51        }
52    }
53}
54
55// --- output ---------------------------------------------------------------------
56
57#[unsafe(no_mangle)]
58pub unsafe extern "C" fn rorb_out_write_null_value(out: *mut RorbOut) {
59    unsafe { &mut *out }.with(|s| {
60        s.write_null_value();
61        Ok(())
62    });
63}
64
65/// Starts a value: returns 1 when the caller writes its state (then
66/// calls `rorb_out_end_value`), 0 when an indirection was written or the
67/// stream failed.
68#[unsafe(no_mangle)]
69pub unsafe extern "C" fn rorb_out_begin_value(
70    out: *mut RorbOut,
71    key: u64,
72    count: usize,
73    ids: *const *const c_char,
74    id_lens: *const usize,
75    chunked: i32,
76) -> i32 {
77    unsafe { begin_value(&mut *out, key, None, count, ids, id_lens, chunked) }
78}
79
80/// Whether the stream keeps the caller's instances written
81/// (`rorb_out_begin_host_value`): 1 for the stream of `rorb_any_insert`.
82#[unsafe(no_mangle)]
83pub unsafe extern "C" fn rorb_out_keeps_hosts(out: *mut RorbOut) -> i32 {
84    i32::from(unsafe { &*out }.written.is_some())
85}
86
87/// Like `rorb_out_begin_value`, and takes `host`, a reference to the
88/// caller's instance (released with `release` when not kept): an any
89/// whose value is read back from the stream keeps it, so that extracting
90/// gives the same instance, and inserting the instance (the same key)
91/// again reuses the core's instance.
92#[unsafe(no_mangle)]
93pub unsafe extern "C" fn rorb_out_begin_host_value(
94    out: *mut RorbOut,
95    key: u64,
96    host: *mut c_void,
97    release: ReleaseFn,
98    count: usize,
99    ids: *const *const c_char,
100    id_lens: *const usize,
101    chunked: i32,
102) -> i32 {
103    let host = Owned::new(host, release);
104    unsafe { begin_value(&mut *out, key, Some(host), count, ids, id_lens, chunked) }
105}
106
107unsafe fn begin_value(
108    out: &mut RorbOut,
109    key: u64,
110    host: Option<Owned>,
111    count: usize,
112    ids: *const *const c_char,
113    id_lens: *const usize,
114    chunked: i32,
115) -> i32 {
116    let mut state = false;
117    let mut slot = 0;
118    out.with(|s| {
119        let mut list = Vec::with_capacity(count);
120        for i in 0..count {
121            list.push(unsafe { str_arg(*ids.add(i), *id_lens.add(i)) }?);
122        }
123        slot = s.value_count();
124        state = s.begin_value(key, &list, chunked != 0)?;
125        Ok(())
126    });
127    let state = state && out.error.is_none();
128    if state {
129        if let Some(written) = &mut out.written {
130            written.push(Written { slot, key, host });
131        }
132    }
133    i32::from(state)
134}
135
136#[unsafe(no_mangle)]
137pub unsafe extern "C" fn rorb_out_end_value(out: *mut RorbOut) {
138    unsafe { &mut *out }.with(|s| Ok(s.end_value()?));
139}
140
141// --- input ----------------------------------------------------------------------
142
143/// Reads what stands where a value is expected. For an indirection,
144/// `*slot` is the slot of the value it refers to; for a new value, its
145/// own slot and `*id_count` the number of repository ids sent (read with
146/// `rorb_in_value_id`). After an error, returns `RORB_VALUE_NULL`.
147#[unsafe(no_mangle)]
148pub unsafe extern "C" fn rorb_in_read_value_header(
149    input: *mut RorbIn,
150    slot: *mut usize,
151    id_count: *mut usize,
152) -> i32 {
153    let input = unsafe { &mut *input };
154    let e = input.marshal();
155    let header = input.read(|s| s.read_value_header().map(Some).map_err(|_| e));
156    unsafe {
157        *slot = 0;
158        *id_count = 0;
159    }
160    match header {
161        None | Some(ValueHeader::Null) => VALUE_NULL,
162        Some(ValueHeader::Indirection(n)) => {
163            // To a value skipped inside one given back (below).
164            input.hold_host(n);
165            unsafe { *slot = n };
166            VALUE_INDIRECTION
167        }
168        Some(ValueHeader::Value { slot: n, ids, .. }) => {
169            unsafe { *slot = n };
170            if input.hold_host(n) {
171                // The caller's instance is given back: its state (always
172                // chunked in this stream) is skipped.
173                let e = input.marshal();
174                input.read(|s| s.end_value().map_err(|_| e));
175                return VALUE_INDIRECTION;
176            }
177            unsafe { *id_count = ids.len() };
178            input.value_ids = ids;
179            VALUE_NEW
180        }
181    }
182}
183
184impl RorbIn {
185    /// For the stream of `rorb_any_extract`: keeps for `slot` the
186    /// caller's instance the core instance written there stands for, if
187    /// it has one and none is kept yet; whether one is kept now.
188    fn hold_host(&mut self, slot: usize) -> bool {
189        if matches!(self.values.get(slot), Some(Some(_))) {
190            return false;
191        }
192        let Some(host) = self
193            .bound
194            .as_ref()
195            .and_then(|b| b.get(slot))
196            .and_then(host_of)
197        else {
198            return false;
199        };
200        if self.values.len() <= slot {
201            self.values.resize_with(slot + 1, || None);
202        }
203        self.values[slot] = Some(Held {
204            ptr: host.ptr,
205            release: None,
206            key: None,
207            _host: Some(host),
208        });
209        true
210    }
211}
212
213/// The repository id `index` of the last value header read (UTF-8,
214/// valid until the next value header).
215#[unsafe(no_mangle)]
216pub unsafe extern "C" fn rorb_in_value_id(
217    input: *mut RorbIn,
218    index: usize,
219    len: *mut usize,
220) -> *const c_char {
221    let input = unsafe { &*input };
222    match input.value_ids.get(index) {
223        Some(id) => {
224            unsafe { *len = id.len() };
225            id.as_ptr().cast()
226        }
227        None => {
228            unsafe { *len = 0 };
229            c"".as_ptr()
230        }
231    }
232}
233
234/// Ends the value whose header was read last, skipping the state not
235/// read (of a truncated derived type).
236#[unsafe(no_mangle)]
237pub unsafe extern "C" fn rorb_in_end_value(input: *mut RorbIn) {
238    let input = unsafe { &mut *input };
239    let e = input.marshal();
240    input.read(|s| s.end_value().map_err(|_| e));
241}
242
243/// Keeps `ptr`, the caller's instance of the value at `slot`, until the
244/// stream ends; `release(ptr)` is then called (unless it is NULL).
245#[unsafe(no_mangle)]
246pub unsafe extern "C" fn rorb_in_set_value(
247    input: *mut RorbIn,
248    slot: usize,
249    ptr: *mut c_void,
250    release: ReleaseFn,
251) {
252    unsafe { set_value(&mut *input, slot, None, ptr, release) }
253}
254
255/// Like `rorb_in_set_value`, with the caller's key of the instance (as it
256/// writes it with `rorb_out_begin_host_value`): the stream of
257/// `rorb_any_extract` then gives `ptr` to the any's core instance, which
258/// keeps it instead of the stream.
259#[unsafe(no_mangle)]
260pub unsafe extern "C" fn rorb_in_set_host_value(
261    input: *mut RorbIn,
262    slot: usize,
263    key: u64,
264    ptr: *mut c_void,
265    release: ReleaseFn,
266) {
267    unsafe { set_value(&mut *input, slot, Some(key), ptr, release) }
268}
269
270/// Whether the stream gives the caller's instances it reads to the core
271/// (`rorb_in_set_host_value`): 1 for the stream of `rorb_any_extract`.
272#[unsafe(no_mangle)]
273pub unsafe extern "C" fn rorb_in_keeps_hosts(input: *mut RorbIn) -> i32 {
274    i32::from(unsafe { &*input }.bound.is_some())
275}
276
277unsafe fn set_value(
278    input: &mut RorbIn,
279    slot: usize,
280    key: Option<u64>,
281    ptr: *mut c_void,
282    release: ReleaseFn,
283) {
284    if input.values.len() <= slot {
285        input.values.resize_with(slot + 1, || None);
286    }
287    input.values[slot] = Some(Held {
288        ptr,
289        release,
290        key,
291        _host: None,
292    });
293}
294
295/// The instance kept for `slot`, or NULL (an indirection to a value the
296/// caller did not read, say).
297#[unsafe(no_mangle)]
298pub unsafe extern "C" fn rorb_in_get_value(input: *mut RorbIn, slot: usize) -> *mut c_void {
299    match unsafe { &*input }.values.get(slot) {
300        Some(Some(held)) => held.ptr,
301        _ => std::ptr::null_mut(),
302    }
303}
304
305// --- the registry of the core ---------------------------------------------------
306
307/// Makes the valuetype `tc` known to the core, which reads the values in
308/// anys (see `rustorb_core::register_value_type`).
309#[unsafe(no_mangle)]
310pub unsafe extern "C" fn rorb_register_value_type(tc: *const TypeCode) {
311    if let Some(tc) = unsafe { tc.as_ref() } {
312        rustorb_core::register_value_type(tc);
313    }
314}
315
316/// Finds the valuetype of a repository id: a new TypeCode handle (taken
317/// over) or NULL.
318pub type ResolveFn =
319    Option<unsafe extern "C" fn(*mut c_void, *const c_char, usize) -> *mut TypeCode>;
320
321struct Resolver {
322    resolve: unsafe extern "C" fn(*mut c_void, *const c_char, usize) -> *mut TypeCode,
323    context: *mut c_void,
324}
325
326// The caller makes `resolve` callable from any thread with `context`.
327unsafe impl Send for Resolver {}
328unsafe impl Sync for Resolver {}
329
330impl Resolver {
331    fn find(&self, id: &str) -> Option<TypeCode> {
332        let tc = unsafe { (self.resolve)(self.context, id.as_ptr().cast(), id.len()) };
333        if tc.is_null() {
334            None
335        } else {
336            Some(*unsafe { Box::from_raw(tc) })
337        }
338    }
339}
340
341/// Asks `resolve(context, id, len)` for the valuetypes the core reads
342/// that are not registered (NULL removes it).
343#[unsafe(no_mangle)]
344pub unsafe extern "C" fn rorb_set_value_type_resolver(resolve: ResolveFn, context: *mut c_void) {
345    let resolver = resolve.map(|resolve| {
346        let r = Resolver { resolve, context };
347        std::sync::Arc::new(move |id: &str| r.find(id))
348            as std::sync::Arc<rustorb_core::ValueTypeResolver>
349    });
350    rustorb_core::set_value_type_resolver(resolver);
351}