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}
25
26impl<'a> OutStream<'a> {
27    /// A stream over `enc` outside any message, with the native code
28    /// sets (UTF-8 and UTF-16). Bindings use it to marshal the value of an
29    /// `any` on its own, to read it back with [`InStream::standalone`].
30    pub fn standalone(enc: &'a mut Encoder) -> OutStream<'a> {
31        OutStream {
32            enc,
33            code_sets: CodeSets::NATIVE,
34            orb: None,
35        }
36    }
37
38    /// The transmission code sets of the connection.
39    pub fn code_sets(&self) -> CodeSets {
40        self.code_sets
41    }
42
43    /// Uses `code_sets` for the `char` and `wchar` data that follows, as
44    /// on a standalone stream that must match another ORB's native code
45    /// sets.
46    pub fn set_code_sets(&mut self, code_sets: CodeSets) {
47        self.code_sets = code_sets;
48    }
49
50    /// Writes a `string` in the negotiated `char` code set.
51    pub fn write_string(&mut self, s: &str) -> Result<(), SystemException> {
52        let bytes = self.code_sets.encode_string(s)?;
53        Ok(self.enc.write_string_bytes(&bytes)?)
54    }
55
56    /// Writes a `wchar` (one UTF-16 code unit).
57    pub fn write_wchar(&mut self, c: u16) -> Result<(), SystemException> {
58        self.check_wchar()?;
59        Ok(self.enc.write_wchar(c)?)
60    }
61
62    /// Writes a `wstring`.
63    pub fn write_wstring(&mut self, s: &str) -> Result<(), SystemException> {
64        self.check_wchar()?;
65        Ok(self.enc.write_wstring(s)?)
66    }
67
68    /// Writes an object reference; `None` is a nil reference.
69    pub fn write_object(&mut self, obj: Option<&ObjectRef>) -> Result<(), SystemException> {
70        match obj {
71            Some(obj) => {
72                if self.orb.is_none() {
73                    self.orb = Some(obj.orb().clone());
74                }
75                obj.ior().encode(self.enc)?
76            }
77            None => Ior::nil().encode(self.enc)?,
78        }
79        Ok(())
80    }
81
82    /// Writes a TypeCode. An unresolved recursive placeholder is
83    /// `BAD_TYPECODE`.
84    pub fn write_typecode(&mut self, tc: &TypeCode) -> Result<(), SystemException> {
85        tc.encode(self.enc).map_err(|e| match e {
86            rustorb_cdr::Error::InvalidTypeCode(_) => {
87                SystemException::new(SystemExceptionKind::BAD_TYPECODE, 0, CompletionStatus::No)
88            }
89            e => e.into(),
90        })
91    }
92
93    /// Writes a value of type `tc`. A value that does not fit the type is
94    /// `BAD_PARAM`.
95    pub fn write_value(&mut self, tc: &TypeCode, v: &Value) -> Result<(), SystemException> {
96        value::write(self, tc, v)
97    }
98
99    /// Writes a `fixed` of `digits.len()` digits (each 0 to 9, most
100    /// significant first) as packed decimal. A digit over 9 or more than
101    /// 31 digits is `BAD_PARAM`.
102    pub fn write_fixed(&mut self, digits: &[u8], negative: bool) -> Result<(), SystemException> {
103        let n = digits.len();
104        if n > 31 || digits.iter().any(|&d| d > 9) {
105            return Err(SystemException::new(
106                SystemExceptionKind::BAD_PARAM,
107                0,
108                CompletionStatus::No,
109            ));
110        }
111        // Two digits per octet, a leading zero digit when the count is
112        // even, and the sign in the last half octet.
113        let mut nibbles = Vec::with_capacity(n + 2);
114        if n % 2 == 0 {
115            nibbles.push(0);
116        }
117        nibbles.extend_from_slice(digits);
118        nibbles.push(if negative { 0xd } else { 0xc });
119        let bytes: Vec<u8> = nibbles.chunks(2).map(|p| (p[0] << 4) | p[1]).collect();
120        self.enc.write_octets(&bytes);
121        Ok(())
122    }
123
124    /// Writes an `any`: its TypeCode, then its value.
125    pub fn write_any(&mut self, any: &Any) -> Result<(), SystemException> {
126        self.write_typecode(any.typecode())?;
127        value::write(self, any.typecode(), any.value())
128    }
129
130    fn check_wchar(&self) -> Result<(), SystemException> {
131        if self.code_sets.wchar_data.is_none() {
132            return Err(SystemException::new(
133                SystemExceptionKind::BAD_PARAM,
134                crate::minor::WCHAR_TCS_NOT_KNOWN,
135                CompletionStatus::No,
136            ));
137        }
138        Ok(())
139    }
140}
141
142impl Deref for OutStream<'_> {
143    type Target = Encoder;
144
145    fn deref(&self) -> &Encoder {
146        self.enc
147    }
148}
149
150impl DerefMut for OutStream<'_> {
151    fn deref_mut(&mut self) -> &mut Encoder {
152        self.enc
153    }
154}
155
156/// The stream a reply, a user exception or the arguments of a request
157/// are read from.
158///
159/// It dereferences to the CDR [`Decoder`] of the message body, and adds
160/// the operations that depend on the connection, like [`OutStream`].
161/// Errors are `MARSHAL` (or `DATA_CONVERSION`), completed yes when reading
162/// a reply and completed no when a servant reads its arguments.
163#[derive(Debug)]
164pub struct InStream<'a> {
165    pub(crate) dec: Decoder<'a>,
166    pub(crate) code_sets: CodeSets,
167    /// The ORB of the object references read; `None` for a standalone
168    /// stream without one, which reads only nil references.
169    pub(crate) orb: Option<&'a Orb>,
170    pub(crate) completed: CompletionStatus,
171    /// Whether `wchar` data needs a negotiated `wchar` code set, as for
172    /// request arguments (`BAD_PARAM`, `WCHAR_TCS_NOT_KNOWN`).
173    pub(crate) wchar_needs_code_set: bool,
174    /// The valuetypes read, by their slot in the stream, for
175    /// indirections.
176    pub(crate) values: Vec<Option<crate::ValueRef>>,
177    /// The valuetypes and value boxes of generated code read, by their
178    /// slot in the stream (see `idl::ValueHandle`).
179    pub(crate) typed_values: Vec<Option<Box<dyn std::any::Any>>>,
180    /// While the core reads the state of a custom valuetype of generated
181    /// code (for an Any), the items its `unmarshal` has read (see
182    /// `idl::DataInputStream`).
183    pub(crate) custom_items: Option<Vec<crate::Value>>,
184    /// The message body `dec` reads, when it reads one: for
185    /// [`detach`](InStream::detach).
186    pub(crate) body: Option<&'a Body>,
187}
188
189/// The rest of an [`InStream`] over a message body, owned, to be read
190/// later ([`ServerRequest`](crate::dii::ServerRequest)).
191pub(crate) struct DetachedInput {
192    body: Body,
193    skip: usize,
194    code_sets: CodeSets,
195    orb: Option<Orb>,
196    completed: CompletionStatus,
197    wchar_needs_code_set: bool,
198}
199
200impl DetachedInput {
201    /// A stream at the place the detached one was.
202    pub(crate) fn stream(&self) -> InStream<'_> {
203        let mut dec = self.body.decoder();
204        // Within the body: it was read that far.
205        let _ = dec.skip(self.skip);
206        InStream {
207            dec,
208            code_sets: self.code_sets,
209            orb: self.orb.as_ref(),
210            completed: self.completed,
211            wchar_needs_code_set: self.wchar_needs_code_set,
212            values: Vec::new(),
213            typed_values: Vec::new(),
214            custom_items: None,
215            body: Some(&self.body),
216        }
217    }
218}
219
220impl Drop for InStream<'_> {
221    fn drop(&mut self) {
222        // The valuetypes read are kept for indirections until the end of
223        // the stream; those in cycles that nothing read from the stream
224        // still refers to are freed.
225        let values: Vec<_> = self
226            .values
227            .drain(..)
228            .flatten()
229            .map(|v| crate::Value::Valuetype(Some(v)))
230            .collect();
231        if !values.is_empty() {
232            crate::Value::List(values).release();
233        }
234    }
235}
236
237impl<'a> InStream<'a> {
238    /// A stream over `dec` outside any message, with the native code sets,
239    /// as [`OutStream::standalone`] writes. Object references read belong
240    /// to `orb`; without one, only nil references can be read
241    /// (`BAD_INV_ORDER`). Errors are completed no.
242    pub fn standalone(dec: Decoder<'a>, orb: Option<&'a Orb>) -> InStream<'a> {
243        InStream {
244            dec,
245            code_sets: CodeSets::NATIVE,
246            orb,
247            completed: CompletionStatus::No,
248            wchar_needs_code_set: false,
249            values: Vec::new(),
250            typed_values: Vec::new(),
251            custom_items: None,
252            body: None,
253        }
254    }
255
256    /// The rest of the stream, owned, if it reads a message body and no
257    /// valuetype has been read (later ones could refer to it).
258    pub(crate) fn detach(&self) -> Option<DetachedInput> {
259        let body = self.body?;
260        if !self.values.is_empty() || !self.typed_values.is_empty() {
261            return None;
262        }
263        Some(DetachedInput {
264            body: body.clone(),
265            skip: self.dec.position() - body.decoder().position(),
266            code_sets: self.code_sets,
267            orb: self.orb.cloned(),
268            completed: self.completed,
269            wchar_needs_code_set: self.wchar_needs_code_set,
270        })
271    }
272
273    /// The transmission code sets of the connection.
274    pub fn code_sets(&self) -> CodeSets {
275        self.code_sets
276    }
277
278    /// Uses `code_sets` for the `char` and `wchar` data that follows, as
279    /// on a standalone stream that must match another ORB's native code
280    /// sets.
281    pub fn set_code_sets(&mut self, code_sets: CodeSets) {
282        self.code_sets = code_sets;
283    }
284
285    /// Reads a value with its [`CdrDecode`] implementation.
286    pub fn read<T: CdrDecode>(&mut self) -> Result<T, SystemException> {
287        let completed = self.completed;
288        T::decode(&mut self.dec).map_err(|_| marshal_with(completed))
289    }
290
291    /// Reads a `string` in the negotiated `char` code set.
292    pub fn read_string(&mut self) -> Result<String, SystemException> {
293        let completed = self.completed;
294        let bytes = self
295            .dec
296            .read_string_bytes()
297            .map_err(|_| marshal_with(completed))?;
298        self.code_sets.decode_string(bytes).map_err(|mut e| {
299            e.completed = completed;
300            e
301        })
302    }
303
304    /// Reads a `wchar` (one UTF-16 code unit).
305    pub fn read_wchar(&mut self) -> Result<u16, SystemException> {
306        self.check_wchar()?;
307        let completed = self.completed;
308        self.dec.read_wchar().map_err(|_| marshal_with(completed))
309    }
310
311    /// Reads a `wstring`.
312    pub fn read_wstring(&mut self) -> Result<String, SystemException> {
313        self.check_wchar()?;
314        let completed = self.completed;
315        self.dec.read_wstring().map_err(|_| marshal_with(completed))
316    }
317
318    fn check_wchar(&self) -> Result<(), SystemException> {
319        if self.wchar_needs_code_set && self.code_sets.wchar_data.is_none() {
320            return Err(SystemException::new(
321                SystemExceptionKind::BAD_PARAM,
322                crate::minor::WCHAR_TCS_NOT_KNOWN,
323                self.completed,
324            ));
325        }
326        Ok(())
327    }
328
329    /// Reads an object reference; a nil reference is `None`.
330    pub fn read_object(&mut self) -> Result<Option<ObjectRef>, SystemException> {
331        let completed = self.completed;
332        let ior = Ior::decode(&mut self.dec).map_err(|_| marshal_with(completed))?;
333        if ior.is_nil() {
334            return Ok(None);
335        }
336        let orb = self.orb.ok_or_else(|| {
337            SystemException::new(SystemExceptionKind::BAD_INV_ORDER, 0, completed)
338        })?;
339        Ok(Some(ObjectRef::new(orb.clone(), ior)))
340    }
341
342    /// Reads a `char` in the negotiated `char` code set.
343    pub fn read_char_value(&mut self) -> Result<char, SystemException> {
344        let completed = self.completed;
345        let b = self.dec.read_char().map_err(|_| marshal_with(completed))?;
346        let s = self.code_sets.decode_string(&[b]).map_err(|mut e| {
347            e.completed = completed;
348            e
349        })?;
350        s.chars().next().ok_or_else(|| marshal_with(completed))
351    }
352
353    /// Reads a TypeCode.
354    pub fn read_typecode(&mut self) -> Result<TypeCode, SystemException> {
355        let completed = self.completed;
356        TypeCode::decode(&mut self.dec).map_err(|_| marshal_with(completed))
357    }
358
359    /// Reads a value of type `tc`.
360    pub fn read_value(&mut self, tc: &TypeCode) -> Result<Value, SystemException> {
361        value::read(self, tc)
362    }
363
364    /// Reads a `fixed` of `n` digits: the digits, most significant first,
365    /// and whether it is negative. A malformed digit or sign is `MARSHAL`.
366    pub fn read_fixed(&mut self, n: usize) -> Result<(Vec<u8>, bool), SystemException> {
367        let e = self.marshal_error();
368        let bytes = self.dec.read_octets(n / 2 + 1).map_err(|_| e.clone())?;
369        let mut nibbles: Vec<u8> = bytes.iter().flat_map(|b| [b >> 4, b & 0xf]).collect();
370        let sign = nibbles.pop().unwrap_or(0xc);
371        if n % 2 == 0 {
372            nibbles.remove(0);
373        }
374        if nibbles.iter().any(|&d| d > 9) || !matches!(sign, 0xc | 0xd | 0xf) {
375            return Err(e);
376        }
377        Ok((nibbles, sign == 0xd))
378    }
379
380    /// Reads an `any`.
381    pub fn read_any(&mut self) -> Result<Any, SystemException> {
382        let tc = self.read_typecode()?;
383        let v = value::read(self, &tc)?;
384        Ok(Any::new(tc, v))
385    }
386
387    /// `MARSHAL` with the completion status of the stream.
388    pub fn marshal_error(&self) -> SystemException {
389        marshal_with(self.completed)
390    }
391
392    /// The completion status errors of this stream carry: yes for a
393    /// reply, no for request arguments.
394    pub fn completion_status(&self) -> CompletionStatus {
395        self.completed
396    }
397
398    /// Whether every byte of the body was read.
399    pub fn is_empty(&self) -> bool {
400        self.dec.is_empty()
401    }
402}
403
404impl<'a> Deref for InStream<'a> {
405    type Target = Decoder<'a>;
406
407    fn deref(&self) -> &Decoder<'a> {
408        &self.dec
409    }
410}
411
412impl DerefMut for InStream<'_> {
413    fn deref_mut(&mut self) -> &mut Self::Target {
414        &mut self.dec
415    }
416}
417
418pub(crate) fn marshal(_: rustorb_cdr::Error) -> SystemException {
419    marshal_with(CompletionStatus::Yes)
420}
421
422fn marshal_with(completed: CompletionStatus) -> SystemException {
423    SystemException::new(SystemExceptionKind::MARSHAL, 0, completed)
424}