Skip to main content

rustorb_cdr/
decoder.rs

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