Skip to main content

rustorb_core/
stream.rs

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/// The stream request arguments are written to.
12///
13/// It dereferences to the CDR [`Encoder`] of the message body, and adds
14/// the operations that depend on the connection: `string` in the
15/// negotiated code set, `wchar` and `wstring` only when a wide code set was
16/// negotiated, and object references.
17#[derive(Debug)]
18pub struct OutStream<'a> {
19    pub(crate) enc: &'a mut Encoder,
20    pub(crate) code_sets: CodeSets,
21    /// The ORB of the first object reference written, so that a standalone
22    /// stream can be read back with it (`Any::insert`).
23    pub(crate) orb: Option<Orb>,
24    /// What a binding asked to know of the valuetypes written
25    /// ([`OutStream::log_values`]).
26    pub(crate) values: Option<ValueLog>,
27}
28
29/// The valuetypes written to an [`OutStream`] that logs them.
30#[derive(Debug, Default)]
31pub(crate) struct ValueLog {
32    /// Whether every value is written chunked.
33    pub(crate) chunked: bool,
34    /// The instances written (not as indirections), in order: the n-th is
35    /// read back at slot n.
36    pub(crate) written: Vec<crate::ValueRef>,
37}
38
39impl<'a> OutStream<'a> {
40    /// A stream over `enc` outside any message, with the native code
41    /// sets (UTF-8 and UTF-16). Bindings use it to marshal the value of an
42    /// `any` on its own, to read it back with [`InStream::standalone`].
43    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    /// Makes the stream keep the valuetype instances it writes, for
53    /// [`OutStream::written_values`], and write each value chunked (so
54    /// that a reader can skip one whole, nested values included). A
55    /// binding uses it to find the instance a value read back stands for.
56    pub fn log_values(&mut self) {
57        self.values = Some(ValueLog {
58            chunked: true,
59            written: Vec::new(),
60        });
61    }
62
63    /// The instances written since [`OutStream::log_values`] (not those
64    /// written as indirections), in order: the reader of the stream reads
65    /// the n-th at slot n.
66    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    /// The transmission code sets of the connection.
80    pub fn code_sets(&self) -> CodeSets {
81        self.code_sets
82    }
83
84    /// Uses `code_sets` for the `char` and `wchar` data that follows, as
85    /// on a standalone stream that must match another ORB's native code
86    /// sets.
87    pub fn set_code_sets(&mut self, code_sets: CodeSets) {
88        self.code_sets = code_sets;
89    }
90
91    /// Writes a `string` in the negotiated `char` code set.
92    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    /// Writes a `wchar` (one UTF-16 code unit).
98    pub fn write_wchar(&mut self, c: u16) -> Result<(), SystemException> {
99        self.check_wchar()?;
100        Ok(self.enc.write_wchar(c)?)
101    }
102
103    /// Writes a `wstring`.
104    pub fn write_wstring(&mut self, s: &str) -> Result<(), SystemException> {
105        self.check_wchar()?;
106        Ok(self.enc.write_wstring(s)?)
107    }
108
109    /// Writes an object reference; `None` is a nil reference.
110    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    /// Writes a TypeCode. An unresolved recursive placeholder is
124    /// `BAD_TYPECODE`.
125    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    /// Writes a value of type `tc`. A value that does not fit the type is
135    /// `BAD_PARAM`.
136    pub fn write_value(&mut self, tc: &TypeCode, v: &Value) -> Result<(), SystemException> {
137        value::write(self, tc, v)
138    }
139
140    /// Writes a `fixed` of `digits.len()` digits (each 0 to 9, most
141    /// significant first) as packed decimal. A digit over 9 or more than
142    /// 31 digits is `BAD_PARAM`.
143    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        // Two digits per octet, a leading zero digit when the count is
153        // even, and the sign in the last half octet.
154        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    /// Writes an `any`: its TypeCode, then its value.
166    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/// The stream a reply, a user exception or the arguments of a request
198/// are read from.
199///
200/// It dereferences to the CDR [`Decoder`] of the message body, and adds
201/// the operations that depend on the connection, like [`OutStream`].
202/// Errors are `MARSHAL` (or `DATA_CONVERSION`), completed yes when reading
203/// a reply and completed no when a servant reads its arguments.
204#[derive(Debug)]
205pub struct InStream<'a> {
206    pub(crate) dec: Decoder<'a>,
207    pub(crate) code_sets: CodeSets,
208    /// The ORB of the object references read; `None` for a standalone
209    /// stream without one, which reads only nil references.
210    pub(crate) orb: Option<&'a Orb>,
211    pub(crate) completed: CompletionStatus,
212    /// Whether `wchar` data needs a negotiated `wchar` code set, as for
213    /// request arguments (`BAD_PARAM`, `WCHAR_TCS_NOT_KNOWN`).
214    pub(crate) wchar_needs_code_set: bool,
215    /// The valuetypes read, by their slot in the stream, for
216    /// indirections.
217    pub(crate) values: Vec<Option<crate::ValueRef>>,
218    /// The valuetypes and value boxes of generated code read, by their
219    /// slot in the stream (see `idl::ValueHandle`).
220    pub(crate) typed_values: Vec<Option<Box<dyn std::any::Any>>>,
221    /// While the core reads the state of a custom valuetype of generated
222    /// code (for an Any), the items its `unmarshal` has read (see
223    /// `idl::DataInputStream`).
224    pub(crate) custom_items: Option<Vec<crate::Value>>,
225    /// The message body `dec` reads, when it reads one: for
226    /// [`detach`](InStream::detach).
227    pub(crate) body: Option<&'a Body>,
228}
229
230/// The rest of an [`InStream`] over a message body, owned, to be read
231/// later ([`ServerRequest`](crate::dii::ServerRequest)).
232pub(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    /// A stream at the place the detached one was.
243    pub(crate) fn stream(&self) -> InStream<'_> {
244        let mut dec = self.body.decoder();
245        // Within the body: it was read that far.
246        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        // The valuetypes read are kept for indirections until the end of
264        // the stream; those in cycles that nothing read from the stream
265        // still refers to are freed.
266        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    /// A stream over `dec` outside any message, with the native code sets,
280    /// as [`OutStream::standalone`] writes. Object references read belong
281    /// to `orb`; without one, only nil references can be read
282    /// (`BAD_INV_ORDER`). Errors are completed no.
283    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    /// Makes the value read at `slot` (the n-th value of the stream) be
298    /// read into `v`, replacing its state, if it has the type of `v`;
299    /// otherwise a new instance is made as usual. A binding uses it to
300    /// keep the instance a value it wrote already stands for.
301    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    /// The instance read at `slot`, if any.
309    pub fn value_at(&self, slot: usize) -> Option<&crate::ValueRef> {
310        self.values.get(slot).and_then(Option::as_ref)
311    }
312
313    /// The rest of the stream, owned, if it reads a message body and no
314    /// valuetype has been read (later ones could refer to it).
315    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    /// The transmission code sets of the connection.
331    pub fn code_sets(&self) -> CodeSets {
332        self.code_sets
333    }
334
335    /// Uses `code_sets` for the `char` and `wchar` data that follows, as
336    /// on a standalone stream that must match another ORB's native code
337    /// sets.
338    pub fn set_code_sets(&mut self, code_sets: CodeSets) {
339        self.code_sets = code_sets;
340    }
341
342    /// Reads a value with its [`CdrDecode`] implementation.
343    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    /// Reads a `string` in the negotiated `char` code set.
349    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    /// Reads a `wchar` (one UTF-16 code unit).
362    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    /// Reads a `wstring`.
369    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    /// Reads an object reference; a nil reference is `None`.
387    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    /// Reads a `char` in the negotiated `char` code set.
400    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    /// Reads a TypeCode.
411    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    /// Reads a value of type `tc`.
417    pub fn read_value(&mut self, tc: &TypeCode) -> Result<Value, SystemException> {
418        value::read(self, tc)
419    }
420
421    /// Reads a `fixed` of `n` digits: the digits, most significant first,
422    /// and whether it is negative. A malformed digit or sign is `MARSHAL`.
423    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    /// Reads an `any`.
438    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    /// `MARSHAL` with the completion status of the stream.
445    pub fn marshal_error(&self) -> SystemException {
446        marshal_with(self.completed)
447    }
448
449    /// The completion status errors of this stream carry: yes for a
450    /// reply, no for request arguments.
451    pub fn completion_status(&self) -> CompletionStatus {
452        self.completed
453    }
454
455    /// Whether every byte of the body was read.
456    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}