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