Skip to main content

rustorb_cdr/
decoder.rs

1use std::sync::Arc;
2
3use crate::{ByteOrder, Encoding, Error, LongDouble, Octets, Result, SHARE_MIN};
4
5/// Reads CDR from a byte slice.
6///
7/// Alignment is relative to the stream offset of the first byte, which is
8/// `0` unless the decoder was created with [`Decoder::with_offset`].
9/// [`Decoder::set_segments`] restarts the stream offset at given bytes,
10/// for data joined from several messages.
11#[derive(Debug, Clone)]
12pub struct Decoder<'a> {
13    pub(crate) buf: &'a [u8],
14    /// The buffer `buf` lies in, when it is shared.
15    shared: Option<&'a Arc<Vec<u8>>>,
16    pub(crate) pos: usize,
17    pub(crate) order: ByteOrder,
18    encoding: Encoding,
19    base: usize,
20    /// The stream offset alignment counts from (`XCDR.origin`).
21    pub(crate) origin: usize,
22    segments: &'a [Segment],
23    wstring_default_order: ByteOrder,
24    /// What the valuetypes read so far need (indirections, chunks);
25    /// made with the first value.
26    pub(crate) values: Option<Box<crate::value::ReadState>>,
27}
28
29/// A point in a decoder's buffer from which the stream offset restarts.
30///
31/// The byte at index `start` of the buffer is at stream offset `offset`,
32/// and the bytes after it follow on, until the next segment. This
33/// describes a message joined from fragments whose contents are aligned
34/// relative to each fragment rather than to the joined message.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct Segment {
37    /// Index of the first byte of the segment in the buffer.
38    pub start: usize,
39    /// Stream offset of that byte.
40    pub offset: usize,
41}
42
43macro_rules! read_number {
44    ($(#[$doc:meta] $name:ident: $ty:ty;)*) => {
45        $(
46            #[$doc]
47            pub fn $name(&mut self) -> Result<$ty> {
48                self.align(size_of::<$ty>())?;
49                let bytes = self.read_array()?;
50                Ok(match self.order {
51                    ByteOrder::Big => <$ty>::from_be_bytes(bytes),
52                    ByteOrder::Little => <$ty>::from_le_bytes(bytes),
53                })
54            }
55        )*
56    };
57}
58
59impl<'a> Decoder<'a> {
60    /// Creates a decoder whose first byte is at stream offset 0.
61    pub fn new(buf: &'a [u8], order: ByteOrder, encoding: Encoding) -> Decoder<'a> {
62        Decoder::with_offset(buf, order, encoding, 0)
63    }
64
65    /// Creates a decoder whose first byte is at stream offset `base`.
66    pub fn with_offset(
67        buf: &'a [u8],
68        order: ByteOrder,
69        encoding: Encoding,
70        base: usize,
71    ) -> Decoder<'a> {
72        Decoder {
73            buf,
74            shared: None,
75            pos: 0,
76            order,
77            encoding,
78            base,
79            origin: 0,
80            segments: &[],
81            wstring_default_order: ByteOrder::Big,
82            values: None,
83        }
84    }
85
86    /// Restarts the stream offset at the given buffer indexes. `segments`
87    /// must be sorted by `start`; bytes before the first segment keep the
88    /// offset given when the decoder was created.
89    pub fn set_segments(&mut self, segments: &'a [Segment]) {
90        debug_assert!(segments.windows(2).all(|w| w[0].start < w[1].start));
91        self.segments = segments;
92    }
93
94    /// Opens an encapsulation: reads the byte order octet and returns a
95    /// decoder positioned after it, with alignment starting at that octet.
96    pub fn encapsulation(buf: &'a [u8], encoding: Encoding) -> Result<Decoder<'a>> {
97        let (&flag, _) = buf.split_first().ok_or(Error::EmptyEncapsulation)?;
98        let order = ByteOrder::from_flag(flag)?;
99        let mut dec = Decoder::new(buf, order, encoding);
100        dec.pos = 1;
101        Ok(dec)
102    }
103
104    /// Sets the byte order assumed for a GIOP 1.2 `wstring` or `wchar`
105    /// without a BOM. The specification says big endian, which is the
106    /// default; some ORBs use the stream byte order instead.
107    pub fn set_wstring_default_order(&mut self, order: ByteOrder) {
108        self.wstring_default_order = order;
109    }
110
111    /// The byte order of the stream.
112    pub fn byte_order(&self) -> ByteOrder {
113        self.order
114    }
115
116    /// The encoding whose rules apply.
117    pub fn encoding(&self) -> Encoding {
118        self.encoding
119    }
120
121    /// The stream offset of the next byte.
122    pub fn position(&self) -> usize {
123        let i = self.segments.partition_point(|s| s.start <= self.pos);
124        match i.checked_sub(1) {
125            Some(i) => {
126                let segment = self.segments[i];
127                segment.offset + (self.pos - segment.start)
128            }
129            None => self.base + self.pos,
130        }
131    }
132
133    /// Bytes left to read.
134    pub fn remaining(&self) -> usize {
135        self.buf.len() - self.pos
136    }
137
138    /// Whether every byte has been read.
139    pub fn is_empty(&self) -> bool {
140        self.remaining() == 0
141    }
142
143    /// The bytes left to read, without consuming them.
144    pub fn remaining_bytes(&self) -> &'a [u8] {
145        &self.buf[self.pos..]
146    }
147
148    /// Skips padding until the stream offset is a multiple of `align`, or
149    /// of the encoding's [`max_align`](Encoding::max_align) when that is
150    /// smaller.
151    ///
152    /// Inside a chunked valuetype, a chunk that ends here is followed by
153    /// the next one: its length is read and the data aligned in it. In an
154    /// XCDR stream the offset counts from the alignment origin (see
155    /// [`set_origin`](Decoder::set_origin)).
156    pub fn align(&mut self, align: usize) -> Result<()> {
157        let align = align.min(self.encoding.max_align());
158        loop {
159            self.chunk_boundary()?;
160            let rem = self.position().wrapping_sub(self.origin) % align;
161            if rem == 0 {
162                return Ok(());
163            }
164            // Padding that runs past the end of a chunk continues in the
165            // next one, after its length.
166            let mut pad = align - rem;
167            if let Some(end) = self.chunk_end() {
168                pad = pad.min(end - self.pos);
169            }
170            self.read_octets_raw(pad)?;
171        }
172    }
173
174    /// The stream offset alignment counts from: 0 unless changed with
175    /// [`set_origin`](Decoder::set_origin).
176    pub fn origin(&self) -> usize {
177        self.origin
178    }
179
180    /// Makes alignment count from stream offset `origin`. This is the XCDR
181    /// `PUSH(ORIGIN)`; [`read_parameter`](Decoder::read_parameter) does it
182    /// itself.
183    pub fn set_origin(&mut self, origin: usize) {
184        self.origin = origin;
185    }
186
187    /// Skips `n` bytes.
188    pub fn skip(&mut self, n: usize) -> Result<()> {
189        self.read_octets(n).map(|_| ())
190    }
191
192    /// Reads `n` raw octets without alignment.
193    pub fn read_octets(&mut self, n: usize) -> Result<&'a [u8]> {
194        if n > 0 {
195            self.chunk_boundary()?;
196            self.check_in_chunk(n)?;
197        }
198        self.read_octets_raw(n)
199    }
200
201    /// Skips padding, ignoring chunks.
202    pub(crate) fn align_raw(&mut self, align: usize) -> Result<()> {
203        let rem = self.position() % align;
204        if rem != 0 {
205            self.read_octets_raw(align - rem)?;
206        }
207        Ok(())
208    }
209
210    /// Reads an aligned `unsigned long`, ignoring chunks.
211    pub(crate) fn read_u32_raw(&mut self) -> Result<u32> {
212        self.align_raw(4)?;
213        let bytes: [u8; 4] = self
214            .read_octets_raw(4)?
215            .try_into()
216            .expect("read_octets_raw returned 4 bytes");
217        Ok(match self.order {
218            ByteOrder::Big => u32::from_be_bytes(bytes),
219            ByteOrder::Little => u32::from_le_bytes(bytes),
220        })
221    }
222
223    /// Reads `n` octets, ignoring chunks.
224    pub(crate) fn read_octets_raw(&mut self, n: usize) -> Result<&'a [u8]> {
225        let remaining = self.remaining();
226        if n > remaining {
227            return Err(Error::UnexpectedEof {
228                needed: n,
229                remaining,
230            });
231        }
232        let bytes = &self.buf[self.pos..self.pos + n];
233        self.pos += n;
234        Ok(bytes)
235    }
236
237    fn read_array<const N: usize>(&mut self) -> Result<[u8; N]> {
238        let bytes = self.read_octets(N)?;
239        Ok(bytes.try_into().expect("read_octets returned N bytes"))
240    }
241
242    /// Reads an `octet`.
243    pub fn read_octet(&mut self) -> Result<u8> {
244        Ok(self.read_array::<1>()?[0])
245    }
246
247    /// Reads a `boolean`. Octets other than `0` and `1` are rejected.
248    pub fn read_bool(&mut self) -> Result<bool> {
249        match self.read_octet()? {
250            0 => Ok(false),
251            1 => Ok(true),
252            other => Err(Error::InvalidBoolean(other)),
253        }
254    }
255
256    /// Reads a `char` as a single octet in the transmission code set.
257    pub fn read_char(&mut self) -> Result<u8> {
258        self.read_octet()
259    }
260
261    read_number! {
262        /// Reads a `short`.
263        read_i16: i16;
264        /// Reads an `unsigned short`.
265        read_u16: u16;
266        /// Reads a `long`.
267        read_i32: i32;
268        /// Reads an `unsigned long`.
269        read_u32: u32;
270        /// Reads a `long long`.
271        read_i64: i64;
272        /// Reads an `unsigned long long`.
273        read_u64: u64;
274        /// Reads a `float`.
275        read_f32: f32;
276        /// Reads a `double`.
277        read_f64: f64;
278    }
279
280    /// Reads a `long double`: 16 octets on an 8 octet boundary.
281    pub fn read_long_double(&mut self) -> Result<LongDouble> {
282        self.align(8)?;
283        let bytes = self.read_array()?;
284        Ok(LongDouble::from_bits(match self.order {
285            ByteOrder::Big => u128::from_be_bytes(bytes),
286            ByteOrder::Little => u128::from_le_bytes(bytes),
287        }))
288    }
289
290    /// Reads a sequence length and checks that `len * min_element_size`
291    /// bytes are left, so a corrupt length cannot cause a huge allocation.
292    pub fn read_len(&mut self, min_element_size: usize) -> Result<usize> {
293        let len = self.read_u32()?;
294        let remaining = self.remaining();
295        let needed = (len as usize).saturating_mul(min_element_size);
296        if needed > remaining {
297            return Err(Error::LengthTooLarge { len, remaining });
298        }
299        Ok(len as usize)
300    }
301
302    /// Reads a `sequence<octet>` without copying.
303    pub fn read_octet_seq(&mut self) -> Result<&'a [u8]> {
304        let len = self.read_len(1)?;
305        self.read_octets(len)
306    }
307
308    /// Tells the decoder that its bytes lie in `buf`, so that
309    /// [`read_octet_seq_shared`](Decoder::read_octet_seq_shared) can share
310    /// them.
311    pub fn set_shared(&mut self, buf: &'a Arc<Vec<u8>>) {
312        self.shared = Some(buf);
313    }
314
315    /// Reads a `sequence<octet>` that keeps pointing into the decoder's
316    /// buffer, when that is shared (see
317    /// [`set_shared`](Decoder::set_shared)) and the sequence is not short;
318    /// otherwise a copy.
319    pub fn read_octet_seq_shared(&mut self) -> Result<Octets> {
320        let len = self.read_len(1)?;
321        self.read_octets_shared(len)
322    }
323
324    /// Reads `len` raw octets like
325    /// [`read_octet_seq_shared`](Decoder::read_octet_seq_shared) reads a
326    /// sequence's.
327    pub fn read_octets_shared(&mut self, len: usize) -> Result<Octets> {
328        let bytes = self.read_octets(len)?;
329        if let Some(buf) = self.shared.filter(|_| bytes.len() >= SHARE_MIN) {
330            let base = buf.as_ptr() as usize;
331            let at = bytes.as_ptr() as usize;
332            if at >= base && at + bytes.len() <= base + buf.len() {
333                let start = at - base;
334                return Ok(Octets::slice_of(
335                    Arc::clone(buf),
336                    start..start + bytes.len(),
337                ));
338            }
339        }
340        Ok(Octets::from(bytes))
341    }
342
343    /// Reads a `string` as bytes in the transmission code set, without the
344    /// terminating NUL.
345    ///
346    /// A length of 0 is not allowed by the specification but is accepted as
347    /// an empty string, since some ORBs send it.
348    pub fn read_string_bytes(&mut self) -> Result<&'a [u8]> {
349        let bytes = self.read_octet_seq()?;
350        match bytes.split_last() {
351            None => Ok(bytes),
352            Some((0, rest)) => Ok(rest),
353            Some(_) => Err(Error::StringNotTerminated),
354        }
355    }
356
357    /// Reads a `string` as UTF-8.
358    pub fn read_string(&mut self) -> Result<String> {
359        let bytes = self.read_string_bytes()?;
360        String::from_utf8(bytes.to_vec()).map_err(|_| Error::InvalidUtf8)
361    }
362
363    /// Reads a `wchar` holding one UTF-16 code unit.
364    pub fn read_wchar(&mut self) -> Result<u16> {
365        match self.encoding {
366            Encoding::Giop1_0 => Err(Error::WcharNotSupported),
367            Encoding::Giop1_1 | Encoding::Xcdr1 | Encoding::Xcdr2 => self.read_u16(),
368            Encoding::Giop1_2 => {
369                let len = self.read_octet()?;
370                if len != 2 && len != 4 {
371                    return Err(Error::InvalidWcharLength(len));
372                }
373                let bytes = self.read_octets(len as usize)?;
374                let units = self.utf16_units(bytes);
375                match units.as_slice() {
376                    [unit] => Ok(*unit),
377                    _ => Err(Error::InvalidWcharLength(len)),
378                }
379            }
380        }
381    }
382
383    /// Reads a `wstring` encoded as UTF-16.
384    ///
385    /// For GIOP 1.2 a leading BOM selects the byte order; without one the
386    /// order set by [`Decoder::set_wstring_default_order`] is used. XCDR
387    /// has an octet length and code units in the stream byte order.
388    pub fn read_wstring(&mut self) -> Result<String> {
389        match self.encoding {
390            Encoding::Giop1_0 => Err(Error::WcharNotSupported),
391            Encoding::Xcdr1 | Encoding::Xcdr2 => {
392                let len = self.read_len(1)?;
393                if len % 2 != 0 {
394                    return Err(Error::OddWstringLength(len as u32));
395                }
396                let mut units = Vec::with_capacity(len / 2);
397                for _ in 0..len / 2 {
398                    units.push(self.read_u16()?);
399                }
400                String::from_utf16(&units).map_err(|_| Error::InvalidUtf16)
401            }
402            Encoding::Giop1_1 => {
403                let len = self.read_len(2)?;
404                let mut units = Vec::with_capacity(len);
405                for _ in 0..len {
406                    units.push(self.read_u16()?);
407                }
408                // The length counts a terminating NUL; tolerate its absence.
409                if units.last() == Some(&0) {
410                    units.pop();
411                }
412                String::from_utf16(&units).map_err(|_| Error::InvalidUtf16)
413            }
414            Encoding::Giop1_2 => {
415                let bytes = self.read_octet_seq()?;
416                if bytes.len() % 2 != 0 {
417                    return Err(Error::OddWstringLength(bytes.len() as u32));
418                }
419                String::from_utf16(&self.utf16_units(bytes)).map_err(|_| Error::InvalidUtf16)
420            }
421        }
422    }
423
424    /// Splits GIOP 1.2 wide character octets into code units, honouring and
425    /// removing a leading BOM.
426    fn utf16_units(&self, bytes: &[u8]) -> Vec<u16> {
427        let (order, data) = match bytes {
428            [0xFE, 0xFF, rest @ ..] => (ByteOrder::Big, rest),
429            [0xFF, 0xFE, rest @ ..] => (ByteOrder::Little, rest),
430            _ => (self.wstring_default_order, bytes),
431        };
432        data.chunks_exact(2)
433            .map(|c| match order {
434                ByteOrder::Big => u16::from_be_bytes([c[0], c[1]]),
435                ByteOrder::Little => u16::from_le_bytes([c[0], c[1]]),
436            })
437            .collect()
438    }
439
440    /// Reads an encapsulation and returns a decoder over its contents.
441    pub fn read_encapsulation(&mut self) -> Result<Decoder<'a>> {
442        let bytes = self.read_octet_seq()?;
443        let mut inner = Decoder::encapsulation(bytes, self.encoding)?;
444        inner.wstring_default_order = self.wstring_default_order;
445        Ok(inner)
446    }
447}