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/// A [`ValueRef`] that does not keep the instance alive (see
285/// [`ValueRef::downgrade`]).
286#[derive(Clone)]
287pub struct WeakValueRef(std::sync::Weak<ValueObj>);
288
289impl WeakValueRef {
290    /// The instance, if it is still alive.
291    pub fn upgrade(&self) -> Option<ValueRef> {
292        self.0.upgrade().map(ValueRef)
293    }
294
295    /// Whether the instance has been dropped (or is being dropped).
296    pub fn is_dead(&self) -> bool {
297        self.0.strong_count() == 0
298    }
299}
300
301impl std::fmt::Debug for WeakValueRef {
302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303        f.write_str("WeakValueRef")
304    }
305}
306
307/// An instance of a valuetype or a value box: its type and its state.
308///
309/// Clones share the instance, as references do in the language
310/// mappings: an instance written twice in a message is sent once, then as
311/// an indirection to it, and is read back as one instance. Instances may
312/// refer to each other in cycles; [`Value::break_cycles`] frees them.
313#[derive(Clone)]
314pub struct ValueRef(Arc<ValueObj>);
315
316struct ValueObj {
317    tc: TypeCode,
318    members: Mutex<Vec<Value>>,
319    native: Mutex<Option<Native>>,
320}
321
322/// An object of a language binding that stands for a [`ValueRef`].
323pub type Native = Arc<dyn std::any::Any + Send + Sync>;
324
325impl ValueRef {
326    /// An instance of the valuetype `tc` (the most derived type) with the
327    /// values of its state members: those of its base types first, then
328    /// its own, in the order of the TypeCodes. An instance of a value box
329    /// has the boxed value as its one member.
330    pub fn new(tc: TypeCode, members: Vec<Value>) -> ValueRef {
331        ValueRef(Arc::new(ValueObj {
332            tc,
333            members: Mutex::new(members),
334            native: Mutex::new(None),
335        }))
336    }
337
338    /// The object of a language binding set with [`ValueRef::set_native`].
339    pub fn native(&self) -> Option<Native> {
340        self.0
341            .native
342            .lock()
343            .unwrap_or_else(|e| e.into_inner())
344            .clone()
345    }
346
347    /// Sets (or, with `None`, removes) the object of a language binding
348    /// that stands for this instance: a custom reader
349    /// ([`register_custom_reader`]) sets the instance it made, so that
350    /// the binding finds it again when it converts the value.
351    pub fn set_native(&self, native: Option<Native>) {
352        *self.0.native.lock().unwrap_or_else(|e| e.into_inner()) = native;
353    }
354
355    /// The type of the instance.
356    pub fn typecode(&self) -> &TypeCode {
357        &self.0.tc
358    }
359
360    /// The repository id of the type of the instance.
361    pub fn id(&self) -> &str {
362        self.0.tc.id().unwrap_or_default()
363    }
364
365    /// The values of the state members.
366    pub fn members(&self) -> Vec<Value> {
367        self.lock().clone()
368    }
369
370    /// Replaces the values of the state members.
371    pub fn set_members(&self, members: Vec<Value>) {
372        *self.lock() = members;
373    }
374
375    /// Takes the values of the state members, leaving none.
376    pub fn take_members(&self) -> Vec<Value> {
377        std::mem::take(&mut *self.lock())
378    }
379
380    /// Whether both are the same instance.
381    pub fn ptr_eq(&self, other: &ValueRef) -> bool {
382        Arc::ptr_eq(&self.0, &other.0)
383    }
384
385    /// A number that identifies the instance while it is alive.
386    pub fn key(&self) -> u64 {
387        Arc::as_ptr(&self.0) as usize as u64
388    }
389
390    /// A reference that does not keep the instance alive.
391    pub fn downgrade(&self) -> WeakValueRef {
392        WeakValueRef(Arc::downgrade(&self.0))
393    }
394
395    fn lock(&self) -> MutexGuard<'_, Vec<Value>> {
396        self.0.members.lock().unwrap_or_else(|e| e.into_inner())
397    }
398
399    /// Whether both have the same type and equal state, the same instance
400    /// being equal to itself however it is reached (for cycles).
401    fn same_state(&self, other: &ValueRef) -> bool {
402        thread_local! {
403            static COMPARING: std::cell::RefCell<Vec<(u64, u64)>> =
404                const { std::cell::RefCell::new(Vec::new()) };
405        }
406        if self.ptr_eq(other) {
407            return true;
408        }
409        if !self.typecode().equal(other.typecode()) {
410            return false;
411        }
412        let pair = (self.key(), other.key());
413        if COMPARING.with(|c| c.borrow().contains(&pair)) {
414            return true;
415        }
416        COMPARING.with(|c| c.borrow_mut().push(pair));
417        // Copies, so that no lock is held while comparing nested values.
418        let equal = self.members() == other.members();
419        COMPARING.with(|c| c.borrow_mut().retain(|p| *p != pair));
420        equal
421    }
422}
423
424impl fmt::Debug for ValueRef {
425    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        // Not the state, which may refer back to this instance.
427        write!(f, "ValueRef({} @ {:#x})", self.id(), self.key())
428    }
429}
430
431/// The valuetypes known to the readers, by repository id.
432static VALUE_TYPES: RwLock<BTreeMap<String, TypeCode>> = RwLock::new(BTreeMap::new());
433
434/// Makes the valuetype `tc` known to every ORB of the process, so that a
435/// value of it can be read where a base type of it is expected.
436///
437/// A value whose type is neither the expected type nor registered is read
438/// as the first of its truncatable base types that is, and is `MARSHAL`
439/// if there is none.
440pub fn register_value_type(tc: &TypeCode) {
441    let tc = tc.unaliased();
442    if let Ok(id) = tc.id() {
443        let id = id.to_owned();
444        VALUE_TYPES
445            .write()
446            .unwrap_or_else(|e| e.into_inner())
447            .insert(id, tc);
448    }
449}
450
451/// The valuetype registered with [`register_value_type`] for `id`.
452pub fn lookup_value_type(id: &str) -> Option<TypeCode> {
453    VALUE_TYPES
454        .read()
455        .unwrap_or_else(|e| e.into_inner())
456        .get(id)
457        .cloned()
458}
459
460/// Finds the valuetype of a repository id that is not registered: a
461/// binding whose valuetypes are only known when asked for (Java, whose
462/// classes are loaded by name) sets one with [`set_value_type_resolver`].
463pub type ValueTypeResolver = dyn Fn(&str) -> Option<TypeCode> + Send + Sync;
464
465static RESOLVER: RwLock<Option<Arc<ValueTypeResolver>>> = RwLock::new(None);
466
467/// Sets (or, with `None`, removes) the resolver asked for repository ids
468/// that are not registered; what it finds is registered.
469pub fn set_value_type_resolver(resolver: Option<Arc<ValueTypeResolver>>) {
470    *RESOLVER.write().unwrap_or_else(|e| e.into_inner()) = resolver;
471}
472
473/// The registered valuetype of `id`, else the one the resolver finds.
474fn find_value_type(id: &str) -> Option<TypeCode> {
475    if let Some(tc) = lookup_value_type(id) {
476        return Some(tc);
477    }
478    let resolver = RESOLVER.read().unwrap_or_else(|e| e.into_inner()).clone()?;
479    let tc = resolver(id)?;
480    if tc.id().ok() != Some(id) {
481        return None;
482    }
483    register_value_type(&tc);
484    lookup_value_type(id)
485}
486
487/// Forgets the valuetype registered for `id`.
488pub fn unregister_value_type(id: &str) {
489    VALUE_TYPES
490        .write()
491        .unwrap_or_else(|e| e.into_inner())
492        .remove(id);
493}
494
495/// Reads the state of a custom valuetype from `input`, into `value`, a new
496/// instance of the type: what the value's marshaling code wrote, read with
497/// [`InStream::read_value`] item by item. The reader sets the state of
498/// `value` to the items read (each a `Value::Any`) so that it can be
499/// written again, and may set an object of its own with
500/// [`ValueRef::set_native`].
501pub type CustomReader =
502    dyn Fn(&ValueRef, &mut InStream<'_>) -> Result<(), SystemException> + Send + Sync;
503
504/// The custom readers, by repository id.
505static CUSTOM_READERS: RwLock<BTreeMap<String, Arc<CustomReader>>> = RwLock::new(BTreeMap::new());
506
507/// Sets the reader of the custom valuetype `id` (`VM_CUSTOM`), the
508/// unmarshaling half of `CORBA::CustomMarshal`. A value of a custom type
509/// without a reader is read as `MARSHAL`, as when no value factory is
510/// registered.
511///
512/// A custom value is written from its state: the items in it, each a
513/// `Value::Any`, are written one after the other with their types, the
514/// way its marshaling code writes them (`CORBA::DataOutputStream`).
515pub fn register_custom_reader(id: &str, reader: Arc<CustomReader>) {
516    CUSTOM_READERS
517        .write()
518        .unwrap_or_else(|e| e.into_inner())
519        .insert(id.to_owned(), reader);
520}
521
522/// Forgets the reader of the custom valuetype `id`.
523pub fn unregister_custom_reader(id: &str) {
524    CUSTOM_READERS
525        .write()
526        .unwrap_or_else(|e| e.into_inner())
527        .remove(id);
528}
529
530fn custom_reader(id: &str) -> Option<Arc<CustomReader>> {
531    CUSTOM_READERS
532        .read()
533        .unwrap_or_else(|e| e.into_inner())
534        .get(id)
535        .cloned()
536}
537
538/// The repository id of `ValueBase`, which every valuetype may stand for.
539pub(crate) const VALUE_BASE_ID: &str = "IDL:omg.org/CORBA/ValueBase:1.0";
540
541/// The TypeCode of `ValueBase`: any value of a known type.
542pub(crate) fn value_base_tc() -> &'static TypeCode {
543    static TC: std::sync::OnceLock<TypeCode> = std::sync::OnceLock::new();
544    TC.get_or_init(|| {
545        TypeCode::value_tc(
546            TCKind::Value,
547            VALUE_BASE_ID,
548            "ValueBase",
549            0,
550            None,
551            &[] as &[(&str, TypeCode, i16)],
552        )
553        .expect("a valid TypeCode")
554    })
555}
556
557const VM_CUSTOM: i16 = 1;
558const VM_ABSTRACT: i16 = 2;
559const VM_TRUNCATABLE: i16 = 3;
560
561/// The types of the state members of a valuetype, those of its base
562/// types first; the boxed type of a value box.
563pub(crate) fn state_types(tc: &TypeCode) -> Vec<TypeCode> {
564    if tc.kind() == TCKind::ValueBox {
565        return tc.content_type().into_iter().collect();
566    }
567    let mut chain = vec![tc.clone()];
568    while let Some(Some(base)) = chain.last().map(|t| t.concrete_base_type().ok().flatten()) {
569        if chain.len() > MAX_DEPTH {
570            break;
571        }
572        chain.push(base.unaliased());
573    }
574    chain
575        .iter()
576        .rev()
577        .flat_map(|t| (0..t.member_count().unwrap_or(0)).map(move |i| member(t, i)))
578        .collect()
579}
580
581/// Whether a value of type `actual` may stand where `expected` is.
582fn is_assignable(actual: &TypeCode, expected: &TypeCode) -> bool {
583    let id = expected.id().unwrap_or_default();
584    if actual.kind() == TCKind::ValueBox || expected.kind() == TCKind::ValueBox {
585        return actual.kind() == expected.kind() && actual.id().unwrap_or_default() == id;
586    }
587    // Abstract valuetypes are not in the base chain of a TypeCode.
588    if expected.type_modifier() == Ok(VM_ABSTRACT) || id == VALUE_BASE_ID {
589        return true;
590    }
591    let mut t = Some(actual.clone());
592    let mut n = 0;
593    while let Some(tc) = t {
594        if tc.id().unwrap_or_default() == id {
595            return true;
596        }
597        n += 1;
598        if n > MAX_DEPTH {
599            break;
600        }
601        t = tc.concrete_base_type().ok().flatten();
602    }
603    false
604}
605
606/// The repository ids a value of type `tc` is sent with: its own, then
607/// those of the base types it is truncatable to.
608fn sent_ids(tc: &TypeCode) -> Vec<String> {
609    let mut ids = vec![tc.id().unwrap_or_default().to_owned()];
610    let mut t = tc.clone();
611    while t.type_modifier() == Ok(VM_TRUNCATABLE) && ids.len() <= MAX_DEPTH {
612        match t.concrete_base_type() {
613            Ok(Some(base)) => {
614                ids.push(base.id().unwrap_or_default().to_owned());
615                t = base;
616            }
617            _ => break,
618        }
619    }
620    ids
621}
622
623/// A value with its type (`CORBA::Any`). The default is an empty Any, of
624/// type `null`.
625///
626/// `Any::new` does not check that the value fits the type; writing an Any
627/// that does not fails with `BAD_PARAM`.
628#[derive(Debug, Clone, PartialEq)]
629pub struct Any {
630    tc: TypeCode,
631    value: Value,
632}
633
634impl Default for Any {
635    fn default() -> Any {
636        Any::new(TypeCode::null(), Value::Void)
637    }
638}
639
640impl Any {
641    /// An Any of type `tc` holding `value`.
642    pub fn new(tc: TypeCode, value: Value) -> Any {
643        Any { tc, value }
644    }
645
646    /// The type of the value.
647    pub fn typecode(&self) -> &TypeCode {
648        &self.tc
649    }
650
651    /// The value.
652    pub fn value(&self) -> &Value {
653        &self.value
654    }
655
656    /// The type and the value.
657    pub fn into_parts(self) -> (TypeCode, Value) {
658        (self.tc, self.value)
659    }
660}
661
662macro_rules! any_from {
663    ($($ty:ty => $kind:ident, $variant:ident;)*) => {
664        $(
665            impl From<$ty> for Any {
666                fn from(v: $ty) -> Any {
667                    Any::new(TypeCode::simple(TCKind::$kind).expect("simple kind"), Value::$variant(v))
668                }
669            }
670        )*
671    };
672}
673
674any_from! {
675    bool => Boolean, Bool;
676    u8 => Octet, Octet;
677    i16 => Short, Short;
678    u16 => UShort, UShort;
679    i32 => Long, Long;
680    u32 => ULong, ULong;
681    i64 => LongLong, LongLong;
682    u64 => ULongLong, ULongLong;
683    f32 => Float, Float;
684    f64 => Double, Double;
685    rustorb_cdr::LongDouble => LongDouble, LongDouble;
686    char => Char, Char;
687}
688
689impl From<&str> for Any {
690    fn from(v: &str) -> Any {
691        Any::new(TypeCode::string(0), Value::String(v.to_owned()))
692    }
693}
694
695impl From<String> for Any {
696    fn from(v: String) -> Any {
697        Any::new(TypeCode::string(0), Value::String(v))
698    }
699}
700
701impl From<TypeCode> for Any {
702    fn from(v: TypeCode) -> Any {
703        Any::new(
704            TypeCode::simple(TCKind::TypeCode).expect("simple kind"),
705            Value::TypeCode(v),
706        )
707    }
708}
709
710fn sys(kind: SystemExceptionKind, completed: CompletionStatus) -> SystemException {
711    SystemException::new(kind, 0, completed)
712}
713
714fn bad_param() -> SystemException {
715    sys(SystemExceptionKind::BAD_PARAM, CompletionStatus::No)
716}
717
718// --- writing ---------------------------------------------------------------------
719
720/// Writes `value` of type `tc`. A value that does not fit the type is
721/// `BAD_PARAM`, a character the code set cannot represent
722/// `DATA_CONVERSION`.
723pub(crate) fn write(
724    out: &mut OutStream<'_>,
725    tc: &TypeCode,
726    value: &Value,
727) -> Result<(), SystemException> {
728    let tc = tc.unaliased();
729    let kind = tc.kind();
730    match (kind, value) {
731        (TCKind::Null | TCKind::Void, _) => {}
732        (TCKind::Short, Value::Short(v)) => v.encode(out)?,
733        (TCKind::Long, Value::Long(v)) => v.encode(out)?,
734        (TCKind::UShort, Value::UShort(v)) => v.encode(out)?,
735        (TCKind::ULong, Value::ULong(v)) => v.encode(out)?,
736        (TCKind::LongLong, Value::LongLong(v)) => v.encode(out)?,
737        (TCKind::ULongLong, Value::ULongLong(v)) => v.encode(out)?,
738        (TCKind::Float, Value::Float(v)) => v.encode(out)?,
739        (TCKind::Double, Value::Double(v)) => v.encode(out)?,
740        (TCKind::LongDouble, Value::LongDouble(v)) => v.encode(out)?,
741        (TCKind::Boolean, Value::Bool(v)) => v.encode(out)?,
742        (TCKind::Octet, Value::Octet(v)) => out.write_octet(*v),
743        (TCKind::Char, Value::Char(c)) => write_char(out, *c)?,
744        (TCKind::WChar, Value::WChar(c)) => out.write_wchar(*c)?,
745        (TCKind::String, Value::String(s)) => {
746            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
747            out.write_string(s)?;
748        }
749        (TCKind::WString, Value::String(s)) => {
750            check_bound(s.chars().count(), tc.length().unwrap_or(0))?;
751            out.write_wstring(s)?;
752        }
753        (TCKind::Principal, Value::Octets(b)) => out.write_octet_seq(b)?,
754        (TCKind::Sequence | TCKind::Array, _) => write_items(out, &tc, value)?,
755        (TCKind::Struct | TCKind::Except, Value::List(items)) => {
756            let count = tc.member_count().unwrap_or(0);
757            if items.len() != count as usize {
758                return Err(bad_param());
759            }
760            if kind == TCKind::Except {
761                // An exception starts with its repository id, as in a
762                // reply.
763                out.write_string(tc.id().unwrap_or_default())?;
764            }
765            for (i, item) in items.iter().enumerate() {
766                write(out, &member(&tc, i as u32), item)?;
767            }
768        }
769        (TCKind::Union, Value::Union { disc, member: m }) => {
770            let disc_tc = tc.discriminator_type().map_err(|_| bad_param())?;
771            let selected = tc.union_member_for(disc).map_err(|_| bad_param())?;
772            if disc.label_key().is_none() || selected != m.as_ref().map(|(i, _)| *i) {
773                return Err(bad_param());
774            }
775            write(out, &disc_tc, disc)?;
776            if let Some((i, v)) = m {
777                write(out, &member(&tc, *i), v)?;
778            }
779        }
780        (TCKind::Enum, Value::Enum(v)) => {
781            if *v >= tc.member_count().unwrap_or(0) {
782                return Err(bad_param());
783            }
784            v.encode(out)?;
785        }
786        (TCKind::Fixed, Value::Fixed { digits, negative }) => {
787            if digits.len() != tc.fixed_digits().unwrap_or(0) as usize {
788                return Err(bad_param());
789            }
790            out.write_fixed(digits, *negative)?;
791        }
792        (TCKind::Objref | TCKind::Component | TCKind::Home, Value::Objref(obj)) => {
793            out.write_object(obj.as_ref())?
794        }
795        (TCKind::TypeCode, Value::TypeCode(t)) => out.write_typecode(t)?,
796        (TCKind::Any, Value::Any(a)) => out.write_any(a)?,
797        (TCKind::Value | TCKind::ValueBox | TCKind::Event, Value::Valuetype(v)) => {
798            write_valuetype(out, &tc, v.as_ref())?
799        }
800        // An abstract interface is a union on a boolean: TRUE and an object
801        // reference, or FALSE and a value (CORBA 3.4 part 2, 9.3.7).
802        (TCKind::AbstractInterface, Value::Objref(obj)) => {
803            out.write_bool(true);
804            out.write_object(obj.as_ref())?
805        }
806        (TCKind::AbstractInterface, Value::Valuetype(v)) => {
807            out.write_bool(false);
808            write_valuetype(out, value_base_tc(), v.as_ref())?
809        }
810        (TCKind::Native, _) => {
811            return Err(sys(SystemExceptionKind::NO_IMPLEMENT, CompletionStatus::No));
812        }
813        _ => return Err(bad_param()),
814    }
815    Ok(())
816}
817
818fn write_valuetype(
819    out: &mut OutStream<'_>,
820    expected: &TypeCode,
821    v: Option<&ValueRef>,
822) -> Result<(), SystemException> {
823    let Some(v) = v else {
824        out.write_null_value();
825        return Ok(());
826    };
827    let tc = v.typecode().unaliased();
828    if !matches!(tc.kind(), TCKind::Value | TCKind::ValueBox | TCKind::Event)
829        || !is_assignable(&tc, expected)
830    {
831        return Err(bad_param());
832    }
833    match tc.type_modifier() {
834        Ok(VM_CUSTOM) => return write_custom(out, &tc, v),
835        Ok(VM_ABSTRACT) => return Err(bad_param()),
836        _ => {}
837    }
838    let ids = sent_ids(&tc);
839    let ids: Vec<&str> = ids.iter().map(String::as_str).collect();
840    // A value of a truncatable type is chunked, so that a receiver can
841    // skip what it does not know.
842    let chunked = ids.len() > 1 || out.values.as_ref().is_some_and(|l| l.chunked);
843    if !out.begin_value(v.key(), &ids, chunked)? {
844        return Ok(());
845    }
846    out.note_value(v);
847    let types = state_types(&tc);
848    let members = v.members();
849    if members.len() != types.len() {
850        return Err(bad_param());
851    }
852    for (t, m) in types.iter().zip(&members) {
853        write(out, t, m)?;
854    }
855    out.end_value()?;
856    Ok(())
857}
858
859/// Writes a custom value: always chunked (CORBA 3.4 part 2, 9.3.4.6), with
860/// its repository id, and the items of its state with their types.
861fn write_custom(
862    out: &mut OutStream<'_>,
863    tc: &TypeCode,
864    v: &ValueRef,
865) -> Result<(), SystemException> {
866    if !out.begin_value(v.key(), &[tc.id().unwrap_or_default()], true)? {
867        return Ok(());
868    }
869    out.note_value(v);
870    for item in v.members() {
871        let Value::Any(item) = item else {
872            return Err(bad_param());
873        };
874        write(out, item.typecode(), item.value())?;
875    }
876    out.end_value()?;
877    Ok(())
878}
879
880fn member(tc: &TypeCode, i: u32) -> TypeCode {
881    tc.member_type(i)
882        .expect("index checked against the TypeCode")
883}
884
885fn write_char(out: &mut OutStream<'_>, c: char) -> Result<(), SystemException> {
886    let bytes = out.code_sets().encode_string(c.encode_utf8(&mut [0; 4]))?;
887    match bytes[..] {
888        [b] => {
889            out.write_char(b);
890            Ok(())
891        }
892        _ => Err(sys(
893            SystemExceptionKind::DATA_CONVERSION,
894            CompletionStatus::No,
895        )),
896    }
897}
898
899fn check_bound(len: usize, bound: u32) -> Result<(), SystemException> {
900    if bound != 0 && len > bound as usize {
901        return Err(bad_param());
902    }
903    Ok(())
904}
905
906fn write_items(
907    out: &mut OutStream<'_>,
908    tc: &TypeCode,
909    value: &Value,
910) -> Result<(), SystemException> {
911    let is_seq = tc.kind() == TCKind::Sequence;
912    let n = tc.length().unwrap_or(0);
913    let check = |len: usize| {
914        if is_seq {
915            check_bound(len, n)
916        } else if len != n as usize {
917            Err(bad_param())
918        } else {
919            Ok(())
920        }
921    };
922    let content = tc.content_type().map_err(|_| bad_param())?;
923    let content_kind = content.unaliased().kind();
924    match (content_kind, value) {
925        (TCKind::Octet, Value::Octets(b)) => {
926            check(b.len())?;
927            if is_seq {
928                out.write_octet_seq_shared(b)?;
929            } else {
930                out.write_octets(b);
931            }
932        }
933        (TCKind::Char, Value::Chars(s)) => {
934            check(s.chars().count())?;
935            let bytes = out.code_sets().encode_string(s)?;
936            if bytes.len() != s.chars().count() {
937                return Err(sys(
938                    SystemExceptionKind::DATA_CONVERSION,
939                    CompletionStatus::No,
940                ));
941            }
942            if is_seq {
943                out.write_len(bytes.len())?;
944            }
945            out.write_octets(&bytes);
946        }
947        (_, Value::List(items)) => {
948            check(items.len())?;
949            if is_seq {
950                out.write_len(items.len())?;
951            }
952            for item in items {
953                write(out, &content, item)?;
954            }
955        }
956        _ => return Err(bad_param()),
957    }
958    Ok(())
959}
960
961// --- reading ---------------------------------------------------------------------
962
963/// Reads a value of type `tc`. Errors are `MARSHAL` with the completion
964/// status of the stream.
965pub(crate) fn read(input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
966    Reader { depth: 0 }.read(input, tc)
967}
968
969struct Reader {
970    depth: usize,
971}
972
973impl Reader {
974    fn read(&mut self, input: &mut InStream<'_>, tc: &TypeCode) -> Result<Value, SystemException> {
975        self.depth += 1;
976        if self.depth > MAX_DEPTH {
977            return Err(input.marshal_error());
978        }
979        let value = self.read_value(input, tc);
980        self.depth -= 1;
981        value
982    }
983
984    fn read_value(
985        &mut self,
986        input: &mut InStream<'_>,
987        tc: &TypeCode,
988    ) -> Result<Value, SystemException> {
989        let tc = tc.unaliased();
990        Ok(match tc.kind() {
991            TCKind::Null | TCKind::Void => Value::Void,
992            TCKind::Short => Value::Short(input.read()?),
993            TCKind::Long => Value::Long(input.read()?),
994            TCKind::UShort => Value::UShort(input.read()?),
995            TCKind::ULong => Value::ULong(input.read()?),
996            TCKind::LongLong => Value::LongLong(input.read()?),
997            TCKind::ULongLong => Value::ULongLong(input.read()?),
998            TCKind::Float => Value::Float(input.read()?),
999            TCKind::Double => Value::Double(input.read()?),
1000            TCKind::LongDouble => Value::LongDouble(input.read()?),
1001            TCKind::Boolean => Value::Bool(input.read()?),
1002            TCKind::Octet => Value::Octet(input.read()?),
1003            TCKind::Char => Value::Char(input.read_char_value()?),
1004            TCKind::WChar => Value::WChar(input.read_wchar()?),
1005            TCKind::String => {
1006                let s = input.read_string()?;
1007                self.check_bound(input, s.chars().count(), &tc)?;
1008                Value::String(s)
1009            }
1010            TCKind::WString => {
1011                let s = input.read_wstring()?;
1012                self.check_bound(input, s.chars().count(), &tc)?;
1013                Value::String(s)
1014            }
1015            TCKind::Principal => Value::Octets(input.read::<Vec<u8>>()?.into()),
1016            TCKind::Sequence => {
1017                let content = tc.content_type().map_err(|_| input.marshal_error())?;
1018                let min = min_size(&content, 0).max(1);
1019                let len = input.read_len(min).map_err(|_| input.marshal_error())?;
1020                self.check_bound(input, len, &tc)?;
1021                self.read_items(input, &content, len)?
1022            }
1023            TCKind::Array => {
1024                let content = tc.content_type().map_err(|_| input.marshal_error())?;
1025                let len = tc.length().unwrap_or(0) as usize;
1026                self.read_items(input, &content, len)?
1027            }
1028            TCKind::Struct | TCKind::Except => {
1029                if tc.kind() == TCKind::Except {
1030                    input.read_string()?;
1031                }
1032                let count = tc.member_count().unwrap_or(0);
1033                let mut items = Vec::with_capacity(count as usize);
1034                for i in 0..count {
1035                    items.push(self.read(input, &member(&tc, i))?);
1036                }
1037                Value::List(items)
1038            }
1039            TCKind::Union => {
1040                let disc_tc = tc.discriminator_type().map_err(|_| input.marshal_error())?;
1041                let disc = self.read(input, &disc_tc)?;
1042                let selected = tc
1043                    .union_member_for(&disc)
1044                    .map_err(|_| input.marshal_error())?;
1045                let m = match selected {
1046                    Some(i) => Some((i, Box::new(self.read(input, &member(&tc, i))?))),
1047                    None => None,
1048                };
1049                Value::Union {
1050                    disc: Box::new(disc),
1051                    member: m,
1052                }
1053            }
1054            TCKind::Enum => {
1055                let v: u32 = input.read()?;
1056                if v >= tc.member_count().unwrap_or(0) {
1057                    return Err(input.marshal_error());
1058                }
1059                Value::Enum(v)
1060            }
1061            TCKind::Fixed => {
1062                let (digits, negative) =
1063                    input.read_fixed(tc.fixed_digits().unwrap_or(0) as usize)?;
1064                Value::Fixed { digits, negative }
1065            }
1066            TCKind::Objref | TCKind::Component | TCKind::Home => {
1067                Value::Objref(input.read_object()?)
1068            }
1069            TCKind::TypeCode => Value::TypeCode(input.read_typecode()?),
1070            TCKind::Any => {
1071                let inner = input.read_typecode()?;
1072                let v = self.read(input, &inner)?;
1073                Value::Any(Box::new(Any::new(inner, v)))
1074            }
1075            TCKind::Value | TCKind::ValueBox | TCKind::Event => {
1076                Value::Valuetype(self.read_valuetype(input, &tc)?)
1077            }
1078            TCKind::AbstractInterface => {
1079                if input.read_bool()? {
1080                    Value::Objref(input.read_object()?)
1081                } else {
1082                    Value::Valuetype(self.read_valuetype(input, value_base_tc())?)
1083                }
1084            }
1085            TCKind::LocalInterface => return Err(input.marshal_error()),
1086            _ => {
1087                return Err(sys(SystemExceptionKind::NO_IMPLEMENT, input.completed));
1088            }
1089        })
1090    }
1091
1092    fn read_valuetype(
1093        &mut self,
1094        input: &mut InStream<'_>,
1095        expected: &TypeCode,
1096    ) -> Result<Option<ValueRef>, SystemException> {
1097        let header = input
1098            .read_value_header()
1099            .map_err(|_| input.marshal_error())?;
1100        let (slot, ids) = match header {
1101            ValueHeader::Null => return Ok(None),
1102            ValueHeader::Indirection(slot) => {
1103                return match input.values.get(slot) {
1104                    Some(Some(v)) => Ok(Some(v.clone())),
1105                    _ => Err(input.marshal_error()),
1106                };
1107            }
1108            ValueHeader::Value { slot, ids, .. } => (slot, ids),
1109        };
1110        let tc = known_type(expected, &ids).ok_or_else(|| input.marshal_error())?;
1111        let custom = match tc.type_modifier() {
1112            Ok(VM_CUSTOM) => {
1113                let id = tc.id().unwrap_or_default();
1114                Some(custom_reader(id).ok_or_else(|| input.marshal_error())?)
1115            }
1116            Ok(VM_ABSTRACT) => return Err(input.marshal_error()),
1117            _ => None,
1118        };
1119        if input.values.len() <= slot {
1120            input.values.resize(slot + 1, None);
1121        }
1122        // An instance set for this slot beforehand (`InStream::preset_value`)
1123        // is read into, if it has the type read.
1124        let v = match input.values[slot].take() {
1125            Some(r) if r.typecode().id().ok() == tc.id().ok() => r,
1126            _ => ValueRef::new(tc.clone(), Vec::new()),
1127        };
1128        input.values[slot] = Some(v.clone());
1129        if let Some(reader) = custom {
1130            reader(&v, input)?;
1131            input.end_value().map_err(|_| input.marshal_error())?;
1132            return Ok(Some(v));
1133        }
1134        let mut members = Vec::new();
1135        for t in state_types(&tc) {
1136            members.push(self.read(input, &t)?);
1137        }
1138        v.set_members(members);
1139        input.end_value().map_err(|_| input.marshal_error())?;
1140        Ok(Some(v))
1141    }
1142
1143    fn check_bound(
1144        &self,
1145        input: &InStream<'_>,
1146        len: usize,
1147        tc: &TypeCode,
1148    ) -> Result<(), SystemException> {
1149        let bound = tc.length().unwrap_or(0);
1150        if bound != 0 && len > bound as usize {
1151            return Err(input.marshal_error());
1152        }
1153        Ok(())
1154    }
1155
1156    fn read_items(
1157        &mut self,
1158        input: &mut InStream<'_>,
1159        content: &TypeCode,
1160        len: usize,
1161    ) -> Result<Value, SystemException> {
1162        Ok(match content.unaliased().kind() {
1163            TCKind::Octet => Value::Octets(
1164                input
1165                    .read_octets_shared(len)
1166                    .map_err(|_| input.marshal_error())?,
1167            ),
1168            TCKind::Char => {
1169                let bytes = input.read_octets(len).map_err(|_| input.marshal_error())?;
1170                let completed = input.completed;
1171                Value::Chars(input.code_sets().decode_string(bytes).map_err(|mut e| {
1172                    e.completed = completed;
1173                    e
1174                })?)
1175            }
1176            _ => {
1177                let mut items = Vec::with_capacity(len.min(4096));
1178                for _ in 0..len {
1179                    items.push(self.read(input, content)?);
1180                }
1181                Value::List(items)
1182            }
1183        })
1184    }
1185}
1186
1187/// The type to read a value sent with the repository ids `ids` as: the
1188/// first of them that is `expected` or a registered valuetype, or
1189/// `expected` when no id was sent (but not `ValueBase`, which has no
1190/// state of its own).
1191fn known_type(expected: &TypeCode, ids: &[String]) -> Option<TypeCode> {
1192    let expected_id = expected.id().unwrap_or_default();
1193    if ids.is_empty() {
1194        return (expected_id != VALUE_BASE_ID).then(|| expected.clone());
1195    }
1196    ids.iter().find_map(|id| {
1197        if id == expected_id {
1198            Some(expected.clone())
1199        } else {
1200            find_value_type(id).filter(|t| is_assignable(t, expected))
1201        }
1202    })
1203}
1204
1205/// The smallest size of a value on the wire, to check sequence lengths
1206/// before allocating.
1207fn min_size(tc: &TypeCode, depth: usize) -> usize {
1208    if depth > 8 {
1209        return 0;
1210    }
1211    let tc = tc.unaliased();
1212    match tc.kind() {
1213        TCKind::Boolean
1214        | TCKind::Char
1215        | TCKind::Octet
1216        | TCKind::WChar
1217        | TCKind::AbstractInterface => 1,
1218        TCKind::Short | TCKind::UShort => 2,
1219        TCKind::Long
1220        | TCKind::ULong
1221        | TCKind::Float
1222        | TCKind::Enum
1223        | TCKind::String
1224        | TCKind::WString
1225        | TCKind::Sequence
1226        | TCKind::Objref
1227        | TCKind::TypeCode
1228        | TCKind::Any
1229        | TCKind::Principal
1230        | TCKind::Value
1231        | TCKind::ValueBox
1232        | TCKind::Event => 4,
1233        TCKind::LongLong | TCKind::ULongLong | TCKind::Double => 8,
1234        TCKind::LongDouble => 16,
1235        TCKind::Fixed => (tc.fixed_digits().unwrap_or(0) as usize + 2) / 2,
1236        TCKind::Array => {
1237            let content = tc.content_type().map(|c| min_size(&c, depth + 1));
1238            content.unwrap_or(0) * tc.length().unwrap_or(0) as usize
1239        }
1240        TCKind::Struct | TCKind::Except => (0..tc.member_count().unwrap_or(0))
1241            .map(|i| min_size(&member(&tc, i), depth + 1))
1242            .fold(0usize, usize::saturating_add),
1243        _ => 0,
1244    }
1245}