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 rustorb_cdr::ValueHeader;
13use rustorb_core::TypeCode;
14
15use crate::str_arg;
16use crate::stream::{RorbIn, RorbOut};
17
18/// `RORB_VALUE_NULL`, `RORB_VALUE_INDIRECTION`, `RORB_VALUE_NEW`.
19pub const VALUE_NULL: i32 = 0;
20pub const VALUE_INDIRECTION: i32 = 1;
21pub const VALUE_NEW: i32 = 2;
22
23/// Releases an instance stored with `rorb_in_set_value`.
24pub type ReleaseFn = Option<unsafe extern "C" fn(*mut c_void)>;
25
26/// An instance of the caller kept by an input stream.
27#[derive(Debug)]
28pub struct Held {
29    ptr: *mut c_void,
30    release: ReleaseFn,
31}
32
33impl Drop for Held {
34    fn drop(&mut self) {
35        if let Some(release) = self.release {
36            unsafe { release(self.ptr) };
37        }
38    }
39}
40
41// --- output ---------------------------------------------------------------------
42
43#[unsafe(no_mangle)]
44pub unsafe extern "C" fn rorb_out_write_null_value(out: *mut RorbOut) {
45    unsafe { &mut *out }.with(|s| {
46        s.write_null_value();
47        Ok(())
48    });
49}
50
51/// Starts a value: returns 1 when the caller writes its state (then
52/// calls `rorb_out_end_value`), 0 when an indirection was written or the
53/// stream failed.
54#[unsafe(no_mangle)]
55pub unsafe extern "C" fn rorb_out_begin_value(
56    out: *mut RorbOut,
57    key: u64,
58    count: usize,
59    ids: *const *const c_char,
60    id_lens: *const usize,
61    chunked: i32,
62) -> i32 {
63    let out = unsafe { &mut *out };
64    let mut state = false;
65    out.with(|s| {
66        let mut list = Vec::with_capacity(count);
67        for i in 0..count {
68            list.push(unsafe { str_arg(*ids.add(i), *id_lens.add(i)) }?);
69        }
70        state = s.begin_value(key, &list, chunked != 0)?;
71        Ok(())
72    });
73    i32::from(state && out.error.is_none())
74}
75
76#[unsafe(no_mangle)]
77pub unsafe extern "C" fn rorb_out_end_value(out: *mut RorbOut) {
78    unsafe { &mut *out }.with(|s| Ok(s.end_value()?));
79}
80
81// --- input ----------------------------------------------------------------------
82
83/// Reads what stands where a value is expected. For an indirection,
84/// `*slot` is the slot of the value it refers to; for a new value, its
85/// own slot and `*id_count` the number of repository ids sent (read with
86/// `rorb_in_value_id`). After an error, returns `RORB_VALUE_NULL`.
87#[unsafe(no_mangle)]
88pub unsafe extern "C" fn rorb_in_read_value_header(
89    input: *mut RorbIn,
90    slot: *mut usize,
91    id_count: *mut usize,
92) -> i32 {
93    let input = unsafe { &mut *input };
94    let e = input.marshal();
95    let header = input.read(|s| s.read_value_header().map(Some).map_err(|_| e));
96    unsafe {
97        *slot = 0;
98        *id_count = 0;
99    }
100    match header {
101        None | Some(ValueHeader::Null) => VALUE_NULL,
102        Some(ValueHeader::Indirection(n)) => {
103            unsafe { *slot = n };
104            VALUE_INDIRECTION
105        }
106        Some(ValueHeader::Value { slot: n, ids, .. }) => {
107            unsafe {
108                *slot = n;
109                *id_count = ids.len();
110            }
111            input.value_ids = ids;
112            VALUE_NEW
113        }
114    }
115}
116
117/// The repository id `index` of the last value header read (UTF-8,
118/// valid until the next value header).
119#[unsafe(no_mangle)]
120pub unsafe extern "C" fn rorb_in_value_id(
121    input: *mut RorbIn,
122    index: usize,
123    len: *mut usize,
124) -> *const c_char {
125    let input = unsafe { &*input };
126    match input.value_ids.get(index) {
127        Some(id) => {
128            unsafe { *len = id.len() };
129            id.as_ptr().cast()
130        }
131        None => {
132            unsafe { *len = 0 };
133            c"".as_ptr()
134        }
135    }
136}
137
138/// Ends the value whose header was read last, skipping the state not
139/// read (of a truncated derived type).
140#[unsafe(no_mangle)]
141pub unsafe extern "C" fn rorb_in_end_value(input: *mut RorbIn) {
142    let input = unsafe { &mut *input };
143    let e = input.marshal();
144    input.read(|s| s.end_value().map_err(|_| e));
145}
146
147/// Keeps `ptr`, the caller's instance of the value at `slot`, until the
148/// stream ends; `release(ptr)` is then called (unless it is NULL).
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn rorb_in_set_value(
151    input: *mut RorbIn,
152    slot: usize,
153    ptr: *mut c_void,
154    release: ReleaseFn,
155) {
156    let input = unsafe { &mut *input };
157    if input.values.len() <= slot {
158        input.values.resize_with(slot + 1, || None);
159    }
160    input.values[slot] = Some(Held { ptr, release });
161}
162
163/// The instance kept for `slot`, or NULL (an indirection to a value the
164/// caller did not read, say).
165#[unsafe(no_mangle)]
166pub unsafe extern "C" fn rorb_in_get_value(input: *mut RorbIn, slot: usize) -> *mut c_void {
167    match unsafe { &*input }.values.get(slot) {
168        Some(Some(held)) => held.ptr,
169        _ => std::ptr::null_mut(),
170    }
171}
172
173// --- the registry of the core ---------------------------------------------------
174
175/// Makes the valuetype `tc` known to the core, which reads the values in
176/// anys (see `rustorb_core::register_value_type`).
177#[unsafe(no_mangle)]
178pub unsafe extern "C" fn rorb_register_value_type(tc: *const TypeCode) {
179    if let Some(tc) = unsafe { tc.as_ref() } {
180        rustorb_core::register_value_type(tc);
181    }
182}
183
184/// Finds the valuetype of a repository id: a new TypeCode handle (taken
185/// over) or NULL.
186pub type ResolveFn =
187    Option<unsafe extern "C" fn(*mut c_void, *const c_char, usize) -> *mut TypeCode>;
188
189struct Resolver {
190    resolve: unsafe extern "C" fn(*mut c_void, *const c_char, usize) -> *mut TypeCode,
191    context: *mut c_void,
192}
193
194// The caller makes `resolve` callable from any thread with `context`.
195unsafe impl Send for Resolver {}
196unsafe impl Sync for Resolver {}
197
198impl Resolver {
199    fn find(&self, id: &str) -> Option<TypeCode> {
200        let tc = unsafe { (self.resolve)(self.context, id.as_ptr().cast(), id.len()) };
201        if tc.is_null() {
202            None
203        } else {
204            Some(*unsafe { Box::from_raw(tc) })
205        }
206    }
207}
208
209/// Asks `resolve(context, id, len)` for the valuetypes the core reads
210/// that are not registered (NULL removes it).
211#[unsafe(no_mangle)]
212pub unsafe extern "C" fn rorb_set_value_type_resolver(resolve: ResolveFn, context: *mut c_void) {
213    let resolver = resolve.map(|resolve| {
214        let r = Resolver { resolve, context };
215        std::sync::Arc::new(move |id: &str| r.find(id))
216            as std::sync::Arc<rustorb_core::ValueTypeResolver>
217    });
218    rustorb_core::set_value_type_resolver(resolver);
219}