1use 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
39pub const GENERATED_CODE_VERSION_1: () = ();
42
43pub type Sys<T> = Result<T, SystemException>;
45
46pub trait IdlType: 'static {
48 type Rust: Borrow<Self::Borrowed> + 'static;
50 type Borrowed: ?Sized;
53 const MIN_SIZE: usize;
56
57 fn type_code() -> TypeCode;
59
60 fn write(v: &Self::Borrowed, out: &mut OutStream<'_>) -> Sys<()>;
62
63 fn read(input: &mut InStream<'_>) -> Sys<Self::Rust>;
65
66 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 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
81pub fn bad_param() -> SystemException {
85 SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
86}
87
88pub fn data_conversion() -> SystemException {
91 SystemException::new(
92 SystemExceptionKind::DATA_CONVERSION,
93 0,
94 CompletionStatus::No,
95 )
96}
97
98pub fn unknown_operation() -> SystemException {
101 SystemException::new(
102 SystemExceptionKind::BAD_OPERATION,
103 minor::UNKNOWN_OPERATION,
104 CompletionStatus::No,
105 )
106}
107
108pub fn system_exception(e: Exception) -> SystemException {
111 match e {
112 Exception::System(e) => e,
113 Exception::User(_) => unlisted_user_exception(),
114 }
115}
116
117pub fn unlisted_user_exception() -> SystemException {
120 SystemException::new(
121 SystemExceptionKind::UNKNOWN,
122 minor::UNLISTED_USER_EXCEPTION,
123 CompletionStatus::Maybe,
124 )
125}
126
127pub 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
136pub fn simple_tc(kind: TCKind) -> TypeCode {
138 TypeCode::simple(kind).expect("a simple kind")
139}
140
141pub fn tc(r: Result<TypeCode, crate::TypeCodeError>) -> TypeCode {
143 r.expect("a TypeCode checked by rustorb-idl")
144}
145
146macro_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, Boolean, 1;
179 Short: i16, Short, 2;
181 UShort: u16, UShort, 2;
183 Long: i32, Long, 4;
185 ULong: u32, ULong, 4;
187 LongLong: i64, LongLong, 8;
189 ULongLong: u64, ULongLong, 8;
191 Float: f32, Float, 4;
193 Double: f64, Double, 8;
195 LongDouble: crate::LongDouble, LongDouble, 16;
197}
198
199#[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#[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#[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#[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#[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#[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#[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#[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#[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
454pub 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#[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#[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#[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#[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#[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
578impl crate::Any {
581 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 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;