Skip to main content

rustorb_core/idl/
mod.rs

1//! The runtime of the code `rustorb-idl -brust` generates (see
2//! `docs/rust-mapping.md`).
3//!
4//! Every IDL type has a descriptor, a type that implements [`IdlType`]:
5//! it names the Rust type of the values ([`IdlType::Rust`]), makes the
6//! TypeCode and marshals the values. The types the generator makes for
7//! structs, unions, enums, exceptions, interfaces and valuetypes are their
8//! own descriptors; the descriptors of the basic and anonymous types are
9//! here ([`Long`], [`WString`], [`Sequence`], ...), and those of typedefs
10//! are in the `alias` module the generator makes next to them.
11//!
12//! The same Rust type can stand for several IDL types (`String` is both
13//! `string` and `wstring`, `char` both `char` and `wchar`); the descriptor
14//! says which. [`Any::insert`](crate::Any::insert) and
15//! [`Any::extract`](crate::Any::extract) take one.
16
17use std::borrow::Borrow;
18use std::marker::PhantomData;
19
20use rustorb_cdr::{ByteOrder, CdrEncode, CdrVersion, Decoder, Encoder};
21
22use crate::{
23    CompletionStatus, Exception, InStream, ObjectRef, OutStream, SystemException,
24    SystemExceptionKind, TCKind, TypeCode, minor,
25};
26
27mod value;
28
29pub use value::{
30    CustomMarshal, DataInputStream, DataOutputStream, ValueHandle, ValueInfo, ValueState, read_box,
31    register_value, write_box,
32};
33
34/// Referred to by every generated file: a generator that writes code for
35/// another version of this runtime fails to compile.
36pub const GENERATED_CODE_VERSION_1: () = ();
37
38/// The result of marshalling.
39pub type Sys<T> = Result<T, SystemException>;
40
41/// The descriptor of an IDL type.
42pub trait IdlType: 'static {
43    /// The Rust type of the values.
44    type Rust: Borrow<Self::Borrowed> + 'static;
45    /// What is written: `str` for strings, a slice for sequences, else
46    /// [`Rust`](IdlType::Rust) itself.
47    type Borrowed: ?Sized;
48    /// The smallest size of a value on the wire, to check the lengths of
49    /// sequences before reading them.
50    const MIN_SIZE: usize;
51
52    /// The TypeCode of the type.
53    fn type_code() -> TypeCode;
54
55    /// Writes a value.
56    fn write(v: &Self::Borrowed, out: &mut OutStream<'_>) -> Sys<()>;
57
58    /// Reads a value.
59    fn read(input: &mut InStream<'_>) -> Sys<Self::Rust>;
60
61    /// Writes the elements of a sequence or an array.
62    fn write_items(items: &[Self::Rust], out: &mut OutStream<'_>) -> Sys<()> {
63        items.iter().try_for_each(|v| Self::write(v.borrow(), out))
64    }
65
66    /// Reads `len` elements of a sequence or an array.
67    fn read_items(len: usize, input: &mut InStream<'_>) -> Sys<Vec<Self::Rust>> {
68        let mut items = Vec::with_capacity(len.min(4096));
69        for _ in 0..len {
70            items.push(Self::read(input)?);
71        }
72        Ok(items)
73    }
74}
75
76// --- errors ---------------------------------------------------------------
77
78/// `BAD_PARAM`, not completed: a value that does not fit its type.
79pub fn bad_param() -> SystemException {
80    SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
81}
82
83/// `DATA_CONVERSION`, not completed: a character or a number the type
84/// cannot hold.
85pub fn data_conversion() -> SystemException {
86    SystemException::new(
87        SystemExceptionKind::DATA_CONVERSION,
88        0,
89        CompletionStatus::No,
90    )
91}
92
93/// `BAD_OPERATION` with minor `UNKNOWN_OPERATION`: what a skeleton
94/// returns for an operation the interface does not have.
95pub fn unknown_operation() -> SystemException {
96    SystemException::new(
97        SystemExceptionKind::BAD_OPERATION,
98        minor::UNKNOWN_OPERATION,
99        CompletionStatus::No,
100    )
101}
102
103/// The system exception a call that raises no user exceptions fails
104/// with: a user exception is `UNKNOWN` (minor `UNLISTED_USER_EXCEPTION`).
105pub fn system_exception(e: Exception) -> SystemException {
106    match e {
107        Exception::System(e) => e,
108        Exception::User(_) => unlisted_user_exception(),
109    }
110}
111
112/// `UNKNOWN` with minor `UNLISTED_USER_EXCEPTION`, for a user exception
113/// the operation does not raise.
114pub fn unlisted_user_exception() -> SystemException {
115    SystemException::new(
116        SystemExceptionKind::UNKNOWN,
117        minor::UNLISTED_USER_EXCEPTION,
118        CompletionStatus::Maybe,
119    )
120}
121
122/// Whether `obj` supports the interface `repository_id`: from the type id
123/// of its IOR when it is that one, else by asking the object (`_is_a`).
124pub fn is_a(obj: &ObjectRef, repository_id: &str) -> Sys<bool> {
125    if obj.type_id() == repository_id {
126        return Ok(true);
127    }
128    obj.is_a(repository_id).map_err(system_exception)
129}
130
131/// The TypeCode of a basic type.
132pub fn simple_tc(kind: TCKind) -> TypeCode {
133    TypeCode::simple(kind).expect("a simple kind")
134}
135
136/// Unwraps the result of making a TypeCode the generator checked.
137pub fn tc(r: Result<TypeCode, crate::TypeCodeError>) -> TypeCode {
138    r.expect("a TypeCode checked by rustorb-idl")
139}
140
141// --- basic types ----------------------------------------------------------
142
143macro_rules! numeric {
144    ($($(#[$doc:meta])* $name:ident: $ty:ty, $kind:ident, $size:expr;)*) => {
145        $(
146            $(#[$doc])*
147            #[derive(Debug)]
148            pub struct $name;
149
150            impl IdlType for $name {
151                type Rust = $ty;
152                type Borrowed = $ty;
153                const MIN_SIZE: usize = $size;
154
155                fn type_code() -> TypeCode {
156                    simple_tc(TCKind::$kind)
157                }
158
159                fn write(v: &$ty, out: &mut OutStream<'_>) -> Sys<()> {
160                    Ok(v.encode(out)?)
161                }
162
163                fn read(input: &mut InStream<'_>) -> Sys<$ty> {
164                    input.read::<$ty>()
165                }
166            }
167        )*
168    };
169}
170
171numeric! {
172    /// `boolean`: `bool`.
173    Boolean: bool, Boolean, 1;
174    /// `short`: `i16`.
175    Short: i16, Short, 2;
176    /// `unsigned short`: `u16`.
177    UShort: u16, UShort, 2;
178    /// `long`: `i32`.
179    Long: i32, Long, 4;
180    /// `unsigned long`: `u32`.
181    ULong: u32, ULong, 4;
182    /// `long long`: `i64`.
183    LongLong: i64, LongLong, 8;
184    /// `unsigned long long`: `u64`.
185    ULongLong: u64, ULongLong, 8;
186    /// `float`: `f32`.
187    Float: f32, Float, 4;
188    /// `double`: `f64`.
189    Double: f64, Double, 8;
190    /// `long double`: [`LongDouble`](crate::LongDouble), the binary128 bits.
191    LongDouble: crate::LongDouble, LongDouble, 16;
192}
193
194/// `octet`: `u8`. Sequences and arrays of octets are copied at once.
195#[derive(Debug)]
196pub struct Octet;
197
198impl IdlType for Octet {
199    type Rust = u8;
200    type Borrowed = u8;
201    const MIN_SIZE: usize = 1;
202
203    fn type_code() -> TypeCode {
204        simple_tc(TCKind::Octet)
205    }
206
207    fn write(v: &u8, out: &mut OutStream<'_>) -> Sys<()> {
208        out.write_octet(*v);
209        Ok(())
210    }
211
212    fn read(input: &mut InStream<'_>) -> Sys<u8> {
213        input.read::<u8>()
214    }
215
216    fn write_items(items: &[u8], out: &mut OutStream<'_>) -> Sys<()> {
217        out.write_octets(items);
218        Ok(())
219    }
220
221    fn read_items(len: usize, input: &mut InStream<'_>) -> Sys<Vec<u8>> {
222        let e = input.marshal_error();
223        Ok(input.read_octets(len).map_err(|_| e)?.to_vec())
224    }
225}
226
227/// `char`: `char`, one octet in the negotiated `char` code set; a
228/// character that is not is `DATA_CONVERSION`.
229#[derive(Debug)]
230pub struct Char;
231
232impl IdlType for Char {
233    type Rust = char;
234    type Borrowed = char;
235    const MIN_SIZE: usize = 1;
236
237    fn type_code() -> TypeCode {
238        simple_tc(TCKind::Char)
239    }
240
241    fn write(v: &char, out: &mut OutStream<'_>) -> Sys<()> {
242        let bytes = out.code_sets().encode_string(v.encode_utf8(&mut [0; 4]))?;
243        match bytes[..] {
244            [b] => {
245                out.write_char(b);
246                Ok(())
247            }
248            _ => Err(data_conversion()),
249        }
250    }
251
252    fn read(input: &mut InStream<'_>) -> Sys<char> {
253        input.read_char_value()
254    }
255}
256
257/// `wchar`: `char`, one UTF-16 code unit; a character outside the Basic
258/// Multilingual Plane is `DATA_CONVERSION`, as is a lone surrogate
259/// received.
260#[derive(Debug)]
261pub struct WChar;
262
263impl IdlType for WChar {
264    type Rust = char;
265    type Borrowed = char;
266    const MIN_SIZE: usize = 1;
267
268    fn type_code() -> TypeCode {
269        simple_tc(TCKind::WChar)
270    }
271
272    fn write(v: &char, out: &mut OutStream<'_>) -> Sys<()> {
273        let unit = u16::try_from(u32::from(*v)).map_err(|_| data_conversion())?;
274        out.write_wchar(unit)
275    }
276
277    fn read(input: &mut InStream<'_>) -> Sys<char> {
278        let unit = input.read_wchar()?;
279        char::from_u32(u32::from(unit)).ok_or_else(|| {
280            SystemException::new(
281                SystemExceptionKind::DATA_CONVERSION,
282                0,
283                input.completion_status(),
284            )
285        })
286    }
287}
288
289/// `string`: `String`.
290#[derive(Debug)]
291pub struct String;
292
293impl IdlType for String {
294    type Rust = std::string::String;
295    type Borrowed = str;
296    const MIN_SIZE: usize = 4;
297
298    fn type_code() -> TypeCode {
299        TypeCode::string(0)
300    }
301
302    fn write(v: &str, out: &mut OutStream<'_>) -> Sys<()> {
303        out.write_string(v)
304    }
305
306    fn read(input: &mut InStream<'_>) -> Sys<std::string::String> {
307        input.read_string()
308    }
309}
310
311/// `wstring`: `String`.
312#[derive(Debug)]
313pub struct WString;
314
315impl IdlType for WString {
316    type Rust = std::string::String;
317    type Borrowed = str;
318    const MIN_SIZE: usize = 4;
319
320    fn type_code() -> TypeCode {
321        TypeCode::wstring(0)
322    }
323
324    fn write(v: &str, out: &mut OutStream<'_>) -> Sys<()> {
325        out.write_wstring(v)
326    }
327
328    fn read(input: &mut InStream<'_>) -> Sys<std::string::String> {
329        input.read_wstring()
330    }
331}
332
333fn check_len_out(len: usize, bound: u32) -> Sys<()> {
334    if len > bound as usize {
335        return Err(bad_param());
336    }
337    Ok(())
338}
339
340fn check_len_in(len: usize, bound: u32, input: &InStream<'_>) -> Sys<()> {
341    if len > bound as usize {
342        return Err(input.marshal_error());
343    }
344    Ok(())
345}
346
347/// `string<N>`: `String` of at most `N` characters. A longer one is
348/// `BAD_PARAM` when sent and `MARSHAL` when received.
349#[derive(Debug)]
350pub struct BoundedString<const N: u32>;
351
352impl<const N: u32> IdlType for BoundedString<N> {
353    type Rust = std::string::String;
354    type Borrowed = str;
355    const MIN_SIZE: usize = 4;
356
357    fn type_code() -> TypeCode {
358        TypeCode::string(N)
359    }
360
361    fn write(v: &str, out: &mut OutStream<'_>) -> Sys<()> {
362        check_len_out(v.chars().count(), N)?;
363        out.write_string(v)
364    }
365
366    fn read(input: &mut InStream<'_>) -> Sys<std::string::String> {
367        let s = input.read_string()?;
368        check_len_in(s.chars().count(), N, input)?;
369        Ok(s)
370    }
371}
372
373/// `wstring<N>`: `String` of at most `N` characters.
374#[derive(Debug)]
375pub struct BoundedWString<const N: u32>;
376
377impl<const N: u32> IdlType for BoundedWString<N> {
378    type Rust = std::string::String;
379    type Borrowed = str;
380    const MIN_SIZE: usize = 4;
381
382    fn type_code() -> TypeCode {
383        TypeCode::wstring(N)
384    }
385
386    fn write(v: &str, out: &mut OutStream<'_>) -> Sys<()> {
387        check_len_out(v.chars().count(), N)?;
388        out.write_wstring(v)
389    }
390
391    fn read(input: &mut InStream<'_>) -> Sys<std::string::String> {
392        let s = input.read_wstring()?;
393        check_len_in(s.chars().count(), N, input)?;
394        Ok(s)
395    }
396}
397
398/// `sequence<T>`: `Vec`.
399#[derive(Debug)]
400pub struct Sequence<T>(PhantomData<T>);
401
402impl<T: IdlType> IdlType for Sequence<T> {
403    type Rust = Vec<T::Rust>;
404    type Borrowed = [T::Rust];
405    const MIN_SIZE: usize = 4;
406
407    fn type_code() -> TypeCode {
408        tc(TypeCode::sequence(&T::type_code(), 0))
409    }
410
411    fn write(v: &[T::Rust], out: &mut OutStream<'_>) -> Sys<()> {
412        out.write_len(v.len())?;
413        T::write_items(v, out)
414    }
415
416    fn read(input: &mut InStream<'_>) -> Sys<Vec<T::Rust>> {
417        let len = read_len(input, T::MIN_SIZE)?;
418        T::read_items(len, input)
419    }
420}
421
422/// `sequence<T, N>`: `Vec` of at most `N` elements. A longer one is
423/// `BAD_PARAM` when sent and `MARSHAL` when received.
424#[derive(Debug)]
425pub struct BoundedSequence<T, const N: u32>(PhantomData<T>);
426
427impl<T: IdlType, const N: u32> IdlType for BoundedSequence<T, N> {
428    type Rust = Vec<T::Rust>;
429    type Borrowed = [T::Rust];
430    const MIN_SIZE: usize = 4;
431
432    fn type_code() -> TypeCode {
433        tc(TypeCode::sequence(&T::type_code(), N))
434    }
435
436    fn write(v: &[T::Rust], out: &mut OutStream<'_>) -> Sys<()> {
437        check_len_out(v.len(), N)?;
438        out.write_len(v.len())?;
439        T::write_items(v, out)
440    }
441
442    fn read(input: &mut InStream<'_>) -> Sys<Vec<T::Rust>> {
443        let len = read_len(input, T::MIN_SIZE)?;
444        check_len_in(len, N, input)?;
445        T::read_items(len, input)
446    }
447}
448
449/// Reads the length of a sequence whose elements take at least
450/// `min_size` octets.
451pub fn read_len(input: &mut InStream<'_>, min_size: usize) -> Sys<usize> {
452    let e = input.marshal_error();
453    input.read_len(min_size.max(1)).map_err(|_| e)
454}
455
456/// `T x[N]`: `[T; N]`. A multidimensional array is an array of arrays.
457#[derive(Debug)]
458pub struct Array<T, const N: usize>(PhantomData<T>);
459
460impl<T: IdlType, const N: usize> IdlType for Array<T, N> {
461    type Rust = [T::Rust; N];
462    type Borrowed = [T::Rust; N];
463    const MIN_SIZE: usize = T::MIN_SIZE.saturating_mul(N);
464
465    fn type_code() -> TypeCode {
466        let n = u32::try_from(N).expect("array length checked by rustorb-idl");
467        tc(TypeCode::array(&T::type_code(), n))
468    }
469
470    fn write(v: &[T::Rust; N], out: &mut OutStream<'_>) -> Sys<()> {
471        T::write_items(v, out)
472    }
473
474    fn read(input: &mut InStream<'_>) -> Sys<[T::Rust; N]> {
475        let items = T::read_items(N, input)?;
476        items.try_into().map_err(|_| input.marshal_error())
477    }
478}
479
480/// `Object`: `Option<ObjectRef>`, `None` for a nil reference.
481#[derive(Debug)]
482pub struct Object;
483
484impl IdlType for Object {
485    type Rust = Option<ObjectRef>;
486    type Borrowed = Option<ObjectRef>;
487    const MIN_SIZE: usize = 4;
488
489    fn type_code() -> TypeCode {
490        TypeCode::object()
491    }
492
493    fn write(v: &Option<ObjectRef>, out: &mut OutStream<'_>) -> Sys<()> {
494        out.write_object(v.as_ref())
495    }
496
497    fn read(input: &mut InStream<'_>) -> Sys<Option<ObjectRef>> {
498        input.read_object()
499    }
500}
501
502/// `any`: [`crate::Any`].
503#[derive(Debug)]
504pub struct Any;
505
506impl IdlType for Any {
507    type Rust = crate::Any;
508    type Borrowed = crate::Any;
509    const MIN_SIZE: usize = 4;
510
511    fn type_code() -> TypeCode {
512        simple_tc(TCKind::Any)
513    }
514
515    fn write(v: &crate::Any, out: &mut OutStream<'_>) -> Sys<()> {
516        out.write_any(v)
517    }
518
519    fn read(input: &mut InStream<'_>) -> Sys<crate::Any> {
520        input.read_any()
521    }
522}
523
524/// `TypeCode`: [`crate::TypeCode`].
525#[derive(Debug)]
526pub struct TypeCodeType;
527
528impl IdlType for TypeCodeType {
529    type Rust = TypeCode;
530    type Borrowed = TypeCode;
531    const MIN_SIZE: usize = 4;
532
533    fn type_code() -> TypeCode {
534        simple_tc(TCKind::TypeCode)
535    }
536
537    fn write(v: &TypeCode, out: &mut OutStream<'_>) -> Sys<()> {
538        out.write_typecode(v)
539    }
540
541    fn read(input: &mut InStream<'_>) -> Sys<TypeCode> {
542        input.read_typecode()
543    }
544}
545
546/// `fixed<D, S>`: [`crate::Fixed`]. A value is sent with digits after `S`
547/// cut off; an integer part longer than `D - S` digits is
548/// `DATA_CONVERSION`.
549#[derive(Debug)]
550pub struct Fixed<const D: u16, const S: u16>;
551
552impl<const D: u16, const S: u16> IdlType for Fixed<D, S> {
553    type Rust = crate::Fixed;
554    type Borrowed = crate::Fixed;
555    const MIN_SIZE: usize = (D as usize + 2) / 2;
556
557    fn type_code() -> TypeCode {
558        let scale = i16::try_from(S).expect("scale checked by rustorb-idl");
559        tc(TypeCode::fixed(D, scale))
560    }
561
562    fn write(v: &crate::Fixed, out: &mut OutStream<'_>) -> Sys<()> {
563        let digits = v.to_digits(D, S).ok_or_else(data_conversion)?;
564        out.write_fixed(&digits, v.is_negative())
565    }
566
567    fn read(input: &mut InStream<'_>) -> Sys<crate::Fixed> {
568        let (digits, negative) = input.read_fixed(D as usize)?;
569        crate::Fixed::from_digits(&digits, S, negative).ok_or_else(|| input.marshal_error())
570    }
571}
572
573// --- Any ------------------------------------------------------------------
574
575impl crate::Any {
576    /// An Any holding `v` as a value of the IDL type `T` (a descriptor):
577    /// `Any::insert::<Point>(&p)`, `Any::insert::<idl::WString>("w")`.
578    /// A value that does not fit the type is `BAD_PARAM` (or
579    /// `DATA_CONVERSION`).
580    pub fn insert<T: IdlType>(v: &T::Borrowed) -> Sys<crate::Any> {
581        let mut enc = Encoder::new(ByteOrder::Big, CdrVersion::Giop1_2);
582        let mut out = OutStream::standalone(&mut enc);
583        T::write(v, &mut out)?;
584        let orb = out.orb.take();
585        let bytes = enc.into_bytes();
586        let dec = Decoder::new(&bytes, ByteOrder::Big, CdrVersion::Giop1_2);
587        let mut input = InStream::standalone(dec, orb.as_ref());
588        let tc = T::type_code();
589        let value = input.read_value(&tc)?;
590        Ok(crate::Any::new(tc, value))
591    }
592
593    /// The value of the Any as a value of the IDL type `T`, if the Any
594    /// holds one: its TypeCode is equivalent to `T`'s.
595    pub fn extract<T: IdlType>(&self) -> Option<T::Rust> {
596        if !self.typecode().equivalent(&T::type_code()) {
597            return None;
598        }
599        let mut enc = Encoder::new(ByteOrder::Big, CdrVersion::Giop1_2);
600        let mut out = OutStream::standalone(&mut enc);
601        out.write_value(self.typecode(), self.value()).ok()?;
602        let orb = out.orb.take();
603        let bytes = enc.into_bytes();
604        let dec = Decoder::new(&bytes, ByteOrder::Big, CdrVersion::Giop1_2);
605        let mut input = InStream::standalone(dec, orb.as_ref());
606        T::read(&mut input).ok()
607    }
608}
609
610#[cfg(test)]
611mod tests;