1use std::ops::{Deref, DerefMut};
2
3use rustorb_cdr::{CdrDecode, CdrEncode, Decoder, Encoder};
4use rustorb_giop::{Body, Ior};
5
6use crate::value::{self, Any, Value};
7use crate::{
8 CodeSets, CompletionStatus, ObjectRef, Orb, SystemException, SystemExceptionKind, TypeCode,
9};
10
11#[derive(Debug)]
18pub struct OutStream<'a> {
19 pub(crate) enc: &'a mut Encoder,
20 pub(crate) code_sets: CodeSets,
21 pub(crate) orb: Option<Orb>,
24 pub(crate) values: Option<ValueLog>,
27}
28
29#[derive(Debug, Default)]
31pub(crate) struct ValueLog {
32 pub(crate) chunked: bool,
34 pub(crate) written: Vec<crate::ValueRef>,
37}
38
39impl<'a> OutStream<'a> {
40 pub fn standalone(enc: &'a mut Encoder) -> OutStream<'a> {
44 OutStream {
45 enc,
46 code_sets: CodeSets::NATIVE,
47 orb: None,
48 values: None,
49 }
50 }
51
52 pub fn log_values(&mut self) {
57 self.values = Some(ValueLog {
58 chunked: true,
59 written: Vec::new(),
60 });
61 }
62
63 pub fn written_values(&mut self) -> Vec<crate::ValueRef> {
67 self.values
68 .as_mut()
69 .map(|l| std::mem::take(&mut l.written))
70 .unwrap_or_default()
71 }
72
73 pub(crate) fn note_value(&mut self, v: &crate::ValueRef) {
74 if let Some(log) = &mut self.values {
75 log.written.push(v.clone());
76 }
77 }
78
79 pub fn code_sets(&self) -> CodeSets {
81 self.code_sets
82 }
83
84 pub fn set_code_sets(&mut self, code_sets: CodeSets) {
88 self.code_sets = code_sets;
89 }
90
91 pub fn write_string(&mut self, s: &str) -> Result<(), SystemException> {
93 let bytes = self.code_sets.encode_string(s)?;
94 Ok(self.enc.write_string_bytes(&bytes)?)
95 }
96
97 pub fn write_wchar(&mut self, c: u16) -> Result<(), SystemException> {
99 self.check_wchar()?;
100 Ok(self.enc.write_wchar(c)?)
101 }
102
103 pub fn write_wstring(&mut self, s: &str) -> Result<(), SystemException> {
105 self.check_wchar()?;
106 Ok(self.enc.write_wstring(s)?)
107 }
108
109 pub fn write_object(&mut self, obj: Option<&ObjectRef>) -> Result<(), SystemException> {
111 match obj {
112 Some(obj) => {
113 if self.orb.is_none() {
114 self.orb = Some(obj.orb().clone());
115 }
116 obj.ior().encode(self.enc)?
117 }
118 None => Ior::nil().encode(self.enc)?,
119 }
120 Ok(())
121 }
122
123 pub fn write_typecode(&mut self, tc: &TypeCode) -> Result<(), SystemException> {
126 tc.encode(self.enc).map_err(|e| match e {
127 rustorb_cdr::Error::InvalidTypeCode(_) => {
128 SystemException::new(SystemExceptionKind::BAD_TYPECODE, 0, CompletionStatus::No)
129 }
130 e => e.into(),
131 })
132 }
133
134 pub fn write_value(&mut self, tc: &TypeCode, v: &Value) -> Result<(), SystemException> {
137 value::write(self, tc, v)
138 }
139
140 pub fn write_fixed(&mut self, digits: &[u8], negative: bool) -> Result<(), SystemException> {
144 let n = digits.len();
145 if n > 31 || digits.iter().any(|&d| d > 9) {
146 return Err(SystemException::new(
147 SystemExceptionKind::BAD_PARAM,
148 0,
149 CompletionStatus::No,
150 ));
151 }
152 let mut nibbles = Vec::with_capacity(n + 2);
155 if n % 2 == 0 {
156 nibbles.push(0);
157 }
158 nibbles.extend_from_slice(digits);
159 nibbles.push(if negative { 0xd } else { 0xc });
160 let bytes: Vec<u8> = nibbles.chunks(2).map(|p| (p[0] << 4) | p[1]).collect();
161 self.enc.write_octets(&bytes);
162 Ok(())
163 }
164
165 pub fn write_any(&mut self, any: &Any) -> Result<(), SystemException> {
167 self.write_typecode(any.typecode())?;
168 value::write(self, any.typecode(), any.value())
169 }
170
171 fn check_wchar(&self) -> Result<(), SystemException> {
172 if self.code_sets.wchar_data.is_none() {
173 return Err(SystemException::new(
174 SystemExceptionKind::BAD_PARAM,
175 crate::minor::WCHAR_TCS_NOT_KNOWN,
176 CompletionStatus::No,
177 ));
178 }
179 Ok(())
180 }
181}
182
183impl Deref for OutStream<'_> {
184 type Target = Encoder;
185
186 fn deref(&self) -> &Encoder {
187 self.enc
188 }
189}
190
191impl DerefMut for OutStream<'_> {
192 fn deref_mut(&mut self) -> &mut Encoder {
193 self.enc
194 }
195}
196
197#[derive(Debug)]
205pub struct InStream<'a> {
206 pub(crate) dec: Decoder<'a>,
207 pub(crate) code_sets: CodeSets,
208 pub(crate) orb: Option<&'a Orb>,
211 pub(crate) completed: CompletionStatus,
212 pub(crate) wchar_needs_code_set: bool,
215 pub(crate) values: Vec<Option<crate::ValueRef>>,
218 pub(crate) typed_values: Vec<Option<Box<dyn std::any::Any>>>,
221 pub(crate) custom_items: Option<Vec<crate::Value>>,
225 pub(crate) body: Option<&'a Body>,
228}
229
230pub(crate) struct DetachedInput {
233 body: Body,
234 skip: usize,
235 code_sets: CodeSets,
236 orb: Option<Orb>,
237 completed: CompletionStatus,
238 wchar_needs_code_set: bool,
239}
240
241impl DetachedInput {
242 pub(crate) fn stream(&self) -> InStream<'_> {
244 let mut dec = self.body.decoder();
245 let _ = dec.skip(self.skip);
247 InStream {
248 dec,
249 code_sets: self.code_sets,
250 orb: self.orb.as_ref(),
251 completed: self.completed,
252 wchar_needs_code_set: self.wchar_needs_code_set,
253 values: Vec::new(),
254 typed_values: Vec::new(),
255 custom_items: None,
256 body: Some(&self.body),
257 }
258 }
259}
260
261impl Drop for InStream<'_> {
262 fn drop(&mut self) {
263 let values: Vec<_> = self
267 .values
268 .drain(..)
269 .flatten()
270 .map(|v| crate::Value::Valuetype(Some(v)))
271 .collect();
272 if !values.is_empty() {
273 crate::Value::List(values).release();
274 }
275 }
276}
277
278impl<'a> InStream<'a> {
279 pub fn standalone(dec: Decoder<'a>, orb: Option<&'a Orb>) -> InStream<'a> {
284 InStream {
285 dec,
286 code_sets: CodeSets::NATIVE,
287 orb,
288 completed: CompletionStatus::No,
289 wchar_needs_code_set: false,
290 values: Vec::new(),
291 typed_values: Vec::new(),
292 custom_items: None,
293 body: None,
294 }
295 }
296
297 pub fn preset_value(&mut self, slot: usize, v: crate::ValueRef) {
302 if self.values.len() <= slot {
303 self.values.resize(slot + 1, None);
304 }
305 self.values[slot] = Some(v);
306 }
307
308 pub fn value_at(&self, slot: usize) -> Option<&crate::ValueRef> {
310 self.values.get(slot).and_then(Option::as_ref)
311 }
312
313 pub(crate) fn detach(&self) -> Option<DetachedInput> {
316 let body = self.body?;
317 if !self.values.is_empty() || !self.typed_values.is_empty() {
318 return None;
319 }
320 Some(DetachedInput {
321 body: body.clone(),
322 skip: self.dec.position() - body.decoder().position(),
323 code_sets: self.code_sets,
324 orb: self.orb.cloned(),
325 completed: self.completed,
326 wchar_needs_code_set: self.wchar_needs_code_set,
327 })
328 }
329
330 pub fn code_sets(&self) -> CodeSets {
332 self.code_sets
333 }
334
335 pub fn set_code_sets(&mut self, code_sets: CodeSets) {
339 self.code_sets = code_sets;
340 }
341
342 pub fn read<T: CdrDecode>(&mut self) -> Result<T, SystemException> {
344 let completed = self.completed;
345 T::decode(&mut self.dec).map_err(|_| marshal_with(completed))
346 }
347
348 pub fn read_string(&mut self) -> Result<String, SystemException> {
350 let completed = self.completed;
351 let bytes = self
352 .dec
353 .read_string_bytes()
354 .map_err(|_| marshal_with(completed))?;
355 self.code_sets.decode_string(bytes).map_err(|mut e| {
356 e.completed = completed;
357 e
358 })
359 }
360
361 pub fn read_wchar(&mut self) -> Result<u16, SystemException> {
363 self.check_wchar()?;
364 let completed = self.completed;
365 self.dec.read_wchar().map_err(|_| marshal_with(completed))
366 }
367
368 pub fn read_wstring(&mut self) -> Result<String, SystemException> {
370 self.check_wchar()?;
371 let completed = self.completed;
372 self.dec.read_wstring().map_err(|_| marshal_with(completed))
373 }
374
375 fn check_wchar(&self) -> Result<(), SystemException> {
376 if self.wchar_needs_code_set && self.code_sets.wchar_data.is_none() {
377 return Err(SystemException::new(
378 SystemExceptionKind::BAD_PARAM,
379 crate::minor::WCHAR_TCS_NOT_KNOWN,
380 self.completed,
381 ));
382 }
383 Ok(())
384 }
385
386 pub fn read_object(&mut self) -> Result<Option<ObjectRef>, SystemException> {
388 let completed = self.completed;
389 let ior = Ior::decode(&mut self.dec).map_err(|_| marshal_with(completed))?;
390 if ior.is_nil() {
391 return Ok(None);
392 }
393 let orb = self.orb.ok_or_else(|| {
394 SystemException::new(SystemExceptionKind::BAD_INV_ORDER, 0, completed)
395 })?;
396 Ok(Some(ObjectRef::new(orb.clone(), ior)))
397 }
398
399 pub fn read_char_value(&mut self) -> Result<char, SystemException> {
401 let completed = self.completed;
402 let b = self.dec.read_char().map_err(|_| marshal_with(completed))?;
403 let s = self.code_sets.decode_string(&[b]).map_err(|mut e| {
404 e.completed = completed;
405 e
406 })?;
407 s.chars().next().ok_or_else(|| marshal_with(completed))
408 }
409
410 pub fn read_typecode(&mut self) -> Result<TypeCode, SystemException> {
412 let completed = self.completed;
413 TypeCode::decode(&mut self.dec).map_err(|_| marshal_with(completed))
414 }
415
416 pub fn read_value(&mut self, tc: &TypeCode) -> Result<Value, SystemException> {
418 value::read(self, tc)
419 }
420
421 pub fn read_fixed(&mut self, n: usize) -> Result<(Vec<u8>, bool), SystemException> {
424 let e = self.marshal_error();
425 let bytes = self.dec.read_octets(n / 2 + 1).map_err(|_| e.clone())?;
426 let mut nibbles: Vec<u8> = bytes.iter().flat_map(|b| [b >> 4, b & 0xf]).collect();
427 let sign = nibbles.pop().unwrap_or(0xc);
428 if n % 2 == 0 {
429 nibbles.remove(0);
430 }
431 if nibbles.iter().any(|&d| d > 9) || !matches!(sign, 0xc | 0xd | 0xf) {
432 return Err(e);
433 }
434 Ok((nibbles, sign == 0xd))
435 }
436
437 pub fn read_any(&mut self) -> Result<Any, SystemException> {
439 let tc = self.read_typecode()?;
440 let v = value::read(self, &tc)?;
441 Ok(Any::new(tc, v))
442 }
443
444 pub fn marshal_error(&self) -> SystemException {
446 marshal_with(self.completed)
447 }
448
449 pub fn completion_status(&self) -> CompletionStatus {
452 self.completed
453 }
454
455 pub fn is_empty(&self) -> bool {
457 self.dec.is_empty()
458 }
459}
460
461impl<'a> Deref for InStream<'a> {
462 type Target = Decoder<'a>;
463
464 fn deref(&self) -> &Decoder<'a> {
465 &self.dec
466 }
467}
468
469impl DerefMut for InStream<'_> {
470 fn deref_mut(&mut self) -> &mut Self::Target {
471 &mut self.dec
472 }
473}
474
475pub(crate) fn marshal(_: rustorb_cdr::Error) -> SystemException {
476 marshal_with(CompletionStatus::Yes)
477}
478
479fn marshal_with(completed: CompletionStatus) -> SystemException {
480 SystemException::new(SystemExceptionKind::MARSHAL, 0, completed)
481}