Skip to main content

rustorb_ffi/
any.rs

1//! `rorb_typecode` and `rorb_any`: TypeCodes and anys.
2//!
3//! A TypeCode handle is a core [`TypeCode`], an any handle a core [`Any`]
4//! (a TypeCode and a [`rustorb_core::Value`]). The caller puts its own
5//! values in an any and takes them out through callbacks that write and
6//! read them on a standalone CDR stream, as it marshals arguments: the
7//! value is converted to and from the core representation on the way.
8
9use std::ffi::{c_char, c_void};
10
11use rustorb_cdr::{ByteOrder, Decoder, Encoder, Encoding};
12use rustorb_core::{
13    Any, CompletionStatus, InStream, ObjectRef, Orb, OutStream, SystemExceptionKind, TCKind,
14    TypeCode, TypeCodeError,
15};
16
17use crate::stream::{In, Out, RorbIn, RorbOut};
18use crate::{
19    CALLBACK_FAILED, Exception, OK, Status, bad_param, guard, into_handle, local, release_handle,
20    set_local, set_system, str_arg, sys,
21};
22
23// --- TypeCodes ------------------------------------------------------------------
24
25unsafe fn tc_error(exc: *mut Exception, e: TypeCodeError) -> Status {
26    match e {
27        TypeCodeError::BadKind => unsafe { set_local(exc, local::TC_BAD_KIND, 0) },
28        TypeCodeError::Bounds => unsafe { set_local(exc, local::TC_BOUNDS, 0) },
29        TypeCodeError::BadParam => unsafe { set_system(exc, &bad_param()) },
30    }
31}
32
33/// Stores the result of a TypeCode operation in `*out`.
34unsafe fn put<T>(
35    exc: *mut Exception,
36    out: *mut T,
37    f: impl FnOnce() -> Result<T, TypeCodeError>,
38) -> Status {
39    guard(exc, || match f() {
40        Ok(v) => {
41            unsafe { out.write(v) };
42            OK
43        }
44        Err(e) => unsafe { tc_error(exc, e) },
45    })
46}
47
48/// Stores a new TypeCode handle in `*out`.
49unsafe fn put_tc(
50    exc: *mut Exception,
51    out: *mut *mut TypeCode,
52    f: impl FnOnce() -> Result<TypeCode, TypeCodeError>,
53) -> Status {
54    unsafe { put(exc, out, || f().map(into_handle)) }
55}
56
57/// A string argument of a TypeCode constructor; invalid UTF-8 is
58/// `BadParam`.
59unsafe fn name_arg<'a>(p: *const c_char, len: usize) -> Result<&'a str, TypeCodeError> {
60    unsafe { str_arg(p, len) }.map_err(|_| TypeCodeError::BadParam)
61}
62
63unsafe fn tc_arg<'a>(tc: *const TypeCode) -> Result<&'a TypeCode, TypeCodeError> {
64    unsafe { tc.as_ref() }.ok_or(TypeCodeError::BadParam)
65}
66
67/// `count` names and types from C arrays.
68unsafe fn members<'a>(
69    count: usize,
70    names: *const *const c_char,
71    name_lens: *const usize,
72    types: *const *const TypeCode,
73) -> Result<Vec<(&'a str, TypeCode)>, TypeCodeError> {
74    let mut out = Vec::with_capacity(count);
75    for i in 0..count {
76        let name = unsafe { name_arg(*names.add(i), *name_lens.add(i)) }?;
77        let tc = unsafe { tc_arg(*types.add(i)) }?;
78        out.push((name, tc.clone()));
79    }
80    Ok(out)
81}
82
83#[unsafe(no_mangle)]
84pub unsafe extern "C" fn rorb_tc_clone(tc: *const TypeCode) -> *mut TypeCode {
85    match unsafe { tc.as_ref() } {
86        Some(tc) => into_handle(tc.clone()),
87        None => std::ptr::null_mut(),
88    }
89}
90
91#[unsafe(no_mangle)]
92pub unsafe extern "C" fn rorb_tc_release(tc: *mut TypeCode) {
93    unsafe { release_handle(tc) }
94}
95
96#[unsafe(no_mangle)]
97pub unsafe extern "C" fn rorb_tc_simple(
98    kind: u32,
99    out: *mut *mut TypeCode,
100    exc: *mut Exception,
101) -> Status {
102    unsafe {
103        put_tc(exc, out, || {
104            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
105            match kind {
106                TCKind::String => Ok(TypeCode::string(0)),
107                TCKind::WString => Ok(TypeCode::wstring(0)),
108                _ => TypeCode::simple(kind),
109            }
110        })
111    }
112}
113
114#[unsafe(no_mangle)]
115pub unsafe extern "C" fn rorb_tc_string(
116    wide: i32,
117    bound: u32,
118    out: *mut *mut TypeCode,
119    exc: *mut Exception,
120) -> Status {
121    unsafe {
122        put_tc(exc, out, || {
123            Ok(if wide != 0 {
124                TypeCode::wstring(bound)
125            } else {
126                TypeCode::string(bound)
127            })
128        })
129    }
130}
131
132#[unsafe(no_mangle)]
133pub unsafe extern "C" fn rorb_tc_fixed(
134    digits: u16,
135    scale: i16,
136    out: *mut *mut TypeCode,
137    exc: *mut Exception,
138) -> Status {
139    unsafe { put_tc(exc, out, || TypeCode::fixed(digits, scale)) }
140}
141
142#[unsafe(no_mangle)]
143pub unsafe extern "C" fn rorb_tc_sequence(
144    content: *const TypeCode,
145    bound: u32,
146    out: *mut *mut TypeCode,
147    exc: *mut Exception,
148) -> Status {
149    unsafe { put_tc(exc, out, || TypeCode::sequence(tc_arg(content)?, bound)) }
150}
151
152#[unsafe(no_mangle)]
153pub unsafe extern "C" fn rorb_tc_array(
154    content: *const TypeCode,
155    length: u32,
156    out: *mut *mut TypeCode,
157    exc: *mut Exception,
158) -> Status {
159    unsafe { put_tc(exc, out, || TypeCode::array(tc_arg(content)?, length)) }
160}
161
162#[unsafe(no_mangle)]
163pub unsafe extern "C" fn rorb_tc_alias(
164    kind: u32,
165    id: *const c_char,
166    id_len: usize,
167    name: *const c_char,
168    name_len: usize,
169    content: *const TypeCode,
170    out: *mut *mut TypeCode,
171    exc: *mut Exception,
172) -> Status {
173    unsafe {
174        put_tc(exc, out, || {
175            let id = name_arg(id, id_len)?;
176            let name = name_arg(name, name_len)?;
177            let content = tc_arg(content)?;
178            match TCKind::from_u32(kind) {
179                Some(TCKind::Alias) => TypeCode::alias(id, name, content),
180                Some(TCKind::ValueBox) => TypeCode::value_box(id, name, content),
181                _ => Err(TypeCodeError::BadParam),
182            }
183        })
184    }
185}
186
187#[unsafe(no_mangle)]
188pub unsafe extern "C" fn rorb_tc_interface(
189    kind: u32,
190    id: *const c_char,
191    id_len: usize,
192    name: *const c_char,
193    name_len: usize,
194    out: *mut *mut TypeCode,
195    exc: *mut Exception,
196) -> Status {
197    unsafe {
198        put_tc(exc, out, || {
199            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
200            TypeCode::interface(kind, name_arg(id, id_len)?, name_arg(name, name_len)?)
201        })
202    }
203}
204
205#[unsafe(no_mangle)]
206pub unsafe extern "C" fn rorb_tc_struct(
207    kind: u32,
208    id: *const c_char,
209    id_len: usize,
210    name: *const c_char,
211    name_len: usize,
212    count: usize,
213    names: *const *const c_char,
214    name_lens: *const usize,
215    types: *const *const TypeCode,
216    out: *mut *mut TypeCode,
217    exc: *mut Exception,
218) -> Status {
219    unsafe {
220        put_tc(exc, out, || {
221            let id = name_arg(id, id_len)?;
222            let name = name_arg(name, name_len)?;
223            let members = members(count, names, name_lens, types)?;
224            match TCKind::from_u32(kind) {
225                Some(TCKind::Struct) => TypeCode::struct_tc(id, name, &members),
226                Some(TCKind::Except) => TypeCode::exception(id, name, &members),
227                _ => Err(TypeCodeError::BadParam),
228            }
229        })
230    }
231}
232
233#[unsafe(no_mangle)]
234pub unsafe extern "C" fn rorb_tc_union(
235    id: *const c_char,
236    id_len: usize,
237    name: *const c_char,
238    name_len: usize,
239    discriminator: *const TypeCode,
240    count: usize,
241    labels: *const u64,
242    default_index: i32,
243    names: *const *const c_char,
244    name_lens: *const usize,
245    types: *const *const TypeCode,
246    out: *mut *mut TypeCode,
247    exc: *mut Exception,
248) -> Status {
249    unsafe {
250        put_tc(exc, out, || {
251            let id = name_arg(id, id_len)?;
252            let name = name_arg(name, name_len)?;
253            let disc = tc_arg(discriminator)?;
254            let unsigned = disc.unaliased().kind() == TCKind::ULongLong;
255            let members = members(count, names, name_lens, types)?
256                .into_iter()
257                .enumerate()
258                .map(|(i, (n, tc))| {
259                    let bits = *labels.add(i);
260                    let label = if i as i32 == default_index {
261                        None
262                    } else if unsigned {
263                        Some(i128::from(bits))
264                    } else {
265                        Some(i128::from(bits as i64))
266                    };
267                    (label, n, tc)
268                })
269                .collect::<Vec<_>>();
270            TypeCode::union_tc(id, name, disc, &members)
271        })
272    }
273}
274
275#[unsafe(no_mangle)]
276pub unsafe extern "C" fn rorb_tc_enum(
277    id: *const c_char,
278    id_len: usize,
279    name: *const c_char,
280    name_len: usize,
281    count: usize,
282    names: *const *const c_char,
283    name_lens: *const usize,
284    out: *mut *mut TypeCode,
285    exc: *mut Exception,
286) -> Status {
287    unsafe {
288        put_tc(exc, out, || {
289            let id = name_arg(id, id_len)?;
290            let name = name_arg(name, name_len)?;
291            let names = (0..count)
292                .map(|i| name_arg(*names.add(i), *name_lens.add(i)))
293                .collect::<Result<Vec<_>, _>>()?;
294            TypeCode::enum_tc(id, name, &names)
295        })
296    }
297}
298
299/// A valuetype (`RORB_TK_VALUE`) or eventtype (`RORB_TK_EVENT`):
300/// `base` is the concrete base type or NULL, and each member has a
301/// visibility (`PRIVATE_MEMBER` 0, `PUBLIC_MEMBER` 1).
302#[unsafe(no_mangle)]
303pub unsafe extern "C" fn rorb_tc_value(
304    kind: u32,
305    id: *const c_char,
306    id_len: usize,
307    name: *const c_char,
308    name_len: usize,
309    modifier: i16,
310    base: *const TypeCode,
311    count: usize,
312    names: *const *const c_char,
313    name_lens: *const usize,
314    types: *const *const TypeCode,
315    visibilities: *const i16,
316    out: *mut *mut TypeCode,
317    exc: *mut Exception,
318) -> Status {
319    unsafe {
320        put_tc(exc, out, || {
321            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
322            let id = name_arg(id, id_len)?;
323            let name = name_arg(name, name_len)?;
324            let members: Vec<(&str, TypeCode, i16)> = members(count, names, name_lens, types)?
325                .into_iter()
326                .enumerate()
327                .map(|(i, (n, t))| (n, t, *visibilities.add(i)))
328                .collect();
329            TypeCode::value_tc(kind, id, name, modifier, base.as_ref(), &members)
330        })
331    }
332}
333
334#[unsafe(no_mangle)]
335pub unsafe extern "C" fn rorb_tc_recursive(
336    id: *const c_char,
337    id_len: usize,
338    out: *mut *mut TypeCode,
339    exc: *mut Exception,
340) -> Status {
341    unsafe { put_tc(exc, out, || Ok(TypeCode::recursive(name_arg(id, id_len)?))) }
342}
343
344#[unsafe(no_mangle)]
345pub unsafe extern "C" fn rorb_tc_kind(tc: *const TypeCode) -> u32 {
346    unsafe { &*tc }.kind().as_u32()
347}
348
349/// Stores a string of the TypeCode, valid while it lives.
350unsafe fn put_str(
351    exc: *mut Exception,
352    p: *mut *const c_char,
353    len: *mut usize,
354    f: impl FnOnce() -> Result<*const str, TypeCodeError>,
355) -> Status {
356    let mut s: *const str = "";
357    let status = unsafe { put(exc, &mut s, f) };
358    if status == OK {
359        let s = unsafe { &*s };
360        unsafe {
361            p.write(s.as_ptr() as *const c_char);
362            len.write(s.len());
363        }
364    }
365    status
366}
367
368#[unsafe(no_mangle)]
369pub unsafe extern "C" fn rorb_tc_id(
370    tc: *const TypeCode,
371    p: *mut *const c_char,
372    len: *mut usize,
373    exc: *mut Exception,
374) -> Status {
375    unsafe { put_str(exc, p, len, || (*tc).id().map(|s| s as *const str)) }
376}
377
378#[unsafe(no_mangle)]
379pub unsafe extern "C" fn rorb_tc_name(
380    tc: *const TypeCode,
381    p: *mut *const c_char,
382    len: *mut usize,
383    exc: *mut Exception,
384) -> Status {
385    unsafe { put_str(exc, p, len, || (*tc).name().map(|s| s as *const str)) }
386}
387
388#[unsafe(no_mangle)]
389pub unsafe extern "C" fn rorb_tc_member_count(
390    tc: *const TypeCode,
391    out: *mut u32,
392    exc: *mut Exception,
393) -> Status {
394    unsafe { put(exc, out, || (*tc).member_count()) }
395}
396
397#[unsafe(no_mangle)]
398pub unsafe extern "C" fn rorb_tc_member_name(
399    tc: *const TypeCode,
400    index: u32,
401    p: *mut *const c_char,
402    len: *mut usize,
403    exc: *mut Exception,
404) -> Status {
405    unsafe {
406        put_str(exc, p, len, || {
407            (*tc).member_name(index).map(|s| s as *const str)
408        })
409    }
410}
411
412#[unsafe(no_mangle)]
413pub unsafe extern "C" fn rorb_tc_member_type(
414    tc: *const TypeCode,
415    index: u32,
416    out: *mut *mut TypeCode,
417    exc: *mut Exception,
418) -> Status {
419    unsafe { put_tc(exc, out, || (*tc).member_type(index)) }
420}
421
422#[unsafe(no_mangle)]
423pub unsafe extern "C" fn rorb_tc_member_label(
424    tc: *const TypeCode,
425    index: u32,
426    out: *mut *mut Any,
427    exc: *mut Exception,
428) -> Status {
429    unsafe { put(exc, out, || (*tc).member_label(index).map(into_handle)) }
430}
431
432#[unsafe(no_mangle)]
433pub unsafe extern "C" fn rorb_tc_discriminator_type(
434    tc: *const TypeCode,
435    out: *mut *mut TypeCode,
436    exc: *mut Exception,
437) -> Status {
438    unsafe { put_tc(exc, out, || (*tc).discriminator_type()) }
439}
440
441#[unsafe(no_mangle)]
442pub unsafe extern "C" fn rorb_tc_default_index(
443    tc: *const TypeCode,
444    out: *mut i32,
445    exc: *mut Exception,
446) -> Status {
447    unsafe { put(exc, out, || (*tc).default_index()) }
448}
449
450#[unsafe(no_mangle)]
451pub unsafe extern "C" fn rorb_tc_length(
452    tc: *const TypeCode,
453    out: *mut u32,
454    exc: *mut Exception,
455) -> Status {
456    unsafe { put(exc, out, || (*tc).length()) }
457}
458
459#[unsafe(no_mangle)]
460pub unsafe extern "C" fn rorb_tc_content_type(
461    tc: *const TypeCode,
462    out: *mut *mut TypeCode,
463    exc: *mut Exception,
464) -> Status {
465    unsafe { put_tc(exc, out, || (*tc).content_type()) }
466}
467
468#[unsafe(no_mangle)]
469pub unsafe extern "C" fn rorb_tc_fixed_digits(
470    tc: *const TypeCode,
471    out: *mut u16,
472    exc: *mut Exception,
473) -> Status {
474    unsafe { put(exc, out, || (*tc).fixed_digits()) }
475}
476
477#[unsafe(no_mangle)]
478pub unsafe extern "C" fn rorb_tc_fixed_scale(
479    tc: *const TypeCode,
480    out: *mut i16,
481    exc: *mut Exception,
482) -> Status {
483    unsafe { put(exc, out, || (*tc).fixed_scale()) }
484}
485
486#[unsafe(no_mangle)]
487pub unsafe extern "C" fn rorb_tc_member_visibility(
488    tc: *const TypeCode,
489    index: u32,
490    out: *mut i16,
491    exc: *mut Exception,
492) -> Status {
493    unsafe { put(exc, out, || (*tc).member_visibility(index)) }
494}
495
496#[unsafe(no_mangle)]
497pub unsafe extern "C" fn rorb_tc_type_modifier(
498    tc: *const TypeCode,
499    out: *mut i16,
500    exc: *mut Exception,
501) -> Status {
502    unsafe { put(exc, out, || (*tc).type_modifier()) }
503}
504
505/// The concrete base type, or NULL for none.
506#[unsafe(no_mangle)]
507pub unsafe extern "C" fn rorb_tc_concrete_base_type(
508    tc: *const TypeCode,
509    out: *mut *mut TypeCode,
510    exc: *mut Exception,
511) -> Status {
512    unsafe {
513        put(exc, out, || {
514            (*tc)
515                .concrete_base_type()
516                .map(|b| b.map_or(std::ptr::null_mut(), into_handle))
517        })
518    }
519}
520
521#[unsafe(no_mangle)]
522pub unsafe extern "C" fn rorb_tc_equal(a: *const TypeCode, b: *const TypeCode) -> i32 {
523    i32::from(unsafe { (*a).equal(&*b) })
524}
525
526#[unsafe(no_mangle)]
527pub unsafe extern "C" fn rorb_tc_equivalent(a: *const TypeCode, b: *const TypeCode) -> i32 {
528    i32::from(unsafe { (*a).equivalent(&*b) })
529}
530
531#[unsafe(no_mangle)]
532pub unsafe extern "C" fn rorb_tc_compact(tc: *const TypeCode) -> *mut TypeCode {
533    into_handle(unsafe { &*tc }.compact())
534}
535
536#[unsafe(no_mangle)]
537pub unsafe extern "C" fn rorb_tc_unaliased(tc: *const TypeCode) -> *mut TypeCode {
538    into_handle(unsafe { &*tc }.unaliased())
539}
540
541// --- anys -----------------------------------------------------------------------
542
543/// Writes the value of an any (`rorb_any_insert`).
544pub type WriteFn = Option<unsafe extern "C" fn(*mut c_void, *mut RorbOut) -> Status>;
545/// Reads the value of an any (`rorb_any_extract`).
546pub type ReadFn = Option<unsafe extern "C" fn(*mut c_void, *mut RorbIn) -> Status>;
547
548#[unsafe(no_mangle)]
549pub extern "C" fn rorb_any_new() -> *mut Any {
550    into_handle(Any::default())
551}
552
553#[unsafe(no_mangle)]
554pub unsafe extern "C" fn rorb_any_clone(any: *const Any) -> *mut Any {
555    match unsafe { any.as_ref() } {
556        Some(any) => into_handle(any.clone()),
557        None => std::ptr::null_mut(),
558    }
559}
560
561#[unsafe(no_mangle)]
562pub unsafe extern "C" fn rorb_any_release(any: *mut Any) {
563    // The valuetypes in it may refer to each other in cycles, which only
564    // the core sees (docs/valuetype.md): those nothing else refers to are
565    // freed.
566    if !any.is_null() {
567        rustorb_core::Value::Any(unsafe { Box::from_raw(any) }).release();
568    }
569}
570
571#[unsafe(no_mangle)]
572pub unsafe extern "C" fn rorb_any_type(any: *const Any) -> *mut TypeCode {
573    into_handle(unsafe { &*any }.typecode().clone())
574}
575
576/// Replaces the TypeCode of an any with an equivalent one.
577#[unsafe(no_mangle)]
578pub unsafe extern "C" fn rorb_any_set_type(
579    any: *mut Any,
580    tc: *const TypeCode,
581    exc: *mut Exception,
582) -> Status {
583    guard(exc, || {
584        let any = unsafe { &mut *any };
585        let tc = unsafe { &*tc };
586        if !any.typecode().equivalent(tc) {
587            let e = sys(SystemExceptionKind::BAD_TYPECODE, 0, CompletionStatus::No);
588            return unsafe { set_system(exc, &e) };
589        }
590        let value = std::mem::take(any).into_parts().1;
591        *any = Any::new(tc.clone(), value);
592        OK
593    })
594}
595
596/// Whether two anys have equal TypeCodes and the same value (floats
597/// compared exactly, object references with `is_equivalent`).
598#[unsafe(no_mangle)]
599pub unsafe extern "C" fn rorb_any_equal(a: *const Any, b: *const Any) -> i32 {
600    let (a, b) = unsafe { (&*a, &*b) };
601    i32::from(a.typecode().equal(b.typecode()) && a.value() == b.value())
602}
603
604/// The value of an any of a discriminator type as a union label number
605/// (two's complement for negative values); 0 if it is not one.
606#[unsafe(no_mangle)]
607pub unsafe extern "C" fn rorb_any_label(any: *const Any, label: *mut u64) -> i32 {
608    match unsafe { &*any }.value().label_key() {
609        Some(v) => {
610            unsafe { label.write(v as u64) };
611            1
612        }
613        None => 0,
614    }
615}
616
617/// The ORB of the object references read back from a standalone stream:
618/// the first one in a value, else the first ORB initialised.
619pub(crate) fn default_orb() -> Option<Orb> {
620    crate::orb::default_orb()
621}
622
623pub(crate) fn encoder() -> Encoder {
624    Encoder::new(ByteOrder::Big, Encoding::Giop1_2)
625}
626
627/// Whether values of type `tc` start with a repository id when marshalled
628/// in an any (exceptions), which the caller's codecs do not write.
629fn exception_id(tc: &TypeCode) -> Option<String> {
630    let tc = tc.unaliased();
631    (tc.kind() == TCKind::Except).then(|| tc.id().unwrap_or_default().to_owned())
632}
633
634/// Makes an any of type `tc` from the value `write` writes, as it would
635/// marshal it as an argument.
636#[unsafe(no_mangle)]
637pub unsafe extern "C" fn rorb_any_insert(
638    tc: *const TypeCode,
639    write: WriteFn,
640    context: *mut c_void,
641    out: *mut *mut Any,
642    exc: *mut Exception,
643) -> Status {
644    guard(exc, || {
645        let tc = unsafe { &*tc };
646        let mut enc = encoder();
647        let mut orb = None;
648        {
649            let mut stream = OutStream::standalone(&mut enc);
650            if let Some(id) = exception_id(tc) {
651                if let Err(e) = stream.write_string(&id) {
652                    return unsafe { set_system(exc, &e) };
653                }
654            }
655            let mut out = Out::standalone(&mut stream);
656            if let Some(write) = write {
657                let status = unsafe { write(context, out.as_ptr()) };
658                if status != OK {
659                    return CALLBACK_FAILED;
660                }
661            }
662            if let Some(e) = out.error.take() {
663                return unsafe { set_system(exc, &e) };
664            }
665            if let Some(o) = out.objects.first() {
666                orb = Some(o.orb().clone());
667            }
668        }
669        let orb = orb.or_else(default_orb);
670        let bytes = enc.into_bytes();
671        let mut input = InStream::standalone(
672            Decoder::new(&bytes, ByteOrder::Big, Encoding::Giop1_2),
673            orb.as_ref(),
674        );
675        match input.read_value(tc) {
676            Ok(v) => {
677                unsafe { out.write(into_handle(Any::new(tc.clone(), v))) };
678                OK
679            }
680            Err(e) => unsafe { set_system(exc, &e) },
681        }
682    })
683}
684
685/// Reads the value of an any with `read`, as it would read an argument
686/// of its type. The caller has checked the type.
687#[unsafe(no_mangle)]
688pub unsafe extern "C" fn rorb_any_extract(
689    any: *const Any,
690    read: ReadFn,
691    context: *mut c_void,
692    exc: *mut Exception,
693) -> Status {
694    guard(exc, || {
695        let any = unsafe { &*any };
696        let mut enc = encoder();
697        {
698            let mut stream = OutStream::standalone(&mut enc);
699            if let Err(e) = stream.write_value(any.typecode(), any.value()) {
700                return unsafe { set_system(exc, &e) };
701            }
702        }
703        let orb = first_object(any.value())
704            .map(|o| o.orb().clone())
705            .or_else(default_orb);
706        let bytes = enc.into_bytes();
707        let mut stream = InStream::standalone(
708            Decoder::new(&bytes, ByteOrder::Big, Encoding::Giop1_2),
709            orb.as_ref(),
710        );
711        if exception_id(any.typecode()).is_some() {
712            if let Err(e) = stream.read_string() {
713                return unsafe { set_system(exc, &e) };
714            }
715        }
716        let mut input = In::new(&mut stream, CompletionStatus::No);
717        if let Some(read) = read {
718            let status = unsafe { read(context, input.as_ptr()) };
719            if status != OK {
720                return CALLBACK_FAILED;
721            }
722        }
723        match input.error.take() {
724            Some(e) => unsafe { set_system(exc, &e) },
725            None => OK,
726        }
727    })
728}
729
730/// The first object reference in a value.
731pub(crate) fn first_object(v: &rustorb_core::Value) -> Option<&ObjectRef> {
732    use rustorb_core::Value;
733    match v {
734        Value::Objref(Some(o)) => Some(o),
735        Value::List(l) => l.iter().find_map(first_object),
736        Value::Union {
737            member: Some((_, m)),
738            ..
739        } => first_object(m),
740        Value::Any(a) => first_object(a.value()),
741        _ => None,
742    }
743}
744
745#[unsafe(no_mangle)]
746pub unsafe extern "C" fn rorb_out_write_typecode(out: *mut RorbOut, tc: *const TypeCode) {
747    unsafe { &mut *out }.with(|s| s.write_typecode(unsafe { &*tc }));
748}
749
750#[unsafe(no_mangle)]
751pub unsafe extern "C" fn rorb_out_write_any(out: *mut RorbOut, any: *const Any) {
752    unsafe { &mut *out }.with(|s| s.write_any(unsafe { &*any }));
753}
754
755/// NULL after an error.
756#[unsafe(no_mangle)]
757pub unsafe extern "C" fn rorb_in_read_typecode(input: *mut RorbIn) -> *mut TypeCode {
758    match unsafe { &mut *input }.read(|s| s.read_typecode().map(Some)) {
759        Some(tc) => into_handle(tc),
760        None => std::ptr::null_mut(),
761    }
762}
763
764/// NULL after an error.
765#[unsafe(no_mangle)]
766pub unsafe extern "C" fn rorb_in_read_any(input: *mut RorbIn) -> *mut Any {
767    match unsafe { &mut *input }.read(|s| s.read_any().map(Some)) {
768        Some(any) => into_handle(any),
769        None => std::ptr::null_mut(),
770    }
771}
772
773/// Writes the value of `any`, without its TypeCode.
774#[unsafe(no_mangle)]
775pub unsafe extern "C" fn rorb_out_write_any_value(out: *mut RorbOut, any: *const Any) {
776    let any = unsafe { &*any };
777    unsafe { &mut *out }.with(|s| s.write_value(any.typecode(), any.value()));
778}
779
780/// Reads a value of type `tc` into a new any; NULL after an error.
781#[unsafe(no_mangle)]
782pub unsafe extern "C" fn rorb_in_read_any_value(
783    input: *mut RorbIn,
784    tc: *const TypeCode,
785) -> *mut Any {
786    let tc = unsafe { &*tc };
787    match unsafe { &mut *input }.read(|s| s.read_value(tc).map(Some)) {
788        Some(v) => into_handle(Any::new(tc.clone(), v)),
789        None => std::ptr::null_mut(),
790    }
791}