Skip to main content

rustorb_ffi/
stream.rs

1//! `rorb_out` and `rorb_in`: the CDR streams given to callbacks.
2//!
3//! Both keep the first error and ignore the calls after it (writes do
4//! nothing, reads return zeros), so that generated code can marshal a
5//! whole value and check once, when the callback returns.
6
7use std::ffi::{c_char, c_void};
8
9use rustorb_core::{
10    CompletionStatus, InStream, LongDouble, ObjectRef, OutStream, ServerReply, SystemException,
11    SystemExceptionKind,
12};
13
14use crate::{into_handle, str_arg, sys};
15
16// --- output ---------------------------------------------------------------------
17
18#[derive(Debug)]
19enum Target<'a, 'b> {
20    Stream(&'a mut OutStream<'b>),
21    /// The result stream of a server reply, taken again for each write
22    /// (each one continues where the last stopped).
23    Reply(*mut ServerReply),
24}
25
26/// An output stream for C.
27#[derive(Debug)]
28pub struct Out<'a, 'b> {
29    target: Target<'a, 'b>,
30    pub(crate) error: Option<SystemException>,
31    /// The object references written, kept only by a standalone stream
32    /// (`rorb_any_insert` reads them back with their ORB).
33    pub(crate) objects: Vec<ObjectRef>,
34    standalone: bool,
35    /// For the stream of `rorb_any_insert`: the new values written, which
36    /// keep their caller's instances (see `host`).
37    pub(crate) written: Option<Vec<crate::host::Written>>,
38}
39
40/// What a `rorb_out*` points to; the lifetimes are those of the callback.
41pub type RorbOut = Out<'static, 'static>;
42
43impl<'a, 'b> Out<'a, 'b> {
44    pub(crate) fn new(stream: &'a mut OutStream<'b>) -> Self {
45        Out {
46            target: Target::Stream(stream),
47            error: None,
48            objects: Vec::new(),
49            standalone: false,
50            written: None,
51        }
52    }
53
54    /// A stream that keeps the object references written.
55    pub(crate) fn standalone(stream: &'a mut OutStream<'b>) -> Self {
56        Out {
57            standalone: true,
58            ..Out::new(stream)
59        }
60    }
61
62    pub(crate) fn reply(reply: *mut ServerReply) -> Self {
63        Out {
64            target: Target::Reply(reply),
65            error: None,
66            objects: Vec::new(),
67            standalone: false,
68            written: None,
69        }
70    }
71
72    /// The server reply of a stream made by [`Out::reply`].
73    pub(crate) fn server_reply(&self) -> *mut ServerReply {
74        match self.target {
75            Target::Reply(r) => r,
76            Target::Stream(_) => unreachable!("not the stream of a server reply"),
77        }
78    }
79
80    /// The pointer given to C, valid while `self` is borrowed.
81    pub(crate) fn as_ptr(&mut self) -> *mut RorbOut {
82        (self as *mut Self).cast()
83    }
84
85    pub(crate) fn with(
86        &mut self,
87        f: impl FnOnce(&mut OutStream<'_>) -> Result<(), SystemException>,
88    ) {
89        if self.error.is_some() {
90            return;
91        }
92        let result = match &mut self.target {
93            Target::Stream(s) => f(s),
94            Target::Reply(r) => {
95                let mut out = unsafe { &mut **r }.output();
96                f(&mut out)
97            }
98        };
99        if let Err(e) = result {
100            self.error = Some(e);
101        }
102    }
103}
104
105macro_rules! write_fns {
106    ($($name:ident($ty:ty) => $method:ident;)*) => {
107        $(
108            #[unsafe(no_mangle)]
109            pub unsafe extern "C" fn $name(out: *mut RorbOut, v: $ty) {
110                unsafe { &mut *out }.with(|s| {
111                    s.$method(v);
112                    Ok(())
113                });
114            }
115        )*
116    };
117}
118
119write_fns! {
120    rorb_out_write_octet(u8) => write_octet;
121    rorb_out_write_short(i16) => write_i16;
122    rorb_out_write_ushort(u16) => write_u16;
123    rorb_out_write_long(i32) => write_i32;
124    rorb_out_write_ulong(u32) => write_u32;
125    rorb_out_write_longlong(i64) => write_i64;
126    rorb_out_write_ulonglong(u64) => write_u64;
127    rorb_out_write_float(f32) => write_f32;
128    rorb_out_write_double(f64) => write_f64;
129}
130
131#[unsafe(no_mangle)]
132pub unsafe extern "C" fn rorb_out_write_boolean(out: *mut RorbOut, v: i32) {
133    unsafe { &mut *out }.with(|s| {
134        s.write_bool(v != 0);
135        Ok(())
136    });
137}
138
139#[unsafe(no_mangle)]
140pub unsafe extern "C" fn rorb_out_write_char(out: *mut RorbOut, v: c_char) {
141    unsafe { &mut *out }.with(|s| {
142        s.write_char(v as u8);
143        Ok(())
144    });
145}
146
147#[unsafe(no_mangle)]
148pub unsafe extern "C" fn rorb_out_write_wchar(out: *mut RorbOut, v: u16) {
149    unsafe { &mut *out }.with(|s| s.write_wchar(v));
150}
151
152#[unsafe(no_mangle)]
153pub unsafe extern "C" fn rorb_out_write_string(out: *mut RorbOut, p: *const c_char, len: usize) {
154    unsafe { &mut *out }.with(|s| {
155        let text = unsafe { str_arg(p, len) }?;
156        s.write_string(text)
157    });
158}
159
160#[unsafe(no_mangle)]
161pub unsafe extern "C" fn rorb_out_write_wstring(out: *mut RorbOut, p: *const u16, len: usize) {
162    unsafe { &mut *out }.with(|s| {
163        let units = if p.is_null() || len == 0 {
164            &[][..]
165        } else {
166            unsafe { std::slice::from_raw_parts(p, len) }
167        };
168        let text = String::from_utf16(units).map_err(|_| {
169            sys(
170                SystemExceptionKind::DATA_CONVERSION,
171                0,
172                CompletionStatus::No,
173            )
174        })?;
175        s.write_wstring(&text)
176    });
177}
178
179#[unsafe(no_mangle)]
180pub unsafe extern "C" fn rorb_out_write_object(out: *mut RorbOut, obj: *mut ObjectRef) {
181    let out = unsafe { &mut *out };
182    let obj = unsafe { obj.as_ref() };
183    if out.standalone && out.error.is_none() {
184        out.objects.extend(obj.cloned());
185    }
186    out.with(|s| s.write_object(obj));
187}
188
189#[unsafe(no_mangle)]
190pub unsafe extern "C" fn rorb_out_write_fixed(
191    out: *mut RorbOut,
192    digits: *const u8,
193    count: usize,
194    negative: i32,
195) {
196    unsafe { &mut *out }
197        .with(|s| s.write_fixed(unsafe { slice::<u8>(digits.cast(), count) }, negative != 0));
198}
199
200#[unsafe(no_mangle)]
201pub unsafe extern "C" fn rorb_out_write_longdouble(out: *mut RorbOut, hi: u64, lo: u64) {
202    unsafe { &mut *out }.with(|s| {
203        s.write_long_double(LongDouble::from_bits(
204            (u128::from(hi) << 64) | u128::from(lo),
205        ));
206        Ok(())
207    });
208}
209
210/// The binary128 bits of `v` (exact).
211#[unsafe(no_mangle)]
212pub unsafe extern "C" fn rorb_longdouble_from_double(v: f64, hi: *mut u64, lo: *mut u64) {
213    let bits = LongDouble::from_f64(v).to_bits();
214    unsafe {
215        *hi = (bits >> 64) as u64;
216        *lo = bits as u64;
217    }
218}
219
220/// The double nearest to the binary128 bits (ties to even).
221#[unsafe(no_mangle)]
222pub extern "C" fn rorb_longdouble_to_double(hi: u64, lo: u64) -> f64 {
223    LongDouble::from_bits((u128::from(hi) << 64) | u128::from(lo)).to_f64()
224}
225
226/// Element kinds of the array functions (`RORB_PRIM_*`).
227mod prim {
228    pub const OCTET: i32 = 0;
229    pub const SHORT: i32 = 1;
230    pub const USHORT: i32 = 2;
231    pub const LONG: i32 = 3;
232    pub const ULONG: i32 = 4;
233    pub const LONGLONG: i32 = 5;
234    pub const ULONGLONG: i32 = 6;
235    pub const FLOAT: i32 = 7;
236    pub const DOUBLE: i32 = 8;
237}
238
239unsafe fn slice<'s, T>(data: *const c_void, count: usize) -> &'s [T] {
240    if data.is_null() || count == 0 {
241        &[]
242    } else {
243        unsafe { std::slice::from_raw_parts(data as *const T, count) }
244    }
245}
246
247unsafe fn slice_mut<'s, T>(data: *mut c_void, count: usize) -> &'s mut [T] {
248    if data.is_null() || count == 0 {
249        &mut []
250    } else {
251        unsafe { std::slice::from_raw_parts_mut(data as *mut T, count) }
252    }
253}
254
255#[unsafe(no_mangle)]
256pub unsafe extern "C" fn rorb_out_write_array(
257    out: *mut RorbOut,
258    kind: i32,
259    data: *const c_void,
260    count: usize,
261) {
262    unsafe { &mut *out }.with(|s| {
263        macro_rules! each {
264            ($ty:ty, $method:ident) => {
265                for v in unsafe { slice::<$ty>(data, count) } {
266                    s.$method(*v);
267                }
268            };
269        }
270        match kind {
271            prim::OCTET => s.write_octets(unsafe { slice::<u8>(data, count) }),
272            prim::SHORT => each!(i16, write_i16),
273            prim::USHORT => each!(u16, write_u16),
274            prim::LONG => each!(i32, write_i32),
275            prim::ULONG => each!(u32, write_u32),
276            prim::LONGLONG => each!(i64, write_i64),
277            prim::ULONGLONG => each!(u64, write_u64),
278            prim::FLOAT => each!(f32, write_f32),
279            prim::DOUBLE => each!(f64, write_f64),
280            _ => return Err(crate::bad_param()),
281        }
282        Ok(())
283    });
284}
285
286#[unsafe(no_mangle)]
287pub unsafe extern "C" fn rorb_out_failed(out: *mut RorbOut) -> i32 {
288    i32::from(unsafe { &*out }.error.is_some())
289}
290
291// --- input ----------------------------------------------------------------------
292
293/// An input stream for C.
294#[derive(Debug)]
295pub struct In<'a, 'b> {
296    stream: &'a mut InStream<'b>,
297    completed: CompletionStatus,
298    pub(crate) error: Option<SystemException>,
299    /// The last string read, until the next call.
300    text: String,
301    wide: Vec<u16>,
302    /// The caller's valuetype instances read, by slot, for indirections
303    /// (`rorb_in_set_value`); released when the stream is dropped.
304    pub(crate) values: Vec<Option<crate::value::Held>>,
305    /// The repository ids of the last value header read.
306    pub(crate) value_ids: Vec<String>,
307    /// Whether the caller owns the stream (`rorb_in_release`).
308    pub(crate) owned: bool,
309    /// For the stream of `rorb_any_extract`: the core instances written to
310    /// it, by slot, whose caller's instances are given back (see `host`).
311    pub(crate) bound: Option<Vec<rustorb_core::ValueRef>>,
312}
313
314/// What a `rorb_in*` points to; the lifetimes are those of the callback.
315pub type RorbIn = In<'static, 'static>;
316
317impl<'a, 'b> In<'a, 'b> {
318    /// A stream whose errors are `MARSHAL` with `completed`.
319    pub(crate) fn new(stream: &'a mut InStream<'b>, completed: CompletionStatus) -> Self {
320        In {
321            stream,
322            completed,
323            error: None,
324            text: String::new(),
325            wide: Vec::new(),
326            values: Vec::new(),
327            value_ids: Vec::new(),
328            owned: false,
329            bound: None,
330        }
331    }
332
333    pub(crate) fn as_ptr(&mut self) -> *mut RorbIn {
334        (self as *mut Self).cast()
335    }
336
337    /// The core's stream.
338    pub(crate) fn stream(&self) -> &InStream<'b> {
339        self.stream
340    }
341
342    pub(crate) fn marshal(&self) -> SystemException {
343        sys(SystemExceptionKind::MARSHAL, 0, self.completed)
344    }
345
346    pub(crate) fn read<T: Default>(
347        &mut self,
348        f: impl FnOnce(&mut InStream<'b>) -> Result<T, SystemException>,
349    ) -> T {
350        if self.error.is_some() {
351            return T::default();
352        }
353        match f(self.stream) {
354            Ok(v) => v,
355            Err(e) => {
356                self.error = Some(e);
357                T::default()
358            }
359        }
360    }
361}
362
363macro_rules! read_fns {
364    ($($name:ident -> $ty:ty;)*) => {
365        $(
366            #[unsafe(no_mangle)]
367            pub unsafe extern "C" fn $name(input: *mut RorbIn) -> $ty {
368                unsafe { &mut *input }.read(|s| s.read::<$ty>())
369            }
370        )*
371    };
372}
373
374read_fns! {
375    rorb_in_read_short -> i16;
376    rorb_in_read_ushort -> u16;
377    rorb_in_read_long -> i32;
378    rorb_in_read_ulong -> u32;
379    rorb_in_read_longlong -> i64;
380    rorb_in_read_ulonglong -> u64;
381    rorb_in_read_float -> f32;
382    rorb_in_read_double -> f64;
383}
384
385#[unsafe(no_mangle)]
386pub unsafe extern "C" fn rorb_in_read_octet(input: *mut RorbIn) -> u8 {
387    let input = unsafe { &mut *input };
388    let e = input.marshal();
389    input.read(|s| s.read_octet().map_err(|_| e))
390}
391
392#[unsafe(no_mangle)]
393pub unsafe extern "C" fn rorb_in_read_boolean(input: *mut RorbIn) -> i32 {
394    i32::from(unsafe { &mut *input }.read(|s| s.read::<bool>()))
395}
396
397#[unsafe(no_mangle)]
398pub unsafe extern "C" fn rorb_in_read_char(input: *mut RorbIn) -> c_char {
399    let input = unsafe { &mut *input };
400    let e = input.marshal();
401    input.read(|s| s.read_char().map_err(|_| e)) as c_char
402}
403
404#[unsafe(no_mangle)]
405pub unsafe extern "C" fn rorb_in_read_wchar(input: *mut RorbIn) -> u16 {
406    unsafe { &mut *input }.read(|s| s.read_wchar())
407}
408
409#[unsafe(no_mangle)]
410pub unsafe extern "C" fn rorb_in_read_string(input: *mut RorbIn, len: *mut usize) -> *const c_char {
411    let input = unsafe { &mut *input };
412    input.text = input.read(|s| s.read_string());
413    unsafe { *len = input.text.len() };
414    input.text.as_ptr() as *const c_char
415}
416
417#[unsafe(no_mangle)]
418pub unsafe extern "C" fn rorb_in_read_wstring(input: *mut RorbIn, len: *mut usize) -> *const u16 {
419    let input = unsafe { &mut *input };
420    let text = input.read(|s| s.read_wstring());
421    input.wide.clear();
422    input.wide.extend(text.encode_utf16());
423    unsafe { *len = input.wide.len() };
424    input.wide.as_ptr()
425}
426
427#[unsafe(no_mangle)]
428pub unsafe extern "C" fn rorb_in_read_object(input: *mut RorbIn) -> *mut ObjectRef {
429    match unsafe { &mut *input }.read(|s| s.read_object()) {
430        Some(obj) => into_handle(obj),
431        None => std::ptr::null_mut(),
432    }
433}
434
435#[unsafe(no_mangle)]
436pub unsafe extern "C" fn rorb_in_read_array(
437    input: *mut RorbIn,
438    kind: i32,
439    data: *mut c_void,
440    count: usize,
441) {
442    let input = unsafe { &mut *input };
443    let e = input.marshal();
444    input.read(|s| {
445        macro_rules! each {
446            ($ty:ty) => {
447                for v in unsafe { slice_mut::<$ty>(data, count) } {
448                    *v = s.read::<$ty>()?;
449                }
450            };
451        }
452        match kind {
453            prim::OCTET => {
454                let bytes = s.read_octets(count).map_err(|_| e)?;
455                unsafe { slice_mut::<u8>(data, count) }.copy_from_slice(bytes);
456            }
457            prim::SHORT => each!(i16),
458            prim::USHORT => each!(u16),
459            prim::LONG => each!(i32),
460            prim::ULONG => each!(u32),
461            prim::LONGLONG => each!(i64),
462            prim::ULONGLONG => each!(u64),
463            prim::FLOAT => each!(f32),
464            prim::DOUBLE => each!(f64),
465            _ => return Err(crate::bad_param()),
466        }
467        Ok(())
468    });
469}
470
471#[unsafe(no_mangle)]
472pub unsafe extern "C" fn rorb_in_read_fixed(
473    input: *mut RorbIn,
474    digits: *mut u8,
475    count: usize,
476) -> i32 {
477    let input = unsafe { &mut *input };
478    let (read, negative) = input.read(|s| s.read_fixed(count));
479    let out = unsafe { slice_mut::<u8>(digits.cast(), count) };
480    if read.len() == count {
481        out.copy_from_slice(&read);
482    } else {
483        out.fill(0);
484    }
485    i32::from(negative)
486}
487
488#[unsafe(no_mangle)]
489pub unsafe extern "C" fn rorb_in_read_longdouble(input: *mut RorbIn, hi: *mut u64, lo: *mut u64) {
490    let bits = unsafe { &mut *input }
491        .read(|s| s.read::<LongDouble>())
492        .to_bits();
493    unsafe {
494        *hi = (bits >> 64) as u64;
495        *lo = bits as u64;
496    }
497}
498
499#[unsafe(no_mangle)]
500pub unsafe extern "C" fn rorb_in_read_length(input: *mut RorbIn, min_element_size: usize) -> u32 {
501    let input = unsafe { &mut *input };
502    let e = input.marshal();
503    input.read(|s| {
504        s.read_len(min_element_size.max(1))
505            .map(|n| n as u32)
506            .map_err(|_| e)
507    })
508}
509
510#[unsafe(no_mangle)]
511pub unsafe extern "C" fn rorb_in_fail(input: *mut RorbIn) {
512    let input = unsafe { &mut *input };
513    if input.error.is_none() {
514        input.error = Some(input.marshal());
515    }
516}
517
518#[unsafe(no_mangle)]
519pub unsafe extern "C" fn rorb_in_failed(input: *mut RorbIn) -> i32 {
520    i32::from(unsafe { &*input }.error.is_some())
521}