rustorb-dds-ffi 0.2.0

Stable C ABI of rustorb-dds, used by its C++ and Java bindings
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! Topic types (`rdds_type`), built bottom-up: primitives, strings and
//! collections from their parts, and enums, bitmasks, bitsets, structs
//! and unions with builders that take one literal, field or member at a
//! time (DDS-XTypes 1.3, 7.5.2.2 `DynamicTypeBuilder`).
//!
//! A recursive type is built with a forward declaration
//! (`rdds_type_forward`) used where the type is used inside itself (in a
//! sequence, a map or an optional member), then defined as the type once
//! that is built (`rdds_type_define`). The defined type is the one to
//! use for a topic.
//!
//! Every function that makes a type copies what it is given; the caller
//! keeps and releases its own handles.

use std::ffi::c_char;
use std::sync::Arc;

use rustorb_dds::DynamicType;
use rustorb_xtypes::type_object::{AppliedBuiltinMemberAnnotations, TypeIdentifier};
use rustorb_xtypes::types::*;

use crate::{Res, Status, bad, cstr, guard, obj, put, release, slice};

/// `rdds_type`.
pub type RddsType = DynamicType;

/// A builder of an enum (`rdds_enum_builder`).
#[derive(Debug)]
pub struct EnumBuilder(EnumType);

/// A builder of a bitmask (`rdds_bitmask_builder`).
#[derive(Debug)]
pub struct BitmaskBuilder(BitmaskType);

/// A builder of a bitset (`rdds_bitset_builder`).
#[derive(Debug)]
pub struct BitsetBuilder(BitsetType);

/// A builder of a struct (`rdds_struct_builder`).
#[derive(Debug)]
pub struct StructBuilder(StructType);

/// A builder of a union (`rdds_union_builder`).
#[derive(Debug)]
pub struct UnionBuilder(UnionType);

/// `RDDS_MEMBER_KEY`.
pub const MEMBER_KEY: u32 = 1;
/// `RDDS_MEMBER_OPTIONAL`.
pub const MEMBER_OPTIONAL: u32 = 2;
/// `RDDS_MEMBER_MUST_UNDERSTAND`.
pub const MEMBER_MUST_UNDERSTAND: u32 = 4;
/// `RDDS_MEMBER_EXTERNAL`.
pub const MEMBER_EXTERNAL: u32 = 8;
/// `RDDS_MEMBER_TRY_CONSTRUCT_USE_DEFAULT`.
pub const MEMBER_USE_DEFAULT: u32 = 16;
/// `RDDS_MEMBER_TRY_CONSTRUCT_TRIM`.
pub const MEMBER_TRIM: u32 = 32;
/// `RDDS_MEMBER_DEFAULT_LABEL`: the `default` branch of a union.
pub const MEMBER_DEFAULT_LABEL: u32 = 64;

/// `RDDS_TYPE_NESTED`.
pub const TYPE_NESTED: u32 = 1;
/// `RDDS_TYPE_AUTOID_HASH`.
pub const TYPE_AUTOID_HASH: u32 = 2;

const PRIMITIVES: [Primitive; 15] = [
    Primitive::Boolean,
    Primitive::Byte,
    Primitive::Int8,
    Primitive::Uint8,
    Primitive::Int16,
    Primitive::Uint16,
    Primitive::Int32,
    Primitive::Uint32,
    Primitive::Int64,
    Primitive::Uint64,
    Primitive::Float32,
    Primitive::Float64,
    Primitive::Float128,
    Primitive::Char8,
    Primitive::Char16,
];

fn extensibility(e: i32) -> Res<Extensibility> {
    Ok(match e {
        0 => Extensibility::Final,
        1 => Extensibility::Appendable,
        2 => Extensibility::Mutable,
        _ => return Err(bad(format!("unknown extensibility {e}"))),
    })
}

fn try_construct(flags: u32) -> TryConstruct {
    if flags & MEMBER_TRIM != 0 {
        TryConstruct::Trim
    } else if flags & MEMBER_USE_DEFAULT != 0 {
        TryConstruct::UseDefault
    } else {
        TryConstruct::Discard
    }
}

unsafe fn ty(p: *const RddsType) -> Res<Type> {
    // SAFETY: NULL or a live handle.
    Ok(unsafe { obj(p, "the type") }?.as_type().clone())
}

unsafe fn hash_id(p: *const c_char) -> Res<Option<String>> {
    if p.is_null() {
        Ok(None)
    } else {
        // SAFETY: a NUL-terminated string.
        Ok(Some(unsafe { cstr(p, "the hash id") }?.to_owned()))
    }
}

fn make(out: *mut *mut RddsType, t: Type) -> Res {
    // SAFETY: `out` is valid for a write (the header).
    unsafe { put(out, DynamicType::from(t)) }
}

/// `rdds_type_primitive`: the primitive type of a DDS-XTypes type kind
/// (`TK_BOOLEAN` ... `TK_CHAR16`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_primitive(kind: u8, out: *mut *mut RddsType) -> Status {
    guard(|| {
        let p = PRIMITIVES
            .iter()
            .find(|p| p.kind() == kind)
            .ok_or_else(|| bad(format!("{kind:#x} is not a primitive type kind")))?;
        make(out, Type::Primitive(*p))
    })
}

/// `rdds_type_string`: `string` or `wstring` (`wide`), bounded unless
/// `bound` is 0.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_string(
    wide: bool,
    bound: u32,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| make(out, Type::String { wide, bound }))
}

/// `rdds_type_sequence`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_sequence(
    element: *const RddsType,
    bound: u32,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let element = Element::new(unsafe { ty(element) }?);
        make(
            out,
            Type::Sequence(Arc::new(SequenceType { element, bound })),
        )
    })
}

/// `rdds_type_array`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_array(
    element: *const RddsType,
    dimensions: *const u32,
    dimensions_len: usize,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let element = Element::new(unsafe { ty(element) }?);
        let dimensions = unsafe { slice(dimensions, dimensions_len) }?.to_vec();
        if dimensions.is_empty() || dimensions.contains(&0) {
            return Err(bad("an array needs dimensions, none of them 0"));
        }
        make(
            out,
            Type::Array(Arc::new(ArrayType {
                element,
                dimensions,
            })),
        )
    })
}

/// `rdds_type_map`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_map(
    key: *const RddsType,
    element: *const RddsType,
    bound: u32,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let key = Element::new(unsafe { ty(key) }?);
        let element = Element::new(unsafe { ty(element) }?);
        make(
            out,
            Type::Map(Arc::new(MapType {
                key,
                element,
                bound,
            })),
        )
    })
}

/// `rdds_type_alias`: a typedef.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_alias(
    name: *const c_char,
    related: *const RddsType,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let name = unsafe { cstr(name, "the name") }?.to_owned();
        let related = unsafe { ty(related) }?;
        make(out, Type::from(AliasType { name, related }))
    })
}

/// `rdds_enum_builder_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_enum_builder_new(
    name: *const c_char,
    bit_bound: u16,
    extensibility_kind: i32,
    out: *mut *mut EnumBuilder,
) -> Status {
    guard(|| {
        let e = EnumType {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            bit_bound,
            extensibility: extensibility(extensibility_kind)?,
            literals: Vec::new(),
        };
        unsafe { put(out, EnumBuilder(e)) }
    })
}

/// `rdds_enum_builder_add_literal`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_enum_builder_add_literal(
    builder: *mut EnumBuilder,
    name: *const c_char,
    value: i32,
    is_default: bool,
) -> Status {
    guard(|| {
        let b = unsafe { builder.as_mut() }.ok_or_else(|| bad("the builder is NULL"))?;
        b.0.literals.push(EnumLiteral {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            value,
            default: is_default,
        });
        Ok(())
    })
}

/// `rdds_enum_builder_build`: the enum; the builder is kept.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_enum_builder_build(
    builder: *const EnumBuilder,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let b = unsafe { obj(builder, "the builder") }?;
        make(out, Type::from(b.0.clone()))
    })
}

/// `rdds_enum_builder_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_enum_builder_release(builder: *mut EnumBuilder) {
    unsafe { release(builder) }
}

/// `rdds_bitmask_builder_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitmask_builder_new(
    name: *const c_char,
    bit_bound: u16,
    extensibility_kind: i32,
    out: *mut *mut BitmaskBuilder,
) -> Status {
    guard(|| {
        let b = BitmaskType {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            bit_bound,
            extensibility: extensibility(extensibility_kind)?,
            flags: Vec::new(),
        };
        unsafe { put(out, BitmaskBuilder(b)) }
    })
}

/// `rdds_bitmask_builder_add_flag`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitmask_builder_add_flag(
    builder: *mut BitmaskBuilder,
    name: *const c_char,
    position: u16,
) -> Status {
    guard(|| {
        let b = unsafe { builder.as_mut() }.ok_or_else(|| bad("the builder is NULL"))?;
        b.0.flags.push(Bitflag {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            position,
        });
        Ok(())
    })
}

/// `rdds_bitmask_builder_build`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitmask_builder_build(
    builder: *const BitmaskBuilder,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let b = unsafe { obj(builder, "the builder") }?;
        make(out, Type::from(b.0.clone()))
    })
}

/// `rdds_bitmask_builder_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitmask_builder_release(builder: *mut BitmaskBuilder) {
    unsafe { release(builder) }
}

/// `rdds_bitset_builder_new`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitset_builder_new(
    name: *const c_char,
    out: *mut *mut BitsetBuilder,
) -> Status {
    guard(|| {
        let b = BitsetType {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            fields: Vec::new(),
        };
        unsafe { put(out, BitsetBuilder(b)) }
    })
}

/// `rdds_bitset_builder_add_field`: `bitcount` bits from `position`,
/// read and written as `holder`, `TK_BOOLEAN` or an integer type kind.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitset_builder_add_field(
    builder: *mut BitsetBuilder,
    name: *const c_char,
    position: u16,
    bitcount: u8,
    holder: u8,
) -> Status {
    guard(|| {
        let b = unsafe { builder.as_mut() }.ok_or_else(|| bad("the builder is NULL"))?;
        let holder = Primitive::of_kind(holder)
            .ok_or_else(|| bad(format!("{holder:#x} is not a primitive type kind")))?;
        b.0.fields.push(Bitfield {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            position,
            bitcount,
            holder,
        });
        Ok(())
    })
}

/// `rdds_bitset_builder_build`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitset_builder_build(
    builder: *const BitsetBuilder,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let b = unsafe { obj(builder, "the builder") }?;
        b.0.check().map_err(|e| bad(e.to_string()))?;
        make(out, Type::from(b.0.clone()))
    })
}

/// `rdds_bitset_builder_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_bitset_builder_release(builder: *mut BitsetBuilder) {
    unsafe { release(builder) }
}

/// `rdds_type_forward`: a forward declaration of the type `name`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_forward(name: *const c_char, out: *mut *mut RddsType) -> Status {
    guard(|| {
        let name = unsafe { cstr(name, "the name") }?;
        make(out, Type::forward(name))
    })
}

/// `rdds_type_define`: defines the forward declaration `forward` as
/// `target`, a type of its name.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_define(
    forward: *const RddsType,
    target: *const RddsType,
) -> Status {
    guard(|| {
        let f = unsafe { ty(forward) }?;
        let t = unsafe { ty(target) }?;
        f.define(t).map_err(|e| bad(e.to_string()))
    })
}

/// `rdds_struct_builder_new`: `flags` of `RDDS_TYPE_NESTED` and
/// `RDDS_TYPE_AUTOID_HASH`; `base` NULL for none.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_struct_builder_new(
    name: *const c_char,
    extensibility_kind: i32,
    flags: u32,
    base: *const RddsType,
    out: *mut *mut StructBuilder,
) -> Status {
    guard(|| {
        let s = StructType {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            extensibility: extensibility(extensibility_kind)?,
            nested: flags & TYPE_NESTED != 0,
            autoid_hash: flags & TYPE_AUTOID_HASH != 0,
            base: if base.is_null() {
                None
            } else {
                Some(unsafe { ty(base) }?)
            },
            members: Vec::new(),
        };
        unsafe { put(out, StructBuilder(s)) }
    })
}

/// `rdds_struct_builder_add_member`: `flags` of `RDDS_MEMBER_*`;
/// `hash_id` the string of `@hashid` (`""` for none given) or NULL.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_struct_builder_add_member(
    builder: *mut StructBuilder,
    name: *const c_char,
    id: u32,
    member_type: *const RddsType,
    flags: u32,
    hash_id_: *const c_char,
) -> Status {
    guard(|| {
        let b = unsafe { builder.as_mut() }.ok_or_else(|| bad("the builder is NULL"))?;
        let m = StructMember {
            key: flags & MEMBER_KEY != 0,
            optional: flags & MEMBER_OPTIONAL != 0,
            must_understand: flags & MEMBER_MUST_UNDERSTAND != 0,
            external: flags & MEMBER_EXTERNAL != 0,
            try_construct: try_construct(flags),
            annotations: AppliedBuiltinMemberAnnotations {
                hash_id: unsafe { hash_id(hash_id_) }?,
                ..Default::default()
            },
            ..StructMember::new(unsafe { cstr(name, "the name") }?, id, unsafe {
                ty(member_type)
            }?)
        };
        b.0.members.push(m);
        Ok(())
    })
}

/// `rdds_struct_builder_build`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_struct_builder_build(
    builder: *const StructBuilder,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let b = unsafe { obj(builder, "the builder") }?;
        make(out, Type::from(b.0.clone()))
    })
}

/// `rdds_struct_builder_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_struct_builder_release(builder: *mut StructBuilder) {
    unsafe { release(builder) }
}

/// `rdds_union_builder_new`: `discriminator_flags` may have
/// `RDDS_MEMBER_KEY` and the try-construct flags.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_union_builder_new(
    name: *const c_char,
    extensibility_kind: i32,
    flags: u32,
    discriminator: *const RddsType,
    discriminator_flags: u32,
    out: *mut *mut UnionBuilder,
) -> Status {
    guard(|| {
        let u = UnionType {
            name: unsafe { cstr(name, "the name") }?.to_owned(),
            extensibility: extensibility(extensibility_kind)?,
            nested: flags & TYPE_NESTED != 0,
            autoid_hash: flags & TYPE_AUTOID_HASH != 0,
            discriminator: unsafe { ty(discriminator) }?,
            discriminator_key: discriminator_flags & MEMBER_KEY != 0,
            discriminator_try_construct: try_construct(discriminator_flags),
            members: Vec::new(),
        };
        unsafe { put(out, UnionBuilder(u)) }
    })
}

/// `rdds_union_builder_add_member`: the case labels, and
/// `RDDS_MEMBER_DEFAULT_LABEL` in `flags` for the `default` branch.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_union_builder_add_member(
    builder: *mut UnionBuilder,
    name: *const c_char,
    id: u32,
    member_type: *const RddsType,
    labels: *const i32,
    labels_len: usize,
    flags: u32,
    hash_id_: *const c_char,
) -> Status {
    guard(|| {
        let b = unsafe { builder.as_mut() }.ok_or_else(|| bad("the builder is NULL"))?;
        let m = UnionMember {
            default: flags & MEMBER_DEFAULT_LABEL != 0,
            external: flags & MEMBER_EXTERNAL != 0,
            try_construct: try_construct(flags),
            annotations: AppliedBuiltinMemberAnnotations {
                hash_id: unsafe { hash_id(hash_id_) }?,
                ..Default::default()
            },
            ..UnionMember::new(
                unsafe { cstr(name, "the name") }?,
                id,
                unsafe { ty(member_type) }?,
                unsafe { slice(labels, labels_len) }?.to_vec(),
            )
        };
        b.0.members.push(m);
        Ok(())
    })
}

/// `rdds_union_builder_build`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_union_builder_build(
    builder: *const UnionBuilder,
    out: *mut *mut RddsType,
) -> Status {
    guard(|| {
        let b = unsafe { obj(builder, "the builder") }?;
        make(out, Type::from(b.0.clone()))
    })
}

/// `rdds_union_builder_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_union_builder_release(builder: *mut UnionBuilder) {
    unsafe { release(builder) }
}

/// `rdds_type_clone`: another handle of the same type.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_clone(t: *const RddsType, out: *mut *mut RddsType) -> Status {
    guard(|| {
        let t = unsafe { obj(t, "the type") }?.clone();
        unsafe { put(out, t) }
    })
}

/// `rdds_type_release`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_release(t: *mut RddsType) {
    unsafe { release(t) }
}

/// `rdds_type_hashes`: the equivalence hashes (14 octets each) of the
/// minimal and complete TypeObjects of a type that can be a topic type
/// (DDS-XTypes 1.3, 7.3.4.9). They identify it on the network. A
/// recursive type has none: it is identified by its strongly connected
/// component (7.3.4.9.2).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rdds_type_hashes(
    t: *const RddsType,
    minimal: *mut u8,
    complete: *mut u8,
) -> Status {
    guard(|| {
        let t = unsafe { obj(t, "the type") }?;
        let objects = TypeObjects::new(t.as_type())?;
        for (id, dst) in [
            (objects.minimal_id(), minimal),
            (objects.complete_id(), complete),
        ] {
            let (TypeIdentifier::Minimal(h) | TypeIdentifier::Complete(h)) = id else {
                return Err(bad("the type has no hash: it is not a topic type"));
            };
            if dst.is_null() {
                return Err(bad("the output pointer is NULL"));
            }
            // SAFETY: room for 14 octets (the header).
            unsafe { std::ptr::copy_nonoverlapping(h.as_ptr(), dst, h.len()) };
        }
        Ok(())
    })
}