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