Skip to main content

rustorb_core/
value.rs

1//! Values of any IDL type, described by a [`TypeCode`], and [`Any`].
2//!
3//! [`Value`] is the form the language bindings marshal through: they
4//! convert their own values to it and the ORB writes it as the TypeCode
5//! says, and the other way when reading. An [`Any`] is a TypeCode with a
6//! value of that type.
7
8use std::collections::BTreeMap;
9use std::fmt;
10use std::sync::{Arc, Mutex, MutexGuard, RwLock};
11
12use rustorb_cdr::{CdrEncode, ValueHeader};
13
14use crate::typecode::{TCKind, TypeCode};
15use crate::{
16    CompletionStatus, InStream, ObjectRef, OutStream, SystemException, SystemExceptionKind,
17};
18
19/// How deep values may nest when read, against stack exhaustion with
20/// recursive types.
21const MAX_DEPTH: usize = 256;
22
23/// A value of an IDL type. Which variant goes with which type:
24///
25/// | Type | Value |
26/// | --- | --- |
27/// | `void`, `null` | `Void` |
28/// | integers, `float`, `double`, `boolean`, `octet` | the variant of the same name |
29/// | `char`, `wchar` | `Char` (a character of the `char` code set), `WChar` (a UTF-16 code unit) |
30/// | `string`, `wstring` | `String` |
31/// | `sequence` and array of `octet`, `Principal` | `Octets` (or `List` of `Octet`) |
32/// | `sequence` and array of `char` | `Chars` (or `List` of `Char`) |
33/// | 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) |
34/// | union | `Union`: the discriminator, and the index of the TypeCode member with its value, `None` when no member is selected |
35/// | enum | `Enum`: the position of the enumerator |
36/// | `long double` | `LongDouble`: the binary128 bits ([`LongDouble`](rustorb_cdr::LongDouble)) |
37/// | `fixed` | `Fixed`: the digits (as many as the type has, most significant first) and the sign |
38/// | object reference | `Objref`, `None` for nil |
39/// | `TypeCode` | `TypeCode` |
40/// | `any` | `Any` |
41/// | valuetype, value box | `Valuetype`: a shared [`ValueRef`], `None` for `null` |
42/// | abstract interface | `Objref` (sent as a reference) or `Valuetype` (sent as a value) |
43///
44/// Aliases take the value of the type they stand for. The state of a
45/// custom valuetype is the items its marshaling code writes, each a
46/// `Value::Any` of the item's type and value (see [`register_custom_reader`]).
47#[derive(Debug, Clone)]
48#[allow(missing_docs)]
49pub enum Value {
50    Void,
51    Bool(bool),
52    Octet(u8),
53    Short(i16),
54    UShort(u16),
55    Long(i32),
56    ULong(u32),
57    LongLong(i64),
58    ULongLong(u64),
59    Float(f32),
60    Double(f64),
61    LongDouble(rustorb_cdr::LongDouble),
62    Char(char),
63    WChar(u16),
64    String(String),
65    Octets(rustorb_cdr::Octets),
66    Chars(String),
67    List(Vec<Value>),
68    Union {
69        disc: Box<Value>,
70        member: Option<(u32, Box<Value>)>,
71    },
72    Enum(u32),
73    Fixed {
74        digits: Vec<u8>,
75        negative: bool,
76    },
77    Objref(Option<ObjectRef>),
78    TypeCode(TypeCode),
79    Any(Box<Any>),
80    Valuetype(Option<ValueRef>),
81}
82
83impl Value {
84    /// The number a union discriminator value stands for, as in union
85    /// labels ([`TypeCode::union_tc`]): integers as they are, `boolean` as
86    /// 0 or 1, `char` and `wchar` as their code, an enumerator as its
87    /// position. `None` for values that cannot be discriminators.
88    pub fn label_key(&self) -> Option<i128> {
89        Some(match *self {
90            Value::Bool(v) => i128::from(v),
91            Value::Octet(v) => i128::from(v),
92            Value::Short(v) => i128::from(v),
93            Value::UShort(v) => i128::from(v),
94            Value::Long(v) => i128::from(v),
95            Value::ULong(v) => i128::from(v),
96            Value::LongLong(v) => i128::from(v),
97            Value::ULongLong(v) => i128::from(v),
98            Value::Char(c) => i128::from(u32::from(c)),
99            Value::WChar(c) => i128::from(c),
100            Value::Enum(v) => i128::from(v),
101            _ => return None,
102        })
103    }
104}
105
106impl PartialEq for Value {
107    fn eq(&self, other: &Value) -> bool {
108        use Value::*;
109        match (self, other) {
110            (Void, Void) => true,
111            (Bool(a), Bool(b)) => a == b,
112            (Octet(a), Octet(b)) => a == b,
113            (Short(a), Short(b)) => a == b,
114            (UShort(a), UShort(b)) => a == b,
115            (Long(a), Long(b)) => a == b,
116            (ULong(a), ULong(b)) => a == b,
117            (LongLong(a), LongLong(b)) => a == b,
118            (ULongLong(a), ULongLong(b)) => a == b,
119            (Float(a), Float(b)) => a == b,
120            (Double(a), Double(b)) => a == b,
121            (LongDouble(a), LongDouble(b)) => a == b,
122            (Char(a), Char(b)) => a == b,
123            (WChar(a), WChar(b)) => a == b,
124            (String(a), String(b)) | (Chars(a), Chars(b)) => a == b,
125            (Octets(a), Octets(b)) => a == b,
126            (Octets(a), List(b)) | (List(b), Octets(a)) => {
127                a.len() == b.len() && a.iter().zip(b).all(|(x, y)| *y == Octet(*x))
128            }
129            (Chars(a), List(b)) | (List(b), Chars(a)) => {
130                a.chars().count() == b.len() && a.chars().zip(b).all(|(x, y)| *y == Char(x))
131            }
132            (List(a), List(b)) => a == b,
133            (
134                Union {
135                    disc: d1,
136                    member: m1,
137                },
138                Union {
139                    disc: d2,
140                    member: m2,
141                },
142            ) => d1 == d2 && m1 == m2,
143            (Enum(a), Enum(b)) => a == b,
144            (
145                Fixed {
146                    digits: d1,
147                    negative: n1,
148                },
149                Fixed {
150                    digits: d2,
151                    negative: n2,
152                },
153            ) => d1 == d2 && n1 == n2,
154            (Objref(a), Objref(b)) => match (a, b) {
155                (None, None) => true,
156                (Some(a), Some(b)) => a.is_equivalent(b),
157                _ => false,
158            },
159            (TypeCode(a), TypeCode(b)) => a.equal(b),
160            (Any(a), Any(b)) => a == b,
161            (Valuetype(a), Valuetype(b)) => match (a, b) {
162                (None, None) => true,
163                (Some(a), Some(b)) => a.same_state(b),
164                _ => false,
165            },
166            _ => false,
167        }
168    }
169}
170
171impl Value {
172    /// Breaks the reference cycles that valuetypes in this value may
173    /// form, so that they are freed: the state of every [`ValueRef`] in it
174    /// is emptied. For a binding that is done with a value it made.
175    pub fn break_cycles(self) {
176        let mut stack = vec![self];
177        while let Some(v) = stack.pop() {
178            match v {
179                Value::List(items) => stack.extend(items),
180                Value::Union { disc, member } => {
181                    stack.push(*disc);
182                    stack.extend(member.map(|(_, v)| *v));
183                }
184                Value::Any(a) => stack.push(a.value),
185                Value::Valuetype(Some(r)) => {
186                    r.set_native(None);
187                    stack.extend(r.take_members());
188                }
189                _ => {}
190            }
191        }
192    }
193
194    /// Drops the value, and first breaks the reference cycles among the
195    /// valuetypes in it that nothing else refers to, so that they are
196    /// freed: for a binding that drops a value it may share. Instances
197    /// that are referred to from elsewhere (another value, a binding's
198    /// object), and those they refer to, are left as they are.
199    ///
200    /// The instances reachable from the value are counted: one whose
201    /// references are not all from the value and the instances reachable
202    /// from it is referred to from elsewhere (trial deletion).
203    pub fn release(self) {
204        use std::collections::HashMap;
205        use std::collections::hash_map::Entry;
206
207        // The instances reachable from the value: a clone of each, how
208        // many references to it there are from the value and from them,
209        // and the instances each refers to.
210        type Nodes = HashMap<u64, (ValueRef, usize, Vec<u64>)>;
211        fn visit(r: &ValueRef, nodes: &mut Nodes, pending: &mut Vec<u64>) -> u64 {
212            let key = r.key();
213            match nodes.entry(key) {
214                Entry::Occupied(mut e) => e.get_mut().1 += 1,
215                Entry::Vacant(e) => {
216                    e.insert((r.clone(), 1, Vec::new()));
217                    pending.push(key);
218                }
219            }
220            key
221        }
222        let mut nodes = Nodes::new();
223        let mut pending = Vec::new();
224        each_ref(&self, &mut |r| {
225            visit(r, &mut nodes, &mut pending);
226        });
227        if nodes.is_empty() {
228            return;
229        }
230        while let Some(key) = pending.pop() {
231            let node = nodes[&key].0.clone();
232            let mut children = Vec::new();
233            for m in node.lock().iter() {
234                each_ref(m, &mut |r| {
235                    children.push(visit(r, &mut nodes, &mut pending))
236                });
237            }
238            nodes.get_mut(&key).expect("visited").2 = children;
239        }
240        // Referred to from elsewhere: more references than those counted
241        // and the clone in `nodes`.
242        let mut live: Vec<u64> = nodes
243            .iter()
244            .filter(|(_, (r, internal, _))| Arc::strong_count(&r.0) > internal + 1)
245            .map(|(k, _)| *k)
246            .collect();
247        let mut reached: std::collections::HashSet<u64> = live.iter().copied().collect();
248        while let Some(key) = live.pop() {
249            for child in &nodes[&key].2 {
250                if reached.insert(*child) {
251                    live.push(*child);
252                }
253            }
254        }
255        let mut freed = Vec::new();
256        for (key, (r, _, _)) in &nodes {
257            if !reached.contains(key) {
258                freed.push(r.take_members());
259            }
260        }
261        drop(nodes);
262        drop(freed);
263    }
264}
265
266/// Calls `f` on each [`ValueRef`] directly in `v` (not in the state of the
267/// instances).
268fn each_ref(v: &Value, f: &mut impl FnMut(&ValueRef)) {
269    let mut stack = vec![v];
270    while let Some(v) = stack.pop() {
271        match v {
272            Value::List(items) => stack.extend(items),
273            Value::Union { disc, member } => {
274                stack.push(disc);
275                stack.extend(member.as_ref().map(|(_, v)| &**v));
276            }
277            Value::Any(a) => stack.push(&a.value),
278            Value::Valuetype(Some(r)) => f(r),
279            _ => {}
280        }
281    }
282}
283
284/// An instance of a valuetype or a value box: its type and its state.
285///
286/// Clones share the instance, as references do in the language
287/// mappings: an instance written twice in a message is sent once, then as
288/// an indirection to it, and is read back as one instance. Instances may
289/// refer to each other in cycles; [`Value::break_cycles`] frees them.
290#[derive(Clone)]
291pub struct ValueRef(Arc<ValueObj>);
292
293struct ValueObj {
294    tc: TypeCode,
295    members: Mutex<Vec<Value>>,
296    native: Mutex<Option<Native>>,
297}
298
299/// An object of a language binding that stands for a [`ValueRef`].
300pub type Native = Arc<dyn std::any::Any + Send + Sync>;
301
302impl ValueRef {
303    /// An instance of the valuetype `tc` (the most derived type) with the
304    /// values of its state members: those of its base types first, then
305    /// its own, in the order of the TypeCodes. An instance of a value box
306    /// has the boxed value as its one member.
307    pub fn new(tc: TypeCode, members: Vec<Value>) -> ValueRef {
308        ValueRef(Arc::new(ValueObj {
309            tc,
310            members: Mutex::new(members),
311            native: Mutex::new(None),
312        }))
313    }
314
315    /// The object of a language binding set with [`ValueRef::set_native`].
316    pub fn native(&self) -> Option<Native> {
317        self.0
318            .native
319            .lock()
320            .unwrap_or_else(|e| e.into_inner())
321            .clone()
322    }
323
324    /// Sets (or, with `None`, removes) the object of a language binding
325    /// that stands for this instance: a custom reader
326    /// ([`register_custom_reader`]) sets the instance it made, so that
327    /// the binding finds it again when it converts the value.
328    pub fn set_native(&self, native: Option<Native>) {
329        *self.0.native.lock().unwrap_or_else(|e| e.into_inner()) = native;
330    }
331
332    /// The type of the instance.
333    pub fn typecode(&self) -> &TypeCode {
334        &self.0.tc
335    }
336
337    /// The repository id of the type of the instance.
338    pub fn id(&self) -> &str {
339        self.0.tc.id().unwrap_or_default()
340    }
341
342    /// The values of the state members.
343    pub fn members(&self) -> Vec<Value> {
344        self.lock().clone()
345    }
346
347    /// Replaces the values of the state members.
348    pub fn set_members(&self, members: Vec<Value>) {
349        *self.lock() = members;
350    }
351
352    /// Takes the values of the state members, leaving none.
353    pub fn take_members(&self) -> Vec<Value> {
354        std::mem::take(&mut *self.lock())
355    }
356
357    /// Whether both are the same instance.
358    pub fn ptr_eq(&self, other: &ValueRef) -> bool {
359        Arc::ptr_eq(&self.0, &other.0)
360    }
361
362    /// A number that identifies the instance while it is alive.
363    pub fn key(&self) -> u64 {
364        Arc::as_ptr(&self.0) as usize as u64
365    }
366
367    fn lock(&self) -> MutexGuard<'_, Vec<Value>> {
368        self.0.members.lock().unwrap_or_else(|e| e.into_inner())
369    }
370
371    /// Whether both have the same type and equal state, the same instance
372    /// being equal to itself however it is reached (for cycles).
373    fn same_state(&self, other: &ValueRef) -> bool {
374        thread_local! {
375            static COMPARING: std::cell::RefCell<Vec<(u64, u64)>> =
376                const { std::cell::RefCell::new(Vec::new()) };
377        }
378        if self.ptr_eq(other) {
379            return true;
380        }
381        if !self.typecode().equal(other.typecode()) {
382            return false;
383        }
384        let pair = (self.key(), other.key());
385        if COMPARING.with(|c| c.borrow().contains(&pair)) {
386            return true;
387        }
388        COMPARING.with(|c| c.borrow_mut().push(pair));
389        // Copies, so that no lock is held while comparing nested values.
390        let equal = self.members() == other.members();
391        COMPARING.with(|c| c.borrow_mut().retain(|p| *p != pair));
392        equal
393    }
394}
395
396impl fmt::Debug for ValueRef {
397    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
398        // Not the state, which may refer back to this instance.
399        write!(f, "ValueRef({} @ {:#x})", self.id(), self.key())
400    }
401}
402
403/// The valuetypes known to the readers, by repository id.
404static VALUE_TYPES: RwLock<BTreeMap<String, TypeCode>> = RwLock::new(BTreeMap::new());
405
406/// Makes the valuetype `tc` known to every ORB of the process, so that a
407/// value of it can be read where a base type of it is expected.
408///
409/// A value whose type is neither the expected type nor registered is read
410/// as the first of its truncatable base types that is, and is `MARSHAL`
411/// if there is none.
412pub fn register_value_type(tc: &TypeCode) {
413    let tc = tc.unaliased();
414    if let Ok(id) = tc.id() {
415        let id = id.to_owned();
416        VALUE_TYPES
417            .write()
418            .unwrap_or_else(|e| e.into_inner())
419            .insert(id, tc);
420    }
421}
422
423/// The valuetype registered with [`register_value_type`] for `id`.
424pub fn lookup_value_type(id: &str) -> Option<TypeCode> {
425    VALUE_TYPES
426        .read()
427        .unwrap_or_else(|e| e.into_inner())
428        .get(id)
429        .cloned()
430}
431
432/// Finds the valuetype of a repository id that is not registered: a
433/// binding whose valuetypes are only known when asked for (Java, whose
434/// classes are loaded by name) sets one with [`set_value_type_resolver`].
435pub type ValueTypeResolver = dyn Fn(&str) -> Option<TypeCode> + Send + Sync;
436
437static RESOLVER: RwLock<Option<Arc<ValueTypeResolver>>> = RwLock::new(None);
438
439/// Sets (or, with `None`, removes) the resolver asked for repository ids
440/// that are not registered; what it finds is registered.
441pub fn set_value_type_resolver(resolver: Option<Arc<ValueTypeResolver>>) {
442    *RESOLVER.write().unwrap_or_else(|e| e.into_inner()) = resolver;
443}
444
445/// The registered valuetype of `id`, else the one the resolver finds.
446fn find_value_type(id: &str) -> Option<TypeCode> {
447    if let Some(tc) = lookup_value_type(id) {
448        return Some(tc);
449    }
450    let resolver = RESOLVER.read().unwrap_or_else(|e| e.into_inner()).clone()?;
451    let tc = resolver(id)?;
452    if tc.id().ok() != Some(id) {
453        return None;
454    }
455    register_value_type(&tc);
456    lookup_value_type(id)
457}
458
459/// Forgets the valuetype registered for `id`.
460pub fn unregister_value_type(id: &str) {
461    VALUE_TYPES
462        .write()
463        .unwrap_or_else(|e| e.into_inner())
464        .remove(id);
465}
466
467/// Reads the state of a custom valuetype from `input`, into `value`, a new
468/// instance of the type: what the value's marshaling code wrote, read with
469/// [`InStream::read_value`] item by item. The reader sets the state of
470/// `value` to the items read (each a `Value::Any`) so that it can be
471/// written again, and may set an object of its own with
472/// [`ValueRef::set_native`].
473pub type CustomReader =
474    dyn Fn(&ValueRef, &mut InStream<'_>) -> Result<(), SystemException> + Send + Sync;
475
476/// The custom readers, by repository id.
477static CUSTOM_READERS: RwLock<BTreeMap<String, Arc<CustomReader>>> = RwLock::new(BTreeMap::new());
478
479/// Sets the reader of the custom valuetype `id` (`VM_CUSTOM`), the
480/// unmarshaling half of `CORBA::CustomMarshal`. A value of a custom type
481/// without a reader is read as `MARSHAL`, as when no value factory is
482/// registered.
483///
484/// A custom value is written from its state: the items in it, each a
485/// `Value::Any`, are written one after the other with their types, the
486/// way its marshaling code writes them (`CORBA::DataOutputStream`).
487pub fn register_custom_reader(id: &str, reader: Arc<CustomReader>) {
488    CUSTOM_READERS
489        .write()
490        .unwrap_or_else(|e| e.into_inner())
491        .insert(id.to_owned(), reader);
492}
493
494/// Forgets the reader of the custom valuetype `id`.
495pub fn unregister_custom_reader(id: &str) {
496    CUSTOM_READERS
497        .write()
498        .unwrap_or_else(|e| e.into_inner())
499        .remove(id);
500}
501
502fn custom_reader(id: &str) -> Option<Arc<CustomReader>> {
503    CUSTOM_READERS
504        .read()
505        .unwrap_or_else(|e| e.into_inner())
506        .get(id)
507        .cloned()
508}
509
510/// The repository id of `ValueBase`, which every valuetype may stand for.
511pub(crate) const VALUE_BASE_ID: &str = "IDL:omg.org/CORBA/ValueBase:1.0";
512
513/// The TypeCode of `ValueBase`: any value of a known type.
514pub(crate) fn value_base_tc() -> &'static TypeCode {
515    static TC: std::sync::OnceLock<TypeCode> = std::sync::OnceLock::new();
516    TC.get_or_init(|| {
517        TypeCode::value_tc(
518            TCKind::Value,
519            VALUE_BASE_ID,
520            "ValueBase",
521            0,
522            None,
523            &[] as &[(&str, TypeCode, i16)],
524        )
525        .expect("a valid TypeCode")
526    })
527}
528
529const VM_CUSTOM: i16 = 1;
530const VM_ABSTRACT: i16 = 2;
531const VM_TRUNCATABLE: i16 = 3;
532
533/// The types of the state members of a valuetype, those of its base
534/// types first; the boxed type of a value box.
535pub(crate) fn state_types(tc: &TypeCode) -> Vec<TypeCode> {
536    if tc.kind() == TCKind::ValueBox {
537        return tc.content_type().into_iter().collect();
538    }
539    let mut chain = vec![tc.clone()];
540    while let Some(Some(base)) = chain.last().map(|t| t.concrete_base_type().ok().flatten()) {
541        if chain.len() > MAX_DEPTH {
542            break;
543        }
544        chain.push(base.unaliased());
545    }
546    chain
547        .iter()
548        .rev()
549        .flat_map(|t| (0..t.member_count().unwrap_or(0)).map(move |i| member(t, i)))
550        .collect()
551}
552
553/// Whether a value of type `actual` may stand where `expected` is.
554fn is_assignable(actual: &TypeCode, expected: &TypeCode) -> bool {
555    let id = expected.id().unwrap_or_default();
556    if actual.kind() == TCKind::ValueBox || expected.kind() == TCKind::ValueBox {
557        return actual.kind() == expected.kind() && actual.id().unwrap_or_default() == id;
558    }
559    // Abstract valuetypes are not in the base chain of a TypeCode.
560    if expected.type_modifier() == Ok(VM_ABSTRACT) || id == VALUE_BASE_ID {
561        return true;
562    }
563    let mut t = Some(actual.clone());
564    let mut n = 0;
565    while let Some(tc) = t {
566        if tc.id().unwrap_or_default() == id {
567            return true;
568        }
569        n += 1;
570        if n > MAX_DEPTH {
571            break;
572        }
573        t = tc.concrete_base_type().ok().flatten();
574    }
575    false
576}
577
578/// The repository ids a value of type `tc` is sent with: its own, then
579/// those of the base types it is truncatable to.
580fn sent_ids(tc: &TypeCode) -> Vec<String> {
581    let mut ids = vec![tc.id().unwrap_or_default().to_owned()];
582    let mut t = tc.clone();
583    while t.type_modifier() == Ok(VM_TRUNCATABLE) && ids.len() <= MAX_DEPTH {
584        match t.concrete_base_type() {
585            Ok(Some(base)) => {
586                ids.push(base.id().unwrap_or_default().to_owned());
587                t = base;
588            }
589            _ => break,
590        }
591    }
592    ids
593}
594
595/// A value with its type (`CORBA::Any`). The default is an empty Any, of
596/// type `null`.
597///
598/// `Any::new` does not check that the value fits the type; writing an Any
599/// that does not fails with `BAD_PARAM`.
600#[derive(Debug, Clone, PartialEq)]
601pub struct Any {
602    tc: TypeCode,
603    value: Value,
604}
605
606impl Default for Any {
607    fn default() -> Any {
608        Any::new(TypeCode::null(), Value::Void)
609    }
610}
611
612impl Any {
613    /// An Any of type `tc` holding `value`.
614    pub fn new(tc: TypeCode, value: Value) -> Any {
615        Any { tc, value }
616    }
617
618    /// The type of the value.
619    pub fn typecode(&self) -> &TypeCode {
620        &self.tc
621    }
622
623    /// The value.
624    pub fn value(&self) -> &Value {
625        &self.value
626    }
627
628    /// The type and the value.
629    pub fn into_parts(self) -> (TypeCode, Value) {
630        (self.tc, self.value)
631    }
632}
633
634macro_rules! any_from {
635    ($($ty:ty => $kind:ident, $variant:ident;)*) => {
636        $(
637            impl From<$ty> for Any {
638                fn from(v: $ty) -> Any {
639                    Any::new(TypeCode::simple(TCKind::$kind).expect("simple kind"), Value::$variant(v))
640                }
641            }
642        )*
643    };
644}
645
646any_from! {
647    bool => Boolean, Bool;
648    u8 => Octet, Octet;
649    i16 => Short, Short;
650    u16 => UShort, UShort;
651    i32 => Long, Long;
652    u32 => ULong, ULong;
653    i64 => LongLong, LongLong;
654    u64 => ULongLong, ULongLong;
655    f32 => Float, Float;
656    f64 => Double, Double;
657    rustorb_cdr::LongDouble => LongDouble, LongDouble;
658    char => Char, Char;
659}
660
661impl From<&str> for Any {
662    fn from(v: &str) -> Any {
663        Any::new(TypeCode::string(0), Value::String(v.to_owned()))
664    }
665}
666
667impl From<String> for Any {
668    fn from(v: String) -> Any {
669        Any::new(TypeCode::string(0), Value::String(v))
670    }
671}
672
673impl From<TypeCode> for Any {
674    fn from(v: TypeCode) -> Any {
675        Any::new(
676            TypeCode::simple(TCKind::TypeCode).expect("simple kind"),
677            Value::TypeCode(v),
678        )
679    }
680}
681
682fn sys(kind: SystemExceptionKind, completed: CompletionStatus) -> SystemException {
683    SystemException::new(kind, 0, completed)
684}
685
686fn bad_param() -> SystemException {
687    sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No)
688}
689
690// --- writing ---------------------------------------------------------------------
691
692/// Writes `value` of type `tc`. A value that does not fit the type is
693/// `BAD_PARAM`, a character the code set cannot represent
694/// `DATA_CONVERSION`.
695pub(crate) fn write(
696    out: &mut OutStream<'_>,
697    tc: &TypeCode,
698    value: &Value,
699) -> Result<(), SystemException> {
700    let tc = tc.unaliased();
701    let kind = tc.kind();
702    match (kind, value) {
703        (TCKind::Null | TCKind::Void, _) => {}
704        (TCKind::Short, Value::Short(v)) => v.encode(out)?,
705        (TCKind::Long, Value::Long(v)) => v.encode(out)?,
706        (TCKind::UShort, Value::UShort(v)) => v.encode(out)?,
707        (TCKind::ULong, Value::ULong(v)) => v.encode(out)?,
708        (TCKind::LongLong, Value::LongLong(v)) => v.encode(out)?,
709        (TCKind::ULongLong, Value::ULongLong(v)) => v.encode(out)?,
710        (TCKind::Float, Value::Float(v)) => v.encode(out)?,
711        (TCKind::Double, Value::Double(v)) => v.encode(out)?,
712        (TCKind::LongDouble, Value::LongDouble(v)) => v.encode(out)?,
713        (TCKind::Boolean, Value::Bool(v)) => v.encode(out)?,
714        (TCKind::Octet, Value::Octet(v)) => out.write_octet(*v),
715        (TCKind::Char, Value::Char(c)) => write_char(out, *c)?,
716        (TCKind::WChar, Value::WChar(c)) => out.write_wchar(*c)?,
717        (TCKind::String, Value::String(s)) => {
718            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
719            out.write_string(s)?;
720        }
721        (TCKind::WString, Value::String(s)) => {
722            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
723            out.write_wstring(s)?;
724        }
725        (TCKind::Principal, Value::Octets(b)) => out.write_octet_seq(b)?,
726        (TCKind::Sequence | TCKind::Array, _) => write_items(out, &tc, value)?,
727        (TCKind::Struct | TCKind::Except, Value::List(items)) => {
728            let count = tc.member_count().unwrap_or(0);
729            if items.len() != count as usize {
730                return Err(bad_param());
731            }
732            if kind == TCKind::Except {
733                // An exception starts with its repository id, as in a
734                // reply.
735                out.write_string(tc.id().unwrap_or_default())?;
736            }
737            for (i, item) in items.iter().enumerate() {
738                write(out, &member(&tc, i as u32), item)?;
739            }
740        }
741        (TCKind::Union, Value::Union { disc, member: m }) => {
742            let disc_tc = tc.discriminator_type().map_err(|_| bad_param())?;
743            let selected = tc.union_member_for(disc).map_err(|_| bad_param())?;
744            if disc.label_key().is_none() || selected != m.as_ref().map(|(i, _)| *i) {
745                return Err(bad_param());
746            }
747            write(out, &disc_tc, disc)?;
748            if let Some((i, v)) = m {
749                write(out, &member(&tc, *i), v)?;
750            }
751        }
752        (TCKind::Enum, Value::Enum(v)) => {
753            if *v >= tc.member_count().unwrap_or(0) {
754                return Err(bad_param());
755            }
756            v.encode(out)?;
757        }
758        (TCKind::Fixed, Value::Fixed { digits, negative }) => {
759            if digits.len() != tc.fixed_digits().unwrap_or(0) as usize {
760                return Err(bad_param());
761            }
762            out.write_fixed(digits, *negative)?;
763        }
764        (TCKind::Objref | TCKind::Component | TCKind::Home, Value::Objref(obj)) => {
765            out.write_object(obj.as_ref())?
766        }
767        (TCKind::TypeCode, Value::TypeCode(t)) => out.write_typecode(t)?,
768        (TCKind::Any, Value::Any(a)) => out.write_any(a)?,
769        (TCKind::Value | TCKind::ValueBox | TCKind::Event, Value::Valuetype(v)) => {
770            write_valuetype(out, &tc, v.as_ref())?
771        }
772        // An abstract interface is a union on a boolean: TRUE and an object
773        // reference, or FALSE and a value (CORBA 3.4 part 2, 9.3.7).
774        (TCKind::AbstractInterface, Value::Objref(obj)) => {
775            out.write_bool(true);
776            out.write_object(obj.as_ref())?
777        }
778        (TCKind::AbstractInterface, Value::Valuetype(v)) => {
779            out.write_bool(false);
780            write_valuetype(out, value_base_tc(), v.as_ref())?
781        }
782        (TCKind::Native, _) => {
783            return Err(sys(SystemExceptionKind::NO_IMPLEMENT, CompletionStatus::No));
784        }
785        _ => return Err(bad_param()),
786    }
787    Ok(())
788}
789
790fn write_valuetype(
791    out: &mut OutStream<'_>,
792    expected: &TypeCode,
793    v: Option<&ValueRef>,
794) -> Result<(), SystemException> {
795    let Some(v) = v else {
796        out.write_null_value();
797        return Ok(());
798    };
799    let tc = v.typecode().unaliased();
800    if !matches!(tc.kind(), TCKind::Value | TCKind::ValueBox | TCKind::Event)
801        || !is_assignable(&tc, expected)
802    {
803        return Err(bad_param());
804    }
805    match tc.type_modifier() {
806        Ok(VM_CUSTOM) => return write_custom(out, &tc, v),
807        Ok(VM_ABSTRACT) => return Err(bad_param()),
808        _ => {}
809    }
810    let ids = sent_ids(&tc);
811    let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
812    // A value of a truncatable type is chunked, so that a receiver can
813    // skip what it does not know.
814    if !out.begin_value(v.key(), &ids, ids.len() > 1)? {
815        return Ok(());
816    }
817    let types = state_types(&tc);
818    let members = v.members();
819    if members.len() != types.len() {
820        return Err(bad_param());
821    }
822    for (t, m) in types.iter().zip(&members) {
823        write(out, t, m)?;
824    }
825    out.end_value()?;
826    Ok(())
827}
828
829/// Writes a custom value: always chunked (CORBA 3.4 part 2, 9.3.4.6), with
830/// its repository id, and the items of its state with their types.
831fn write_custom(
832    out: &mut OutStream<'_>,
833    tc: &TypeCode,
834    v: &ValueRef,
835) -> Result<(), SystemException> {
836    if !out.begin_value(v.key(), &[tc.id().unwrap_or_default()], true)? {
837        return Ok(());
838    }
839    for item in v.members() {
840        let Value::Any(item) = item else {
841            return Err(bad_param());
842        };
843        write(out, item.typecode(), item.value())?;
844    }
845    out.end_value()?;
846    Ok(())
847}
848
849fn member(tc: &TypeCode, i: u32) -> TypeCode {
850    tc.member_type(i)
851        .expect("index checked against the TypeCode")
852}
853
854fn write_char(out: &mut OutStream<'_>, c: char) -> Result<(), SystemException> {
855    let bytes = out.code_sets().encode_string(c.encode_utf8(&mut [0; 4]))?;
856    match bytes[..] {
857        [b] => {
858            out.write_char(b);
859            Ok(())
860        }
861        _ => Err(sys(
862            SystemExceptionKind::DATA_CONVERSION,
863            CompletionStatus::No,
864        )),
865    }
866}
867
868fn check_bound(len: usize, bound: u32) -> Result<(), SystemException> {
869    if bound != 0 && len > bound as usize {
870        return Err(bad_param());
871    }
872    Ok(())
873}
874
875fn write_items(
876    out: &mut OutStream<'_>,
877    tc: &TypeCode,
878    value: &Value,
879) -> Result<(), SystemException> {
880    let is_seq = tc.kind() == TCKind::Sequence;
881    let n = tc.length().unwrap_or(0);
882    let check = |len: usize| {
883        if is_seq {
884            check_bound(len, n)
885        } else if len != n as usize {
886            Err(bad_param())
887        } else {
888            Ok(())
889        }
890    };
891    let content = tc.content_type().map_err(|_| bad_param())?;
892    let content_kind = content.unaliased().kind();
893    match (content_kind, value) {
894        (TCKind::Octet, Value::Octets(b)) => {
895            check(b.len())?;
896            if is_seq {
897                out.write_octet_seq_shared(b)?;
898            } else {
899                out.write_octets(b);
900            }
901        }
902        (TCKind::Char, Value::Chars(s)) => {
903            check(s.chars().count())?;
904            let bytes = out.code_sets().encode_string(s)?;
905            if bytes.len() != s.chars().count() {
906                return Err(sys(
907                    SystemExceptionKind::DATA_CONVERSION,
908                    CompletionStatus::No,
909                ));
910            }
911            if is_seq {
912                out.write_len(bytes.len())?;
913            }
914            out.write_octets(&bytes);
915        }
916        (_, Value::List(items)) => {
917            check(items.len())?;
918            if is_seq {
919                out.write_len(items.len())?;
920            }
921            for item in items {
922                write(out, &content, item)?;
923            }
924        }
925        _ => return Err(bad_param()),
926    }
927    Ok(())
928}
929
930// --- reading ---------------------------------------------------------------------
931
932/// Reads a value of type `tc`. Errors are `MARSHAL` with the completion
933/// status of the stream.
934pub(crate) fn read(input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
935    Reader { depth: 0 }.read(input, tc)
936}
937
938struct Reader {
939    depth: usize,
940}
941
942impl Reader {
943    fn read(&mut self, input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
944        self.depth += 1;
945        if self.depth > MAX_DEPTH {
946            return Err(input.marshal_error());
947        }
948        let value = self.read_value(input, tc);
949        self.depth -= 1;
950        value
951    }
952
953    fn read_value(
954        &mut self,
955        input: &mut InStream<'_>,
956        tc: &TypeCode,
957    ) -> Result<Value, SystemException> {
958        let tc = tc.unaliased();
959        Ok(match tc.kind() {
960            TCKind::Null | TCKind::Void => Value::Void,
961            TCKind::Short => Value::Short(input.read()?),
962            TCKind::Long => Value::Long(input.read()?),
963            TCKind::UShort => Value::UShort(input.read()?),
964            TCKind::ULong => Value::ULong(input.read()?),
965            TCKind::LongLong => Value::LongLong(input.read()?),
966            TCKind::ULongLong => Value::ULongLong(input.read()?),
967            TCKind::Float => Value::Float(input.read()?),
968            TCKind::Double => Value::Double(input.read()?),
969            TCKind::LongDouble => Value::LongDouble(input.read()?),
970            TCKind::Boolean => Value::Bool(input.read()?),
971            TCKind::Octet => Value::Octet(input.read()?),
972            TCKind::Char => Value::Char(input.read_char_value()?),
973            TCKind::WChar => Value::WChar(input.read_wchar()?),
974            TCKind::String => {
975                let s = input.read_string()?;
976                self.check_bound(input, s.chars().count(), &tc)?;
977                Value::String(s)
978            }
979            TCKind::WString => {
980                let s = input.read_wstring()?;
981                self.check_bound(input, s.chars().count(), &tc)?;
982                Value::String(s)
983            }
984            TCKind::Principal => Value::Octets(input.read::<Vec<u8>>()?.into()),
985            TCKind::Sequence => {
986                let content = tc.content_type().map_err(|_| input.marshal_error())?;
987                let min = min_size(&content, 0).max(1);
988                let len = input.read_len(min).map_err(|_| input.marshal_error())?;
989                self.check_bound(input, len, &tc)?;
990                self.read_items(input, &content, len)?
991            }
992            TCKind::Array => {
993                let content = tc.content_type().map_err(|_| input.marshal_error())?;
994                let len = tc.length().unwrap_or(0) as usize;
995                self.read_items(input, &content, len)?
996            }
997            TCKind::Struct | TCKind::Except => {
998                if tc.kind() == TCKind::Except {
999                    input.read_string()?;
1000                }
1001                let count = tc.member_count().unwrap_or(0);
1002                let mut items = Vec::with_capacity(count as usize);
1003                for i in 0..count {
1004                    items.push(self.read(input, &member(&tc, i))?);
1005                }
1006                Value::List(items)
1007            }
1008            TCKind::Union => {
1009                let disc_tc = tc.discriminator_type().map_err(|_| input.marshal_error())?;
1010                let disc = self.read(input, &disc_tc)?;
1011                let selected = tc
1012                    .union_member_for(&disc)
1013                    .map_err(|_| input.marshal_error())?;
1014                let m = match selected {
1015                    Some(i) => Some((i, Box::new(self.read(input, &member(&tc, i))?))),
1016                    None => None,
1017                };
1018                Value::Union {
1019                    disc: Box::new(disc),
1020                    member: m,
1021                }
1022            }
1023            TCKind::Enum => {
1024                let v: u32 = input.read()?;
1025                if v >= tc.member_count().unwrap_or(0) {
1026                    return Err(input.marshal_error());
1027                }
1028                Value::Enum(v)
1029            }
1030            TCKind::Fixed => {
1031                let (digits, negative) =
1032                    input.read_fixed(tc.fixed_digits().unwrap_or(0) as usize)?;
1033                Value::Fixed { digits, negative }
1034            }
1035            TCKind::Objref | TCKind::Component | TCKind::Home => {
1036                Value::Objref(input.read_object()?)
1037            }
1038            TCKind::TypeCode => Value::TypeCode(input.read_typecode()?),
1039            TCKind::Any => {
1040                let inner = input.read_typecode()?;
1041                let v = self.read(input, &inner)?;
1042                Value::Any(Box::new(Any::new(inner, v)))
1043            }
1044            TCKind::Value | TCKind::ValueBox | TCKind::Event => {
1045                Value::Valuetype(self.read_valuetype(input, &tc)?)
1046            }
1047            TCKind::AbstractInterface => {
1048                if input.read_bool()? {
1049                    Value::Objref(input.read_object()?)
1050                } else {
1051                    Value::Valuetype(self.read_valuetype(input, value_base_tc())?)
1052                }
1053            }
1054            TCKind::LocalInterface => return Err(input.marshal_error()),
1055            _ => {
1056                return Err(sys(SystemExceptionKind::NO_IMPLEMENT, input.completed));
1057            }
1058        })
1059    }
1060
1061    fn read_valuetype(
1062        &mut self,
1063        input: &mut InStream<'_>,
1064        expected: &TypeCode,
1065    ) -> Result<Option<ValueRef>, SystemException> {
1066        let header = input
1067            .read_value_header()
1068            .map_err(|_| input.marshal_error())?;
1069        let (slot, ids) = match header {
1070            ValueHeader::Null => return Ok(None),
1071            ValueHeader::Indirection(slot) => {
1072                return match input.values.get(slot) {
1073                    Some(Some(v)) => Ok(Some(v.clone())),
1074                    _ => Err(input.marshal_error()),
1075                };
1076            }
1077            ValueHeader::Value { slot, ids, .. } => (slot, ids),
1078        };
1079        let tc = known_type(expected, &ids).ok_or_else(|| input.marshal_error())?;
1080        let custom = match tc.type_modifier() {
1081            Ok(VM_CUSTOM) => {
1082                let id = tc.id().unwrap_or_default();
1083                Some(custom_reader(id).ok_or_else(|| input.marshal_error())?)
1084            }
1085            Ok(VM_ABSTRACT) => return Err(input.marshal_error()),
1086            _ => None,
1087        };
1088        let v = ValueRef::new(tc.clone(), Vec::new());
1089        if input.values.len() <= slot {
1090            input.values.resize(slot + 1, None);
1091        }
1092        input.values[slot] = Some(v.clone());
1093        if let Some(reader) = custom {
1094            reader(&v, input)?;
1095            input.end_value().map_err(|_| input.marshal_error())?;
1096            return Ok(Some(v));
1097        }
1098        let mut members = Vec::new();
1099        for t in state_types(&tc) {
1100            members.push(self.read(input, &t)?);
1101        }
1102        v.set_members(members);
1103        input.end_value().map_err(|_| input.marshal_error())?;
1104        Ok(Some(v))
1105    }
1106
1107    fn check_bound(
1108        &self,
1109        input: &InStream<'_>,
1110        len: usize,
1111        tc: &TypeCode,
1112    ) -> Result<(), SystemException> {
1113        let bound = tc.length().unwrap_or(0);
1114        if bound != 0 && len > bound as usize {
1115            return Err(input.marshal_error());
1116        }
1117        Ok(())
1118    }
1119
1120    fn read_items(
1121        &mut self,
1122        input: &mut InStream<'_>,
1123        content: &TypeCode,
1124        len: usize,
1125    ) -> Result<Value, SystemException> {
1126        Ok(match content.unaliased().kind() {
1127            TCKind::Octet => Value::Octets(
1128                input
1129                    .read_octets_shared(len)
1130                    .map_err(|_| input.marshal_error())?,
1131            ),
1132            TCKind::Char => {
1133                let bytes = input.read_octets(len).map_err(|_| input.marshal_error())?;
1134                let completed = input.completed;
1135                Value::Chars(input.code_sets().decode_string(bytes).map_err(|mut e| {
1136                    e.completed = completed;
1137                    e
1138                })?)
1139            }
1140            _ => {
1141                let mut items = Vec::with_capacity(len.min(4096));
1142                for _ in 0..len {
1143                    items.push(self.read(input, content)?);
1144                }
1145                Value::List(items)
1146            }
1147        })
1148    }
1149}
1150
1151/// The type to read a value sent with the repository ids `ids` as: the
1152/// first of them that is `expected` or a registered valuetype, or
1153/// `expected` when no id was sent (but not `ValueBase`, which has no
1154/// state of its own).
1155fn known_type(expected: &TypeCode, ids: &[String]) -> Option<TypeCode> {
1156    let expected_id = expected.id().unwrap_or_default();
1157    if ids.is_empty() {
1158        return (expected_id != VALUE_BASE_ID).then(|| expected.clone());
1159    }
1160    ids.iter().find_map(|id| {
1161        if id == expected_id {
1162            Some(expected.clone())
1163        } else {
1164            find_value_type(id).filter(|t| is_assignable(t, expected))
1165        }
1166    })
1167}
1168
1169/// The smallest size of a value on the wire, to check sequence lengths
1170/// before allocating.
1171fn min_size(tc: &TypeCode, depth: usize) -> usize {
1172    if depth > 8 {
1173        return 0;
1174    }
1175    let tc = tc.unaliased();
1176    match tc.kind() {
1177        TCKind::Boolean
1178        | TCKind::Char
1179        | TCKind::Octet
1180        | TCKind::WChar
1181        | TCKind::AbstractInterface => 1,
1182        TCKind::Short | TCKind::UShort => 2,
1183        TCKind::Long
1184        | TCKind::ULong
1185        | TCKind::Float
1186        | TCKind::Enum
1187        | TCKind::String
1188        | TCKind::WString
1189        | TCKind::Sequence
1190        | TCKind::Objref
1191        | TCKind::TypeCode
1192        | TCKind::Any
1193        | TCKind::Principal
1194        | TCKind::Value
1195        | TCKind::ValueBox
1196        | TCKind::Event => 4,
1197        TCKind::LongLong | TCKind::ULongLong | TCKind::Double => 8,
1198        TCKind::LongDouble => 16,
1199        TCKind::Fixed => (tc.fixed_digits().unwrap_or(0) as usize + 2) / 2,
1200        TCKind::Array => {
1201            let content = tc.content_type().map(|c| min_size(&c, depth + 1));
1202            content.unwrap_or(0) * tc.length().unwrap_or(0) as usize
1203        }
1204        TCKind::Struct | TCKind::Except => (0..tc.member_count().unwrap_or(0))
1205            .map(|i| min_size(&member(&tc, i), depth + 1))
1206            .fold(0usize, usize::saturating_add),
1207        _ => 0,
1208    }
1209}