Skip to main content

rustorb_core/dynany/
mod.rs

1//! `DynamicAny`: building and taking apart values of types known only by
2//! their TypeCode.
3//!
4//! A [`DynAny`] is a tree of components that follows the TypeCode: a
5//! struct, an exception, a sequence, an array, a union, a valuetype or a
6//! value box has components, which are DynAnys themselves and share their
7//! state with it; the other types have none and hold their value. Every
8//! constructed DynAny has a current position, which the `insert_*` and
9//! `get_*` operations work on.
10//!
11//! [`DynAnyFactory`] makes DynAnys from an [`Any`] or a [`TypeCode`]. The
12//! operations of the derived interfaces of the IDL (`DynStruct`,
13//! `DynUnion`...) are all on [`DynAny`]; on a DynAny of another kind they
14//! are `BAD_OPERATION`, as a failed narrow would be in a language mapping.
15//! [`DynAny::kind`] tells which apply.
16//!
17//! Valuetype instances that are shared in the value, or refer to each
18//! other in cycles, are one DynAny each, reached from every place the
19//! instance is; [`DynAny::to_any`] gives them back as shared instances.
20//! Such cycles keep the DynAnys alive until [`DynAny::destroy`].
21
22use std::collections::HashMap;
23use std::fmt;
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::{Arc, Mutex, MutexGuard};
26
27use crate::typecode::{TCKind, TypeCode};
28use crate::value::state_types;
29use crate::{
30    Any, CompletionStatus, Fixed, LongDouble, SystemException, SystemExceptionKind, Value, ValueRef,
31};
32
33#[cfg(test)]
34mod tests;
35
36/// How deep the components of a DynAny made from a TypeCode may nest.
37const MAX_DEPTH: usize = 256;
38
39/// Why a DynAny operation failed: the exceptions of `DynamicAny`, or a
40/// system exception (`OBJECT_NOT_EXIST` after [`DynAny::destroy`],
41/// `BAD_OPERATION` for an operation of another kind of DynAny,
42/// `NO_IMPLEMENT` for abstract interfaces).
43#[derive(Debug, Clone, PartialEq)]
44pub enum DynAnyError {
45    /// `DynAny::InvalidValue`: the value is not one the operation accepts
46    /// (out of bounds, no current component...).
47    InvalidValue,
48    /// `DynAny::TypeMismatch`: the type does not fit.
49    TypeMismatch,
50    /// `DynAnyFactory::InconsistentTypeCode`: no DynAny can have this
51    /// type.
52    InconsistentTypeCode,
53    /// `MustTruncate`: a valuetype instance is of a type derived from the
54    /// declared one, and truncation was refused.
55    MustTruncate,
56    /// A system exception.
57    System(SystemException),
58}
59
60impl fmt::Display for DynAnyError {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        match self {
63            DynAnyError::InvalidValue => f.write_str("DynAny::InvalidValue"),
64            DynAnyError::TypeMismatch => f.write_str("DynAny::TypeMismatch"),
65            DynAnyError::InconsistentTypeCode => f.write_str("DynAnyFactory::InconsistentTypeCode"),
66            DynAnyError::MustTruncate => f.write_str("MustTruncate"),
67            DynAnyError::System(e) => write!(f, "{e}"),
68        }
69    }
70}
71
72impl std::error::Error for DynAnyError {}
73
74impl From<SystemException> for DynAnyError {
75    fn from(e: SystemException) -> DynAnyError {
76        DynAnyError::System(e)
77    }
78}
79
80fn system(kind: SystemExceptionKind) -> DynAnyError {
81    DynAnyError::System(SystemException::new(kind, 0, CompletionStatus::No))
82}
83
84type Result<T> = std::result::Result<T, DynAnyError>;
85
86/// `DynamicAny::DynAnyFactory`, the initial reference `DynAnyFactory`.
87/// It keeps no state.
88#[derive(Debug, Clone, Copy, Default)]
89pub struct DynAnyFactory;
90
91impl DynAnyFactory {
92    /// A DynAny with the type and the value of `value`. A valuetype
93    /// instance of a type derived from the declared one is truncated to
94    /// the declared type.
95    pub fn create_dyn_any(&self, value: &Any) -> Result<DynAny> {
96        DynAny::top(value.typecode(), value.value(), true)
97    }
98
99    /// [`create_dyn_any`](DynAnyFactory::create_dyn_any), but
100    /// `MustTruncate` where a valuetype would be truncated.
101    pub fn create_dyn_any_without_truncation(&self, value: &Any) -> Result<DynAny> {
102        DynAny::top(value.typecode(), value.value(), false)
103    }
104
105    /// A DynAny of type `tc` with the default value: zero, false, empty
106    /// strings and sequences, the first enumerator, a union with the
107    /// first label value of its TypeCode, nil references, `null` valuetypes, an empty any and a
108    /// `null` TypeCode, and structs and arrays of those.
109    /// `InconsistentTypeCode` for `Principal`, `native`, abstract and
110    /// local interfaces, an enum without enumerators and
111    /// an unresolved recursive TypeCode.
112    pub fn create_dyn_any_from_type_code(&self, tc: &TypeCode) -> Result<DynAny> {
113        let life = Arc::new(Life::default());
114        let state = default_state(tc, &life, 0)?;
115        Ok(DynAny::node(tc.clone(), &life, false, state))
116    }
117
118    /// DynAnys of the values, each as
119    /// [`create_dyn_any`](DynAnyFactory::create_dyn_any) or, without
120    /// `allow_truncate`, as
121    /// [`create_dyn_any_without_truncation`](DynAnyFactory::create_dyn_any_without_truncation).
122    pub fn create_multiple_dyn_anys(
123        &self,
124        values: &[Any],
125        allow_truncate: bool,
126    ) -> Result<Vec<DynAny>> {
127        values
128            .iter()
129            .map(|v| DynAny::top(v.typecode(), v.value(), allow_truncate))
130            .collect()
131    }
132
133    /// The values of the DynAnys.
134    pub fn create_multiple_anys(&self, values: &[DynAny]) -> Result<Vec<Any>> {
135        values.iter().map(DynAny::to_any).collect()
136    }
137}
138
139/// The lifetime of the DynAnys of one tree: [`DynAny::destroy`] on the
140/// top one ends it.
141#[derive(Default)]
142struct Life {
143    destroyed: AtomicBool,
144}
145
146/// `DynamicAny::DynAny` and the interfaces derived from it. Clones are
147/// the same object, as references are.
148#[derive(Clone)]
149pub struct DynAny(Arc<Node>);
150
151struct Node {
152    /// The type as given, aliases included; the operations look at the
153    /// unaliased type.
154    tc: TypeCode,
155    life: Arc<Life>,
156    /// A component of another DynAny: destroy() does nothing.
157    component: bool,
158    state: Mutex<State>,
159}
160
161/// The state of a DynAny, by the kind of its unaliased type.
162enum State {
163    /// Types without components: the value.
164    Basic(Value),
165    /// Structs, exceptions, sequences and arrays: the members or
166    /// elements.
167    Items { items: Vec<DynAny>, pos: i32 },
168    /// Unions: the discriminator and, when the discriminator selects one,
169    /// the index of the member and the member.
170    Union {
171        disc: DynAny,
172        member: Option<(u32, DynAny)>,
173        pos: i32,
174    },
175    /// Valuetypes and value boxes: `None` for `null`, else the state
176    /// members (the boxed value of a value box).
177    Value {
178        members: Option<Vec<DynAny>>,
179        pos: i32,
180    },
181}
182
183impl State {
184    fn items(items: Vec<DynAny>) -> State {
185        let pos = if items.is_empty() { -1 } else { 0 };
186        State::Items { items, pos }
187    }
188
189    fn value(members: Option<Vec<DynAny>>) -> State {
190        let pos = match &members {
191            Some(m) if !m.is_empty() => 0,
192            _ => -1,
193        };
194        State::Value { members, pos }
195    }
196}
197
198impl fmt::Debug for DynAny {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        write!(f, "DynAny({:?})", self.0.tc)
201    }
202}
203
204/// Whether DynAnys of this (unaliased) kind have components.
205fn is_constructed(kind: TCKind) -> bool {
206    matches!(
207        kind,
208        TCKind::Struct
209            | TCKind::Except
210            | TCKind::Union
211            | TCKind::Sequence
212            | TCKind::Array
213            | TCKind::Value
214            | TCKind::ValueBox
215            | TCKind::Event
216    )
217}
218
219fn member_type(tc: &TypeCode, i: u32) -> Result<TypeCode> {
220    tc.member_type(i)
221        .map_err(|_| system(SystemExceptionKind::BAD_TYPECODE))
222}
223
224fn content_type(tc: &TypeCode) -> Result<TypeCode> {
225    tc.content_type()
226        .map_err(|_| system(SystemExceptionKind::BAD_TYPECODE))
227}
228
229fn bad_value() -> DynAnyError {
230    system(SystemExceptionKind::BAD_PARAM)
231}
232
233// --- default values ------------------------------------------------------------
234
235/// The state of a DynAny of type `tc` made from the TypeCode alone.
236fn default_state(tc: &TypeCode, life: &Arc<Life>, depth: usize) -> Result<State> {
237    if depth > MAX_DEPTH || tc.unaliased().is_recursive_placeholder() {
238        return Err(DynAnyError::InconsistentTypeCode);
239    }
240    let t = tc.unaliased();
241    Ok(match t.kind() {
242        TCKind::Struct | TCKind::Except => {
243            let n = t.member_count().unwrap_or(0);
244            let items = (0..n)
245                .map(|i| default_child(&member_type(&t, i)?, life, depth))
246                .collect::<Result<_>>()?;
247            State::items(items)
248        }
249        TCKind::Sequence => State::items(Vec::new()),
250        TCKind::Array => {
251            let content = content_type(&t)?;
252            let n = t.length().unwrap_or(0);
253            let items = (0..n)
254                .map(|_| default_child(&content, life, depth))
255                .collect::<Result<_>>()?;
256            State::items(items)
257        }
258        TCKind::Union => {
259            let (disc, member) = union_first(&t)?;
260            let disc_tc = t
261                .discriminator_type()
262                .map_err(|_| DynAnyError::InconsistentTypeCode)?;
263            let disc = DynAny::node(disc_tc, life, true, State::Basic(disc));
264            let member = match member {
265                Some(i) => Some((i, default_child(&member_type(&t, i)?, life, depth)?)),
266                None => None,
267            };
268            State::Union {
269                disc,
270                member,
271                pos: 0,
272            }
273        }
274        TCKind::Value | TCKind::ValueBox | TCKind::Event => State::value(None),
275        kind => State::Basic(default_basic(&t, kind)?),
276    })
277}
278
279/// A component made from its TypeCode.
280fn default_child(tc: &TypeCode, life: &Arc<Life>, depth: usize) -> Result<DynAny> {
281    let state = default_state(tc, life, depth + 1)?;
282    Ok(DynAny::node(tc.clone(), life, true, state))
283}
284
285fn default_basic(t: &TypeCode, kind: TCKind) -> Result<Value> {
286    Ok(match kind {
287        TCKind::Null | TCKind::Void => Value::Void,
288        TCKind::Short => Value::Short(0),
289        TCKind::UShort => Value::UShort(0),
290        TCKind::Long => Value::Long(0),
291        TCKind::ULong => Value::ULong(0),
292        TCKind::LongLong => Value::LongLong(0),
293        TCKind::ULongLong => Value::ULongLong(0),
294        TCKind::Float => Value::Float(0.0),
295        TCKind::Double => Value::Double(0.0),
296        TCKind::LongDouble => Value::LongDouble(LongDouble::ZERO),
297        TCKind::Boolean => Value::Bool(false),
298        TCKind::Char => Value::Char('\0'),
299        TCKind::WChar => Value::WChar(0),
300        TCKind::Octet => Value::Octet(0),
301        TCKind::String | TCKind::WString => Value::String(String::new()),
302        TCKind::Enum => {
303            if t.member_count().unwrap_or(0) == 0 {
304                return Err(DynAnyError::InconsistentTypeCode);
305            }
306            Value::Enum(0)
307        }
308        TCKind::Fixed => Value::Fixed {
309            digits: vec![0; t.fixed_digits().unwrap_or(0) as usize],
310            negative: false,
311        },
312        TCKind::Objref | TCKind::Component | TCKind::Home => Value::Objref(None),
313        TCKind::TypeCode => Value::TypeCode(TypeCode::null()),
314        TCKind::Any => Value::Any(Box::default()),
315        _ => return Err(DynAnyError::InconsistentTypeCode),
316    })
317}
318
319/// The labels of a union, by member: `None` for the default member.
320fn labels(t: &TypeCode) -> Vec<Option<i128>> {
321    (0..t.member_count().unwrap_or(0))
322        .map(|i| t.member_label_value(i).ok().flatten())
323        .collect()
324}
325
326/// A discriminator value no label of the union `t` uses, if there is one.
327fn unused_discriminator(t: &TypeCode) -> Option<Value> {
328    let disc = t.discriminator_type().ok()?;
329    let used: Vec<i128> = labels(t).into_iter().flatten().collect();
330    // Labels are finitely many: counting up from 0 finds a free value
331    // unless the type has few values and they are all used.
332    (0..=used.len() as i128)
333        .find(|l| !used.contains(l))
334        .and_then(|l| disc.label_to_value(l))
335}
336
337/// The discriminator value and the member of a union made from its
338/// TypeCode: the first label value, or an unused value (the default
339/// member) if the union has no label but the default.
340fn union_first(t: &TypeCode) -> Result<(Value, Option<u32>)> {
341    let first = labels(t).into_iter().flatten().next();
342    let disc = match first {
343        Some(l) => t
344            .discriminator_type()
345            .ok()
346            .and_then(|d| d.label_to_value(l)),
347        None => unused_discriminator(t),
348    }
349    .ok_or(DynAnyError::InconsistentTypeCode)?;
350    let member = t.union_member_for(&disc).ok().flatten();
351    Ok((disc, member))
352}
353
354// --- from values -----------------------------------------------------------------
355
356/// Makes DynAnys from values, one for each valuetype instance.
357struct FromValue<'a> {
358    life: &'a Arc<Life>,
359    truncate: bool,
360    /// The valuetype instances made so far, by instance and declared type.
361    values: HashMap<(u64, String), DynAny>,
362    depth: usize,
363}
364
365impl FromValue<'_> {
366    fn node(&mut self, tc: &TypeCode, value: &Value, component: bool) -> Result<DynAny> {
367        if let Some(d) = self
368            .instance_key(tc, value)
369            .and_then(|k| self.values.get(&k))
370        {
371            return Ok(d.clone());
372        }
373        let d = DynAny::node(tc.clone(), self.life, component, State::Basic(Value::Void));
374        self.fill(&d, value)?;
375        Ok(d)
376    }
377
378    /// The key of a valuetype instance in `values`.
379    fn instance_key(&self, tc: &TypeCode, value: &Value) -> Option<(u64, String)> {
380        let t = tc.unaliased();
381        match (t.kind(), value) {
382            (TCKind::Value | TCKind::ValueBox | TCKind::Event, Value::Valuetype(Some(r))) => {
383                Some((r.key(), t.id().unwrap_or_default().to_owned()))
384            }
385            _ => None,
386        }
387    }
388
389    /// Gives `d` the state of `value`, of the type of `d`. On an error `d`
390    /// is left as it was.
391    fn fill(&mut self, d: &DynAny, value: &Value) -> Result<()> {
392        let state = match (self.instance_key(&d.0.tc, value), value) {
393            (Some(key), Value::Valuetype(Some(r))) => {
394                // Registered before its members are made, which may refer
395                // to it.
396                self.values.insert(key, d.clone());
397                State::value(Some(self.valuetype_members(&d.unaliased(), r)?))
398            }
399            _ => self.state(&d.0.tc, value)?,
400        };
401        *d.lock() = state;
402        Ok(())
403    }
404
405    fn state(&mut self, tc: &TypeCode, value: &Value) -> Result<State> {
406        self.depth += 1;
407        if self.depth > MAX_DEPTH {
408            return Err(system(SystemExceptionKind::BAD_PARAM));
409        }
410        let state = self.state_inner(&tc.unaliased(), value);
411        self.depth -= 1;
412        state
413    }
414
415    fn state_inner(&mut self, t: &TypeCode, value: &Value) -> Result<State> {
416        Ok(match (t.kind(), value) {
417            (TCKind::Struct | TCKind::Except, Value::List(items)) => {
418                let n = t.member_count().unwrap_or(0);
419                if items.len() != n as usize {
420                    return Err(bad_value());
421                }
422                let items = items
423                    .iter()
424                    .enumerate()
425                    .map(|(i, v)| self.node(&member_type(t, i as u32)?, v, true))
426                    .collect::<Result<_>>()?;
427                State::items(items)
428            }
429            (TCKind::Sequence | TCKind::Array, _) => {
430                let content = content_type(t)?;
431                let values: Vec<Value> = match value {
432                    Value::List(items) => items.clone(),
433                    Value::Octets(b) => b.iter().map(|&b| Value::Octet(b)).collect(),
434                    Value::Chars(s) => s.chars().map(Value::Char).collect(),
435                    _ => return Err(bad_value()),
436                };
437                let n = t.length().unwrap_or(0) as usize;
438                let fits = if t.kind() == TCKind::Sequence {
439                    n == 0 || values.len() <= n
440                } else {
441                    values.len() == n
442                };
443                if !fits {
444                    return Err(bad_value());
445                }
446                let items = values
447                    .iter()
448                    .map(|v| self.node(&content, v, true))
449                    .collect::<Result<_>>()?;
450                State::items(items)
451            }
452            (TCKind::Union, Value::Union { disc, member }) => {
453                let disc_tc = t.discriminator_type().map_err(|_| bad_value())?;
454                let selected = t.union_member_for(disc).map_err(|_| bad_value())?;
455                if disc.label_key().is_none() || selected != member.as_ref().map(|(i, _)| *i) {
456                    return Err(bad_value());
457                }
458                let disc = self.node(&disc_tc, disc, true)?;
459                let member = match member {
460                    Some((i, v)) => Some((*i, self.node(&member_type(t, *i)?, v, true)?)),
461                    None => None,
462                };
463                State::Union {
464                    disc,
465                    member,
466                    pos: 0,
467                }
468            }
469            (TCKind::Value | TCKind::ValueBox | TCKind::Event, Value::Valuetype(None)) => {
470                State::value(None)
471            }
472            (kind, v) if !is_constructed(kind) => State::Basic(check_basic(t, kind, v)?),
473            _ => return Err(bad_value()),
474        })
475    }
476
477    /// The members of the instance `r` as a value of the declared type
478    /// `t`: those of a derived type's own members are cut off, if
479    /// truncation is allowed.
480    fn valuetype_members(&mut self, t: &TypeCode, r: &ValueRef) -> Result<Vec<DynAny>> {
481        let types = state_types(t);
482        let actual = r.typecode().unaliased();
483        let mut values = r.members();
484        if actual.id().ok() != t.id().ok() {
485            if !self.truncate {
486                return Err(DynAnyError::MustTruncate);
487            }
488            // The members of the base types come first.
489            if values.len() < types.len() {
490                return Err(bad_value());
491            }
492            values.truncate(types.len());
493        }
494        if values.len() != types.len() {
495            return Err(bad_value());
496        }
497        types
498            .iter()
499            .zip(&values)
500            .map(|(tc, v)| self.node(tc, v, true))
501            .collect()
502    }
503}
504
505/// `value` if it is a value of the type `t` (of kind `kind`, without
506/// components).
507fn check_basic(t: &TypeCode, kind: TCKind, value: &Value) -> Result<Value> {
508    let ok = match (kind, value) {
509        (TCKind::Null | TCKind::Void, _) => return Ok(Value::Void),
510        (TCKind::Short, Value::Short(_))
511        | (TCKind::UShort, Value::UShort(_))
512        | (TCKind::Long, Value::Long(_))
513        | (TCKind::ULong, Value::ULong(_))
514        | (TCKind::LongLong, Value::LongLong(_))
515        | (TCKind::ULongLong, Value::ULongLong(_))
516        | (TCKind::Float, Value::Float(_))
517        | (TCKind::Double, Value::Double(_))
518        | (TCKind::LongDouble, Value::LongDouble(_))
519        | (TCKind::Boolean, Value::Bool(_))
520        | (TCKind::Char, Value::Char(_))
521        | (TCKind::WChar, Value::WChar(_))
522        | (TCKind::Octet, Value::Octet(_))
523        | (TCKind::Objref | TCKind::Component | TCKind::Home, Value::Objref(_))
524        | (TCKind::TypeCode, Value::TypeCode(_))
525        | (TCKind::Any, Value::Any(_)) => true,
526        (TCKind::String | TCKind::WString, Value::String(s)) => {
527            fits_bound(s, t.length().unwrap_or(0))
528        }
529        (TCKind::Enum, Value::Enum(v)) => *v < t.member_count().unwrap_or(0),
530        (TCKind::Fixed, Value::Fixed { digits, .. }) => {
531            digits.len() == t.fixed_digits().unwrap_or(0) as usize && digits.iter().all(|&d| d < 10)
532        }
533        (TCKind::AbstractInterface | TCKind::Native, _) => {
534            return Err(system(SystemExceptionKind::NO_IMPLEMENT));
535        }
536        _ => false,
537    };
538    if ok {
539        Ok(value.clone())
540    } else {
541        Err(bad_value())
542    }
543}
544
545fn fits_bound(s: &str, bound: u32) -> bool {
546    bound == 0 || s.chars().count() <= bound as usize
547}
548
549// --- to values -------------------------------------------------------------------
550
551/// Makes values from DynAnys, one instance for each valuetype DynAny.
552#[derive(Default)]
553struct ToValue {
554    values: HashMap<usize, ValueRef>,
555}
556
557impl ToValue {
558    fn value(&mut self, d: &DynAny) -> Result<Value> {
559        d.check()?;
560        let t = d.0.tc.unaliased();
561        if let Some(r) = self.values.get(&d.key()) {
562            return Ok(Value::Valuetype(Some(r.clone())));
563        }
564        // Copies of what is needed, so that no lock is held while the
565        // components are converted.
566        enum Parts {
567            Basic(Value),
568            Items(Vec<DynAny>),
569            Union(DynAny, Option<(u32, DynAny)>),
570            Value(Option<Vec<DynAny>>),
571        }
572        d.sync_union();
573        let parts = match &*d.lock() {
574            State::Basic(v) => Parts::Basic(v.clone()),
575            State::Items { items, .. } => Parts::Items(items.clone()),
576            State::Union { disc, member, .. } => Parts::Union(disc.clone(), member.clone()),
577            State::Value { members, .. } => Parts::Value(members.clone()),
578        };
579        Ok(match parts {
580            Parts::Basic(v) => v,
581            Parts::Items(items) => {
582                let content = match t.kind() {
583                    TCKind::Sequence | TCKind::Array => {
584                        t.content_type().ok().map(|c| c.unaliased().kind())
585                    }
586                    _ => None,
587                };
588                let values = items
589                    .iter()
590                    .map(|i| self.value(i))
591                    .collect::<Result<Vec<_>>>()?;
592                match content {
593                    Some(TCKind::Octet) => Value::Octets(
594                        values
595                            .iter()
596                            .map(|v| match v {
597                                Value::Octet(b) => *b,
598                                _ => 0,
599                            })
600                            .collect(),
601                    ),
602                    Some(TCKind::Char) => Value::Chars(
603                        values
604                            .iter()
605                            .map(|v| match v {
606                                Value::Char(c) => *c,
607                                _ => '\0',
608                            })
609                            .collect(),
610                    ),
611                    _ => Value::List(values),
612                }
613            }
614            Parts::Union(disc, member) => Value::Union {
615                disc: Box::new(self.value(&disc)?),
616                member: match member {
617                    Some((i, m)) => Some((i, Box::new(self.value(&m)?))),
618                    None => None,
619                },
620            },
621            Parts::Value(None) => Value::Valuetype(None),
622            Parts::Value(Some(members)) => {
623                // Registered before its members are converted, which may
624                // refer to it.
625                let r = ValueRef::new(t.clone(), Vec::new());
626                self.values.insert(d.key(), r.clone());
627                let values = members
628                    .iter()
629                    .map(|m| self.value(m))
630                    .collect::<Result<Vec<_>>>()?;
631                r.set_members(values);
632                Value::Valuetype(Some(r))
633            }
634        })
635    }
636}
637
638// --- the DynAny operations ---------------------------------------------------------
639
640macro_rules! basic_ops {
641    ($($insert:ident, $get:ident, $ty:ty, $kind:ident, $variant:ident;)*) => {
642        $(
643            #[doc = concat!("`", stringify!($insert), "`: see [`DynAny::insert_basic`].")]
644            pub fn $insert(&self, v: $ty) -> Result<()> {
645                self.insert_basic(TCKind::$kind, Value::$variant(v))
646            }
647
648            #[doc = concat!("`", stringify!($get), "`: see [`DynAny::get_basic`].")]
649            pub fn $get(&self) -> Result<$ty> {
650                match self.get_basic(TCKind::$kind)? {
651                    Value::$variant(v) => Ok(v),
652                    _ => Err(DynAnyError::TypeMismatch),
653                }
654            }
655        )*
656    };
657}
658
659macro_rules! seq_ops {
660    ($($insert:ident, $get:ident, $ty:ty, $kind:ident, $variant:ident;)*) => {
661        $(
662            #[doc = concat!("`", stringify!($insert), "`: see [`DynAny::insert_seq`].")]
663            pub fn $insert(&self, v: &[$ty]) -> Result<()> {
664                self.insert_seq(TCKind::$kind, v.iter().map(|x| Value::$variant(x.clone())).collect())
665            }
666
667            #[doc = concat!("`", stringify!($get), "`: see [`DynAny::get_seq`].")]
668            pub fn $get(&self) -> Result<Vec<$ty>> {
669                self.get_seq(TCKind::$kind)?
670                    .into_iter()
671                    .map(|v| match v {
672                        Value::$variant(x) => Ok(x),
673                        _ => Err(DynAnyError::TypeMismatch),
674                    })
675                    .collect()
676            }
677        )*
678    };
679}
680
681impl DynAny {
682    fn node(tc: TypeCode, life: &Arc<Life>, component: bool, state: State) -> DynAny {
683        DynAny(Arc::new(Node {
684            tc,
685            life: Arc::clone(life),
686            component,
687            state: Mutex::new(state),
688        }))
689    }
690
691    fn top(tc: &TypeCode, value: &Value, truncate: bool) -> Result<DynAny> {
692        let life = Arc::new(Life::default());
693        let mut from = FromValue {
694            life: &life,
695            truncate,
696            values: HashMap::new(),
697            depth: 0,
698        };
699        from.node(tc, value, false)
700    }
701
702    /// A component of `self` with the type and value of `value`.
703    fn child(&self, tc: &TypeCode, value: &Value) -> Result<DynAny> {
704        FromValue {
705            life: &self.0.life,
706            truncate: true,
707            values: HashMap::new(),
708            depth: 0,
709        }
710        .node(tc, value, true)
711    }
712
713    /// A component of `self` with the default value of `tc`.
714    fn default_child(&self, tc: &TypeCode) -> Result<DynAny> {
715        default_child(tc, &self.0.life, 0)
716    }
717
718    fn lock(&self) -> MutexGuard<'_, State> {
719        self.0.state.lock().unwrap_or_else(|e| e.into_inner())
720    }
721
722    fn key(&self) -> usize {
723        Arc::as_ptr(&self.0) as usize
724    }
725
726    /// `OBJECT_NOT_EXIST` once the tree is destroyed.
727    fn check(&self) -> Result<()> {
728        if self.0.life.destroyed.load(Ordering::Acquire) {
729            return Err(system(SystemExceptionKind::OBJECT_NOT_EXIST));
730        }
731        Ok(())
732    }
733
734    fn unaliased(&self) -> TypeCode {
735        self.0.tc.unaliased()
736    }
737
738    /// The unaliased kind of the type, which tells which interface of
739    /// `DynamicAny` the DynAny is: `DynStruct` for structs and exceptions,
740    /// `DynFixed`, `DynEnum`, `DynUnion`, `DynSequence`, `DynArray`,
741    /// `DynValue` (valuetypes and eventtypes), `DynValueBox`, plain
742    /// `DynAny` for the others.
743    pub fn kind(&self) -> TCKind {
744        self.0.tc.unaliased().kind()
745    }
746
747    /// `BAD_OPERATION` unless the DynAny is of one of `kinds`.
748    fn expect(&self, kinds: &[TCKind]) -> Result<TypeCode> {
749        self.check()?;
750        let t = self.unaliased();
751        if kinds.contains(&t.kind()) {
752            Ok(t)
753        } else {
754            Err(system(SystemExceptionKind::BAD_OPERATION))
755        }
756    }
757
758    /// Whether both are the same DynAny.
759    pub fn ptr_eq(&self, other: &DynAny) -> bool {
760        Arc::ptr_eq(&self.0, &other.0)
761    }
762
763    // --- DynAny ---------------------------------------------------------------
764
765    /// `type`: the TypeCode of the DynAny, aliases included.
766    pub fn type_code(&self) -> Result<TypeCode> {
767        self.check()?;
768        Ok(self.0.tc.clone())
769    }
770
771    /// `assign`: gives this DynAny the value of `other`. `TypeMismatch`
772    /// if the types are not equivalent.
773    pub fn assign(&self, other: &DynAny) -> Result<()> {
774        self.check()?;
775        let value = other.to_any()?;
776        self.from_any(&value)
777    }
778
779    /// `from_any`: gives this DynAny the value of `value`. `TypeMismatch`
780    /// if the types are not equivalent; `InvalidValue` if the value does
781    /// not fit the type.
782    pub fn from_any(&self, value: &Any) -> Result<()> {
783        self.check()?;
784        if !value.typecode().equivalent(&self.0.tc) {
785            return Err(DynAnyError::TypeMismatch);
786        }
787        self.fill(value.value()).map_err(|e| match e {
788            DynAnyError::System(_) => DynAnyError::InvalidValue,
789            e => e,
790        })
791    }
792
793    /// Gives this DynAny the value `value`, its components in its tree.
794    fn fill(&self, value: &Value) -> Result<()> {
795        FromValue {
796            life: &self.0.life,
797            truncate: true,
798            values: HashMap::new(),
799            depth: 0,
800        }
801        .fill(self, value)
802    }
803
804    /// `to_any`: the value as an Any of the type of the DynAny.
805    pub fn to_any(&self) -> Result<Any> {
806        let value = ToValue::default().value(self)?;
807        Ok(Any::new(self.0.tc.clone(), value))
808    }
809
810    /// `equal`: whether both have equivalent types and equal values.
811    pub fn equal(&self, other: &DynAny) -> Result<bool> {
812        let a = self.to_any()?;
813        let b = other.to_any()?;
814        let equal = a.typecode().equivalent(b.typecode()) && a.value() == b.value();
815        // Copies, whose valuetypes may form cycles.
816        Value::Any(Box::new(a)).release();
817        Value::Any(Box::new(b)).release();
818        Ok(equal)
819    }
820
821    /// `destroy`: destroys a DynAny made by the factory or by
822    /// [`copy`](DynAny::copy) and its components; using them afterwards
823    /// is `OBJECT_NOT_EXIST`. Destroying a component does nothing.
824    pub fn destroy(&self) -> Result<()> {
825        self.check()?;
826        if self.0.component {
827            return Ok(());
828        }
829        self.0.life.destroyed.store(true, Ordering::Release);
830        // Breaks the cycles that valuetype instances may form.
831        let mut stack = vec![self.clone()];
832        while let Some(d) = stack.pop() {
833            match std::mem::replace(&mut *d.lock(), State::Basic(Value::Void)) {
834                State::Basic(v) => v.break_cycles(),
835                State::Items { items, .. } => stack.extend(items),
836                State::Union { disc, member, .. } => {
837                    stack.push(disc);
838                    stack.extend(member.map(|(_, m)| m));
839                }
840                State::Value { members, .. } => stack.extend(members.into_iter().flatten()),
841            }
842        }
843        Ok(())
844    }
845
846    /// `copy`: a new DynAny with the type and the value of this one.
847    pub fn copy(&self) -> Result<DynAny> {
848        let value = self.to_any()?;
849        DynAny::top(value.typecode(), value.value(), true)
850    }
851
852    /// The DynAny the `insert_*` and `get_*` operations work on: this one
853    /// if its type has no components, else the current component
854    /// (`InvalidValue` if there is none).
855    fn target(&self) -> Result<DynAny> {
856        self.check()?;
857        if !is_constructed(self.kind()) {
858            return Ok(self.clone());
859        }
860        self.current_component()?.ok_or(DynAnyError::InvalidValue)
861    }
862
863    /// `insert_<type>` with the value of the type `kind` (`Objref` for
864    /// `insert_reference`, `Value` for `insert_val`): sets the value of
865    /// the [target](DynAny) if its unaliased type is of that kind, else
866    /// `TypeMismatch`. A string longer than a bounded string type is
867    /// `InvalidValue`.
868    pub fn insert_basic(&self, kind: TCKind, value: Value) -> Result<()> {
869        let target = self.target()?;
870        let t = target.unaliased();
871        let actual = t.kind();
872        let same = actual == kind
873            || (kind == TCKind::Objref && matches!(actual, TCKind::Component | TCKind::Home))
874            || (kind == TCKind::Value && matches!(actual, TCKind::ValueBox | TCKind::Event));
875        if !same {
876            return Err(DynAnyError::TypeMismatch);
877        }
878        match value {
879            Value::Valuetype(v) => target.insert_valuetype(&t, v),
880            value => {
881                if let Value::String(s) = &value {
882                    if !fits_bound(s, t.length().unwrap_or(0)) {
883                        return Err(DynAnyError::InvalidValue);
884                    }
885                }
886                let value = check_basic(&t, actual, &value).map_err(|e| match e {
887                    DynAnyError::System(_) => DynAnyError::TypeMismatch,
888                    e => e,
889                })?;
890                *target.lock() = State::Basic(value);
891                Ok(())
892            }
893        }
894    }
895
896    fn insert_valuetype(&self, t: &TypeCode, v: Option<ValueRef>) -> Result<()> {
897        if let Some(r) = &v {
898            if !is_assignable_to(r.typecode(), t) {
899                return Err(DynAnyError::TypeMismatch);
900            }
901        }
902        self.fill(&Value::Valuetype(v))
903    }
904
905    /// `get_<type>`: the value of the [target](DynAny) if its unaliased
906    /// type is of the kind `kind`, else `TypeMismatch`.
907    pub fn get_basic(&self, kind: TCKind) -> Result<Value> {
908        let target = self.target()?;
909        let actual = target.kind();
910        let same = actual == kind
911            || (kind == TCKind::Objref && matches!(actual, TCKind::Component | TCKind::Home))
912            || (kind == TCKind::Value && matches!(actual, TCKind::ValueBox | TCKind::Event));
913        if !same {
914            return Err(DynAnyError::TypeMismatch);
915        }
916        if kind == TCKind::Value {
917            return ToValue::default().value(&target);
918        }
919        match &*target.lock() {
920            State::Basic(v) => Ok(v.clone()),
921            _ => Err(DynAnyError::TypeMismatch),
922        }
923    }
924
925    basic_ops! {
926        insert_boolean, get_boolean, bool, Boolean, Bool;
927        insert_octet, get_octet, u8, Octet, Octet;
928        insert_char, get_char, char, Char, Char;
929        insert_short, get_short, i16, Short, Short;
930        insert_ushort, get_ushort, u16, UShort, UShort;
931        insert_long, get_long, i32, Long, Long;
932        insert_ulong, get_ulong, u32, ULong, ULong;
933        insert_float, get_float, f32, Float, Float;
934        insert_double, get_double, f64, Double, Double;
935        insert_longdouble, get_longdouble, LongDouble, LongDouble, LongDouble;
936        insert_longlong, get_longlong, i64, LongLong, LongLong;
937        insert_ulonglong, get_ulonglong, u64, ULongLong, ULongLong;
938        insert_wchar, get_wchar, u16, WChar, WChar;
939        insert_typecode, get_typecode, TypeCode, TypeCode, TypeCode;
940        insert_reference, get_reference, Option<crate::ObjectRef>, Objref, Objref;
941        insert_val, get_val, Option<ValueRef>, Value, Valuetype;
942    }
943
944    /// `insert_string`.
945    pub fn insert_string(&self, v: &str) -> Result<()> {
946        self.insert_basic(TCKind::String, Value::String(v.to_owned()))
947    }
948
949    /// `get_string`.
950    pub fn get_string(&self) -> Result<String> {
951        match self.get_basic(TCKind::String)? {
952            Value::String(s) => Ok(s),
953            _ => Err(DynAnyError::TypeMismatch),
954        }
955    }
956
957    /// `insert_wstring`.
958    pub fn insert_wstring(&self, v: &str) -> Result<()> {
959        self.insert_basic(TCKind::WString, Value::String(v.to_owned()))
960    }
961
962    /// `get_wstring`.
963    pub fn get_wstring(&self) -> Result<String> {
964        match self.get_basic(TCKind::WString)? {
965            Value::String(s) => Ok(s),
966            _ => Err(DynAnyError::TypeMismatch),
967        }
968    }
969
970    /// `insert_any`.
971    pub fn insert_any(&self, v: &Any) -> Result<()> {
972        self.insert_basic(TCKind::Any, Value::Any(Box::new(v.clone())))
973    }
974
975    /// `get_any`.
976    pub fn get_any(&self) -> Result<Any> {
977        match self.get_basic(TCKind::Any)? {
978            Value::Any(a) => Ok(*a),
979            _ => Err(DynAnyError::TypeMismatch),
980        }
981    }
982
983    /// `insert_dyn_any`: [`insert_any`](DynAny::insert_any) with the
984    /// value of `v`.
985    pub fn insert_dyn_any(&self, v: &DynAny) -> Result<()> {
986        self.insert_any(&v.to_any()?)
987    }
988
989    /// `get_dyn_any`: a new DynAny of the value in the any.
990    pub fn get_dyn_any(&self) -> Result<DynAny> {
991        let a = self.get_any()?;
992        DynAny::top(a.typecode(), a.value(), true)
993    }
994
995    /// `insert_abstract` / `get_abstract`: `NO_IMPLEMENT`.
996    pub fn no_implement(&self) -> Result<()> {
997        self.check()?;
998        Err(system(SystemExceptionKind::NO_IMPLEMENT))
999    }
1000
1001    /// The DynAny the `insert_<type>_seq` and `get_<type>_seq`
1002    /// operations work on: this one if it is a sequence or array of
1003    /// elements of the kind `kind` or has no components, else the current
1004    /// component.
1005    fn seq_target(&self, kind: TCKind) -> Result<DynAny> {
1006        self.check()?;
1007        if self.seq_of(kind).is_ok() {
1008            return Ok(self.clone());
1009        }
1010        self.target()
1011    }
1012
1013    /// `insert_<type>_seq`: sets the elements of the target (this DynAny
1014    /// if it is a sequence or array of that kind or has no components,
1015    /// else its current component), a sequence or array of elements of
1016    /// the kind `kind`, else
1017    /// `TypeMismatch`. Too many elements for a bounded sequence, or not
1018    /// as many as an array has, is `InvalidValue`. The position becomes
1019    /// the first element.
1020    pub fn insert_seq(&self, kind: TCKind, values: Vec<Value>) -> Result<()> {
1021        let target = self.seq_target(kind)?;
1022        let t = target.seq_of(kind)?;
1023        let content = content_type(&t)?;
1024        let len = values.len();
1025        target.check_length(&t, len)?;
1026        let items = values
1027            .iter()
1028            .map(|v| target.child(&content, v))
1029            .collect::<Result<Vec<_>>>()
1030            .map_err(|_| DynAnyError::TypeMismatch)?;
1031        *target.lock() = State::items(items);
1032        Ok(())
1033    }
1034
1035    /// `get_<type>_seq`: the elements of the target (this DynAny if it is
1036    /// a sequence or array of that kind or has no components, else its
1037    /// current component), a sequence or array of elements of the kind
1038    /// `kind`, else
1039    /// `TypeMismatch`.
1040    pub fn get_seq(&self, kind: TCKind) -> Result<Vec<Value>> {
1041        let target = self.seq_target(kind)?;
1042        target.seq_of(kind)?;
1043        let items = match &*target.lock() {
1044            State::Items { items, .. } => items.clone(),
1045            _ => return Err(DynAnyError::TypeMismatch),
1046        };
1047        let mut to = ToValue::default();
1048        items.iter().map(|i| to.value(i)).collect()
1049    }
1050
1051    /// The unaliased type if it is a sequence or array of `kind`.
1052    fn seq_of(&self, kind: TCKind) -> Result<TypeCode> {
1053        let t = self.unaliased();
1054        if !matches!(t.kind(), TCKind::Sequence | TCKind::Array)
1055            || content_type(&t)?.unaliased().kind() != kind
1056        {
1057            return Err(DynAnyError::TypeMismatch);
1058        }
1059        Ok(t)
1060    }
1061
1062    fn check_length(&self, t: &TypeCode, len: usize) -> Result<()> {
1063        let n = t.length().unwrap_or(0) as usize;
1064        let ok = if t.kind() == TCKind::Sequence {
1065            n == 0 || len <= n
1066        } else {
1067            len == n
1068        };
1069        if ok {
1070            Ok(())
1071        } else {
1072            Err(DynAnyError::InvalidValue)
1073        }
1074    }
1075
1076    seq_ops! {
1077        insert_boolean_seq, get_boolean_seq, bool, Boolean, Bool;
1078        insert_octet_seq, get_octet_seq, u8, Octet, Octet;
1079        insert_char_seq, get_char_seq, char, Char, Char;
1080        insert_short_seq, get_short_seq, i16, Short, Short;
1081        insert_ushort_seq, get_ushort_seq, u16, UShort, UShort;
1082        insert_long_seq, get_long_seq, i32, Long, Long;
1083        insert_ulong_seq, get_ulong_seq, u32, ULong, ULong;
1084        insert_float_seq, get_float_seq, f32, Float, Float;
1085        insert_double_seq, get_double_seq, f64, Double, Double;
1086        insert_longdouble_seq, get_longdouble_seq, LongDouble, LongDouble, LongDouble;
1087        insert_longlong_seq, get_longlong_seq, i64, LongLong, LongLong;
1088        insert_ulonglong_seq, get_ulonglong_seq, u64, ULongLong, ULongLong;
1089        insert_wchar_seq, get_wchar_seq, u16, WChar, WChar;
1090    }
1091
1092    // --- iteration ------------------------------------------------------------
1093
1094    /// Keeps a union's member in step with its discriminator, which may
1095    /// have been changed through its component: a discriminator that
1096    /// selects another member gets that member with its default value.
1097    fn sync_union(&self) {
1098        let disc = match &*self.lock() {
1099            State::Union { disc, .. } => disc.clone(),
1100            _ => return,
1101        };
1102        let Ok(value) = disc.to_any() else { return };
1103        let t = self.unaliased();
1104        let selected = t.union_member_for(value.value()).ok().flatten();
1105        let current = match &*self.lock() {
1106            State::Union { member, .. } => member.as_ref().map(|(i, _)| *i),
1107            _ => return,
1108        };
1109        if selected == current {
1110            return;
1111        }
1112        // A member with several labels is one entry of the TypeCode per
1113        // label, with the same name: it stays active, with its value.
1114        if let (Some(i), Some(j)) = (selected, current) {
1115            if same_member(&t, i, j) {
1116                if let State::Union {
1117                    member: Some(m), ..
1118                } = &mut *self.lock()
1119                {
1120                    m.0 = i;
1121                }
1122                return;
1123            }
1124        }
1125        let member = selected.and_then(|i| {
1126            let tc = member_type(&t, i).ok()?;
1127            Some((i, self.default_child(&tc).ok()?))
1128        });
1129        if let State::Union { member: m, pos, .. } = &mut *self.lock() {
1130            *m = member;
1131            if *pos >= if m.is_some() { 2 } else { 1 } {
1132                *pos = -1;
1133            }
1134        }
1135    }
1136
1137    /// `component_count`: the members of a struct, exception or
1138    /// valuetype (0 for `null`), the elements of a sequence or array, 2
1139    /// for a union with an active member and 1 without, 1 for a value
1140    /// box that is not `null`, 0 for the other types.
1141    pub fn component_count(&self) -> Result<u32> {
1142        self.check()?;
1143        self.sync_union();
1144        Ok(match &*self.lock() {
1145            State::Basic(_) => 0,
1146            State::Items { items, .. } => items.len() as u32,
1147            State::Union { member, .. } => 1 + u32::from(member.is_some()),
1148            State::Value { members, .. } => members.as_ref().map_or(0, |m| m.len() as u32),
1149        })
1150    }
1151
1152    fn pos_mut(state: &mut State) -> Option<&mut i32> {
1153        match state {
1154            State::Basic(_) => None,
1155            State::Items { pos, .. } | State::Union { pos, .. } | State::Value { pos, .. } => {
1156                Some(pos)
1157            }
1158        }
1159    }
1160
1161    /// `seek`: makes `index` the current position. True if there is a
1162    /// component there; else the position becomes -1 and the result is
1163    /// false.
1164    pub fn seek(&self, index: i32) -> Result<bool> {
1165        let count = self.component_count()? as i32;
1166        let mut state = self.lock();
1167        let Some(pos) = DynAny::pos_mut(&mut state) else {
1168            return Ok(false);
1169        };
1170        if (0..count).contains(&index) {
1171            *pos = index;
1172            Ok(true)
1173        } else {
1174            *pos = -1;
1175            Ok(false)
1176        }
1177    }
1178
1179    /// `rewind`: `seek(0)`.
1180    pub fn rewind(&self) -> Result<()> {
1181        self.seek(0).map(|_| ())
1182    }
1183
1184    /// `next`: moves to the next component (from -1 to the first). True
1185    /// if there is one; else the position becomes -1 and the result is
1186    /// false.
1187    pub fn next(&self) -> Result<bool> {
1188        let count = self.component_count()? as i32;
1189        let mut state = self.lock();
1190        let Some(pos) = DynAny::pos_mut(&mut state) else {
1191            return Ok(false);
1192        };
1193        if *pos + 1 < count {
1194            *pos += 1;
1195            Ok(true)
1196        } else {
1197            *pos = -1;
1198            Ok(false)
1199        }
1200    }
1201
1202    /// The current position, -1 when there is no current component.
1203    pub fn position(&self) -> Result<i32> {
1204        self.check()?;
1205        self.sync_union();
1206        Ok(DynAny::pos_mut(&mut self.lock()).map_or(-1, |p| *p))
1207    }
1208
1209    /// `current_component`: the component at the current position,
1210    /// `None` at -1. `TypeMismatch` for a DynAny that cannot have
1211    /// components (`DynEnum`, `DynFixed`, basic types), for an exception
1212    /// without members and for a `null` valuetype or value box.
1213    pub fn current_component(&self) -> Result<Option<DynAny>> {
1214        self.check()?;
1215        let t = self.unaliased();
1216        let kind = t.kind();
1217        if !is_constructed(kind) || (kind == TCKind::Except && t.member_count() == Ok(0)) {
1218            return Err(DynAnyError::TypeMismatch);
1219        }
1220        self.sync_union();
1221        let state = self.lock();
1222        if let State::Value { members: None, .. } = &*state {
1223            return Err(DynAnyError::TypeMismatch);
1224        }
1225        Ok(match &*state {
1226            State::Basic(_) => None,
1227            State::Items { items, pos } => usize::try_from(*pos)
1228                .ok()
1229                .and_then(|p| items.get(p))
1230                .cloned(),
1231            State::Union { disc, member, pos } => match pos {
1232                0 => Some(disc.clone()),
1233                1 => member.as_ref().map(|(_, m)| m.clone()),
1234                _ => None,
1235            },
1236            State::Value { members, pos } => usize::try_from(*pos)
1237                .ok()
1238                .and_then(|p| members.as_ref()?.get(p))
1239                .cloned(),
1240        })
1241    }
1242
1243    // --- DynFixed ---------------------------------------------------------------
1244
1245    /// `DynFixed::get_value`: the value as a fixed-point literal without
1246    /// the `d` suffix and without zeros at the end of the fraction, such
1247    /// as `-123.45`, `-12.5` or `0`.
1248    pub fn get_fixed_value(&self) -> Result<String> {
1249        let t = self.expect(&[TCKind::Fixed])?;
1250        let State::Basic(Value::Fixed { digits, negative }) = &*self.lock() else {
1251            return Err(DynAnyError::TypeMismatch);
1252        };
1253        let scale = u16::try_from(t.fixed_scale().unwrap_or(0)).unwrap_or(0);
1254        let f = Fixed::from_digits(digits, scale, *negative).ok_or_else(bad_value)?;
1255        // Without the zeros at the end of the fraction, as omniORB.
1256        let s = f.to_string();
1257        Ok(if s.contains('.') {
1258            s.trim_end_matches('0').trim_end_matches('.').to_owned()
1259        } else {
1260            s
1261        })
1262    }
1263
1264    /// `DynFixed::set_value`: sets the value from a fixed-point literal
1265    /// (an optional sign, digits with an optional point, an optional `d`
1266    /// or `D`, blanks around). `TypeMismatch` if it is not one,
1267    /// `InvalidValue` if its integer part has too many digits. Digits
1268    /// after the scale are cut off, and the result is then false.
1269    pub fn set_fixed_value(&self, literal: &str) -> Result<bool> {
1270        let t = self.expect(&[TCKind::Fixed])?;
1271        let f: Fixed = literal
1272            .trim()
1273            .parse()
1274            .map_err(|_| DynAnyError::TypeMismatch)?;
1275        let digits = t.fixed_digits().unwrap_or(0);
1276        let scale = u16::try_from(t.fixed_scale().unwrap_or(0)).unwrap_or(0);
1277        // Exact if the digits cut off are all zero.
1278        let exact = f.scale() <= scale
1279            || f.digits()[f.digits().len() - (f.scale() - scale) as usize..]
1280                .iter()
1281                .all(|&d| d == 0);
1282        let fitted = f
1283            .to_digits(digits, scale)
1284            .ok_or(DynAnyError::InvalidValue)?;
1285        let negative = f.is_negative() && fitted.iter().any(|&d| d != 0);
1286        *self.lock() = State::Basic(Value::Fixed {
1287            digits: fitted,
1288            negative,
1289        });
1290        Ok(exact)
1291    }
1292
1293    // --- DynEnum --------------------------------------------------------------
1294
1295    /// `DynEnum::get_as_ulong`: the position of the enumerator.
1296    pub fn get_enum_as_ulong(&self) -> Result<u32> {
1297        self.expect(&[TCKind::Enum])?;
1298        match &*self.lock() {
1299            State::Basic(Value::Enum(v)) => Ok(*v),
1300            _ => Err(DynAnyError::TypeMismatch),
1301        }
1302    }
1303
1304    /// `DynEnum::set_as_ulong`: `InvalidValue` if there is no enumerator
1305    /// at `v`.
1306    pub fn set_enum_as_ulong(&self, v: u32) -> Result<()> {
1307        let t = self.expect(&[TCKind::Enum])?;
1308        if v >= t.member_count().unwrap_or(0) {
1309            return Err(DynAnyError::InvalidValue);
1310        }
1311        *self.lock() = State::Basic(Value::Enum(v));
1312        Ok(())
1313    }
1314
1315    /// `DynEnum::get_as_string`: the name of the enumerator.
1316    pub fn get_enum_as_string(&self) -> Result<String> {
1317        let t = self.expect(&[TCKind::Enum])?;
1318        let v = self.get_enum_as_ulong()?;
1319        Ok(t.member_name(v).unwrap_or_default().to_owned())
1320    }
1321
1322    /// `DynEnum::set_as_string`: `InvalidValue` if no enumerator has the
1323    /// name.
1324    pub fn set_enum_as_string(&self, name: &str) -> Result<()> {
1325        let t = self.expect(&[TCKind::Enum])?;
1326        let v = (0..t.member_count().unwrap_or(0))
1327            .find(|&i| t.member_name(i) == Ok(name))
1328            .ok_or(DynAnyError::InvalidValue)?;
1329        *self.lock() = State::Basic(Value::Enum(v));
1330        Ok(())
1331    }
1332
1333    // --- DynStruct and DynValue -------------------------------------------------
1334
1335    const MEMBERED: [TCKind; 4] = [TCKind::Struct, TCKind::Except, TCKind::Value, TCKind::Event];
1336
1337    /// The names and types of the members of a struct, exception or
1338    /// valuetype (with those of its base types first).
1339    fn member_types(t: &TypeCode) -> Vec<(String, TypeCode)> {
1340        match t.kind() {
1341            TCKind::Value | TCKind::Event => value_member_names(t)
1342                .into_iter()
1343                .zip(state_types(t))
1344                .collect(),
1345            _ => (0..t.member_count().unwrap_or(0))
1346                .map(|i| {
1347                    (
1348                        t.member_name(i).unwrap_or_default().to_owned(),
1349                        t.member_type(i).unwrap_or_else(|_| TypeCode::null()),
1350                    )
1351                })
1352                .collect(),
1353        }
1354    }
1355
1356    /// `current_member_name` of `DynStruct` and `DynValue`.
1357    /// `TypeMismatch` without members (or `null`), `InvalidValue` at
1358    /// position -1.
1359    pub fn current_member_name(&self) -> Result<String> {
1360        let t = self.expect(&Self::MEMBERED)?;
1361        let i = self.current_member(&t)?;
1362        Ok(DynAny::member_types(&t).swap_remove(i).0)
1363    }
1364
1365    /// `current_member_kind` of `DynStruct` and `DynValue`: the kind of
1366    /// the member's type, aliases included.
1367    pub fn current_member_kind(&self) -> Result<TCKind> {
1368        let t = self.expect(&Self::MEMBERED)?;
1369        let i = self.current_member(&t)?;
1370        Ok(DynAny::member_types(&t).swap_remove(i).1.kind())
1371    }
1372
1373    fn current_member(&self, t: &TypeCode) -> Result<usize> {
1374        let count = self.component_count()? as i32;
1375        // An exception without members, a null valuetype.
1376        if DynAny::member_types(t).is_empty() || count == 0 {
1377            return Err(DynAnyError::TypeMismatch);
1378        }
1379        let pos = self.position()?;
1380        if pos < 0 || pos >= count {
1381            return Err(DynAnyError::InvalidValue);
1382        }
1383        Ok(pos as usize)
1384    }
1385
1386    fn member_items(&self) -> Result<Vec<DynAny>> {
1387        Ok(match &*self.lock() {
1388            State::Items { items, .. } => items.clone(),
1389            State::Value { members, .. } => members.clone().ok_or(DynAnyError::InvalidValue)?,
1390            _ => return Err(DynAnyError::TypeMismatch),
1391        })
1392    }
1393
1394    /// `get_members` of `DynStruct` and `DynValue`: the names and values
1395    /// of the members. `InvalidValue` for a `null` valuetype.
1396    pub fn get_members(&self) -> Result<Vec<(String, Any)>> {
1397        self.get_members_as_dyn_any()?
1398            .into_iter()
1399            .map(|(n, d)| Ok((n, d.to_any()?)))
1400            .collect()
1401    }
1402
1403    /// `get_members_as_dyn_any`: the names and the components.
1404    pub fn get_members_as_dyn_any(&self) -> Result<Vec<(String, DynAny)>> {
1405        let t = self.expect(&Self::MEMBERED)?;
1406        let names = DynAny::member_types(&t).into_iter().map(|(n, _)| n);
1407        Ok(names.zip(self.member_items()?).collect())
1408    }
1409
1410    /// `set_members` of `DynStruct` and `DynValue`: as many values as
1411    /// there are members (else `InvalidValue`), each with the name of its
1412    /// member or an empty one and a type equivalent to the member's
1413    /// (else `TypeMismatch`). A `null` valuetype is no longer `null`.
1414    pub fn set_members(&self, values: &[(String, Any)]) -> Result<()> {
1415        let t = self.expect(&Self::MEMBERED)?;
1416        let types = DynAny::member_types(&t);
1417        if values.len() != types.len() {
1418            return Err(DynAnyError::InvalidValue);
1419        }
1420        let mut items = Vec::with_capacity(values.len());
1421        for ((name, tc), (n, v)) in types.iter().zip(values) {
1422            if (!n.is_empty() && n != name) || !v.typecode().equivalent(tc) {
1423                return Err(DynAnyError::TypeMismatch);
1424            }
1425            items.push(
1426                self.child(tc, v.value())
1427                    .map_err(|_| DynAnyError::InvalidValue)?,
1428            );
1429        }
1430        *self.lock() = match t.kind() {
1431            TCKind::Value | TCKind::Event => State::value(Some(items)),
1432            _ => State::items(items),
1433        };
1434        Ok(())
1435    }
1436
1437    /// `set_members_as_dyn_any`: [`set_members`](DynAny::set_members)
1438    /// with the values of the DynAnys.
1439    pub fn set_members_as_dyn_any(&self, values: &[(String, DynAny)]) -> Result<()> {
1440        let values = values
1441            .iter()
1442            .map(|(n, d)| Ok((n.clone(), d.to_any()?)))
1443            .collect::<Result<Vec<_>>>()?;
1444        self.set_members(&values)
1445    }
1446
1447    // --- DynUnion ---------------------------------------------------------------
1448
1449    /// `DynUnion::get_discriminator`: the discriminator component.
1450    pub fn get_discriminator(&self) -> Result<DynAny> {
1451        self.expect(&[TCKind::Union])?;
1452        self.sync_union();
1453        match &*self.lock() {
1454            State::Union { disc, .. } => Ok(disc.clone()),
1455            _ => Err(DynAnyError::TypeMismatch),
1456        }
1457    }
1458
1459    /// `DynUnion::set_discriminator`: sets the discriminator to the value
1460    /// of `d` (`TypeMismatch` if its type is not equivalent to the
1461    /// discriminator type). The member it selects keeps its value if it
1462    /// was already active and gets its default value otherwise; the
1463    /// position becomes 1 if there is an active member, else 0.
1464    pub fn set_discriminator(&self, d: &DynAny) -> Result<()> {
1465        let t = self.expect(&[TCKind::Union])?;
1466        let disc_tc = t
1467            .discriminator_type()
1468            .map_err(|_| DynAnyError::TypeMismatch)?;
1469        let value = d.to_any()?;
1470        if !value.typecode().equivalent(&disc_tc) {
1471            return Err(DynAnyError::TypeMismatch);
1472        }
1473        self.set_disc_value(value.value().clone())
1474    }
1475
1476    fn set_disc_value(&self, value: Value) -> Result<()> {
1477        let disc = self.get_discriminator()?;
1478        *disc.lock() = State::Basic(value);
1479        self.sync_union();
1480        if let State::Union { member, pos, .. } = &mut *self.lock() {
1481            *pos = if member.is_some() { 1 } else { 0 };
1482        }
1483        Ok(())
1484    }
1485
1486    /// `DynUnion::set_to_default_member`: sets the discriminator to a
1487    /// value no label uses, which selects the default member.
1488    /// `TypeMismatch` if the union has no default member.
1489    pub fn set_to_default_member(&self) -> Result<()> {
1490        let t = self.expect(&[TCKind::Union])?;
1491        if t.default_index().unwrap_or(-1) < 0 {
1492            return Err(DynAnyError::TypeMismatch);
1493        }
1494        if self.is_default_selected(&t)? {
1495            if let State::Union { pos, .. } = &mut *self.lock() {
1496                *pos = 0;
1497            }
1498            return Ok(());
1499        }
1500        let value = unused_discriminator(&t).ok_or(DynAnyError::TypeMismatch)?;
1501        self.set_disc_value(value)?;
1502        if let State::Union { pos, .. } = &mut *self.lock() {
1503            *pos = 0;
1504        }
1505        Ok(())
1506    }
1507
1508    fn is_default_selected(&self, t: &TypeCode) -> Result<bool> {
1509        self.sync_union();
1510        let current = match &*self.lock() {
1511            State::Union { member, .. } => member.as_ref().map(|(i, _)| *i as i32),
1512            _ => None,
1513        };
1514        Ok(current.is_some() && current == t.default_index().ok())
1515    }
1516
1517    /// `DynUnion::set_to_no_active_member`: sets the discriminator to a
1518    /// value no label uses. `TypeMismatch` if the union has a default
1519    /// member or its labels use every value of the discriminator type.
1520    pub fn set_to_no_active_member(&self) -> Result<()> {
1521        let t = self.expect(&[TCKind::Union])?;
1522        if t.default_index().unwrap_or(-1) >= 0 {
1523            return Err(DynAnyError::TypeMismatch);
1524        }
1525        if !self.has_no_active_member()? {
1526            let value = unused_discriminator(&t).ok_or(DynAnyError::TypeMismatch)?;
1527            self.set_disc_value(value)?;
1528        }
1529        if let State::Union { pos, .. } = &mut *self.lock() {
1530            *pos = 0;
1531        }
1532        Ok(())
1533    }
1534
1535    /// `DynUnion::has_no_active_member`.
1536    pub fn has_no_active_member(&self) -> Result<bool> {
1537        self.expect(&[TCKind::Union])?;
1538        self.sync_union();
1539        Ok(matches!(&*self.lock(), State::Union { member: None, .. }))
1540    }
1541
1542    /// `DynUnion::discriminator_kind`: the kind of the discriminator
1543    /// type, aliases included.
1544    pub fn discriminator_kind(&self) -> Result<TCKind> {
1545        let t = self.expect(&[TCKind::Union])?;
1546        Ok(t.discriminator_type()
1547            .map_err(|_| DynAnyError::TypeMismatch)?
1548            .kind())
1549    }
1550
1551    fn active_member(&self) -> Result<(u32, DynAny)> {
1552        self.expect(&[TCKind::Union])?;
1553        self.sync_union();
1554        match &*self.lock() {
1555            State::Union {
1556                member: Some((i, m)),
1557                ..
1558            } => Ok((*i, m.clone())),
1559            _ => Err(DynAnyError::InvalidValue),
1560        }
1561    }
1562
1563    /// `DynUnion::member`: the active member. `InvalidValue` without one.
1564    pub fn member(&self) -> Result<DynAny> {
1565        Ok(self.active_member()?.1)
1566    }
1567
1568    /// `DynUnion::member_name`: the name of the active member.
1569    /// `InvalidValue` without one.
1570    pub fn member_name(&self) -> Result<String> {
1571        let (i, _) = self.active_member()?;
1572        Ok(self
1573            .unaliased()
1574            .member_name(i)
1575            .unwrap_or_default()
1576            .to_owned())
1577    }
1578
1579    /// `DynUnion::member_kind`: the kind of the type of the active member,
1580    /// aliases included. `InvalidValue` without one.
1581    pub fn member_kind(&self) -> Result<TCKind> {
1582        let (i, _) = self.active_member()?;
1583        Ok(member_type(&self.unaliased(), i)?.kind())
1584    }
1585
1586    // --- DynSequence and DynArray -------------------------------------------------
1587
1588    /// `DynSequence::get_length`.
1589    pub fn get_length(&self) -> Result<u32> {
1590        self.expect(&[TCKind::Sequence])?;
1591        self.component_count()
1592    }
1593
1594    /// `DynSequence::set_length`: new elements get their default value.
1595    /// When the sequence grows and there was no current position, the
1596    /// first new element becomes current; when it shrinks past the
1597    /// current position, the position becomes -1. Longer than the bound
1598    /// is `InvalidValue`.
1599    pub fn set_length(&self, len: u32) -> Result<()> {
1600        let t = self.expect(&[TCKind::Sequence])?;
1601        self.check_length(&t, len as usize)?;
1602        let content = content_type(&t)?;
1603        let old = self.component_count()? as usize;
1604        let mut new_items = Vec::new();
1605        for _ in old..len as usize {
1606            new_items.push(self.default_child(&content)?);
1607        }
1608        if let State::Items { items, pos } = &mut *self.lock() {
1609            let len = len as usize;
1610            if len < items.len() {
1611                items.truncate(len);
1612                if *pos >= len as i32 {
1613                    *pos = -1;
1614                }
1615            } else if len > items.len() {
1616                if *pos < 0 {
1617                    *pos = items.len() as i32;
1618                }
1619                items.extend(new_items);
1620            }
1621        }
1622        Ok(())
1623    }
1624
1625    /// `get_elements` of `DynSequence` and `DynArray`.
1626    pub fn get_elements(&self) -> Result<Vec<Any>> {
1627        self.get_elements_as_dyn_any()?
1628            .iter()
1629            .map(DynAny::to_any)
1630            .collect()
1631    }
1632
1633    /// `get_elements_as_dyn_any`: the components.
1634    pub fn get_elements_as_dyn_any(&self) -> Result<Vec<DynAny>> {
1635        self.expect(&[TCKind::Sequence, TCKind::Array])?;
1636        self.member_items()
1637    }
1638
1639    /// `set_elements` of `DynSequence` and `DynArray`: `TypeMismatch` if
1640    /// a value's type is not equivalent to the element type,
1641    /// `InvalidValue` if there are more than the bound of a sequence or
1642    /// not as many as an array has.
1643    pub fn set_elements(&self, values: &[Any]) -> Result<()> {
1644        let t = self.expect(&[TCKind::Sequence, TCKind::Array])?;
1645        let content = content_type(&t)?;
1646        if values.iter().any(|v| !v.typecode().equivalent(&content)) {
1647            return Err(DynAnyError::TypeMismatch);
1648        }
1649        self.check_length(&t, values.len())?;
1650        let items = values
1651            .iter()
1652            .map(|v| self.child(&content, v.value()))
1653            .collect::<Result<Vec<_>>>()
1654            .map_err(|_| DynAnyError::InvalidValue)?;
1655        *self.lock() = State::items(items);
1656        Ok(())
1657    }
1658
1659    /// `set_elements_as_dyn_any`: [`set_elements`](DynAny::set_elements)
1660    /// with the values of the DynAnys.
1661    pub fn set_elements_as_dyn_any(&self, values: &[DynAny]) -> Result<()> {
1662        let values = values
1663            .iter()
1664            .map(DynAny::to_any)
1665            .collect::<Result<Vec<_>>>()?;
1666        self.set_elements(&values)
1667    }
1668
1669    // --- DynValueCommon, DynValueBox -------------------------------------------------
1670
1671    const VALUES: [TCKind; 3] = [TCKind::Value, TCKind::ValueBox, TCKind::Event];
1672
1673    /// `DynValueCommon::is_null`.
1674    pub fn is_null(&self) -> Result<bool> {
1675        self.expect(&Self::VALUES)?;
1676        Ok(matches!(&*self.lock(), State::Value { members: None, .. }))
1677    }
1678
1679    /// `DynValueCommon::set_to_null`.
1680    pub fn set_to_null(&self) -> Result<()> {
1681        self.expect(&Self::VALUES)?;
1682        *self.lock() = State::value(None);
1683        Ok(())
1684    }
1685
1686    /// `DynValueCommon::set_to_value`: a `null` value gets members with
1687    /// their default values; a value that is not `null` is left as it is.
1688    pub fn set_to_value(&self) -> Result<()> {
1689        let t = self.expect(&Self::VALUES)?;
1690        if !self.is_null()? {
1691            return Ok(());
1692        }
1693        let members = state_types(&t)
1694            .iter()
1695            .map(|tc| self.default_child(tc))
1696            .collect::<Result<Vec<_>>>()?;
1697        *self.lock() = State::value(Some(members));
1698        Ok(())
1699    }
1700
1701    /// `DynValueBox::get_boxed_value`. `InvalidValue` if `null`.
1702    pub fn get_boxed_value(&self) -> Result<Any> {
1703        self.get_boxed_value_as_dyn_any()?.to_any()
1704    }
1705
1706    /// `DynValueBox::get_boxed_value_as_dyn_any`: the component.
1707    /// `InvalidValue` if `null`.
1708    pub fn get_boxed_value_as_dyn_any(&self) -> Result<DynAny> {
1709        self.expect(&[TCKind::ValueBox])?;
1710        match &*self.lock() {
1711            State::Value {
1712                members: Some(m), ..
1713            } => m.first().cloned().ok_or(DynAnyError::InvalidValue),
1714            _ => Err(DynAnyError::InvalidValue),
1715        }
1716    }
1717
1718    /// `DynValueBox::set_boxed_value`: `TypeMismatch` if the type of
1719    /// `value` is not equivalent to the boxed type. A `null` value box
1720    /// is no longer `null`.
1721    pub fn set_boxed_value(&self, value: &Any) -> Result<()> {
1722        let t = self.expect(&[TCKind::ValueBox])?;
1723        let content = content_type(&t)?;
1724        if !value.typecode().equivalent(&content) {
1725            return Err(DynAnyError::TypeMismatch);
1726        }
1727        let item = self
1728            .child(&content, value.value())
1729            .map_err(|_| DynAnyError::InvalidValue)?;
1730        *self.lock() = State::value(Some(vec![item]));
1731        Ok(())
1732    }
1733
1734    /// `DynValueBox::set_boxed_value_as_dyn_any`.
1735    pub fn set_boxed_value_as_dyn_any(&self, value: &DynAny) -> Result<()> {
1736        self.set_boxed_value(&value.to_any()?)
1737    }
1738}
1739
1740/// Whether the members `i` and `j` of the union `t` are one member with
1741/// several labels.
1742fn same_member(t: &TypeCode, i: u32, j: u32) -> bool {
1743    let (Ok(a), Ok(b)) = (t.member_name(i), t.member_name(j)) else {
1744        return false;
1745    };
1746    let (Ok(ta), Ok(tb)) = (t.member_type(i), t.member_type(j)) else {
1747        return false;
1748    };
1749    let (lo, hi) = (i.min(j), i.max(j));
1750    // The labels of one member are next to each other.
1751    !a.is_empty() && a == b && ta.equal(&tb) && (lo..=hi).all(|k| t.member_name(k) == Ok(a))
1752}
1753
1754/// The names of the state members of a valuetype, those of its base types
1755/// first, in the order of [`state_types`].
1756fn value_member_names(tc: &TypeCode) -> Vec<String> {
1757    let mut chain = vec![tc.clone()];
1758    while let Some(Some(base)) = chain.last().map(|t| t.concrete_base_type().ok().flatten()) {
1759        if chain.len() > MAX_DEPTH {
1760            break;
1761        }
1762        chain.push(base.unaliased());
1763    }
1764    chain
1765        .iter()
1766        .rev()
1767        .flat_map(|t| {
1768            (0..t.member_count().unwrap_or(0))
1769                .map(move |i| t.member_name(i).unwrap_or_default().to_owned())
1770        })
1771        .collect()
1772}
1773
1774/// Whether an instance of `actual` may be the value of a DynAny of type
1775/// `expected`: the same type or a type derived from it.
1776fn is_assignable_to(actual: &TypeCode, expected: &TypeCode) -> bool {
1777    let id = expected.id().unwrap_or_default();
1778    let mut t = Some(actual.unaliased());
1779    let mut n = 0;
1780    while let Some(tc) = t {
1781        if tc.id().unwrap_or_default() == id {
1782            return true;
1783        }
1784        n += 1;
1785        if n > MAX_DEPTH {
1786            break;
1787        }
1788        t = tc.concrete_base_type().ok().flatten();
1789    }
1790    false
1791}