1use 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#[derive(Debug)]
19enum Target<'a, 'b> {
20 Stream(&'a mut OutStream<'b>),
21 Reply(*mut ServerReply),
24}
25
26#[derive(Debug)]
28pub struct Out<'a, 'b> {
29 target: Target<'a, 'b>,
30 pub(crate) error: Option<SystemException>,
31 pub(crate) objects: Vec<ObjectRef>,
34 standalone: bool,
35}
36
37pub 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 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 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 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#[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#[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
221mod 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#[derive(Debug)]
290pub struct In<'a, 'b> {
291 stream: &'a mut InStream<'b>,
292 completed: CompletionStatus,
293 pub(crate) error: Option<SystemException>,
294 text: String,
296 wide: Vec<u16>,
297 pub(crate) values: Vec<Option<crate::value::Held>>,
300 pub(crate) value_ids: Vec<String>,
302 pub(crate) owned: bool,
304}
305
306pub type RorbIn = In<'static, 'static>;
308
309impl<'a, 'b> In<'a, 'b> {
310 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 stream(&self) -> &InStream<'b> {
330 self.stream
331 }
332
333 pub(crate) fn marshal(&self) -> SystemException {
334 sys(SystemExceptionKind::MARSHAL, 0, self.completed)
335 }
336
337 pub(crate) fn read<T: Default>(
338 &mut self,
339 f: impl FnOnce(&mut InStream<'b>) -> Result<T, SystemException>,
340 ) -> T {
341 if self.error.is_some() {
342 return T::default();
343 }
344 match f(self.stream) {
345 Ok(v) => v,
346 Err(e) => {
347 self.error = Some(e);
348 T::default()
349 }
350 }
351 }
352}
353
354macro_rules! read_fns {
355 ($($name:ident -> $ty:ty;)*) => {
356 $(
357 #[unsafe(no_mangle)]
358 pub unsafe extern "C" fn $name(input: *mut RorbIn) -> $ty {
359 unsafe { &mut *input }.read(|s| s.read::<$ty>())
360 }
361 )*
362 };
363}
364
365read_fns! {
366 rorb_in_read_short -> i16;
367 rorb_in_read_ushort -> u16;
368 rorb_in_read_long -> i32;
369 rorb_in_read_ulong -> u32;
370 rorb_in_read_longlong -> i64;
371 rorb_in_read_ulonglong -> u64;
372 rorb_in_read_float -> f32;
373 rorb_in_read_double -> f64;
374}
375
376#[unsafe(no_mangle)]
377pub unsafe extern "C" fn rorb_in_read_octet(input: *mut RorbIn) -> u8 {
378 let input = unsafe { &mut *input };
379 let e = input.marshal();
380 input.read(|s| s.read_octet().map_err(|_| e))
381}
382
383#[unsafe(no_mangle)]
384pub unsafe extern "C" fn rorb_in_read_boolean(input: *mut RorbIn) -> i32 {
385 i32::from(unsafe { &mut *input }.read(|s| s.read::<bool>()))
386}
387
388#[unsafe(no_mangle)]
389pub unsafe extern "C" fn rorb_in_read_char(input: *mut RorbIn) -> c_char {
390 let input = unsafe { &mut *input };
391 let e = input.marshal();
392 input.read(|s| s.read_char().map_err(|_| e)) as c_char
393}
394
395#[unsafe(no_mangle)]
396pub unsafe extern "C" fn rorb_in_read_wchar(input: *mut RorbIn) -> u16 {
397 unsafe { &mut *input }.read(|s| s.read_wchar())
398}
399
400#[unsafe(no_mangle)]
401pub unsafe extern "C" fn rorb_in_read_string(input: *mut RorbIn, len: *mut usize) -> *const c_char {
402 let input = unsafe { &mut *input };
403 input.text = input.read(|s| s.read_string());
404 unsafe { *len = input.text.len() };
405 input.text.as_ptr() as *const c_char
406}
407
408#[unsafe(no_mangle)]
409pub unsafe extern "C" fn rorb_in_read_wstring(input: *mut RorbIn, len: *mut usize) -> *const u16 {
410 let input = unsafe { &mut *input };
411 let text = input.read(|s| s.read_wstring());
412 input.wide.clear();
413 input.wide.extend(text.encode_utf16());
414 unsafe { *len = input.wide.len() };
415 input.wide.as_ptr()
416}
417
418#[unsafe(no_mangle)]
419pub unsafe extern "C" fn rorb_in_read_object(input: *mut RorbIn) -> *mut ObjectRef {
420 match unsafe { &mut *input }.read(|s| s.read_object()) {
421 Some(obj) => into_handle(obj),
422 None => std::ptr::null_mut(),
423 }
424}
425
426#[unsafe(no_mangle)]
427pub unsafe extern "C" fn rorb_in_read_array(
428 input: *mut RorbIn,
429 kind: i32,
430 data: *mut c_void,
431 count: usize,
432) {
433 let input = unsafe { &mut *input };
434 let e = input.marshal();
435 input.read(|s| {
436 macro_rules! each {
437 ($ty:ty) => {
438 for v in unsafe { slice_mut::<$ty>(data, count) } {
439 *v = s.read::<$ty>()?;
440 }
441 };
442 }
443 match kind {
444 prim::OCTET => {
445 let bytes = s.read_octets(count).map_err(|_| e)?;
446 unsafe { slice_mut::<u8>(data, count) }.copy_from_slice(bytes);
447 }
448 prim::SHORT => each!(i16),
449 prim::USHORT => each!(u16),
450 prim::LONG => each!(i32),
451 prim::ULONG => each!(u32),
452 prim::LONGLONG => each!(i64),
453 prim::ULONGLONG => each!(u64),
454 prim::FLOAT => each!(f32),
455 prim::DOUBLE => each!(f64),
456 _ => return Err(crate::bad_param()),
457 }
458 Ok(())
459 });
460}
461
462#[unsafe(no_mangle)]
463pub unsafe extern "C" fn rorb_in_read_fixed(
464 input: *mut RorbIn,
465 digits: *mut u8,
466 count: usize,
467) -> i32 {
468 let input = unsafe { &mut *input };
469 let (read, negative) = input.read(|s| s.read_fixed(count));
470 let out = unsafe { slice_mut::<u8>(digits.cast(), count) };
471 if read.len() == count {
472 out.copy_from_slice(&read);
473 } else {
474 out.fill(0);
475 }
476 i32::from(negative)
477}
478
479#[unsafe(no_mangle)]
480pub unsafe extern "C" fn rorb_in_read_longdouble(input: *mut RorbIn, hi: *mut u64, lo: *mut u64) {
481 let bits = unsafe { &mut *input }
482 .read(|s| s.read::<LongDouble>())
483 .to_bits();
484 unsafe {
485 *hi = (bits >> 64) as u64;
486 *lo = bits as u64;
487 }
488}
489
490#[unsafe(no_mangle)]
491pub unsafe extern "C" fn rorb_in_read_length(input: *mut RorbIn, min_element_size: usize) -> u32 {
492 let input = unsafe { &mut *input };
493 let e = input.marshal();
494 input.read(|s| {
495 s.read_len(min_element_size.max(1))
496 .map(|n| n as u32)
497 .map_err(|_| e)
498 })
499}
500
501#[unsafe(no_mangle)]
502pub unsafe extern "C" fn rorb_in_fail(input: *mut RorbIn) {
503 let input = unsafe { &mut *input };
504 if input.error.is_none() {
505 input.error = Some(input.marshal());
506 }
507}
508
509#[unsafe(no_mangle)]
510pub unsafe extern "C" fn rorb_in_failed(input: *mut RorbIn) -> i32 {
511 i32::from(unsafe { &*input }.error.is_some())
512}