Skip to main content

rustorb_dds_ffi/
stream.rs

1//! Samples as streams of values in the order of their type.
2//!
3//! An output stream (`rdds_out`) takes the values of a sample: the
4//! members of a struct in order (those of its base first), the length of
5//! a sequence or map and then its elements (a map's as key, value, key,
6//! value...), the elements of an array (all its dimensions, row by row),
7//! whether an optional member is present and then its value if it is,
8//! the discriminator of a union and then the value of the member it
9//! selects (nothing when it selects none), a bitset as one integer (as
10//! a bitmask: the bits of its fields, the first field in the lowest
11//! bits). Aliases and `@external` are
12//! transparent. The elements of a sequence or array of a primitive type
13//! other than `float128` go in one call (`rdds_out_*_array`) after the
14//! length of a sequence. An input stream (`rdds_in`) gives the values of
15//! a sample in the same order.
16//!
17//! The stream does not know the type: a writer matches the values to its
18//! type when it writes them, and fails with `RETCODE_BAD_PARAMETER` on
19//! values that do not fit. Reading a value of the wrong kind sets a
20//! sticky error on the input stream (`rdds_in_status`) and returns zero.
21
22use std::ffi::c_char;
23
24use rustorb_cdr::LongDouble;
25use rustorb_dds::{DynamicData, DynamicDataFactory, DynamicType, MEMBER_ID_INVALID};
26use rustorb_xtypes::type_object::*;
27use rustorb_xtypes::types::{Primitive, Type};
28
29use crate::{Fail, OK, Res, Status, bad, guard, guard_value, put, release, set};
30
31const ME: MemberId = MEMBER_ID_INVALID;
32
33/// The elements of a sequence or array of a primitive type.
34#[derive(Debug, Clone, PartialEq)]
35pub enum Bulk {
36    Boolean(Vec<bool>),
37    Byte(Vec<u8>),
38    Int8(Vec<i8>),
39    Uint8(Vec<u8>),
40    Int16(Vec<i16>),
41    Uint16(Vec<u16>),
42    Int32(Vec<i32>),
43    Uint32(Vec<u32>),
44    Int64(Vec<i64>),
45    Uint64(Vec<u64>),
46    Float32(Vec<f32>),
47    Float64(Vec<f64>),
48    Char8(Vec<u8>),
49    Char16(Vec<u16>),
50}
51
52impl Bulk {
53    fn len(&self) -> usize {
54        match self {
55            Bulk::Boolean(v) => v.len(),
56            Bulk::Byte(v) | Bulk::Uint8(v) | Bulk::Char8(v) => v.len(),
57            Bulk::Int8(v) => v.len(),
58            Bulk::Int16(v) => v.len(),
59            Bulk::Uint16(v) | Bulk::Char16(v) => v.len(),
60            Bulk::Int32(v) => v.len(),
61            Bulk::Uint32(v) => v.len(),
62            Bulk::Int64(v) => v.len(),
63            Bulk::Uint64(v) => v.len(),
64            Bulk::Float32(v) => v.len(),
65            Bulk::Float64(v) => v.len(),
66        }
67    }
68}
69
70/// One value of the stream.
71#[derive(Debug, Clone, PartialEq)]
72pub enum Value {
73    Boolean(bool),
74    Byte(u8),
75    Int8(i8),
76    Uint8(u8),
77    Int16(i16),
78    Uint16(u16),
79    Int32(i32),
80    Uint32(u32),
81    Int64(i64),
82    Uint64(u64),
83    Float32(f32),
84    Float64(f64),
85    Float128(LongDouble),
86    Char8(u8),
87    Char16(u16),
88    String(String),
89    WString(Vec<u16>),
90    /// Of a sequence or map.
91    Length(u32),
92    /// Of an optional member.
93    Present(bool),
94    Discriminator(i64),
95    Enum(i32),
96    Bitmask(u64),
97    Bulk(Bulk),
98}
99
100impl Value {
101    fn name(&self) -> &'static str {
102        match self {
103            Value::Boolean(_) => "boolean",
104            Value::Byte(_) => "octet",
105            Value::Int8(_) => "int8",
106            Value::Uint8(_) => "uint8",
107            Value::Int16(_) => "int16",
108            Value::Uint16(_) => "uint16",
109            Value::Int32(_) => "int32",
110            Value::Uint32(_) => "uint32",
111            Value::Int64(_) => "int64",
112            Value::Uint64(_) => "uint64",
113            Value::Float32(_) => "float32",
114            Value::Float64(_) => "float64",
115            Value::Float128(_) => "float128",
116            Value::Char8(_) => "char8",
117            Value::Char16(_) => "char16",
118            Value::String(_) => "string",
119            Value::WString(_) => "wstring",
120            Value::Length(_) => "length",
121            Value::Present(_) => "presence",
122            Value::Discriminator(_) => "discriminator",
123            Value::Enum(_) => "enum",
124            Value::Bitmask(_) => "bitmask",
125            Value::Bulk(_) => "array of primitives",
126        }
127    }
128}
129
130/// `rdds_out`: the values of a sample being written.
131#[derive(Debug, Default)]
132pub struct Out {
133    pub(crate) values: Vec<Value>,
134    pub(crate) error: Option<String>,
135}
136
137/// `rdds_in`: the values of a sample being read.
138#[derive(Debug, Default)]
139pub struct In {
140    values: Vec<Value>,
141    next: usize,
142    error: Option<String>,
143}
144
145fn resolve(mut ty: &Type) -> &Type {
146    while let Type::Alias(a) = ty {
147        ty = &a.related;
148    }
149    ty
150}
151
152/// The primitive of the elements of a sequence or array of `ty` that go
153/// as a [`Bulk`], if they do.
154fn bulk_element(ty: &Type) -> Option<Primitive> {
155    let element = match resolve(ty) {
156        Type::Sequence(s) => &s.element.ty,
157        Type::Array(a) => &a.element.ty,
158        _ => return None,
159    };
160    match resolve(element) {
161        Type::Primitive(Primitive::Float128) => None,
162        Type::Primitive(p) => Some(*p),
163        _ => None,
164    }
165}
166
167// ---------- values to DynamicData ------------------------------------------
168
169struct Reader<'a> {
170    values: &'a [Value],
171    next: usize,
172}
173
174impl<'a> Reader<'a> {
175    fn take(&mut self, what: &str) -> Res<&'a Value> {
176        let v = self
177            .values
178            .get(self.next)
179            .ok_or_else(|| bad(format!("the sample ends where a {what} is expected")))?;
180        self.next += 1;
181        Ok(v)
182    }
183}
184
185fn mismatch(expected: &str, got: &Value) -> Fail {
186    bad(format!(
187        "a {expected} is expected in the sample, not a {}",
188        got.name()
189    ))
190}
191
192fn char8(c: u8) -> char {
193    char::from(c)
194}
195
196fn char16(c: u16) -> Res<char> {
197    char::from_u32(c.into()).ok_or_else(|| bad(format!("{c:#x} is not a wchar")))
198}
199
200fn fill(d: &mut DynamicData, r: &mut Reader<'_>) -> Res {
201    let ty = d.get_type();
202    let kind = d.get_kind();
203    macro_rules! one {
204        ($variant:ident, $set:ident, $what:literal) => {{
205            match r.take($what)? {
206                Value::$variant(x) => d.$set(ME, *x)?,
207                v => return Err(mismatch($what, v)),
208            }
209        }};
210    }
211    match kind {
212        TK_BOOLEAN => one!(Boolean, set_boolean_value, "boolean"),
213        TK_BYTE => match r.take("octet")? {
214            Value::Byte(x) | Value::Uint8(x) => d.set_byte_value(ME, *x)?,
215            v => return Err(mismatch("octet", v)),
216        },
217        TK_UINT8 => match r.take("uint8")? {
218            Value::Byte(x) | Value::Uint8(x) => d.set_uint8_value(ME, *x)?,
219            v => return Err(mismatch("uint8", v)),
220        },
221        TK_INT8 => one!(Int8, set_int8_value, "int8"),
222        TK_INT16 => one!(Int16, set_int16_value, "int16"),
223        TK_UINT16 => one!(Uint16, set_uint16_value, "uint16"),
224        TK_INT32 => one!(Int32, set_int32_value, "int32"),
225        TK_UINT32 => one!(Uint32, set_uint32_value, "uint32"),
226        TK_INT64 => one!(Int64, set_int64_value, "int64"),
227        TK_UINT64 => one!(Uint64, set_uint64_value, "uint64"),
228        TK_FLOAT32 => one!(Float32, set_float32_value, "float32"),
229        TK_FLOAT64 => one!(Float64, set_float64_value, "float64"),
230        TK_FLOAT128 => one!(Float128, set_float128_value, "float128"),
231        TK_CHAR8 => match r.take("char8")? {
232            Value::Char8(c) => d.set_char8_value(ME, char8(*c))?,
233            v => return Err(mismatch("char8", v)),
234        },
235        TK_CHAR16 => match r.take("char16")? {
236            Value::Char16(c) => d.set_char16_value(ME, char16(*c)?)?,
237            v => return Err(mismatch("char16", v)),
238        },
239        TK_STRING8 => match r.take("string")? {
240            Value::String(s) => d.set_string_value(ME, s)?,
241            v => return Err(mismatch("string", v)),
242        },
243        TK_STRING16 => match r.take("wstring")? {
244            Value::WString(s) => {
245                let s = String::from_utf16(s).map_err(|_| bad("a wstring is not UTF-16"))?;
246                d.set_wstring_value(ME, &s)?
247            }
248            v => return Err(mismatch("wstring", v)),
249        },
250        TK_ENUM => match r.take("enum")? {
251            // The narrowest integer that holds it, which any bit bound
252            // takes.
253            Value::Enum(x) => {
254                if let Ok(x) = i8::try_from(*x) {
255                    d.set_int8_value(ME, x)?
256                } else if let Ok(x) = i16::try_from(*x) {
257                    d.set_int16_value(ME, x)?
258                } else {
259                    d.set_int32_value(ME, *x)?
260                }
261            }
262            v => return Err(mismatch("enum", v)),
263        },
264        // A bitset as one integer, as the bitmask: its fields' bits.
265        TK_BITMASK | TK_BITSET => match r.take("bitmask")? {
266            Value::Bitmask(x) => {
267                let x = *x;
268                if let Ok(x) = u8::try_from(x) {
269                    d.set_uint8_value(ME, x)?
270                } else if let Ok(x) = u16::try_from(x) {
271                    d.set_uint16_value(ME, x)?
272                } else if let Ok(x) = u32::try_from(x) {
273                    d.set_uint32_value(ME, x)?
274                } else {
275                    d.set_uint64_value(ME, x)?
276                }
277            }
278            v => return Err(mismatch("bitmask", v)),
279        },
280        TK_SEQUENCE | TK_ARRAY => {
281            let sequence = kind == TK_SEQUENCE;
282            let n = if sequence {
283                match r.take("length")? {
284                    Value::Length(n) => *n as usize,
285                    v => return Err(mismatch("length", v)),
286                }
287            } else {
288                d.get_item_count() as usize
289            };
290            if sequence {
291                d.clear_all_values()?;
292            }
293            if bulk_element(ty.as_type()).is_some() {
294                let b = match r.take("array of primitives")? {
295                    Value::Bulk(b) => b,
296                    v => return Err(mismatch("array of primitives", v)),
297                };
298                if b.len() != n {
299                    return Err(bad(format!("{} elements where {n} are expected", b.len())));
300                }
301                set_bulk(d, b)?;
302            } else {
303                for i in 0..n {
304                    fill(d.loan_value(i as MemberId)?, r)?;
305                }
306            }
307        }
308        TK_MAP => {
309            let Type::Map(m) = resolve(ty.as_type()) else {
310                return Err(bad("a map type is expected"));
311            };
312            let (kt, et) = (
313                DynamicType::from(m.key.ty.clone()),
314                DynamicType::from(m.element.ty.clone()),
315            );
316            let n = match r.take("length")? {
317                Value::Length(n) => *n,
318                v => return Err(mismatch("length", v)),
319            };
320            d.clear_all_values()?;
321            for _ in 0..n {
322                let mut k = DynamicDataFactory::create_data(&kt);
323                fill(&mut k, r)?;
324                let mut e = DynamicDataFactory::create_data(&et);
325                fill(&mut e, r)?;
326                d.map_insert(k, e)?;
327            }
328        }
329        TK_STRUCTURE => {
330            for m in ty.members() {
331                if m.get_descriptor().is_optional {
332                    match r.take("presence")? {
333                        Value::Present(true) => {}
334                        Value::Present(false) => {
335                            d.clear_value(m.get_id())?;
336                            continue;
337                        }
338                        v => return Err(mismatch("presence", v)),
339                    }
340                }
341                fill(d.loan_value(m.get_id())?, r)?;
342            }
343        }
344        TK_UNION => {
345            match r.take("discriminator")? {
346                Value::Discriminator(x) => d.set_discriminator_value(*x)?,
347                v => return Err(mismatch("discriminator", v)),
348            }
349            if let Some(id) = d.selected_member() {
350                fill(d.loan_value(id)?, r)?;
351            }
352        }
353        k => return Err(bad(format!("type kind {k:#x} is not supported"))),
354    }
355    Ok(())
356}
357
358fn set_bulk(d: &mut DynamicData, b: &Bulk) -> Res {
359    match (d.get_kind_of_elements(), b) {
360        (TK_BOOLEAN, Bulk::Boolean(v)) => d.set_boolean_values(ME, v)?,
361        (TK_BYTE, Bulk::Byte(v) | Bulk::Uint8(v)) => d.set_byte_values(ME, v)?,
362        (TK_UINT8, Bulk::Byte(v) | Bulk::Uint8(v)) => d.set_uint8_values(ME, v)?,
363        (TK_INT8, Bulk::Int8(v)) => d.set_int8_values(ME, v)?,
364        (TK_INT16, Bulk::Int16(v)) => d.set_int16_values(ME, v)?,
365        (TK_UINT16, Bulk::Uint16(v)) => d.set_uint16_values(ME, v)?,
366        (TK_INT32, Bulk::Int32(v)) => d.set_int32_values(ME, v)?,
367        (TK_UINT32, Bulk::Uint32(v)) => d.set_uint32_values(ME, v)?,
368        (TK_INT64, Bulk::Int64(v)) => d.set_int64_values(ME, v)?,
369        (TK_UINT64, Bulk::Uint64(v)) => d.set_uint64_values(ME, v)?,
370        (TK_FLOAT32, Bulk::Float32(v)) => d.set_float32_values(ME, v)?,
371        (TK_FLOAT64, Bulk::Float64(v)) => d.set_float64_values(ME, v)?,
372        (TK_CHAR8, Bulk::Char8(v)) => {
373            let v: Vec<char> = v.iter().map(|c| char8(*c)).collect();
374            d.set_char8_values(ME, &v)?
375        }
376        (TK_CHAR16, Bulk::Char16(v)) => {
377            let v = v.iter().map(|c| char16(*c)).collect::<Res<Vec<char>>>()?;
378            d.set_char16_values(ME, &v)?
379        }
380        (k, b) => {
381            return Err(bad(format!(
382                "an array of {} elements does not fit elements of kind {k:#x}",
383                Value::Bulk(b.clone()).name()
384            )));
385        }
386    }
387    Ok(())
388}
389
390/// A sample of `ty` from the values of `out`.
391pub(crate) fn to_data(ty: &DynamicType, out: &Out) -> Res<DynamicData> {
392    if let Some(e) = &out.error {
393        return Err(bad(e.clone()));
394    }
395    let mut d = DynamicDataFactory::create_data(ty);
396    let mut r = Reader {
397        values: &out.values,
398        next: 0,
399    };
400    fill(&mut d, &mut r)?;
401    if r.next != out.values.len() {
402        return Err(bad(format!(
403            "{} values after the end of the sample",
404            out.values.len() - r.next
405        )));
406    }
407    Ok(d)
408}
409
410// ---------- DynamicData to values ------------------------------------------
411
412fn emit(d: &DynamicData, out: &mut Vec<Value>) -> Res {
413    let ty = d.get_type();
414    let kind = d.get_kind();
415    macro_rules! one {
416        ($variant:ident, $get:ident) => {
417            out.push(Value::$variant(d.$get(ME)?))
418        };
419    }
420    match kind {
421        TK_BOOLEAN => one!(Boolean, get_boolean_value),
422        TK_BYTE => one!(Byte, get_byte_value),
423        TK_UINT8 => one!(Uint8, get_uint8_value),
424        TK_INT8 => one!(Int8, get_int8_value),
425        TK_INT16 => one!(Int16, get_int16_value),
426        TK_UINT16 => one!(Uint16, get_uint16_value),
427        TK_INT32 => one!(Int32, get_int32_value),
428        TK_UINT32 => one!(Uint32, get_uint32_value),
429        TK_INT64 => one!(Int64, get_int64_value),
430        TK_UINT64 => one!(Uint64, get_uint64_value),
431        TK_FLOAT32 => one!(Float32, get_float32_value),
432        TK_FLOAT64 => one!(Float64, get_float64_value),
433        TK_FLOAT128 => one!(Float128, get_float128_value),
434        TK_CHAR8 => out.push(Value::Char8(u32::from(d.get_char8_value(ME)?) as u8)),
435        TK_CHAR16 => out.push(Value::Char16(u32::from(d.get_char16_value(ME)?) as u16)),
436        TK_STRING8 => out.push(Value::String(d.get_string_value(ME)?)),
437        TK_STRING16 => out.push(Value::WString(
438            d.get_wstring_value(ME)?.encode_utf16().collect(),
439        )),
440        TK_ENUM => out.push(Value::Enum(d.get_int32_value(ME)?)),
441        TK_BITMASK | TK_BITSET => out.push(Value::Bitmask(d.get_uint64_value(ME)?)),
442        TK_SEQUENCE | TK_ARRAY => {
443            let n = d.get_item_count();
444            if kind == TK_SEQUENCE {
445                out.push(Value::Length(n));
446            }
447            if bulk_element(ty.as_type()).is_some() {
448                out.push(Value::Bulk(get_bulk(d)?));
449            } else {
450                for i in 0..n {
451                    emit(d.get_value(i)?, out)?;
452                }
453            }
454        }
455        TK_MAP => {
456            let entries = d.map_entries()?;
457            out.push(Value::Length(entries.len() as u32));
458            for (k, v) in entries {
459                emit(k, out)?;
460                emit(v, out)?;
461            }
462        }
463        TK_STRUCTURE => {
464            for m in ty.members() {
465                let optional = m.get_descriptor().is_optional;
466                if optional {
467                    let present = d.is_present(m.get_id());
468                    out.push(Value::Present(present));
469                    if !present {
470                        continue;
471                    }
472                }
473                emit(d.get_value(m.get_id())?, out)?;
474            }
475        }
476        TK_UNION => {
477            out.push(Value::Discriminator(d.get_discriminator_value()?));
478            if let Some(id) = d.selected_member() {
479                emit(d.get_value(id)?, out)?;
480            }
481        }
482        k => return Err(bad(format!("type kind {k:#x} is not supported"))),
483    }
484    Ok(())
485}
486
487fn get_bulk(d: &DynamicData) -> Res<Bulk> {
488    Ok(match d.get_kind_of_elements() {
489        TK_BOOLEAN => Bulk::Boolean(d.get_boolean_values(ME)?),
490        TK_BYTE => Bulk::Byte(d.get_byte_values(ME)?),
491        TK_UINT8 => Bulk::Uint8(d.get_uint8_values(ME)?),
492        TK_INT8 => Bulk::Int8(d.get_int8_values(ME)?),
493        TK_INT16 => Bulk::Int16(d.get_int16_values(ME)?),
494        TK_UINT16 => Bulk::Uint16(d.get_uint16_values(ME)?),
495        TK_INT32 => Bulk::Int32(d.get_int32_values(ME)?),
496        TK_UINT32 => Bulk::Uint32(d.get_uint32_values(ME)?),
497        TK_INT64 => Bulk::Int64(d.get_int64_values(ME)?),
498        TK_UINT64 => Bulk::Uint64(d.get_uint64_values(ME)?),
499        TK_FLOAT32 => Bulk::Float32(d.get_float32_values(ME)?),
500        TK_FLOAT64 => Bulk::Float64(d.get_float64_values(ME)?),
501        TK_CHAR8 => Bulk::Char8(
502            d.get_char8_values(ME)?
503                .into_iter()
504                .map(|c| u32::from(c) as u8)
505                .collect(),
506        ),
507        TK_CHAR16 => Bulk::Char16(
508            d.get_char16_values(ME)?
509                .into_iter()
510                .map(|c| u32::from(c) as u16)
511                .collect(),
512        ),
513        k => return Err(bad(format!("elements of kind {k:#x} are not primitives"))),
514    })
515}
516
517/// An input stream of the values of `d`.
518pub(crate) fn from_data(d: &DynamicData) -> Res<In> {
519    let mut values = Vec::new();
520    emit(d, &mut values)?;
521    Ok(In {
522        values,
523        next: 0,
524        error: None,
525    })
526}
527
528trait ElementKind {
529    fn get_kind_of_elements(&self) -> TypeKind;
530}
531
532impl ElementKind for DynamicData {
533    /// The kind of the elements of a sequence or array, aliases resolved.
534    fn get_kind_of_elements(&self) -> TypeKind {
535        bulk_element(self.get_type().as_type()).map_or(TK_NONE, Primitive::kind)
536    }
537}
538
539// ---------- the C functions: output ----------------------------------------
540
541/// `rdds_out_new`.
542#[unsafe(no_mangle)]
543pub unsafe extern "C" fn rdds_out_new(out: *mut *mut Out) -> Status {
544    guard(|| unsafe { put(out, Out::default()) })
545}
546
547/// `rdds_out_clear`: empties the stream to write another sample.
548#[unsafe(no_mangle)]
549pub unsafe extern "C" fn rdds_out_clear(s: *mut Out) {
550    if let Some(s) = unsafe { s.as_mut() } {
551        s.values.clear();
552        s.error = None;
553    }
554}
555
556/// `rdds_out_release`.
557#[unsafe(no_mangle)]
558pub unsafe extern "C" fn rdds_out_release(s: *mut Out) {
559    unsafe { release(s) }
560}
561
562fn push(s: *mut Out, v: impl FnOnce() -> Result<Value, String>) {
563    let Some(s) = (unsafe { s.as_mut() }) else {
564        return;
565    };
566    guard_value((), || {
567        if s.error.is_some() {
568            return;
569        }
570        match v() {
571            Ok(v) => s.values.push(v),
572            Err(e) => s.error = Some(e),
573        }
574    })
575}
576
577macro_rules! out_scalar {
578    ($($name:ident, $t:ty, $variant:ident;)*) => {$(
579        #[doc = concat!("`", stringify!($name), "`.")]
580        #[unsafe(no_mangle)]
581        pub unsafe extern "C" fn $name(s: *mut Out, v: $t) {
582            push(s, || Ok(Value::$variant(v)))
583        }
584    )*};
585}
586
587out_scalar! {
588    rdds_out_boolean, bool, Boolean;
589    rdds_out_octet, u8, Byte;
590    rdds_out_int8, i8, Int8;
591    rdds_out_uint8, u8, Uint8;
592    rdds_out_int16, i16, Int16;
593    rdds_out_uint16, u16, Uint16;
594    rdds_out_int32, i32, Int32;
595    rdds_out_uint32, u32, Uint32;
596    rdds_out_int64, i64, Int64;
597    rdds_out_uint64, u64, Uint64;
598    rdds_out_float32, f32, Float32;
599    rdds_out_float64, f64, Float64;
600    rdds_out_char8, u8, Char8;
601    rdds_out_char16, u16, Char16;
602    rdds_out_length, u32, Length;
603    rdds_out_present, bool, Present;
604    rdds_out_discriminator, i64, Discriminator;
605    rdds_out_enum, i32, Enum;
606    rdds_out_bitmask, u64, Bitmask;
607}
608
609/// `rdds_out_float128`: the IEEE 754 binary128 bits, high and low halves.
610#[unsafe(no_mangle)]
611pub unsafe extern "C" fn rdds_out_float128(s: *mut Out, high: u64, low: u64) {
612    push(s, || {
613        Ok(Value::Float128(LongDouble::from_bits(
614            (u128::from(high) << 64) | u128::from(low),
615        )))
616    })
617}
618
619/// `rdds_out_string`: `len` octets of UTF-8.
620#[unsafe(no_mangle)]
621pub unsafe extern "C" fn rdds_out_string(s: *mut Out, v: *const c_char, len: usize) {
622    push(s, || {
623        let bytes = unsafe { crate::slice(v.cast::<u8>(), len) }.map_err(|f| f.1)?;
624        String::from_utf8(bytes.to_vec())
625            .map(Value::String)
626            .map_err(|_| "a string is not UTF-8".to_owned())
627    })
628}
629
630/// `rdds_out_wstring`: `len` UTF-16 code units.
631#[unsafe(no_mangle)]
632pub unsafe extern "C" fn rdds_out_wstring(s: *mut Out, v: *const u16, len: usize) {
633    push(s, || {
634        let units = unsafe { crate::slice(v, len) }.map_err(|f| f.1)?;
635        Ok(Value::WString(units.to_vec()))
636    })
637}
638
639macro_rules! out_array {
640    ($($name:ident, $t:ty, $variant:ident;)*) => {$(
641        #[doc = concat!("`", stringify!($name), "`: `n` elements.")]
642        #[unsafe(no_mangle)]
643        pub unsafe extern "C" fn $name(s: *mut Out, v: *const $t, n: usize) {
644            push(s, || {
645                let v = unsafe { crate::slice(v, n) }.map_err(|f| f.1)?;
646                Ok(Value::Bulk(Bulk::$variant(v.to_vec())))
647            })
648        }
649    )*};
650}
651
652out_array! {
653    rdds_out_boolean_array, bool, Boolean;
654    rdds_out_octet_array, u8, Byte;
655    rdds_out_int8_array, i8, Int8;
656    rdds_out_uint8_array, u8, Uint8;
657    rdds_out_int16_array, i16, Int16;
658    rdds_out_uint16_array, u16, Uint16;
659    rdds_out_int32_array, i32, Int32;
660    rdds_out_uint32_array, u32, Uint32;
661    rdds_out_int64_array, i64, Int64;
662    rdds_out_uint64_array, u64, Uint64;
663    rdds_out_float32_array, f32, Float32;
664    rdds_out_float64_array, f64, Float64;
665    rdds_out_char8_array, u8, Char8;
666    rdds_out_char16_array, u16, Char16;
667}
668
669// ---------- the C functions: input -----------------------------------------
670
671/// `rdds_in_status`: `RETCODE_OK`, or `RETCODE_BAD_PARAMETER` after a
672/// read that did not fit the sample (and its message,
673/// `rdds_last_error_message`, is set).
674#[unsafe(no_mangle)]
675pub unsafe extern "C" fn rdds_in_status(s: *const In) -> Status {
676    match unsafe { s.as_ref() } {
677        Some(In { error: None, .. }) => OK,
678        Some(In { error: Some(e), .. }) => guard(|| Err(bad(e.clone()))),
679        None => guard(|| Err(bad("the stream is NULL"))),
680    }
681}
682
683/// `rdds_in_at_end`: whether every value was read.
684#[unsafe(no_mangle)]
685pub unsafe extern "C" fn rdds_in_at_end(s: *const In) -> bool {
686    unsafe { s.as_ref() }.is_none_or(|s| s.next >= s.values.len())
687}
688
689/// `rdds_in_release`.
690#[unsafe(no_mangle)]
691pub unsafe extern "C" fn rdds_in_release(s: *mut In) {
692    unsafe { release(s) }
693}
694
695/// The next value if `f` takes it; otherwise the error is set and None.
696fn pull<'a, T>(s: *mut In, what: &str, f: impl FnOnce(&'a Value) -> Option<T>) -> Option<T> {
697    let s: &'a mut In = unsafe { s.as_mut() }?;
698    if s.error.is_some() {
699        return None;
700    }
701    let got = s.values.get(s.next);
702    match got.and_then(f) {
703        Some(x) => {
704            s.next += 1;
705            Some(x)
706        }
707        None => {
708            s.error = Some(match got {
709                Some(v) => format!("a {what} was read where the sample has a {}", v.name()),
710                None => format!("a {what} was read after the end of the sample"),
711            });
712            None
713        }
714    }
715}
716
717macro_rules! in_scalar {
718    ($($name:ident, $t:ty, $what:literal, $($pat:pat => $e:expr),+;)*) => {$(
719        #[doc = concat!("`", stringify!($name), "`.")]
720        #[unsafe(no_mangle)]
721        pub unsafe extern "C" fn $name(s: *mut In) -> $t {
722            guard_value(<$t>::default(), || {
723                pull(s, $what, |v| match v { $($pat => Some($e),)+ _ => None })
724                    .unwrap_or_default()
725            })
726        }
727    )*};
728}
729
730in_scalar! {
731    rdds_in_boolean, bool, "boolean", Value::Boolean(x) => *x;
732    rdds_in_octet, u8, "octet", Value::Byte(x) | Value::Uint8(x) => *x;
733    rdds_in_int8, i8, "int8", Value::Int8(x) => *x;
734    rdds_in_uint8, u8, "uint8", Value::Uint8(x) | Value::Byte(x) => *x;
735    rdds_in_int16, i16, "int16", Value::Int16(x) => *x;
736    rdds_in_uint16, u16, "uint16", Value::Uint16(x) => *x;
737    rdds_in_int32, i32, "int32", Value::Int32(x) => *x;
738    rdds_in_uint32, u32, "uint32", Value::Uint32(x) => *x;
739    rdds_in_int64, i64, "int64", Value::Int64(x) => *x;
740    rdds_in_uint64, u64, "uint64", Value::Uint64(x) => *x;
741    rdds_in_float32, f32, "float32", Value::Float32(x) => *x;
742    rdds_in_float64, f64, "float64", Value::Float64(x) => *x;
743    rdds_in_char8, u8, "char8", Value::Char8(x) => *x;
744    rdds_in_char16, u16, "char16", Value::Char16(x) => *x;
745    rdds_in_length, u32, "length", Value::Length(x) => *x;
746    rdds_in_present, bool, "presence", Value::Present(x) => *x;
747    rdds_in_discriminator, i64, "discriminator", Value::Discriminator(x) => *x;
748    rdds_in_enum, i32, "enum", Value::Enum(x) => *x;
749    rdds_in_bitmask, u64, "bitmask", Value::Bitmask(x) => *x;
750}
751
752/// `rdds_in_float128`: the binary128 bits into `*high` and `*low`.
753#[unsafe(no_mangle)]
754pub unsafe extern "C" fn rdds_in_float128(s: *mut In, high: *mut u64, low: *mut u64) {
755    guard_value((), || {
756        let bits = pull(s, "float128", |v| match v {
757            Value::Float128(x) => Some(x.to_bits()),
758            _ => None,
759        })
760        .unwrap_or(0);
761        let _ = unsafe { set(high, (bits >> 64) as u64) };
762        let _ = unsafe { set(low, bits as u64) };
763    })
764}
765
766/// `rdds_in_string`: the UTF-8 octets of a string (not NUL-terminated),
767/// valid until the stream is released.
768#[unsafe(no_mangle)]
769pub unsafe extern "C" fn rdds_in_string(s: *mut In, v: *mut *const c_char, len: *mut usize) {
770    guard_value((), || {
771        let (p, n) = pull(s, "string", |x| match x {
772            Value::String(x) => Some((x.as_ptr().cast::<c_char>(), x.len())),
773            _ => None,
774        })
775        .unwrap_or((c"".as_ptr(), 0));
776        let _ = unsafe { set(v, p) };
777        let _ = unsafe { set(len, n) };
778    })
779}
780
781/// `rdds_in_wstring`: the UTF-16 code units of a wstring, valid until
782/// the stream is released.
783#[unsafe(no_mangle)]
784pub unsafe extern "C" fn rdds_in_wstring(s: *mut In, v: *mut *const u16, len: *mut usize) {
785    guard_value((), || {
786        let (p, n) = pull(s, "wstring", |x| match x {
787            Value::WString(x) => Some((x.as_ptr(), x.len())),
788            _ => None,
789        })
790        .unwrap_or((std::ptr::null(), 0));
791        let _ = unsafe { set(v, p) };
792        let _ = unsafe { set(len, n) };
793    })
794}
795
796macro_rules! in_array {
797    ($($name:ident, $t:ty, $what:literal, $($variant:ident)|+;)*) => {$(
798        #[doc = concat!("`", stringify!($name), "`: exactly `n` elements into `v`.")]
799        #[unsafe(no_mangle)]
800        pub unsafe extern "C" fn $name(s: *mut In, v: *mut $t, n: usize) {
801            guard_value((), || {
802                let Some(src) = pull(s, $what, |x| match x {
803                    $(Value::Bulk(Bulk::$variant(x)))|+ if x.len() == n => Some(x.as_slice()),
804                    _ => None,
805                }) else {
806                    return;
807                };
808                if n > 0 && !v.is_null() {
809                    // SAFETY: room for `n` elements (the header).
810                    unsafe { std::ptr::copy_nonoverlapping(src.as_ptr(), v, n) };
811                }
812            })
813        }
814    )*};
815}
816
817in_array! {
818    rdds_in_boolean_array, bool, "array of booleans", Boolean;
819    rdds_in_octet_array, u8, "array of octets", Byte | Uint8;
820    rdds_in_int8_array, i8, "array of int8", Int8;
821    rdds_in_uint8_array, u8, "array of uint8", Uint8 | Byte;
822    rdds_in_int16_array, i16, "array of int16", Int16;
823    rdds_in_uint16_array, u16, "array of uint16", Uint16;
824    rdds_in_int32_array, i32, "array of int32", Int32;
825    rdds_in_uint32_array, u32, "array of uint32", Uint32;
826    rdds_in_int64_array, i64, "array of int64", Int64;
827    rdds_in_uint64_array, u64, "array of uint64", Uint64;
828    rdds_in_float32_array, f32, "array of float32", Float32;
829    rdds_in_float64_array, f64, "array of float64", Float64;
830    rdds_in_char8_array, u8, "array of char8", Char8;
831    rdds_in_char16_array, u16, "array of char16", Char16;
832}
833
834/// `rdds_type_serialize`: the serialized payload of a sample (with its
835/// encapsulation header), in XCDR1 (`xcdr2` false) or XCDR2, little
836/// endian; `*data` is freed with `rdds_bytes_free`. For tests and tools.
837#[unsafe(no_mangle)]
838pub unsafe extern "C" fn rdds_type_serialize(
839    t: *const DynamicType,
840    sample: *const Out,
841    xcdr2: bool,
842    data: *mut *mut u8,
843    len: *mut usize,
844) -> Status {
845    guard(|| {
846        let t = unsafe { crate::obj(t, "the type") }?;
847        let sample = unsafe { crate::obj(sample, "the sample") }?;
848        let d = to_data(t, sample)?;
849        let enc = if xcdr2 {
850            rustorb_cdr::Encoding::Xcdr2
851        } else {
852            rustorb_cdr::Encoding::Xcdr1
853        };
854        let bytes = d.to_payload(enc, rustorb_cdr::ByteOrder::Little)?;
855        let bytes = bytes.into_boxed_slice();
856        unsafe { set(len, bytes.len()) }?;
857        unsafe { set(data, Box::into_raw(bytes).cast::<u8>()) }
858    })
859}
860
861/// `rdds_type_deserialize`: a sample from its serialized payload.
862#[unsafe(no_mangle)]
863pub unsafe extern "C" fn rdds_type_deserialize(
864    t: *const DynamicType,
865    data: *const u8,
866    len: usize,
867    out: *mut *mut In,
868) -> Status {
869    guard(|| {
870        let t = unsafe { crate::obj(t, "the type") }?;
871        let bytes = unsafe { crate::slice(data, len) }?;
872        let d = DynamicData::from_payload(t, bytes)?;
873        unsafe { put(out, from_data(&d)?) }
874    })
875}
876
877/// `rdds_bytes_free`: frees what `rdds_type_serialize` made.
878#[unsafe(no_mangle)]
879pub unsafe extern "C" fn rdds_bytes_free(data: *mut u8, len: usize) {
880    if !data.is_null() {
881        // SAFETY: a boxed slice of `len` octets made by this library.
882        drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(data, len)) });
883    }
884}