Skip to main content

rustorb_cdr/
encoder.rs

1use crate::{ByteOrder, Encoding, Error, LongDouble, Octets, Result, SHARE_MIN};
2
3/// Writes CDR into a growable buffer.
4///
5/// Alignment is relative to the stream offset of the first byte, which is
6/// `0` unless the encoder was created with [`Encoder::with_offset`].
7///
8/// An encoder that [allows shared octets](Encoder::allow_shared) keeps
9/// large octet sequences written with
10/// [`write_octet_seq_shared`](Encoder::write_octet_seq_shared) apart from
11/// its buffer: [`into_parts`](Encoder::into_parts) gives the buffer and
12/// where each goes, for a vectored write, and
13/// [`into_bytes`](Encoder::into_bytes) puts them in place.
14#[derive(Debug, Clone)]
15pub struct Encoder {
16    pub(crate) buf: Vec<u8>,
17    /// Shared octet sequences, each with the buffer length at which it
18    /// goes.
19    shared: Vec<(usize, Octets)>,
20    /// Their total length.
21    shared_len: usize,
22    allow_shared: bool,
23    pub(crate) order: ByteOrder,
24    encoding: Encoding,
25    base: usize,
26    /// The stream offset alignment counts from (`XCDR.origin`); 0 except
27    /// inside an XCDR stream.
28    pub(crate) origin: usize,
29    wstring_bom: bool,
30    /// The valuetypes written so far (for indirections) and the chunk
31    /// being written; made with the first value.
32    pub(crate) values: Option<Box<crate::value::WriteState>>,
33}
34
35macro_rules! write_number {
36    ($(#[$doc:meta] $name:ident: $ty:ty;)*) => {
37        $(
38            #[$doc]
39            pub fn $name(&mut self, value: $ty) {
40                self.align(size_of::<$ty>());
41                match self.order {
42                    ByteOrder::Big => self.buf.extend_from_slice(&value.to_be_bytes()),
43                    ByteOrder::Little => self.buf.extend_from_slice(&value.to_le_bytes()),
44                }
45            }
46        )*
47    };
48}
49
50impl Encoder {
51    /// Creates an encoder whose first byte is at stream offset 0.
52    pub fn new(order: ByteOrder, encoding: Encoding) -> Encoder {
53        Encoder::with_offset(order, encoding, 0)
54    }
55
56    /// Creates an encoder whose first byte is at stream offset `base`.
57    pub fn with_offset(order: ByteOrder, encoding: Encoding, base: usize) -> Encoder {
58        Encoder {
59            buf: Vec::new(),
60            shared: Vec::new(),
61            shared_len: 0,
62            allow_shared: false,
63            order,
64            encoding,
65            base,
66            origin: 0,
67            wstring_bom: true,
68            values: None,
69        }
70    }
71
72    /// Starts an encapsulation: offset 0, with the byte order octet written.
73    pub fn encapsulation(order: ByteOrder, encoding: Encoding) -> Encoder {
74        let mut enc = Encoder::new(order, encoding);
75        enc.write_octet(order.flag());
76        enc
77    }
78
79    /// Chooses how a GIOP 1.2 `wstring` is written: with a BOM followed by
80    /// code units in the stream byte order (the default, as omniORB does),
81    /// or, when `false`, big endian without a BOM (the form the
82    /// specification defines for a missing BOM). Readers that follow
83    /// CORBA 2.4 or later accept both.
84    pub fn set_wstring_bom(&mut self, bom: bool) {
85        self.wstring_bom = bom;
86    }
87
88    /// The byte order of the stream.
89    pub fn byte_order(&self) -> ByteOrder {
90        self.order
91    }
92
93    /// The encoding whose rules apply.
94    pub fn encoding(&self) -> Encoding {
95        self.encoding
96    }
97
98    /// The stream offset of the next byte.
99    pub fn position(&self) -> usize {
100        self.base + self.len()
101    }
102
103    /// Bytes written so far, shared octets included.
104    pub fn len(&self) -> usize {
105        self.buf.len() + self.shared_len
106    }
107
108    /// Whether nothing has been written.
109    pub fn is_empty(&self) -> bool {
110        self.len() == 0
111    }
112
113    /// The bytes written into the buffer so far: all of them, unless
114    /// shared octets were kept apart.
115    pub fn as_bytes(&self) -> &[u8] {
116        &self.buf
117    }
118
119    /// Mutable access to the buffer, for patching lengths. Indexes are
120    /// buffer indexes, which differ from stream offsets after shared
121    /// octets.
122    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
123        &mut self.buf
124    }
125
126    /// Drops bytes past `len`, which must not be before shared octets.
127    pub fn truncate(&mut self, len: usize) {
128        debug_assert!(self.shared.last().is_none_or(|(at, _)| *at <= len));
129        self.buf.truncate(len);
130    }
131
132    /// Consumes the encoder and returns the bytes, shared octets copied in
133    /// place.
134    pub fn into_bytes(self) -> Vec<u8> {
135        if self.shared.is_empty() {
136            return self.buf;
137        }
138        let mut out = Vec::with_capacity(self.len());
139        let mut from = 0;
140        for (at, octets) in &self.shared {
141            out.extend_from_slice(&self.buf[from..*at]);
142            out.extend_from_slice(octets);
143            from = *at;
144        }
145        out.extend_from_slice(&self.buf[from..]);
146        out
147    }
148
149    /// Consumes the encoder and returns the buffer and the shared octets,
150    /// each with the buffer length at which it goes.
151    pub fn into_parts(self) -> (Vec<u8>, Vec<(usize, Octets)>) {
152        (self.buf, self.shared)
153    }
154
155    /// Makes room for at least `additional` more bytes in the buffer.
156    pub fn reserve(&mut self, additional: usize) {
157        self.buf.reserve(additional);
158    }
159
160    /// Lets [`write_octet_seq_shared`](Encoder::write_octet_seq_shared)
161    /// keep large octet sequences apart from the buffer. Only for an
162    /// encoder whose result goes out through
163    /// [`into_parts`](Encoder::into_parts) or
164    /// [`into_bytes`](Encoder::into_bytes), not one read through
165    /// [`as_bytes`](Encoder::as_bytes).
166    pub fn allow_shared(&mut self, allow: bool) {
167        self.allow_shared = allow;
168    }
169
170    /// Pads with zero octets until the stream offset is a multiple of
171    /// `align`, or of the encoding's [`max_align`](Encoding::max_align)
172    /// when that is smaller.
173    ///
174    /// In an XCDR stream the offset counts from the alignment origin (see
175    /// [`set_origin`](Encoder::set_origin)).
176    pub fn align(&mut self, align: usize) {
177        let align = align.min(self.encoding.max_align());
178        let rem = (self.position() - self.origin) % align;
179        if rem != 0 {
180            self.buf.resize(self.buf.len() + align - rem, 0);
181        }
182    }
183
184    /// The stream offset alignment counts from: 0 unless changed with
185    /// [`set_origin`](Encoder::set_origin).
186    pub fn origin(&self) -> usize {
187        self.origin
188    }
189
190    /// Makes alignment count from stream offset `origin`, which must not
191    /// be past [`position`](Encoder::position). This is the XCDR
192    /// `PUSH(ORIGIN)`; the parameter headers of
193    /// [`begin_parameter`](Encoder::begin_parameter) do it themselves.
194    pub fn set_origin(&mut self, origin: usize) {
195        debug_assert!(origin <= self.position());
196        self.origin = origin;
197    }
198
199    /// Writes an `octet`.
200    pub fn write_octet(&mut self, value: u8) {
201        self.buf.push(value);
202    }
203
204    /// Writes a `boolean`.
205    pub fn write_bool(&mut self, value: bool) {
206        self.buf.push(u8::from(value));
207    }
208
209    /// Writes a `char` as a single octet in the transmission code set.
210    pub fn write_char(&mut self, value: u8) {
211        self.buf.push(value);
212    }
213
214    write_number! {
215        /// Writes a `short`.
216        write_i16: i16;
217        /// Writes an `unsigned short`.
218        write_u16: u16;
219        /// Writes a `long`.
220        write_i32: i32;
221        /// Writes an `unsigned long`.
222        write_u32: u32;
223        /// Writes a `long long`.
224        write_i64: i64;
225        /// Writes an `unsigned long long`.
226        write_u64: u64;
227        /// Writes a `float`.
228        write_f32: f32;
229        /// Writes a `double`.
230        write_f64: f64;
231    }
232
233    /// Writes a `long double`: 16 octets on an 8 octet boundary.
234    pub fn write_long_double(&mut self, value: LongDouble) {
235        self.align(8);
236        let bits = value.to_bits();
237        self.buf.extend_from_slice(&match self.order {
238            ByteOrder::Big => bits.to_be_bytes(),
239            ByteOrder::Little => bits.to_le_bytes(),
240        });
241    }
242
243    /// Writes raw octets without alignment or a length.
244    pub fn write_octets(&mut self, bytes: &[u8]) {
245        self.buf.extend_from_slice(bytes);
246    }
247
248    /// Writes a sequence length.
249    pub fn write_len(&mut self, len: usize) -> Result<()> {
250        let len = u32::try_from(len).map_err(|_| Error::LengthOverflow(len))?;
251        self.write_u32(len);
252        Ok(())
253    }
254
255    /// Writes a `sequence<octet>`.
256    pub fn write_octet_seq(&mut self, bytes: &[u8]) -> Result<()> {
257        self.write_len(bytes.len())?;
258        self.write_octets(bytes);
259        Ok(())
260    }
261
262    /// Writes a `sequence<octet>` without copying a large one, if the
263    /// encoder [allows it](Encoder::allow_shared) and no valuetype is
264    /// being written (whose chunk lengths count the buffer), and the
265    /// encoding is a GIOP one (XCDR headers are patched in the buffer). Otherwise
266    /// like [`write_octet_seq`](Encoder::write_octet_seq).
267    pub fn write_octet_seq_shared(&mut self, octets: &Octets) -> Result<()> {
268        if !self.allow_shared
269            || octets.len() < SHARE_MIN
270            || self.values.is_some()
271            || !self.encoding.is_giop()
272        {
273            return self.write_octet_seq(octets);
274        }
275        self.write_len(octets.len())?;
276        self.shared.push((self.buf.len(), octets.clone()));
277        self.shared_len += octets.len();
278        Ok(())
279    }
280
281    /// Writes a `string` from bytes already in the transmission code set.
282    ///
283    /// The length includes the terminating NUL, which is appended here.
284    pub fn write_string_bytes(&mut self, bytes: &[u8]) -> Result<()> {
285        self.write_len(bytes.len() + 1)?;
286        self.write_octets(bytes);
287        self.write_octet(0);
288        Ok(())
289    }
290
291    /// Writes a `string` as UTF-8.
292    pub fn write_string(&mut self, value: &str) -> Result<()> {
293        self.write_string_bytes(value.as_bytes())
294    }
295
296    /// Writes a `wchar` holding one UTF-16 code unit.
297    ///
298    /// GIOP 1.1 and XCDR (`Char16`, DDS-XTypes 7.4.1.1.1) write an aligned
299    /// `unsigned short` in the stream byte order. GIOP 1.2 writes an octet length of 2 followed by the code unit in big
300    /// endian without a BOM, as omniORB does.
301    pub fn write_wchar(&mut self, value: u16) -> Result<()> {
302        match self.encoding {
303            Encoding::Giop1_0 => return Err(Error::WcharNotSupported),
304            Encoding::Giop1_1 | Encoding::Xcdr1 | Encoding::Xcdr2 => self.write_u16(value),
305            Encoding::Giop1_2 => {
306                self.write_octet(2);
307                self.write_octets(&value.to_be_bytes());
308            }
309        }
310        Ok(())
311    }
312
313    /// Writes a `wstring` encoded as UTF-16.
314    ///
315    /// GIOP 1.1 writes the number of code units including a terminating
316    /// NUL, then aligned code units in the stream byte order. GIOP 1.2
317    /// writes the octet length, then the code units without a terminator:
318    /// by default a BOM followed by the stream byte order, or big endian
319    /// without a BOM (see [`Encoder::set_wstring_bom`]). An empty string is
320    /// just a zero length. XCDR (DDS-XTypes 7.4.1.1.2) writes the length in
321    /// octets, then the code units in the stream byte order, without a BOM
322    /// or a terminator.
323    pub fn write_wstring(&mut self, value: &str) -> Result<()> {
324        match self.encoding {
325            Encoding::Giop1_0 => Err(Error::WcharNotSupported),
326            Encoding::Xcdr1 | Encoding::Xcdr2 => {
327                let units: Vec<u16> = value.encode_utf16().collect();
328                self.write_len(units.len().saturating_mul(2))?;
329                for unit in units {
330                    self.write_u16(unit);
331                }
332                Ok(())
333            }
334            Encoding::Giop1_1 => {
335                let units: Vec<u16> = value.encode_utf16().collect();
336                self.write_len(units.len() + 1)?;
337                for unit in units {
338                    self.write_u16(unit);
339                }
340                self.write_u16(0);
341                Ok(())
342            }
343            Encoding::Giop1_2 => {
344                let order = if self.wstring_bom {
345                    self.order
346                } else {
347                    ByteOrder::Big
348                };
349                let bom = (self.wstring_bom && !value.is_empty()).then_some(0xFEFF);
350                let bytes: Vec<u8> = bom
351                    .into_iter()
352                    .chain(value.encode_utf16())
353                    .flat_map(|unit| match order {
354                        ByteOrder::Big => unit.to_be_bytes(),
355                        ByteOrder::Little => unit.to_le_bytes(),
356                    })
357                    .collect();
358                self.write_octet_seq(&bytes)
359            }
360        }
361    }
362
363    /// Writes an encapsulation as a `sequence<octet>`.
364    ///
365    /// `f` writes the contents into a fresh encoder whose alignment starts
366    /// at the byte order octet. The encapsulation uses this stream's byte
367    /// order and version.
368    pub fn write_encapsulation<F>(&mut self, f: F) -> Result<()>
369    where
370        F: FnOnce(&mut Encoder) -> Result<()>,
371    {
372        let mut inner = Encoder::encapsulation(self.order, self.encoding);
373        inner.wstring_bom = self.wstring_bom;
374        f(&mut inner)?;
375        self.write_octet_seq(&inner.buf)
376    }
377}