rustorb-ffi 0.6.0

Stable C ABI layer of rustorb used by the C++ and Java bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! `rorb_typecode` and `rorb_any`: TypeCodes and anys.
//!
//! A TypeCode handle is a core [`TypeCode`], an any handle a core [`Any`]
//! (a TypeCode and a [`rustorb_core::Value`]). The caller puts its own
//! values in an any and takes them out through callbacks that write and
//! read them on a standalone CDR stream, as it marshals arguments: the
//! value is converted to and from the core representation on the way.

use std::ffi::{c_char, c_void};

use rustorb_cdr::{ByteOrder, Decoder, Encoder, Encoding};
use rustorb_core::{
    Any, CompletionStatus, InStream, ObjectRef, Orb, OutStream, SystemExceptionKind, TCKind,
    TypeCode, TypeCodeError,
};

use crate::host;
use crate::stream::{In, Out, RorbIn, RorbOut};
use crate::{
    CALLBACK_FAILED, Exception, OK, Status, bad_param, guard, into_handle, local, release_handle,
    set_local, set_system, str_arg, sys,
};

// --- TypeCodes ------------------------------------------------------------------

unsafe fn tc_error(exc: *mut Exception, e: TypeCodeError) -> Status {
    match e {
        TypeCodeError::BadKind => unsafe { set_local(exc, local::TC_BAD_KIND, 0) },
        TypeCodeError::Bounds => unsafe { set_local(exc, local::TC_BOUNDS, 0) },
        TypeCodeError::BadParam => unsafe { set_system(exc, &bad_param()) },
    }
}

/// Stores the result of a TypeCode operation in `*out`.
unsafe fn put<T>(
    exc: *mut Exception,
    out: *mut T,
    f: impl FnOnce() -> Result<T, TypeCodeError>,
) -> Status {
    guard(exc, || match f() {
        Ok(v) => {
            unsafe { out.write(v) };
            OK
        }
        Err(e) => unsafe { tc_error(exc, e) },
    })
}

/// Stores a new TypeCode handle in `*out`.
unsafe fn put_tc(
    exc: *mut Exception,
    out: *mut *mut TypeCode,
    f: impl FnOnce() -> Result<TypeCode, TypeCodeError>,
) -> Status {
    unsafe { put(exc, out, || f().map(into_handle)) }
}

/// A string argument of a TypeCode constructor; invalid UTF-8 is
/// `BadParam`.
unsafe fn name_arg<'a>(p: *const c_char, len: usize) -> Result<&'a str, TypeCodeError> {
    unsafe { str_arg(p, len) }.map_err(|_| TypeCodeError::BadParam)
}

unsafe fn tc_arg<'a>(tc: *const TypeCode) -> Result<&'a TypeCode, TypeCodeError> {
    unsafe { tc.as_ref() }.ok_or(TypeCodeError::BadParam)
}

/// `count` names and types from C arrays.
unsafe fn members<'a>(
    count: usize,
    names: *const *const c_char,
    name_lens: *const usize,
    types: *const *const TypeCode,
) -> Result<Vec<(&'a str, TypeCode)>, TypeCodeError> {
    let mut out = Vec::with_capacity(count);
    for i in 0..count {
        let name = unsafe { name_arg(*names.add(i), *name_lens.add(i)) }?;
        let tc = unsafe { tc_arg(*types.add(i)) }?;
        out.push((name, tc.clone()));
    }
    Ok(out)
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_clone(tc: *const TypeCode) -> *mut TypeCode {
    match unsafe { tc.as_ref() } {
        Some(tc) => into_handle(tc.clone()),
        None => std::ptr::null_mut(),
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_release(tc: *mut TypeCode) {
    unsafe { release_handle(tc) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_simple(
    kind: u32,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
            match kind {
                TCKind::String => Ok(TypeCode::string(0)),
                TCKind::WString => Ok(TypeCode::wstring(0)),
                _ => TypeCode::simple(kind),
            }
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_string(
    wide: i32,
    bound: u32,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            Ok(if wide != 0 {
                TypeCode::wstring(bound)
            } else {
                TypeCode::string(bound)
            })
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_fixed(
    digits: u16,
    scale: i16,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || TypeCode::fixed(digits, scale)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_sequence(
    content: *const TypeCode,
    bound: u32,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || TypeCode::sequence(tc_arg(content)?, bound)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_array(
    content: *const TypeCode,
    length: u32,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || TypeCode::array(tc_arg(content)?, length)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_alias(
    kind: u32,
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    content: *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let id = name_arg(id, id_len)?;
            let name = name_arg(name, name_len)?;
            let content = tc_arg(content)?;
            match TCKind::from_u32(kind) {
                Some(TCKind::Alias) => TypeCode::alias(id, name, content),
                Some(TCKind::ValueBox) => TypeCode::value_box(id, name, content),
                _ => Err(TypeCodeError::BadParam),
            }
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_interface(
    kind: u32,
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
            TypeCode::interface(kind, name_arg(id, id_len)?, name_arg(name, name_len)?)
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_struct(
    kind: u32,
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    count: usize,
    names: *const *const c_char,
    name_lens: *const usize,
    types: *const *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let id = name_arg(id, id_len)?;
            let name = name_arg(name, name_len)?;
            let members = members(count, names, name_lens, types)?;
            match TCKind::from_u32(kind) {
                Some(TCKind::Struct) => TypeCode::struct_tc(id, name, &members),
                Some(TCKind::Except) => TypeCode::exception(id, name, &members),
                _ => Err(TypeCodeError::BadParam),
            }
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_union(
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    discriminator: *const TypeCode,
    count: usize,
    labels: *const u64,
    default_index: i32,
    names: *const *const c_char,
    name_lens: *const usize,
    types: *const *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let id = name_arg(id, id_len)?;
            let name = name_arg(name, name_len)?;
            let disc = tc_arg(discriminator)?;
            let unsigned = disc.unaliased().kind() == TCKind::ULongLong;
            let members = members(count, names, name_lens, types)?
                .into_iter()
                .enumerate()
                .map(|(i, (n, tc))| {
                    let bits = *labels.add(i);
                    let label = if i as i32 == default_index {
                        None
                    } else if unsigned {
                        Some(i128::from(bits))
                    } else {
                        Some(i128::from(bits as i64))
                    };
                    (label, n, tc)
                })
                .collect::<Vec<_>>();
            TypeCode::union_tc(id, name, disc, &members)
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_enum(
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    count: usize,
    names: *const *const c_char,
    name_lens: *const usize,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let id = name_arg(id, id_len)?;
            let name = name_arg(name, name_len)?;
            let names = (0..count)
                .map(|i| name_arg(*names.add(i), *name_lens.add(i)))
                .collect::<Result<Vec<_>, _>>()?;
            TypeCode::enum_tc(id, name, &names)
        })
    }
}

/// A valuetype (`RORB_TK_VALUE`) or eventtype (`RORB_TK_EVENT`):
/// `base` is the concrete base type or NULL, and each member has a
/// visibility (`PRIVATE_MEMBER` 0, `PUBLIC_MEMBER` 1).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_value(
    kind: u32,
    id: *const c_char,
    id_len: usize,
    name: *const c_char,
    name_len: usize,
    modifier: i16,
    base: *const TypeCode,
    count: usize,
    names: *const *const c_char,
    name_lens: *const usize,
    types: *const *const TypeCode,
    visibilities: *const i16,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_tc(exc, out, || {
            let kind = TCKind::from_u32(kind).ok_or(TypeCodeError::BadParam)?;
            let id = name_arg(id, id_len)?;
            let name = name_arg(name, name_len)?;
            let members: Vec<(&str, TypeCode, i16)> = members(count, names, name_lens, types)?
                .into_iter()
                .enumerate()
                .map(|(i, (n, t))| (n, t, *visibilities.add(i)))
                .collect();
            TypeCode::value_tc(kind, id, name, modifier, base.as_ref(), &members)
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_recursive(
    id: *const c_char,
    id_len: usize,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || Ok(TypeCode::recursive(name_arg(id, id_len)?))) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_kind(tc: *const TypeCode) -> u32 {
    unsafe { &*tc }.kind().as_u32()
}

/// Stores a string of the TypeCode, valid while it lives.
unsafe fn put_str(
    exc: *mut Exception,
    p: *mut *const c_char,
    len: *mut usize,
    f: impl FnOnce() -> Result<*const str, TypeCodeError>,
) -> Status {
    let mut s: *const str = "";
    let status = unsafe { put(exc, &mut s, f) };
    if status == OK {
        let s = unsafe { &*s };
        unsafe {
            p.write(s.as_ptr() as *const c_char);
            len.write(s.len());
        }
    }
    status
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_id(
    tc: *const TypeCode,
    p: *mut *const c_char,
    len: *mut usize,
    exc: *mut Exception,
) -> Status {
    unsafe { put_str(exc, p, len, || (*tc).id().map(|s| s as *const str)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_name(
    tc: *const TypeCode,
    p: *mut *const c_char,
    len: *mut usize,
    exc: *mut Exception,
) -> Status {
    unsafe { put_str(exc, p, len, || (*tc).name().map(|s| s as *const str)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_member_count(
    tc: *const TypeCode,
    out: *mut u32,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).member_count()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_member_name(
    tc: *const TypeCode,
    index: u32,
    p: *mut *const c_char,
    len: *mut usize,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put_str(exc, p, len, || {
            (*tc).member_name(index).map(|s| s as *const str)
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_member_type(
    tc: *const TypeCode,
    index: u32,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || (*tc).member_type(index)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_member_label(
    tc: *const TypeCode,
    index: u32,
    out: *mut *mut Any,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).member_label(index).map(into_handle)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_discriminator_type(
    tc: *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || (*tc).discriminator_type()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_default_index(
    tc: *const TypeCode,
    out: *mut i32,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).default_index()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_length(
    tc: *const TypeCode,
    out: *mut u32,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).length()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_content_type(
    tc: *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe { put_tc(exc, out, || (*tc).content_type()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_fixed_digits(
    tc: *const TypeCode,
    out: *mut u16,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).fixed_digits()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_fixed_scale(
    tc: *const TypeCode,
    out: *mut i16,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).fixed_scale()) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_member_visibility(
    tc: *const TypeCode,
    index: u32,
    out: *mut i16,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).member_visibility(index)) }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_type_modifier(
    tc: *const TypeCode,
    out: *mut i16,
    exc: *mut Exception,
) -> Status {
    unsafe { put(exc, out, || (*tc).type_modifier()) }
}

/// The concrete base type, or NULL for none.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_concrete_base_type(
    tc: *const TypeCode,
    out: *mut *mut TypeCode,
    exc: *mut Exception,
) -> Status {
    unsafe {
        put(exc, out, || {
            (*tc)
                .concrete_base_type()
                .map(|b| b.map_or(std::ptr::null_mut(), into_handle))
        })
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_equal(a: *const TypeCode, b: *const TypeCode) -> i32 {
    i32::from(unsafe { (*a).equal(&*b) })
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_equivalent(a: *const TypeCode, b: *const TypeCode) -> i32 {
    i32::from(unsafe { (*a).equivalent(&*b) })
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_compact(tc: *const TypeCode) -> *mut TypeCode {
    into_handle(unsafe { &*tc }.compact())
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_tc_unaliased(tc: *const TypeCode) -> *mut TypeCode {
    into_handle(unsafe { &*tc }.unaliased())
}

// --- anys -----------------------------------------------------------------------

/// Writes the value of an any (`rorb_any_insert`).
pub type WriteFn = Option<unsafe extern "C" fn(*mut c_void, *mut RorbOut) -> Status>;
/// Reads the value of an any (`rorb_any_extract`).
pub type ReadFn = Option<unsafe extern "C" fn(*mut c_void, *mut RorbIn) -> Status>;

#[unsafe(no_mangle)]
pub extern "C" fn rorb_any_new() -> *mut Any {
    into_handle(Any::default())
}

/// An any of type `tc` without a value: the result and the `out`
/// arguments of a DII request before the call. Marshalling it, or
/// extracting its value, is `BAD_PARAM`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_typed(tc: *const TypeCode) -> *mut Any {
    into_handle(Any::new(unsafe { &*tc }.clone(), rustorb_core::Value::Void))
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_clone(any: *const Any) -> *mut Any {
    match unsafe { any.as_ref() } {
        Some(any) => into_handle(any.clone()),
        None => std::ptr::null_mut(),
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_release(any: *mut Any) {
    // The valuetypes in it may refer to each other in cycles, which only
    // the core sees (docs/valuetype.md): those nothing else refers to are
    // freed.
    if !any.is_null() {
        rustorb_core::Value::Any(unsafe { Box::from_raw(any) }).release();
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_type(any: *const Any) -> *mut TypeCode {
    into_handle(unsafe { &*any }.typecode().clone())
}

/// Replaces the TypeCode of an any with an equivalent one.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_set_type(
    any: *mut Any,
    tc: *const TypeCode,
    exc: *mut Exception,
) -> Status {
    guard(exc, || {
        let any = unsafe { &mut *any };
        let tc = unsafe { &*tc };
        if !any.typecode().equivalent(tc) {
            let e = sys(SystemExceptionKind::BAD_TYPECODE, 0, CompletionStatus::No);
            return unsafe { set_system(exc, &e) };
        }
        let value = std::mem::take(any).into_parts().1;
        *any = Any::new(tc.clone(), value);
        OK
    })
}

/// Whether two anys have equal TypeCodes and the same value (floats
/// compared exactly, object references with `is_equivalent`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_equal(a: *const Any, b: *const Any) -> i32 {
    let (a, b) = unsafe { (&*a, &*b) };
    i32::from(a.typecode().equal(b.typecode()) && a.value() == b.value())
}

/// The value of an any of a discriminator type as a union label number
/// (two's complement for negative values); 0 if it is not one.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_label(any: *const Any, label: *mut u64) -> i32 {
    match unsafe { &*any }.value().label_key() {
        Some(v) => {
            unsafe { label.write(v as u64) };
            1
        }
        None => 0,
    }
}

/// The ORB of the object references read back from a standalone stream:
/// the first one in a value, else the first ORB initialised.
pub(crate) fn default_orb() -> Option<Orb> {
    crate::orb::default_orb()
}

pub(crate) fn encoder() -> Encoder {
    Encoder::new(ByteOrder::Big, Encoding::Giop1_2)
}

/// Whether values of type `tc` start with a repository id when marshalled
/// in an any (exceptions), which the caller's codecs do not write.
fn exception_id(tc: &TypeCode) -> Option<String> {
    let tc = tc.unaliased();
    (tc.kind() == TCKind::Except).then(|| tc.id().unwrap_or_default().to_owned())
}

/// Makes an any of type `tc` from the value `write` writes, as it would
/// marshal it as an argument.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_insert(
    tc: *const TypeCode,
    write: WriteFn,
    context: *mut c_void,
    out: *mut *mut Any,
    exc: *mut Exception,
) -> Status {
    guard(exc, || {
        let tc = unsafe { &*tc };
        let mut enc = encoder();
        let mut orb = None;
        let written;
        {
            let mut stream = OutStream::standalone(&mut enc);
            if let Some(id) = exception_id(tc) {
                if let Err(e) = stream.write_string(&id) {
                    return unsafe { set_system(exc, &e) };
                }
            }
            let mut out = Out::standalone(&mut stream);
            out.written = Some(Vec::new());
            if let Some(write) = write {
                crate::stack::commit();
                let status = unsafe { write(context, out.as_ptr()) };
                if status != OK {
                    return CALLBACK_FAILED;
                }
            }
            if let Some(e) = out.error.take() {
                return unsafe { set_system(exc, &e) };
            }
            if let Some(o) = out.objects.first() {
                orb = Some(o.orb().clone());
            }
            written = out.written.take().unwrap_or_default();
        }
        let orb = orb.or_else(default_orb);
        let bytes = enc.into_bytes();
        let mut input = InStream::standalone(
            Decoder::new(&bytes, ByteOrder::Big, Encoding::Giop1_2),
            orb.as_ref(),
        );
        // An instance of the caller that a core instance stands for
        // already is read into that one (see `host`).
        for w in &written {
            if let Some(v) = host::lookup(w.key) {
                input.preset_value(w.slot, v);
            }
        }
        match input.read_value(tc) {
            Ok(v) => {
                for w in written {
                    let Some(r) = input.value_at(w.slot) else {
                        continue;
                    };
                    if r.native().is_some() {
                        // Reused, or made by a custom reader.
                        continue;
                    }
                    if let Some(h) = w.host {
                        let (ptr, release) = h.take();
                        host::attach(r, w.key, ptr, release);
                    }
                }
                unsafe { out.write(into_handle(Any::new(tc.clone(), v))) };
                OK
            }
            Err(e) => unsafe { set_system(exc, &e) },
        }
    })
}

/// Reads the value of an any with `read`, as it would read an argument
/// of its type. The caller has checked the type.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_any_extract(
    any: *const Any,
    read: ReadFn,
    context: *mut c_void,
    exc: *mut Exception,
) -> Status {
    guard(exc, || {
        let any = unsafe { &*any };
        let mut enc = encoder();
        let bound;
        {
            let mut stream = OutStream::standalone(&mut enc);
            stream.log_values();
            if let Err(e) = stream.write_value(any.typecode(), any.value()) {
                return unsafe { set_system(exc, &e) };
            }
            bound = stream.written_values();
        }
        let orb = first_object(any.value())
            .map(|o| o.orb().clone())
            .or_else(default_orb);
        let bytes = enc.into_bytes();
        let mut stream = InStream::standalone(
            Decoder::new(&bytes, ByteOrder::Big, Encoding::Giop1_2),
            orb.as_ref(),
        );
        if exception_id(any.typecode()).is_some() {
            if let Err(e) = stream.read_string() {
                return unsafe { set_system(exc, &e) };
            }
        }
        let mut input = In::new(&mut stream, CompletionStatus::No);
        input.bound = Some(bound);
        if let Some(read) = read {
            crate::stack::commit();
            let status = unsafe { read(context, input.as_ptr()) };
            if status != OK {
                return CALLBACK_FAILED;
            }
        }
        if let Some(e) = input.error.take() {
            return unsafe { set_system(exc, &e) };
        }
        // The caller's instances read stand for the core instances from
        // now on (see `host`).
        let bound = input.bound.take().unwrap_or_default();
        for (held, v) in input.values.iter_mut().zip(&bound) {
            let Some(held) = held else { continue };
            let Some(key) = held.key else { continue };
            if v.native().is_none() {
                let (ptr, release) = held.take();
                host::attach(v, key, ptr, release);
            }
        }
        OK
    })
}

/// The first object reference in a value.
pub(crate) fn first_object(v: &rustorb_core::Value) -> Option<&ObjectRef> {
    use rustorb_core::Value;
    match v {
        Value::Objref(Some(o)) => Some(o),
        Value::List(l) => l.iter().find_map(first_object),
        Value::Union {
            member: Some((_, m)),
            ..
        } => first_object(m),
        Value::Any(a) => first_object(a.value()),
        _ => None,
    }
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_out_write_typecode(out: *mut RorbOut, tc: *const TypeCode) {
    unsafe { &mut *out }.with(|s| s.write_typecode(unsafe { &*tc }));
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_out_write_any(out: *mut RorbOut, any: *const Any) {
    unsafe { &mut *out }.with(|s| s.write_any(unsafe { &*any }));
}

/// NULL after an error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_in_read_typecode(input: *mut RorbIn) -> *mut TypeCode {
    match unsafe { &mut *input }.read(|s| s.read_typecode().map(Some)) {
        Some(tc) => into_handle(tc),
        None => std::ptr::null_mut(),
    }
}

/// NULL after an error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_in_read_any(input: *mut RorbIn) -> *mut Any {
    match unsafe { &mut *input }.read(|s| s.read_any().map(Some)) {
        Some(any) => into_handle(any),
        None => std::ptr::null_mut(),
    }
}

/// Writes the value of `any`, without its TypeCode.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_out_write_any_value(out: *mut RorbOut, any: *const Any) {
    let any = unsafe { &*any };
    unsafe { &mut *out }.with(|s| s.write_value(any.typecode(), any.value()));
}

/// Reads a value of type `tc` into a new any; NULL after an error.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rorb_in_read_any_value(
    input: *mut RorbIn,
    tc: *const TypeCode,
) -> *mut Any {
    let tc = unsafe { &*tc };
    match unsafe { &mut *input }.read(|s| s.read_value(tc).map(Some)) {
        Some(v) => into_handle(Any::new(tc.clone(), v)),
        None => std::ptr::null_mut(),
    }
}