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