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