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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors
//! TypeLookup Service IDL (XTypes 1.3 ยง7.6.3.3).
//!
//! This is a DDS-RPC service with two operations:
//! - `getTypes(TypeIdentifier[])` โ†’ `TypeObject[]` (Minimal/Complete)
//! - `getTypeDependencies(TypeIdentifier[], continuation_point)`
//!   โ†’ `TypeIdentifierWithSize[] + continuation_point`
//!
//! We define the IDL structures manually. A future
//! `zerodds-idlc` codegen will generate these directly from the OMG-IDL
//! snippet.

use alloc::vec::Vec;

use zerodds_cdr::{BufferReader, BufferWriter, EncodeError};

use crate::error::TypeCodecError;
use crate::type_identifier::TypeIdentifier;
use crate::type_information::TypeIdentifierWithSize;
use crate::type_object::common::{decode_seq, encode_seq};
use crate::type_object::{CompleteTypeObject, MinimalTypeObject};

// ============================================================================
// getTypes
// ============================================================================

/// Request for `TypeLookup::getTypes`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GetTypesRequest {
    /// Requested TypeIdentifiers (typically EK_MINIMAL/EK_COMPLETE).
    pub type_ids: Vec<TypeIdentifier>,
}

impl GetTypesRequest {
    /// Encode.
    ///
    /// # Errors
    /// Buffer overflow.
    pub fn encode_into(&self, w: &mut BufferWriter) -> Result<(), EncodeError> {
        encode_seq(w, &self.type_ids, |w, t| t.encode_into(w))
    }

    /// Decode.
    ///
    /// # Errors
    /// Buffer underflow.
    pub fn decode_from(r: &mut BufferReader<'_>) -> Result<Self, TypeCodecError> {
        let type_ids = decode_seq(r, |rr| {
            TypeIdentifier::decode_from(rr).map_err(|e| zerodds_cdr::DecodeError::InvalidString {
                offset: 0,
                reason: match e {
                    zerodds_cdr::DecodeError::UnexpectedEof { .. } => "eof",
                    _ => "decode",
                },
            })
        })?;
        Ok(Self { type_ids })
    }
}

/// A getTypes reply item: a TypeObject (Minimal or Complete).
/// The kind is discriminated in the first byte of the serialized form
/// (see [`crate::type_object::TypeObject`]).
///
/// Variant size as [`crate::type_object::TypeObject`] โ€” boxing the
/// `Complete` variant would be a micro-optimization requiring a refactor
/// at many call sites; ReplyTypeObject lives on the TypeLookup reply
/// path, not on the sample hot path.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplyTypeObject {
    /// Minimal variant.
    Minimal(MinimalTypeObject),
    /// Complete variant.
    Complete(CompleteTypeObject),
}

/// Reply for `TypeLookup::getTypes`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GetTypesReply {
    /// List of the returned TypeObjects. Not-found ones are
    /// typically omitted; the caller must match by TypeIdentifier
    /// (via the hash).
    pub types: Vec<ReplyTypeObject>,
}

impl GetTypesReply {
    /// Encode as sequence<TypeObject>.
    ///
    /// # Errors
    /// Buffer overflow.
    pub fn encode_into(&self, w: &mut BufferWriter) -> Result<(), EncodeError> {
        encode_seq(w, &self.types, |w, t| match t {
            ReplyTypeObject::Minimal(m) => {
                crate::type_object::TypeObject::Minimal(m.clone()).encode_into(w)
            }
            ReplyTypeObject::Complete(c) => {
                crate::type_object::TypeObject::Complete(c.clone()).encode_into(w)
            }
        })
    }

    /// Decode.
    ///
    /// # Errors
    /// Buffer underflow / unknown TypeKind.
    pub fn decode_from(r: &mut BufferReader<'_>) -> Result<Self, TypeCodecError> {
        let n = r.read_u32()? as usize;
        // DoS cap: a malicious peer must not make us allocate GB of RAM
        // with `u32::MAX` type objects. `safe_capacity` caps
        // to still-readable bytes / min-elem-size (1 byte per TypeObject
        // as a conservative lower bound โ€” a real TypeObject is
        // at least ~20 bytes).
        let cap = crate::type_object::common::safe_capacity(n, 1, r.remaining());
        let mut types = Vec::with_capacity(cap);
        for _ in 0..n {
            let to = crate::type_object::TypeObject::decode_from(r)?;
            types.push(match to {
                crate::type_object::TypeObject::Minimal(m) => ReplyTypeObject::Minimal(m),
                crate::type_object::TypeObject::Complete(c) => ReplyTypeObject::Complete(c),
            });
        }
        Ok(Self { types })
    }
}

// ============================================================================
// getTypeDependencies
// ============================================================================

/// Opaque continuation point for paginated dependency lists.
/// XTypes spec ยง7.6.3.3.3 allows up to 32 bytes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContinuationPoint(pub Vec<u8>);

impl ContinuationPoint {
    /// Maximum length (ยง7.6.3.3.3).
    pub const MAX_LEN: usize = 32;

    /// Encode as a fixed-length octet[32] โ€” we encode it as a
    /// sequence<octet> for simplicity (the spec allows both via
    /// @bound; most implementations use sequence).
    ///
    /// # Errors
    /// Buffer overflow.
    pub fn encode_into(&self, w: &mut BufferWriter) -> Result<(), EncodeError> {
        let len = u32::try_from(self.0.len().min(Self::MAX_LEN)).unwrap_or(Self::MAX_LEN as u32);
        w.write_u32(len)?;
        w.write_bytes(&self.0[..len as usize])
    }

    /// Decode.
    ///
    /// # Errors
    /// Buffer underflow / length > MAX_LEN.
    pub fn decode_from(r: &mut BufferReader<'_>) -> Result<Self, TypeCodecError> {
        let len = r.read_u32()? as usize;
        if len > Self::MAX_LEN {
            return Err(TypeCodecError::UnknownTypeKind { kind: 0 });
        }
        Ok(Self(r.read_bytes(len)?.to_vec()))
    }
}

/// Request for `TypeLookup::getTypeDependencies`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GetTypeDependenciesRequest {
    /// TypeIds whose dependencies we need.
    pub type_ids: Vec<TypeIdentifier>,
    /// Continuation point from the previous reply (empty on the first request).
    pub continuation_point: ContinuationPoint,
}

impl GetTypeDependenciesRequest {
    /// Encode.
    ///
    /// # Errors
    /// Buffer overflow.
    pub fn encode_into(&self, w: &mut BufferWriter) -> Result<(), EncodeError> {
        encode_seq(w, &self.type_ids, |w, t| t.encode_into(w))?;
        self.continuation_point.encode_into(w)
    }

    /// Decode.
    ///
    /// # Errors
    /// Buffer underflow.
    pub fn decode_from(r: &mut BufferReader<'_>) -> Result<Self, TypeCodecError> {
        let type_ids = decode_seq(r, |rr| {
            TypeIdentifier::decode_from(rr).map_err(|_| zerodds_cdr::DecodeError::InvalidString {
                offset: 0,
                reason: "type_id",
            })
        })?;
        let continuation_point = ContinuationPoint::decode_from(r)?;
        Ok(Self {
            type_ids,
            continuation_point,
        })
    }
}

/// Reply for `TypeLookup::getTypeDependencies`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GetTypeDependenciesReply {
    /// Dependencies.
    pub dependent_typeids: Vec<TypeIdentifierWithSize>,
    /// Continuation point (empty = end).
    pub continuation_point: ContinuationPoint,
}

impl GetTypeDependenciesReply {
    /// Encode.
    ///
    /// # Errors
    /// Buffer overflow.
    pub fn encode_into(&self, w: &mut BufferWriter) -> Result<(), EncodeError> {
        encode_seq(w, &self.dependent_typeids, |w, t| t.encode_into(w))?;
        self.continuation_point.encode_into(w)
    }

    /// Decode.
    ///
    /// # Errors
    /// Buffer underflow.
    pub fn decode_from(r: &mut BufferReader<'_>) -> Result<Self, TypeCodecError> {
        let dependent_typeids = decode_seq(r, |rr| {
            TypeIdentifierWithSize::decode_from(rr).map_err(|_| {
                zerodds_cdr::DecodeError::InvalidString {
                    offset: 0,
                    reason: "ti_size",
                }
            })
        })?;
        let continuation_point = ContinuationPoint::decode_from(r)?;
        Ok(Self {
            dependent_typeids,
            continuation_point,
        })
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::type_identifier::{EquivalenceHash, PrimitiveKind};
    use zerodds_cdr::{BufferReader, BufferWriter, Endianness};

    fn roundtrip_get_types_request(req: GetTypesRequest) {
        let mut w = BufferWriter::new(Endianness::Little);
        req.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypesRequest::decode_from(&mut r).unwrap();
        assert_eq!(decoded, req);
    }

    #[test]
    fn get_types_request_roundtrips() {
        roundtrip_get_types_request(GetTypesRequest {
            type_ids: alloc::vec![
                TypeIdentifier::EquivalenceHashMinimal(EquivalenceHash([0x01; 14])),
                TypeIdentifier::Primitive(PrimitiveKind::Int64),
            ],
        });
    }

    #[test]
    fn continuation_point_roundtrip_and_max_len() {
        let cp = ContinuationPoint(alloc::vec![0x11, 0x22, 0x33]);
        let mut w = BufferWriter::new(Endianness::Little);
        cp.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        assert_eq!(ContinuationPoint::decode_from(&mut r).unwrap(), cp);

        // MAX_LEN clamp
        let oversized = ContinuationPoint(alloc::vec![0xFF; 64]);
        let mut w = BufferWriter::new(Endianness::Little);
        oversized.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = ContinuationPoint::decode_from(&mut r).unwrap();
        assert_eq!(decoded.0.len(), ContinuationPoint::MAX_LEN);
    }

    #[test]
    fn get_types_reply_roundtrip_with_mixed_minimal_and_complete() {
        use crate::builder::TypeObjectBuilder;
        let min = MinimalTypeObject::Struct(
            TypeObjectBuilder::struct_type("::X")
                .member("a", TypeIdentifier::Primitive(PrimitiveKind::Int32), |m| m)
                .build_minimal(),
        );
        let com = CompleteTypeObject::Struct(
            TypeObjectBuilder::struct_type("::X")
                .member("a", TypeIdentifier::Primitive(PrimitiveKind::Int32), |m| m)
                .build_complete(),
        );
        let reply = GetTypesReply {
            types: alloc::vec![
                ReplyTypeObject::Minimal(min),
                ReplyTypeObject::Complete(com),
            ],
        };
        let mut w = BufferWriter::new(Endianness::Little);
        reply.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypesReply::decode_from(&mut r).unwrap();
        assert_eq!(decoded.types.len(), 2);
    }

    #[test]
    fn continuation_point_too_large_on_decode_rejected() {
        // u32 length > MAX_LEN โ†’ UnknownTypeKind (placeholder for
        // "length out of range"; a matching error variant follows.)
        let mut w = BufferWriter::new(Endianness::Little);
        w.write_u32(100).unwrap(); // > MAX_LEN=32
        w.write_bytes(&[0u8; 100]).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let err = ContinuationPoint::decode_from(&mut r).unwrap_err();
        assert!(matches!(err, TypeCodecError::UnknownTypeKind { .. }));
    }

    #[test]
    fn get_type_dependencies_request_reply_roundtrip() {
        let req = GetTypeDependenciesRequest {
            type_ids: alloc::vec![TypeIdentifier::EquivalenceHashMinimal(EquivalenceHash(
                [0xAA; 14]
            ))],
            continuation_point: ContinuationPoint::default(),
        };
        let mut w = BufferWriter::new(Endianness::Little);
        req.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        assert_eq!(
            GetTypeDependenciesRequest::decode_from(&mut r).unwrap(),
            req
        );

        let reply = GetTypeDependenciesReply {
            dependent_typeids: alloc::vec![TypeIdentifierWithSize {
                type_id: TypeIdentifier::EquivalenceHashMinimal(EquivalenceHash([0xBB; 14])),
                typeobject_serialized_size: 128,
            }],
            continuation_point: ContinuationPoint(alloc::vec![0x42]),
        };
        let mut w = BufferWriter::new(Endianness::Little);
        reply.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        assert_eq!(
            GetTypeDependenciesReply::decode_from(&mut r).unwrap(),
            reply
        );
    }

    // ---- Edge cases for empty and boundary sequences --------------------

    #[test]
    fn empty_get_types_request_roundtrips() {
        roundtrip_get_types_request(GetTypesRequest::default());
    }

    #[test]
    fn empty_get_types_reply_roundtrips() {
        let reply = GetTypesReply::default();
        let mut w = BufferWriter::new(Endianness::Little);
        reply.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypesReply::decode_from(&mut r).unwrap();
        assert_eq!(decoded.types.len(), 0);
        assert_eq!(decoded, reply);
    }

    #[test]
    fn empty_get_type_dependencies_request_roundtrips() {
        let req = GetTypeDependenciesRequest::default();
        let mut w = BufferWriter::new(Endianness::Little);
        req.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypeDependenciesRequest::decode_from(&mut r).unwrap();
        assert!(decoded.type_ids.is_empty());
        assert!(decoded.continuation_point.0.is_empty());
        assert_eq!(decoded, req);
    }

    #[test]
    fn empty_get_type_dependencies_reply_roundtrips() {
        let reply = GetTypeDependenciesReply::default();
        let mut w = BufferWriter::new(Endianness::Little);
        reply.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypeDependenciesReply::decode_from(&mut r).unwrap();
        assert!(decoded.dependent_typeids.is_empty());
        assert!(decoded.continuation_point.0.is_empty());
    }

    #[test]
    fn continuation_point_len_zero_encodes_to_four_zero_bytes() {
        let cp = ContinuationPoint(alloc::vec![]);
        let mut w = BufferWriter::new(Endianness::Little);
        cp.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        // length prefix only, no payload.
        assert_eq!(bytes, alloc::vec![0, 0, 0, 0]);
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        assert_eq!(ContinuationPoint::decode_from(&mut r).unwrap(), cp);
    }

    #[test]
    fn continuation_point_len_max_roundtrips() {
        let cp = ContinuationPoint(alloc::vec![0xAB; ContinuationPoint::MAX_LEN]);
        let mut w = BufferWriter::new(Endianness::Little);
        cp.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = ContinuationPoint::decode_from(&mut r).unwrap();
        assert_eq!(decoded.0.len(), ContinuationPoint::MAX_LEN);
        assert_eq!(decoded, cp);
    }

    #[test]
    fn continuation_point_len_max_plus_one_on_decode_rejected() {
        let mut w = BufferWriter::new(Endianness::Little);
        w.write_u32((ContinuationPoint::MAX_LEN + 1) as u32)
            .unwrap();
        w.write_bytes(&[0u8; 33]).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let err = ContinuationPoint::decode_from(&mut r).unwrap_err();
        assert!(matches!(err, TypeCodecError::UnknownTypeKind { .. }));
    }

    #[test]
    fn reply_type_object_minimal_and_complete_serialize_distinct_discriminator() {
        use crate::builder::TypeObjectBuilder;
        let min = ReplyTypeObject::Minimal(MinimalTypeObject::Struct(
            TypeObjectBuilder::struct_type("::X")
                .member("a", TypeIdentifier::Primitive(PrimitiveKind::Int32), |m| m)
                .build_minimal(),
        ));
        let com = ReplyTypeObject::Complete(crate::type_object::CompleteTypeObject::Struct(
            TypeObjectBuilder::struct_type("::X")
                .member("a", TypeIdentifier::Primitive(PrimitiveKind::Int32), |m| m)
                .build_complete(),
        ));
        let reply = GetTypesReply {
            types: alloc::vec![min, com],
        };
        let mut w = BufferWriter::new(Endianness::Little);
        reply.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        // First 4 bytes are the sequence length = 2.
        assert_eq!(&bytes[..4], &[2, 0, 0, 0]);
        // Round-trip yields same variants order.
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        let decoded = GetTypesReply::decode_from(&mut r).unwrap();
        assert!(matches!(decoded.types[0], ReplyTypeObject::Minimal(_)));
        assert!(matches!(decoded.types[1], ReplyTypeObject::Complete(_)));
    }

    #[test]
    fn get_type_dependencies_request_with_continuation_payload_roundtrips() {
        let req = GetTypeDependenciesRequest {
            type_ids: alloc::vec![],
            continuation_point: ContinuationPoint(alloc::vec![0xDE, 0xAD, 0xBE, 0xEF]),
        };
        let mut w = BufferWriter::new(Endianness::Little);
        req.encode_into(&mut w).unwrap();
        let bytes = w.into_bytes();
        let mut r = BufferReader::new(&bytes, Endianness::Little);
        assert_eq!(
            GetTypeDependenciesRequest::decode_from(&mut r).unwrap(),
            req
        );
    }
}