1use 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
34pub const GENERATED_CODE_VERSION_1: () = ();
37
38pub type Sys<T> = Result<T, SystemException>;
40
41pub trait IdlType: 'static {
43 type Rust: Borrow<Self::Borrowed> + 'static;
45 type Borrowed: ?Sized;
48 const MIN_SIZE: usize;
51
52 fn type_code() -> TypeCode;
54
55 fn write(v: &Self::Borrowed, out: &mut OutStream<'_>) -> Sys<()>;
57
58 fn read(input: &mut InStream<'_>) -> Sys<Self::Rust>;
60
61 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 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
76pub fn bad_param() -> SystemException {
80 SystemException::new(SystemExceptionKind::BAD_PARAM, 0, CompletionStatus::No)
81}
82
83pub fn data_conversion() -> SystemException {
86 SystemException::new(
87 SystemExceptionKind::DATA_CONVERSION,
88 0,
89 CompletionStatus::No,
90 )
91}
92
93pub fn unknown_operation() -> SystemException {
96 SystemException::new(
97 SystemExceptionKind::BAD_OPERATION,
98 minor::UNKNOWN_OPERATION,
99 CompletionStatus::No,
100 )
101}
102
103pub fn system_exception(e: Exception) -> SystemException {
106 match e {
107 Exception::System(e) => e,
108 Exception::User(_) => unlisted_user_exception(),
109 }
110}
111
112pub fn unlisted_user_exception() -> SystemException {
115 SystemException::new(
116 SystemExceptionKind::UNKNOWN,
117 minor::UNLISTED_USER_EXCEPTION,
118 CompletionStatus::Maybe,
119 )
120}
121
122pub 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
131pub fn simple_tc(kind: TCKind) -> TypeCode {
133 TypeCode::simple(kind).expect("a simple kind")
134}
135
136pub fn tc(r: Result<TypeCode, crate::TypeCodeError>) -> TypeCode {
138 r.expect("a TypeCode checked by rustorb-idl")
139}
140
141macro_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, Boolean, 1;
174 Short: i16, Short, 2;
176 UShort: u16, UShort, 2;
178 Long: i32, Long, 4;
180 ULong: u32, ULong, 4;
182 LongLong: i64, LongLong, 8;
184 ULongLong: u64, ULongLong, 8;
186 Float: f32, Float, 4;
188 Double: f64, Double, 8;
190 LongDouble: crate::LongDouble, LongDouble, 16;
192}
193
194#[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#[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#[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#[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#[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#[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#[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#[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#[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
449pub 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#[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#[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#[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#[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#[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
573impl crate::Any {
576 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 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;