rustorb-core 0.4.0

ORB core of rustorb: connections, request dispatch and POA
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Values of any IDL type, described by a [`TypeCode`], and [`Any`].
//!
//! [`Value`] is the form the language bindings marshal through: they
//! convert their own values to it and the ORB writes it as the TypeCode
//! says, and the other way when reading. An [`Any`] is a TypeCode with a
//! value of that type.

use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, RwLock};

use rustorb_cdr::{CdrEncode, ValueHeader};

use crate::typecode::{TCKind, TypeCode};
use crate::{
    CompletionStatus, InStream, ObjectRef, OutStream, SystemException, SystemExceptionKind,
};

/// How deep values may nest when read, against stack exhaustion with
/// recursive types.
const MAX_DEPTH: usize = 256;

/// A value of an IDL type. Which variant goes with which type:
///
/// | Type | Value |
/// | --- | --- |
/// | `void`, `null` | `Void` |
/// | integers, `float`, `double`, `boolean`, `octet` | the variant of the same name |
/// | `char`, `wchar` | `Char` (a character of the `char` code set), `WChar` (a UTF-16 code unit) |
/// | `string`, `wstring` | `String` |
/// | `sequence` and array of `octet`, `Principal` | `Octets` (or `List` of `Octet`) |
/// | `sequence` and array of `char` | `Chars` (or `List` of `Char`) |
/// | other `sequence`s and arrays, struct, exception | `List`: the elements or the members in order (an exception is written with its repository id first, as in a reply) |
/// | union | `Union`: the discriminator, and the index of the TypeCode member with its value, `None` when no member is selected |
/// | enum | `Enum`: the position of the enumerator |
/// | `long double` | `LongDouble`: the binary128 bits ([`LongDouble`](rustorb_cdr::LongDouble)) |
/// | `fixed` | `Fixed`: the digits (as many as the type has, most significant first) and the sign |
/// | object reference | `Objref`, `None` for nil |
/// | `TypeCode` | `TypeCode` |
/// | `any` | `Any` |
/// | valuetype, value box | `Valuetype`: a shared [`ValueRef`], `None` for `null` |
/// | abstract interface | `Objref` (sent as a reference) or `Valuetype` (sent as a value) |
///
/// Aliases take the value of the type they stand for. The state of a
/// custom valuetype is the items its marshaling code writes, each a
/// `Value::Any` of the item's type and value (see [`register_custom_reader`]).
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub enum Value {
    Void,
    Bool(bool),
    Octet(u8),
    Short(i16),
    UShort(u16),
    Long(i32),
    ULong(u32),
    LongLong(i64),
    ULongLong(u64),
    Float(f32),
    Double(f64),
    LongDouble(rustorb_cdr::LongDouble),
    Char(char),
    WChar(u16),
    String(String),
    Octets(rustorb_cdr::Octets),
    Chars(String),
    List(Vec<Value>),
    Union {
        disc: Box<Value>,
        member: Option<(u32, Box<Value>)>,
    },
    Enum(u32),
    Fixed {
        digits: Vec<u8>,
        negative: bool,
    },
    Objref(Option<ObjectRef>),
    TypeCode(TypeCode),
    Any(Box<Any>),
    Valuetype(Option<ValueRef>),
}

impl Value {
    /// The number a union discriminator value stands for, as in union
    /// labels ([`TypeCode::union_tc`]): integers as they are, `boolean` as
    /// 0 or 1, `char` and `wchar` as their code, an enumerator as its
    /// position. `None` for values that cannot be discriminators.
    pub fn label_key(&self) -> Option<i128> {
        Some(match *self {
            Value::Bool(v) => i128::from(v),
            Value::Octet(v) => i128::from(v),
            Value::Short(v) => i128::from(v),
            Value::UShort(v) => i128::from(v),
            Value::Long(v) => i128::from(v),
            Value::ULong(v) => i128::from(v),
            Value::LongLong(v) => i128::from(v),
            Value::ULongLong(v) => i128::from(v),
            Value::Char(c) => i128::from(u32::from(c)),
            Value::WChar(c) => i128::from(c),
            Value::Enum(v) => i128::from(v),
            _ => return None,
        })
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Value) -> bool {
        use Value::*;
        match (self, other) {
            (Void, Void) => true,
            (Bool(a), Bool(b)) => a == b,
            (Octet(a), Octet(b)) => a == b,
            (Short(a), Short(b)) => a == b,
            (UShort(a), UShort(b)) => a == b,
            (Long(a), Long(b)) => a == b,
            (ULong(a), ULong(b)) => a == b,
            (LongLong(a), LongLong(b)) => a == b,
            (ULongLong(a), ULongLong(b)) => a == b,
            (Float(a), Float(b)) => a == b,
            (Double(a), Double(b)) => a == b,
            (LongDouble(a), LongDouble(b)) => a == b,
            (Char(a), Char(b)) => a == b,
            (WChar(a), WChar(b)) => a == b,
            (String(a), String(b)) | (Chars(a), Chars(b)) => a == b,
            (Octets(a), Octets(b)) => a == b,
            (Octets(a), List(b)) | (List(b), Octets(a)) => {
                a.len() == b.len() && a.iter().zip(b).all(|(x, y)| *y == Octet(*x))
            }
            (Chars(a), List(b)) | (List(b), Chars(a)) => {
                a.chars().count() == b.len() && a.chars().zip(b).all(|(x, y)| *y == Char(x))
            }
            (List(a), List(b)) => a == b,
            (
                Union {
                    disc: d1,
                    member: m1,
                },
                Union {
                    disc: d2,
                    member: m2,
                },
            ) => d1 == d2 && m1 == m2,
            (Enum(a), Enum(b)) => a == b,
            (
                Fixed {
                    digits: d1,
                    negative: n1,
                },
                Fixed {
                    digits: d2,
                    negative: n2,
                },
            ) => d1 == d2 && n1 == n2,
            (Objref(a), Objref(b)) => match (a, b) {
                (None, None) => true,
                (Some(a), Some(b)) => a.is_equivalent(b),
                _ => false,
            },
            (TypeCode(a), TypeCode(b)) => a.equal(b),
            (Any(a), Any(b)) => a == b,
            (Valuetype(a), Valuetype(b)) => match (a, b) {
                (None, None) => true,
                (Some(a), Some(b)) => a.same_state(b),
                _ => false,
            },
            _ => false,
        }
    }
}

impl Value {
    /// Breaks the reference cycles that valuetypes in this value may
    /// form, so that they are freed: the state of every [`ValueRef`] in it
    /// is emptied. For a binding that is done with a value it made.
    pub fn break_cycles(self) {
        let mut stack = vec![self];
        while let Some(v) = stack.pop() {
            match v {
                Value::List(items) => stack.extend(items),
                Value::Union { disc, member } => {
                    stack.push(*disc);
                    stack.extend(member.map(|(_, v)| *v));
                }
                Value::Any(a) => stack.push(a.value),
                Value::Valuetype(Some(r)) => {
                    r.set_native(None);
                    stack.extend(r.take_members());
                }
                _ => {}
            }
        }
    }

    /// Drops the value, and first breaks the reference cycles among the
    /// valuetypes in it that nothing else refers to, so that they are
    /// freed: for a binding that drops a value it may share. Instances
    /// that are referred to from elsewhere (another value, a binding's
    /// object), and those they refer to, are left as they are.
    ///
    /// The instances reachable from the value are counted: one whose
    /// references are not all from the value and the instances reachable
    /// from it is referred to from elsewhere (trial deletion).
    pub fn release(self) {
        use std::collections::HashMap;
        use std::collections::hash_map::Entry;

        // The instances reachable from the value: a clone of each, how
        // many references to it there are from the value and from them,
        // and the instances each refers to.
        type Nodes = HashMap<u64, (ValueRef, usize, Vec<u64>)>;
        fn visit(r: &ValueRef, nodes: &mut Nodes, pending: &mut Vec<u64>) -> u64 {
            let key = r.key();
            match nodes.entry(key) {
                Entry::Occupied(mut e) => e.get_mut().1 += 1,
                Entry::Vacant(e) => {
                    e.insert((r.clone(), 1, Vec::new()));
                    pending.push(key);
                }
            }
            key
        }
        let mut nodes = Nodes::new();
        let mut pending = Vec::new();
        each_ref(&self, &mut |r| {
            visit(r, &mut nodes, &mut pending);
        });
        if nodes.is_empty() {
            return;
        }
        while let Some(key) = pending.pop() {
            let node = nodes[&key].0.clone();
            let mut children = Vec::new();
            for m in node.lock().iter() {
                each_ref(m, &mut |r| {
                    children.push(visit(r, &mut nodes, &mut pending))
                });
            }
            nodes.get_mut(&key).expect("visited").2 = children;
        }
        // Referred to from elsewhere: more references than those counted
        // and the clone in `nodes`.
        let mut live: Vec<u64> = nodes
            .iter()
            .filter(|(_, (r, internal, _))| Arc::strong_count(&r.0) > internal + 1)
            .map(|(k, _)| *k)
            .collect();
        let mut reached: std::collections::HashSet<u64> = live.iter().copied().collect();
        while let Some(key) = live.pop() {
            for child in &nodes[&key].2 {
                if reached.insert(*child) {
                    live.push(*child);
                }
            }
        }
        let mut freed = Vec::new();
        for (key, (r, _, _)) in &nodes {
            if !reached.contains(key) {
                freed.push(r.take_members());
            }
        }
        drop(nodes);
        drop(freed);
    }
}

/// Calls `f` on each [`ValueRef`] directly in `v` (not in the state of the
/// instances).
fn each_ref(v: &Value, f: &mut impl FnMut(&ValueRef)) {
    let mut stack = vec![v];
    while let Some(v) = stack.pop() {
        match v {
            Value::List(items) => stack.extend(items),
            Value::Union { disc, member } => {
                stack.push(disc);
                stack.extend(member.as_ref().map(|(_, v)| &**v));
            }
            Value::Any(a) => stack.push(&a.value),
            Value::Valuetype(Some(r)) => f(r),
            _ => {}
        }
    }
}

/// An instance of a valuetype or a value box: its type and its state.
///
/// Clones share the instance, as references do in the language
/// mappings: an instance written twice in a message is sent once, then as
/// an indirection to it, and is read back as one instance. Instances may
/// refer to each other in cycles; [`Value::break_cycles`] frees them.
#[derive(Clone)]
pub struct ValueRef(Arc<ValueObj>);

struct ValueObj {
    tc: TypeCode,
    members: Mutex<Vec<Value>>,
    native: Mutex<Option<Native>>,
}

/// An object of a language binding that stands for a [`ValueRef`].
pub type Native = Arc<dyn std::any::Any + Send + Sync>;

impl ValueRef {
    /// An instance of the valuetype `tc` (the most derived type) with the
    /// values of its state members: those of its base types first, then
    /// its own, in the order of the TypeCodes. An instance of a value box
    /// has the boxed value as its one member.
    pub fn new(tc: TypeCode, members: Vec<Value>) -> ValueRef {
        ValueRef(Arc::new(ValueObj {
            tc,
            members: Mutex::new(members),
            native: Mutex::new(None),
        }))
    }

    /// The object of a language binding set with [`ValueRef::set_native`].
    pub fn native(&self) -> Option<Native> {
        self.0
            .native
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Sets (or, with `None`, removes) the object of a language binding
    /// that stands for this instance: a custom reader
    /// ([`register_custom_reader`]) sets the instance it made, so that
    /// the binding finds it again when it converts the value.
    pub fn set_native(&self, native: Option<Native>) {
        *self.0.native.lock().unwrap_or_else(|e| e.into_inner()) = native;
    }

    /// The type of the instance.
    pub fn typecode(&self) -> &TypeCode {
        &self.0.tc
    }

    /// The repository id of the type of the instance.
    pub fn id(&self) -> &str {
        self.0.tc.id().unwrap_or_default()
    }

    /// The values of the state members.
    pub fn members(&self) -> Vec<Value> {
        self.lock().clone()
    }

    /// Replaces the values of the state members.
    pub fn set_members(&self, members: Vec<Value>) {
        *self.lock() = members;
    }

    /// Takes the values of the state members, leaving none.
    pub fn take_members(&self) -> Vec<Value> {
        std::mem::take(&mut *self.lock())
    }

    /// Whether both are the same instance.
    pub fn ptr_eq(&self, other: &ValueRef) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    /// A number that identifies the instance while it is alive.
    pub fn key(&self) -> u64 {
        Arc::as_ptr(&self.0) as usize as u64
    }

    fn lock(&self) -> MutexGuard<'_, Vec<Value>> {
        self.0.members.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Whether both have the same type and equal state, the same instance
    /// being equal to itself however it is reached (for cycles).
    fn same_state(&self, other: &ValueRef) -> bool {
        thread_local! {
            static COMPARING: std::cell::RefCell<Vec<(u64, u64)>> =
                const { std::cell::RefCell::new(Vec::new()) };
        }
        if self.ptr_eq(other) {
            return true;
        }
        if !self.typecode().equal(other.typecode()) {
            return false;
        }
        let pair = (self.key(), other.key());
        if COMPARING.with(|c| c.borrow().contains(&pair)) {
            return true;
        }
        COMPARING.with(|c| c.borrow_mut().push(pair));
        // Copies, so that no lock is held while comparing nested values.
        let equal = self.members() == other.members();
        COMPARING.with(|c| c.borrow_mut().retain(|p| *p != pair));
        equal
    }
}

impl fmt::Debug for ValueRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Not the state, which may refer back to this instance.
        write!(f, "ValueRef({} @ {:#x})", self.id(), self.key())
    }
}

/// The valuetypes known to the readers, by repository id.
static VALUE_TYPES: RwLock<BTreeMap<String, TypeCode>> = RwLock::new(BTreeMap::new());

/// Makes the valuetype `tc` known to every ORB of the process, so that a
/// value of it can be read where a base type of it is expected.
///
/// A value whose type is neither the expected type nor registered is read
/// as the first of its truncatable base types that is, and is `MARSHAL`
/// if there is none.
pub fn register_value_type(tc: &TypeCode) {
    let tc = tc.unaliased();
    if let Ok(id) = tc.id() {
        let id = id.to_owned();
        VALUE_TYPES
            .write()
            .unwrap_or_else(|e| e.into_inner())
            .insert(id, tc);
    }
}

/// The valuetype registered with [`register_value_type`] for `id`.
pub fn lookup_value_type(id: &str) -> Option<TypeCode> {
    VALUE_TYPES
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(id)
        .cloned()
}

/// Finds the valuetype of a repository id that is not registered: a
/// binding whose valuetypes are only known when asked for (Java, whose
/// classes are loaded by name) sets one with [`set_value_type_resolver`].
pub type ValueTypeResolver = dyn Fn(&str) -> Option<TypeCode> + Send + Sync;

static RESOLVER: RwLock<Option<Arc<ValueTypeResolver>>> = RwLock::new(None);

/// Sets (or, with `None`, removes) the resolver asked for repository ids
/// that are not registered; what it finds is registered.
pub fn set_value_type_resolver(resolver: Option<Arc<ValueTypeResolver>>) {
    *RESOLVER.write().unwrap_or_else(|e| e.into_inner()) = resolver;
}

/// The registered valuetype of `id`, else the one the resolver finds.
fn find_value_type(id: &str) -> Option<TypeCode> {
    if let Some(tc) = lookup_value_type(id) {
        return Some(tc);
    }
    let resolver = RESOLVER.read().unwrap_or_else(|e| e.into_inner()).clone()?;
    let tc = resolver(id)?;
    if tc.id().ok() != Some(id) {
        return None;
    }
    register_value_type(&tc);
    lookup_value_type(id)
}

/// Forgets the valuetype registered for `id`.
pub fn unregister_value_type(id: &str) {
    VALUE_TYPES
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .remove(id);
}

/// Reads the state of a custom valuetype from `input`, into `value`, a new
/// instance of the type: what the value's marshaling code wrote, read with
/// [`InStream::read_value`] item by item. The reader sets the state of
/// `value` to the items read (each a `Value::Any`) so that it can be
/// written again, and may set an object of its own with
/// [`ValueRef::set_native`].
pub type CustomReader =
    dyn Fn(&ValueRef, &mut InStream<'_>) -> Result<(), SystemException> + Send + Sync;

/// The custom readers, by repository id.
static CUSTOM_READERS: RwLock<BTreeMap<String, Arc<CustomReader>>> = RwLock::new(BTreeMap::new());

/// Sets the reader of the custom valuetype `id` (`VM_CUSTOM`), the
/// unmarshaling half of `CORBA::CustomMarshal`. A value of a custom type
/// without a reader is read as `MARSHAL`, as when no value factory is
/// registered.
///
/// A custom value is written from its state: the items in it, each a
/// `Value::Any`, are written one after the other with their types, the
/// way its marshaling code writes them (`CORBA::DataOutputStream`).
pub fn register_custom_reader(id: &str, reader: Arc<CustomReader>) {
    CUSTOM_READERS
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .insert(id.to_owned(), reader);
}

/// Forgets the reader of the custom valuetype `id`.
pub fn unregister_custom_reader(id: &str) {
    CUSTOM_READERS
        .write()
        .unwrap_or_else(|e| e.into_inner())
        .remove(id);
}

fn custom_reader(id: &str) -> Option<Arc<CustomReader>> {
    CUSTOM_READERS
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .get(id)
        .cloned()
}

/// The repository id of `ValueBase`, which every valuetype may stand for.
pub(crate) const VALUE_BASE_ID: &str = "IDL:omg.org/CORBA/ValueBase:1.0";

/// The TypeCode of `ValueBase`: any value of a known type.
pub(crate) fn value_base_tc() -> &'static TypeCode {
    static TC: std::sync::OnceLock<TypeCode> = std::sync::OnceLock::new();
    TC.get_or_init(|| {
        TypeCode::value_tc(
            TCKind::Value,
            VALUE_BASE_ID,
            "ValueBase",
            0,
            None,
            &[] as &[(&str, TypeCode, i16)],
        )
        .expect("a valid TypeCode")
    })
}

const VM_CUSTOM: i16 = 1;
const VM_ABSTRACT: i16 = 2;
const VM_TRUNCATABLE: i16 = 3;

/// The types of the state members of a valuetype, those of its base
/// types first; the boxed type of a value box.
pub(crate) fn state_types(tc: &TypeCode) -> Vec<TypeCode> {
    if tc.kind() == TCKind::ValueBox {
        return tc.content_type().into_iter().collect();
    }
    let mut chain = vec![tc.clone()];
    while let Some(Some(base)) = chain.last().map(|t| t.concrete_base_type().ok().flatten()) {
        if chain.len() > MAX_DEPTH {
            break;
        }
        chain.push(base.unaliased());
    }
    chain
        .iter()
        .rev()
        .flat_map(|t| (0..t.member_count().unwrap_or(0)).map(move |i| member(t, i)))
        .collect()
}

/// Whether a value of type `actual` may stand where `expected` is.
fn is_assignable(actual: &TypeCode, expected: &TypeCode) -> bool {
    let id = expected.id().unwrap_or_default();
    if actual.kind() == TCKind::ValueBox || expected.kind() == TCKind::ValueBox {
        return actual.kind() == expected.kind() && actual.id().unwrap_or_default() == id;
    }
    // Abstract valuetypes are not in the base chain of a TypeCode.
    if expected.type_modifier() == Ok(VM_ABSTRACT) || id == VALUE_BASE_ID {
        return true;
    }
    let mut t = Some(actual.clone());
    let mut n = 0;
    while let Some(tc) = t {
        if tc.id().unwrap_or_default() == id {
            return true;
        }
        n += 1;
        if n > MAX_DEPTH {
            break;
        }
        t = tc.concrete_base_type().ok().flatten();
    }
    false
}

/// The repository ids a value of type `tc` is sent with: its own, then
/// those of the base types it is truncatable to.
fn sent_ids(tc: &TypeCode) -> Vec<String> {
    let mut ids = vec![tc.id().unwrap_or_default().to_owned()];
    let mut t = tc.clone();
    while t.type_modifier() == Ok(VM_TRUNCATABLE) && ids.len() <= MAX_DEPTH {
        match t.concrete_base_type() {
            Ok(Some(base)) => {
                ids.push(base.id().unwrap_or_default().to_owned());
                t = base;
            }
            _ => break,
        }
    }
    ids
}

/// A value with its type (`CORBA::Any`). The default is an empty Any, of
/// type `null`.
///
/// `Any::new` does not check that the value fits the type; writing an Any
/// that does not fails with `BAD_PARAM`.
#[derive(Debug, Clone, PartialEq)]
pub struct Any {
    tc: TypeCode,
    value: Value,
}

impl Default for Any {
    fn default() -> Any {
        Any::new(TypeCode::null(), Value::Void)
    }
}

impl Any {
    /// An Any of type `tc` holding `value`.
    pub fn new(tc: TypeCode, value: Value) -> Any {
        Any { tc, value }
    }

    /// The type of the value.
    pub fn typecode(&self) -> &TypeCode {
        &self.tc
    }

    /// The value.
    pub fn value(&self) -> &Value {
        &self.value
    }

    /// The type and the value.
    pub fn into_parts(self) -> (TypeCode, Value) {
        (self.tc, self.value)
    }
}

macro_rules! any_from {
    ($($ty:ty => $kind:ident, $variant:ident;)*) => {
        $(
            impl From<$ty> for Any {
                fn from(v: $ty) -> Any {
                    Any::new(TypeCode::simple(TCKind::$kind).expect("simple kind"), Value::$variant(v))
                }
            }
        )*
    };
}

any_from! {
    bool => Boolean, Bool;
    u8 => Octet, Octet;
    i16 => Short, Short;
    u16 => UShort, UShort;
    i32 => Long, Long;
    u32 => ULong, ULong;
    i64 => LongLong, LongLong;
    u64 => ULongLong, ULongLong;
    f32 => Float, Float;
    f64 => Double, Double;
    rustorb_cdr::LongDouble => LongDouble, LongDouble;
    char => Char, Char;
}

impl From<&str> for Any {
    fn from(v: &str) -> Any {
        Any::new(TypeCode::string(0), Value::String(v.to_owned()))
    }
}

impl From<String> for Any {
    fn from(v: String) -> Any {
        Any::new(TypeCode::string(0), Value::String(v))
    }
}

impl From<TypeCode> for Any {
    fn from(v: TypeCode) -> Any {
        Any::new(
            TypeCode::simple(TCKind::TypeCode).expect("simple kind"),
            Value::TypeCode(v),
        )
    }
}

fn sys(kind: SystemExceptionKind, completed: CompletionStatus) -> SystemException {
    SystemException::new(kind, 0, completed)
}

fn bad_param() -> SystemException {
    sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No)
}

// --- writing ---------------------------------------------------------------------

/// Writes `value` of type `tc`. A value that does not fit the type is
/// `BAD_PARAM`, a character the code set cannot represent
/// `DATA_CONVERSION`.
pub(crate) fn write(
    out: &mut OutStream<'_>,
    tc: &TypeCode,
    value: &Value,
) -> Result<(), SystemException> {
    let tc = tc.unaliased();
    let kind = tc.kind();
    match (kind, value) {
        (TCKind::Null | TCKind::Void, _) => {}
        (TCKind::Short, Value::Short(v)) => v.encode(out)?,
        (TCKind::Long, Value::Long(v)) => v.encode(out)?,
        (TCKind::UShort, Value::UShort(v)) => v.encode(out)?,
        (TCKind::ULong, Value::ULong(v)) => v.encode(out)?,
        (TCKind::LongLong, Value::LongLong(v)) => v.encode(out)?,
        (TCKind::ULongLong, Value::ULongLong(v)) => v.encode(out)?,
        (TCKind::Float, Value::Float(v)) => v.encode(out)?,
        (TCKind::Double, Value::Double(v)) => v.encode(out)?,
        (TCKind::LongDouble, Value::LongDouble(v)) => v.encode(out)?,
        (TCKind::Boolean, Value::Bool(v)) => v.encode(out)?,
        (TCKind::Octet, Value::Octet(v)) => out.write_octet(*v),
        (TCKind::Char, Value::Char(c)) => write_char(out, *c)?,
        (TCKind::WChar, Value::WChar(c)) => out.write_wchar(*c)?,
        (TCKind::String, Value::String(s)) => {
            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
            out.write_string(s)?;
        }
        (TCKind::WString, Value::String(s)) => {
            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
            out.write_wstring(s)?;
        }
        (TCKind::Principal, Value::Octets(b)) => out.write_octet_seq(b)?,
        (TCKind::Sequence | TCKind::Array, _) => write_items(out, &tc, value)?,
        (TCKind::Struct | TCKind::Except, Value::List(items)) => {
            let count = tc.member_count().unwrap_or(0);
            if items.len() != count as usize {
                return Err(bad_param());
            }
            if kind == TCKind::Except {
                // An exception starts with its repository id, as in a
                // reply.
                out.write_string(tc.id().unwrap_or_default())?;
            }
            for (i, item) in items.iter().enumerate() {
                write(out, &member(&tc, i as u32), item)?;
            }
        }
        (TCKind::Union, Value::Union { disc, member: m }) => {
            let disc_tc = tc.discriminator_type().map_err(|_| bad_param())?;
            let selected = tc.union_member_for(disc).map_err(|_| bad_param())?;
            if disc.label_key().is_none() || selected != m.as_ref().map(|(i, _)| *i) {
                return Err(bad_param());
            }
            write(out, &disc_tc, disc)?;
            if let Some((i, v)) = m {
                write(out, &member(&tc, *i), v)?;
            }
        }
        (TCKind::Enum, Value::Enum(v)) => {
            if *v >= tc.member_count().unwrap_or(0) {
                return Err(bad_param());
            }
            v.encode(out)?;
        }
        (TCKind::Fixed, Value::Fixed { digits, negative }) => {
            if digits.len() != tc.fixed_digits().unwrap_or(0) as usize {
                return Err(bad_param());
            }
            out.write_fixed(digits, *negative)?;
        }
        (TCKind::Objref | TCKind::Component | TCKind::Home, Value::Objref(obj)) => {
            out.write_object(obj.as_ref())?
        }
        (TCKind::TypeCode, Value::TypeCode(t)) => out.write_typecode(t)?,
        (TCKind::Any, Value::Any(a)) => out.write_any(a)?,
        (TCKind::Value | TCKind::ValueBox | TCKind::Event, Value::Valuetype(v)) => {
            write_valuetype(out, &tc, v.as_ref())?
        }
        // An abstract interface is a union on a boolean: TRUE and an object
        // reference, or FALSE and a value (CORBA 3.4 part 2, 9.3.7).
        (TCKind::AbstractInterface, Value::Objref(obj)) => {
            out.write_bool(true);
            out.write_object(obj.as_ref())?
        }
        (TCKind::AbstractInterface, Value::Valuetype(v)) => {
            out.write_bool(false);
            write_valuetype(out, value_base_tc(), v.as_ref())?
        }
        (TCKind::Native, _) => {
            return Err(sys(SystemExceptionKind::NO_IMPLEMENT, CompletionStatus::No));
        }
        _ => return Err(bad_param()),
    }
    Ok(())
}

fn write_valuetype(
    out: &mut OutStream<'_>,
    expected: &TypeCode,
    v: Option<&ValueRef>,
) -> Result<(), SystemException> {
    let Some(v) = v else {
        out.write_null_value();
        return Ok(());
    };
    let tc = v.typecode().unaliased();
    if !matches!(tc.kind(), TCKind::Value | TCKind::ValueBox | TCKind::Event)
        || !is_assignable(&tc, expected)
    {
        return Err(bad_param());
    }
    match tc.type_modifier() {
        Ok(VM_CUSTOM) => return write_custom(out, &tc, v),
        Ok(VM_ABSTRACT) => return Err(bad_param()),
        _ => {}
    }
    let ids = sent_ids(&tc);
    let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
    // A value of a truncatable type is chunked, so that a receiver can
    // skip what it does not know.
    if !out.begin_value(v.key(), &ids, ids.len() > 1)? {
        return Ok(());
    }
    let types = state_types(&tc);
    let members = v.members();
    if members.len() != types.len() {
        return Err(bad_param());
    }
    for (t, m) in types.iter().zip(&members) {
        write(out, t, m)?;
    }
    out.end_value()?;
    Ok(())
}

/// Writes a custom value: always chunked (CORBA 3.4 part 2, 9.3.4.6), with
/// its repository id, and the items of its state with their types.
fn write_custom(
    out: &mut OutStream<'_>,
    tc: &TypeCode,
    v: &ValueRef,
) -> Result<(), SystemException> {
    if !out.begin_value(v.key(), &[tc.id().unwrap_or_default()], true)? {
        return Ok(());
    }
    for item in v.members() {
        let Value::Any(item) = item else {
            return Err(bad_param());
        };
        write(out, item.typecode(), item.value())?;
    }
    out.end_value()?;
    Ok(())
}

fn member(tc: &TypeCode, i: u32) -> TypeCode {
    tc.member_type(i)
        .expect("index checked against the TypeCode")
}

fn write_char(out: &mut OutStream<'_>, c: char) -> Result<(), SystemException> {
    let bytes = out.code_sets().encode_string(c.encode_utf8(&mut [0; 4]))?;
    match bytes[..] {
        [b] => {
            out.write_char(b);
            Ok(())
        }
        _ => Err(sys(
            SystemExceptionKind::DATA_CONVERSION,
            CompletionStatus::No,
        )),
    }
}

fn check_bound(len: usize, bound: u32) -> Result<(), SystemException> {
    if bound != 0 && len > bound as usize {
        return Err(bad_param());
    }
    Ok(())
}

fn write_items(
    out: &mut OutStream<'_>,
    tc: &TypeCode,
    value: &Value,
) -> Result<(), SystemException> {
    let is_seq = tc.kind() == TCKind::Sequence;
    let n = tc.length().unwrap_or(0);
    let check = |len: usize| {
        if is_seq {
            check_bound(len, n)
        } else if len != n as usize {
            Err(bad_param())
        } else {
            Ok(())
        }
    };
    let content = tc.content_type().map_err(|_| bad_param())?;
    let content_kind = content.unaliased().kind();
    match (content_kind, value) {
        (TCKind::Octet, Value::Octets(b)) => {
            check(b.len())?;
            if is_seq {
                out.write_octet_seq_shared(b)?;
            } else {
                out.write_octets(b);
            }
        }
        (TCKind::Char, Value::Chars(s)) => {
            check(s.chars().count())?;
            let bytes = out.code_sets().encode_string(s)?;
            if bytes.len() != s.chars().count() {
                return Err(sys(
                    SystemExceptionKind::DATA_CONVERSION,
                    CompletionStatus::No,
                ));
            }
            if is_seq {
                out.write_len(bytes.len())?;
            }
            out.write_octets(&bytes);
        }
        (_, Value::List(items)) => {
            check(items.len())?;
            if is_seq {
                out.write_len(items.len())?;
            }
            for item in items {
                write(out, &content, item)?;
            }
        }
        _ => return Err(bad_param()),
    }
    Ok(())
}

// --- reading ---------------------------------------------------------------------

/// Reads a value of type `tc`. Errors are `MARSHAL` with the completion
/// status of the stream.
pub(crate) fn read(input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
    Reader { depth: 0 }.read(input, tc)
}

struct Reader {
    depth: usize,
}

impl Reader {
    fn read(&mut self, input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
        self.depth += 1;
        if self.depth > MAX_DEPTH {
            return Err(input.marshal_error());
        }
        let value = self.read_value(input, tc);
        self.depth -= 1;
        value
    }

    fn read_value(
        &mut self,
        input: &mut InStream<'_>,
        tc: &TypeCode,
    ) -> Result<Value, SystemException> {
        let tc = tc.unaliased();
        Ok(match tc.kind() {
            TCKind::Null | TCKind::Void => Value::Void,
            TCKind::Short => Value::Short(input.read()?),
            TCKind::Long => Value::Long(input.read()?),
            TCKind::UShort => Value::UShort(input.read()?),
            TCKind::ULong => Value::ULong(input.read()?),
            TCKind::LongLong => Value::LongLong(input.read()?),
            TCKind::ULongLong => Value::ULongLong(input.read()?),
            TCKind::Float => Value::Float(input.read()?),
            TCKind::Double => Value::Double(input.read()?),
            TCKind::LongDouble => Value::LongDouble(input.read()?),
            TCKind::Boolean => Value::Bool(input.read()?),
            TCKind::Octet => Value::Octet(input.read()?),
            TCKind::Char => Value::Char(input.read_char_value()?),
            TCKind::WChar => Value::WChar(input.read_wchar()?),
            TCKind::String => {
                let s = input.read_string()?;
                self.check_bound(input, s.chars().count(), &tc)?;
                Value::String(s)
            }
            TCKind::WString => {
                let s = input.read_wstring()?;
                self.check_bound(input, s.chars().count(), &tc)?;
                Value::String(s)
            }
            TCKind::Principal => Value::Octets(input.read::<Vec<u8>>()?.into()),
            TCKind::Sequence => {
                let content = tc.content_type().map_err(|_| input.marshal_error())?;
                let min = min_size(&content, 0).max(1);
                let len = input.read_len(min).map_err(|_| input.marshal_error())?;
                self.check_bound(input, len, &tc)?;
                self.read_items(input, &content, len)?
            }
            TCKind::Array => {
                let content = tc.content_type().map_err(|_| input.marshal_error())?;
                let len = tc.length().unwrap_or(0) as usize;
                self.read_items(input, &content, len)?
            }
            TCKind::Struct | TCKind::Except => {
                if tc.kind() == TCKind::Except {
                    input.read_string()?;
                }
                let count = tc.member_count().unwrap_or(0);
                let mut items = Vec::with_capacity(count as usize);
                for i in 0..count {
                    items.push(self.read(input, &member(&tc, i))?);
                }
                Value::List(items)
            }
            TCKind::Union => {
                let disc_tc = tc.discriminator_type().map_err(|_| input.marshal_error())?;
                let disc = self.read(input, &disc_tc)?;
                let selected = tc
                    .union_member_for(&disc)
                    .map_err(|_| input.marshal_error())?;
                let m = match selected {
                    Some(i) => Some((i, Box::new(self.read(input, &member(&tc, i))?))),
                    None => None,
                };
                Value::Union {
                    disc: Box::new(disc),
                    member: m,
                }
            }
            TCKind::Enum => {
                let v: u32 = input.read()?;
                if v >= tc.member_count().unwrap_or(0) {
                    return Err(input.marshal_error());
                }
                Value::Enum(v)
            }
            TCKind::Fixed => {
                let (digits, negative) =
                    input.read_fixed(tc.fixed_digits().unwrap_or(0) as usize)?;
                Value::Fixed { digits, negative }
            }
            TCKind::Objref | TCKind::Component | TCKind::Home => {
                Value::Objref(input.read_object()?)
            }
            TCKind::TypeCode => Value::TypeCode(input.read_typecode()?),
            TCKind::Any => {
                let inner = input.read_typecode()?;
                let v = self.read(input, &inner)?;
                Value::Any(Box::new(Any::new(inner, v)))
            }
            TCKind::Value | TCKind::ValueBox | TCKind::Event => {
                Value::Valuetype(self.read_valuetype(input, &tc)?)
            }
            TCKind::AbstractInterface => {
                if input.read_bool()? {
                    Value::Objref(input.read_object()?)
                } else {
                    Value::Valuetype(self.read_valuetype(input, value_base_tc())?)
                }
            }
            TCKind::LocalInterface => return Err(input.marshal_error()),
            _ => {
                return Err(sys(SystemExceptionKind::NO_IMPLEMENT, input.completed));
            }
        })
    }

    fn read_valuetype(
        &mut self,
        input: &mut InStream<'_>,
        expected: &TypeCode,
    ) -> Result<Option<ValueRef>, SystemException> {
        let header = input
            .read_value_header()
            .map_err(|_| input.marshal_error())?;
        let (slot, ids) = match header {
            ValueHeader::Null => return Ok(None),
            ValueHeader::Indirection(slot) => {
                return match input.values.get(slot) {
                    Some(Some(v)) => Ok(Some(v.clone())),
                    _ => Err(input.marshal_error()),
                };
            }
            ValueHeader::Value { slot, ids, .. } => (slot, ids),
        };
        let tc = known_type(expected, &ids).ok_or_else(|| input.marshal_error())?;
        let custom = match tc.type_modifier() {
            Ok(VM_CUSTOM) => {
                let id = tc.id().unwrap_or_default();
                Some(custom_reader(id).ok_or_else(|| input.marshal_error())?)
            }
            Ok(VM_ABSTRACT) => return Err(input.marshal_error()),
            _ => None,
        };
        let v = ValueRef::new(tc.clone(), Vec::new());
        if input.values.len() <= slot {
            input.values.resize(slot + 1, None);
        }
        input.values[slot] = Some(v.clone());
        if let Some(reader) = custom {
            reader(&v, input)?;
            input.end_value().map_err(|_| input.marshal_error())?;
            return Ok(Some(v));
        }
        let mut members = Vec::new();
        for t in state_types(&tc) {
            members.push(self.read(input, &t)?);
        }
        v.set_members(members);
        input.end_value().map_err(|_| input.marshal_error())?;
        Ok(Some(v))
    }

    fn check_bound(
        &self,
        input: &InStream<'_>,
        len: usize,
        tc: &TypeCode,
    ) -> Result<(), SystemException> {
        let bound = tc.length().unwrap_or(0);
        if bound != 0 && len > bound as usize {
            return Err(input.marshal_error());
        }
        Ok(())
    }

    fn read_items(
        &mut self,
        input: &mut InStream<'_>,
        content: &TypeCode,
        len: usize,
    ) -> Result<Value, SystemException> {
        Ok(match content.unaliased().kind() {
            TCKind::Octet => Value::Octets(
                input
                    .read_octets_shared(len)
                    .map_err(|_| input.marshal_error())?,
            ),
            TCKind::Char => {
                let bytes = input.read_octets(len).map_err(|_| input.marshal_error())?;
                let completed = input.completed;
                Value::Chars(input.code_sets().decode_string(bytes).map_err(|mut e| {
                    e.completed = completed;
                    e
                })?)
            }
            _ => {
                let mut items = Vec::with_capacity(len.min(4096));
                for _ in 0..len {
                    items.push(self.read(input, content)?);
                }
                Value::List(items)
            }
        })
    }
}

/// The type to read a value sent with the repository ids `ids` as: the
/// first of them that is `expected` or a registered valuetype, or
/// `expected` when no id was sent (but not `ValueBase`, which has no
/// state of its own).
fn known_type(expected: &TypeCode, ids: &[String]) -> Option<TypeCode> {
    let expected_id = expected.id().unwrap_or_default();
    if ids.is_empty() {
        return (expected_id != VALUE_BASE_ID).then(|| expected.clone());
    }
    ids.iter().find_map(|id| {
        if id == expected_id {
            Some(expected.clone())
        } else {
            find_value_type(id).filter(|t| is_assignable(t, expected))
        }
    })
}

/// The smallest size of a value on the wire, to check sequence lengths
/// before allocating.
fn min_size(tc: &TypeCode, depth: usize) -> usize {
    if depth > 8 {
        return 0;
    }
    let tc = tc.unaliased();
    match tc.kind() {
        TCKind::Boolean
        | TCKind::Char
        | TCKind::Octet
        | TCKind::WChar
        | TCKind::AbstractInterface => 1,
        TCKind::Short | TCKind::UShort => 2,
        TCKind::Long
        | TCKind::ULong
        | TCKind::Float
        | TCKind::Enum
        | TCKind::String
        | TCKind::WString
        | TCKind::Sequence
        | TCKind::Objref
        | TCKind::TypeCode
        | TCKind::Any
        | TCKind::Principal
        | TCKind::Value
        | TCKind::ValueBox
        | TCKind::Event => 4,
        TCKind::LongLong | TCKind::ULongLong | TCKind::Double => 8,
        TCKind::LongDouble => 16,
        TCKind::Fixed => (tc.fixed_digits().unwrap_or(0) as usize + 2) / 2,
        TCKind::Array => {
            let content = tc.content_type().map(|c| min_size(&c, depth + 1));
            content.unwrap_or(0) * tc.length().unwrap_or(0) as usize
        }
        TCKind::Struct | TCKind::Except => (0..tc.member_count().unwrap_or(0))
            .map(|i| min_size(&member(&tc, i), depth + 1))
            .fold(0usize, usize::saturating_add),
        _ => 0,
    }
}