zerodds-types 1.0.0-rc.4

OMG XTypes 1.3 type system: TypeIdentifier + TypeObject (Minimal/Complete) + Assignability + DynamicType + TypeLookup. Pure-Rust no_std + alloc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors
//! DynamicTypeBuilder + DynamicTypeBuilderFactory (XTypes 1.3 §7.5.4, §7.5.5).
//!
//! Spec behavior:
//! - `add_member` validates name and id immediately against existing
//!   members (spec §7.5.4.1.2 preconditions).
//! - `build()` validates the final structure (inheritance cycle,
//!   mandatory discriminator, etc.) and returns an immutable
//!   `DynamicType`.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, Ordering};

use super::descriptor::{MemberDescriptor, MemberId, TypeDescriptor, TypeKind};
use super::error::DynamicError;
use super::type_::{DynamicType, DynamicTypeInner, DynamicTypeMember, primitive_name};

/// XTypes §7.5.4 DynamicTypeBuilder.
#[derive(Debug)]
pub struct DynamicTypeBuilder {
    descriptor: TypeDescriptor,
    members: Vec<DynamicTypeMember>,
    sealed: AtomicBool,
}

impl DynamicTypeBuilder {
    /// Internal — the factory creates builders.
    pub(super) fn new(descriptor: TypeDescriptor) -> Self {
        Self {
            descriptor,
            members: Vec::new(),
            sealed: AtomicBool::new(false),
        }
    }

    /// Current descriptor (read-only view).
    #[must_use]
    pub fn descriptor(&self) -> &TypeDescriptor {
        &self.descriptor
    }

    /// Sets the descriptor anew (spec §7.5.4.1 SetDescriptor) — only
    /// allowed before `build()`.
    ///
    /// # Errors
    /// `PreconditionNotMet` if `build()` was already called.
    pub fn set_descriptor(&mut self, descriptor: TypeDescriptor) -> Result<(), DynamicError> {
        if self.sealed.load(Ordering::Acquire) {
            return Err(DynamicError::PreconditionNotMet(String::from(
                "set_descriptor after build()",
            )));
        }
        descriptor
            .is_consistent()
            .map_err(DynamicError::inconsistent)?;
        self.descriptor = descriptor;
        Ok(())
    }

    /// Adds a member (spec §7.5.4.1.2 AddMember).
    ///
    /// Validates immediately:
    /// - Unique name among the existing members.
    /// - Unique id (only when composite XCDR2-capable).
    /// - The member type is consistent.
    /// - The kind allows members.
    ///
    /// `index` is set automatically if the caller leaves it at 0,
    /// otherwise respected.
    ///
    /// # Errors
    /// `BuilderConflict` on a dup name/id, `IllegalOperation` if the
    /// kind carries no members.
    pub fn add_member(&mut self, mut descriptor: MemberDescriptor) -> Result<(), DynamicError> {
        if self.sealed.load(Ordering::Acquire) {
            return Err(DynamicError::PreconditionNotMet(String::from(
                "add_member after build()",
            )));
        }
        if !self.descriptor.kind.is_aggregable() {
            return Err(DynamicError::IllegalOperation(alloc::format!(
                "add_member on non-composite kind {:?}",
                self.descriptor.kind
            )));
        }
        descriptor
            .is_consistent()
            .map_err(DynamicError::inconsistent)?;

        // Dup-Name-Check.
        if self
            .members
            .iter()
            .any(|m| m.descriptor.name == descriptor.name)
        {
            return Err(DynamicError::builder(alloc::format!(
                "duplicate member name {}",
                descriptor.name
            )));
        }
        // Dup-Id-Check.
        if self
            .members
            .iter()
            .any(|m| m.descriptor.id == descriptor.id)
        {
            return Err(DynamicError::builder(alloc::format!(
                "duplicate member id {}",
                descriptor.id
            )));
        }
        // Auto-index if the caller leaves index=0 for all (the default pattern).
        let auto_index = u32::try_from(self.members.len()).unwrap_or(u32::MAX);
        if descriptor.index == 0 && auto_index != 0 {
            descriptor.index = auto_index;
        } else if descriptor.index == 0 {
            descriptor.index = 0; // erster Member bleibt 0
        }
        // Member-Type bauen.
        let member_type =
            DynamicType::from_inner(descriptor_to_dynamic_type_inner(&descriptor.member_type)?);
        self.members.push(DynamicTypeMember {
            descriptor,
            member_type,
        });
        Ok(())
    }

    /// Adds a member whose type is a fully-resolved `DynamicType` instead of
    /// being (shallowly) reconstructed from `descriptor.member_type`. Used by
    /// the TypeObject → DynamicType bridge to attach a recursively-resolved
    /// nested composite (struct/union/enum) member type — `add_member` would
    /// otherwise rebuild it from the member's shallow `TypeDescriptor` and lose
    /// the nested members. Runs the same validity checks as [`add_member`].
    ///
    /// # Errors
    /// `PreconditionNotMet` after `build()`, `IllegalOperation` on a
    /// non-composite, `Inconsistent`/`Builder` on a malformed or duplicate member.
    pub fn add_member_resolved(
        &mut self,
        mut descriptor: MemberDescriptor,
        member_type: DynamicType,
    ) -> Result<(), DynamicError> {
        if self.sealed.load(Ordering::Acquire) {
            return Err(DynamicError::PreconditionNotMet(String::from(
                "add_member after build()",
            )));
        }
        if !self.descriptor.kind.is_aggregable() {
            return Err(DynamicError::IllegalOperation(alloc::format!(
                "add_member on non-composite kind {:?}",
                self.descriptor.kind
            )));
        }
        descriptor
            .is_consistent()
            .map_err(DynamicError::inconsistent)?;
        if self
            .members
            .iter()
            .any(|m| m.descriptor.name == descriptor.name)
        {
            return Err(DynamicError::builder(alloc::format!(
                "duplicate member name {}",
                descriptor.name
            )));
        }
        if self
            .members
            .iter()
            .any(|m| m.descriptor.id == descriptor.id)
        {
            return Err(DynamicError::builder(alloc::format!(
                "duplicate member id {}",
                descriptor.id
            )));
        }
        let auto_index = u32::try_from(self.members.len()).unwrap_or(u32::MAX);
        if descriptor.index == 0 && auto_index != 0 {
            descriptor.index = auto_index;
        }
        self.members.push(DynamicTypeMember {
            descriptor,
            member_type,
        });
        Ok(())
    }

    /// Convenience wrapper for structs.
    ///
    /// # Errors
    /// See [`add_member`].
    pub fn add_struct_member(
        &mut self,
        name: impl Into<String>,
        id: MemberId,
        ty: TypeDescriptor,
    ) -> Result<(), DynamicError> {
        let mut d = MemberDescriptor::new(name, id, ty);
        d.index = u32::try_from(self.members.len()).unwrap_or(u32::MAX);
        self.add_member(d)
    }

    /// Spec §7.5.4.1.1 Build — finalizes the builder.
    ///
    /// Validations:
    /// - all member descriptors consistent
    /// - inheritance cycle via names
    /// - union: discriminator + at least 1 case
    /// - unique labels in a union
    ///
    /// # Errors
    /// `BuilderConflict` / `Inconsistent`.
    pub fn build(&self) -> Result<DynamicType, DynamicError> {
        if self.sealed.swap(true, Ordering::AcqRel) {
            return Err(DynamicError::PreconditionNotMet(String::from(
                "build() called twice",
            )));
        }
        self.descriptor
            .is_consistent()
            .map_err(DynamicError::inconsistent)?;
        // Cycle check via names — robust for the common case.
        if let Some(b) = &self.descriptor.base_type {
            check_inheritance_chain(&self.descriptor.name, b)?;
        }
        // Union-specific checks.
        if self.descriptor.kind == TypeKind::Union {
            if self.members.is_empty() {
                return Err(DynamicError::builder(
                    "union without case members".to_string(),
                ));
            }
            let mut seen_labels: BTreeMap<i64, &str> = BTreeMap::new();
            let mut default_count = 0_u32;
            for m in &self.members {
                if m.descriptor.is_default_label {
                    default_count += 1;
                }
                for label in &m.descriptor.label {
                    if let Some(prev) = seen_labels.insert(*label, &m.descriptor.name) {
                        return Err(DynamicError::builder(alloc::format!(
                            "duplicate union label {label} (prev member: {prev})"
                        )));
                    }
                }
            }
            if default_count > 1 {
                return Err(DynamicError::builder(
                    "union with multiple default-label members",
                ));
            }
        }
        let inner = DynamicTypeInner {
            descriptor: self.descriptor.clone(),
            members: self.members.clone(),
        };
        Ok(DynamicType {
            inner: Arc::new(inner),
        })
    }
}

/// Walk through the base_type chain — if a name appears twice, it is a
/// cycle. Depth is capped at 64 (DoS cap).
fn check_inheritance_chain(self_name: &str, base: &TypeDescriptor) -> Result<(), DynamicError> {
    let mut seen: alloc::vec::Vec<&str> = alloc::vec![self_name];
    let mut cur = base;
    let mut depth = 0_usize;
    loop {
        if depth >= 64 {
            return Err(DynamicError::builder("inheritance chain exceeds 64 levels"));
        }
        if seen.iter().any(|n| *n == cur.name) {
            return Err(DynamicError::builder(alloc::format!(
                "inheritance cycle through '{}'",
                cur.name
            )));
        }
        seen.push(&cur.name);
        depth += 1;
        if let Some(b) = &cur.base_type {
            cur = b;
        } else {
            return Ok(());
        }
    }
}

/// Constructs a `DynamicTypeInner` from a `TypeDescriptor` (no
/// add_member cycle — members are derived recursively from
/// `descriptor.bound`/`element_type`/`key_element_type`, but are not in
/// the `members` vec, because that only applies to composite types with
/// named members).
pub(super) fn descriptor_to_dynamic_type_inner(
    desc: &TypeDescriptor,
) -> Result<DynamicTypeInner, DynamicError> {
    desc.is_consistent().map_err(DynamicError::inconsistent)?;
    Ok(DynamicTypeInner {
        descriptor: desc.clone(),
        members: Vec::new(),
    })
}

/// XTypes §7.5.5 DynamicTypeBuilderFactory — Singleton im Spec-Sinne.
///
/// Stateless: no global caches except the primitive singleton pool,
/// which is lazily initialized via `OnceLock`.
pub struct DynamicTypeBuilderFactory;

impl DynamicTypeBuilderFactory {
    /// Spec §7.5.5.1.1 `create_type(descriptor)`.
    ///
    /// # Errors
    /// `Inconsistent` if the descriptor is invalid.
    pub fn create_type(descriptor: TypeDescriptor) -> Result<DynamicTypeBuilder, DynamicError> {
        descriptor
            .is_consistent()
            .map_err(DynamicError::inconsistent)?;
        Ok(DynamicTypeBuilder::new(descriptor))
    }

    /// Convenience variant: creates a struct builder directly.
    #[must_use]
    pub fn create_struct(name: impl Into<String>) -> DynamicTypeBuilder {
        DynamicTypeBuilder::new(TypeDescriptor::structure(name))
    }

    /// Convenience variant: creates a union builder directly with the
    /// given discriminator type.
    ///
    /// # Errors
    /// `Inconsistent` if the discriminator is not permitted.
    pub fn create_union(
        name: impl Into<String>,
        discriminator: TypeDescriptor,
    ) -> Result<DynamicTypeBuilder, DynamicError> {
        let desc = TypeDescriptor::union(name, discriminator);
        Self::create_type(desc)
    }

    /// Spec §7.5.5.1.2 `get_primitive_type(kind)` — Singleton-Cache.
    ///
    /// Repeated calls with the same `kind` return the same
    /// `DynamicType` instance (same `Arc` pointer).
    ///
    /// # Errors
    /// `IllegalOperation` if `kind` is not a primitive.
    pub fn get_primitive_type(kind: TypeKind) -> Result<DynamicType, DynamicError> {
        if !kind.is_primitive() {
            return Err(DynamicError::IllegalOperation(alloc::format!(
                "get_primitive_type called with non-primitive {kind:?}"
            )));
        }
        Ok(primitive_singleton(kind))
    }

    /// Spec §7.5.5.1.3 `create_string_type(bound)` — bounded `string<N>`.
    #[must_use]
    pub fn create_string_type(bound: u32) -> DynamicType {
        DynamicType::from_inner(DynamicTypeInner {
            descriptor: TypeDescriptor::string8(bound),
            members: Vec::new(),
        })
    }

    /// Spec §7.5.5.1.4 `create_wstring_type(bound)`.
    #[must_use]
    pub fn create_wstring_type(bound: u32) -> DynamicType {
        DynamicType::from_inner(DynamicTypeInner {
            descriptor: TypeDescriptor::string16(bound),
            members: Vec::new(),
        })
    }
}

// ----------------------------------------------------------------------
// Primitive-Singleton-Cache
// ----------------------------------------------------------------------

#[cfg(feature = "std")]
fn primitive_singleton(kind: TypeKind) -> DynamicType {
    use std::sync::OnceLock;
    type Cell = OnceLock<DynamicType>;
    macro_rules! cell {
        () => {{
            static C: Cell = OnceLock::new();
            &C
        }};
    }
    let cell: &Cell = match kind {
        TypeKind::Boolean => cell!(),
        TypeKind::Byte => cell!(),
        TypeKind::Int8 => cell!(),
        TypeKind::UInt8 => cell!(),
        TypeKind::Int16 => cell!(),
        TypeKind::UInt16 => cell!(),
        TypeKind::Int32 => cell!(),
        TypeKind::UInt32 => cell!(),
        TypeKind::Int64 => cell!(),
        TypeKind::UInt64 => cell!(),
        TypeKind::Float32 => cell!(),
        TypeKind::Float64 => cell!(),
        TypeKind::Float128 => cell!(),
        TypeKind::Char8 => cell!(),
        TypeKind::Char16 => cell!(),
        // Defensive fallback for non-primitive kinds: build anew on each
        // call — the singleton property only holds for primitives, as
        // the spec caller in `get_primitive_type` validates.
        _ => {
            return DynamicType::from_inner(DynamicTypeInner {
                descriptor: TypeDescriptor::primitive(
                    kind,
                    alloc::string::String::from(primitive_name(kind)),
                ),
                members: Vec::new(),
            });
        }
    };
    cell.get_or_init(|| {
        DynamicType::from_inner(DynamicTypeInner {
            descriptor: TypeDescriptor::primitive(
                kind,
                alloc::string::String::from(primitive_name(kind)),
            ),
            members: Vec::new(),
        })
    })
    .clone()
}

#[cfg(not(feature = "std"))]
fn primitive_singleton(kind: TypeKind) -> DynamicType {
    // no_std path: no OnceLock — we build anew each time. The singleton
    // property is thus structural (same content) instead of
    // identity-based.
    DynamicType::from_inner(DynamicTypeInner {
        descriptor: TypeDescriptor::primitive(
            kind,
            alloc::string::String::from(primitive_name(kind)),
        ),
        members: Vec::new(),
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn create_type_rejects_invalid_descriptor() {
        let mut bad = TypeDescriptor::structure("");
        bad.kind = TypeKind::Structure;
        let err = DynamicTypeBuilderFactory::create_type(bad).unwrap_err();
        assert!(matches!(err, DynamicError::Inconsistent(_)));
    }

    #[test]
    fn add_member_rejects_duplicate_name() {
        let mut b = DynamicTypeBuilderFactory::create_struct("::S");
        b.add_struct_member("a", 1, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap();
        let err = b
            .add_struct_member("a", 2, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap_err();
        assert!(matches!(err, DynamicError::BuilderConflict(_)));
    }

    #[test]
    fn add_member_rejects_duplicate_id() {
        let mut b = DynamicTypeBuilderFactory::create_struct("::S");
        b.add_struct_member("a", 5, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap();
        let err = b
            .add_struct_member("b", 5, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap_err();
        assert!(matches!(err, DynamicError::BuilderConflict(_)));
    }

    #[test]
    fn add_member_on_primitive_is_illegal() {
        let mut b = DynamicTypeBuilder::new(TypeDescriptor::primitive(TypeKind::Int32, "int32"));
        let err = b
            .add_struct_member("x", 1, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap_err();
        assert!(matches!(err, DynamicError::IllegalOperation(_)));
    }

    #[test]
    fn build_twice_rejected() {
        let b = DynamicTypeBuilderFactory::create_struct("::S");
        let _ = b.build().unwrap();
        let err = b.build().unwrap_err();
        assert!(matches!(err, DynamicError::PreconditionNotMet(_)));
    }

    #[test]
    fn primitive_singleton_returns_same_arc() {
        let a = DynamicTypeBuilderFactory::get_primitive_type(TypeKind::Int32).unwrap();
        let b = DynamicTypeBuilderFactory::get_primitive_type(TypeKind::Int32).unwrap();
        // same Arc pointer (singleton).
        assert!(Arc::ptr_eq(&a.inner, &b.inner));
    }

    #[test]
    fn primitive_singleton_rejects_non_primitive() {
        assert!(matches!(
            DynamicTypeBuilderFactory::get_primitive_type(TypeKind::Structure),
            Err(DynamicError::IllegalOperation(_))
        ));
    }

    #[test]
    fn union_build_requires_at_least_one_member() {
        let disc = TypeDescriptor::primitive(TypeKind::Int32, "int32");
        let b = DynamicTypeBuilderFactory::create_union("::U", disc).unwrap();
        let err = b.build().unwrap_err();
        assert!(matches!(err, DynamicError::BuilderConflict(_)));
    }

    #[test]
    fn union_duplicate_label_rejected() {
        let disc = TypeDescriptor::primitive(TypeKind::Int32, "int32");
        let mut b = DynamicTypeBuilderFactory::create_union("::U", disc).unwrap();
        let mut a =
            MemberDescriptor::new("a", 1, TypeDescriptor::primitive(TypeKind::Int32, "int32"));
        a.label = alloc::vec![1, 2];
        b.add_member(a).unwrap();
        let mut c =
            MemberDescriptor::new("c", 2, TypeDescriptor::primitive(TypeKind::Int32, "int32"));
        c.label = alloc::vec![2, 3];
        b.add_member(c).unwrap();
        let err = b.build().unwrap_err();
        assert!(matches!(err, DynamicError::BuilderConflict(_)));
    }

    #[test]
    fn build_simple_struct_with_three_members() {
        let mut b = DynamicTypeBuilderFactory::create_struct("::S");
        b.add_struct_member("a", 1, TypeDescriptor::primitive(TypeKind::Int32, "int32"))
            .unwrap();
        b.add_struct_member("b", 2, TypeDescriptor::primitive(TypeKind::Int64, "int64"))
            .unwrap();
        b.add_struct_member("c", 3, TypeDescriptor::string8(64))
            .unwrap();
        let t = b.build().unwrap();
        assert_eq!(t.member_count(), 3);
        assert_eq!(t.member_by_name("b").unwrap().id(), 2);
        assert_eq!(t.member_by_id(3).unwrap().name(), "c");
        assert_eq!(t.member_by_index(0).unwrap().name(), "a");
    }
}