rustorb_cdr/xcdr.rs
1//! The headers of DDS-XTypes Extended CDR (XCDR), clause 7.4 of
2//! DDS-XTypes 1.3, and the RTPS SerializedPayload header around them
3//! (DDSI-RTPS 2.5 clause 10).
4//!
5//! The encoder and decoder write and read values with the alignment of
6//! [`Encoding::Xcdr1`] or [`Encoding::Xcdr2`]; what is here adds the
7//! pieces that only XCDR has:
8//!
9//! - the encapsulation header of a payload
10//! ([`Encoder::xcdr_payload`], [`Decoder::xcdr_payload`]), after which
11//! alignment restarts, and whose options record the final padding;
12//! - the delimiter header (DHEADER) of XCDR2 appendable and mutable types,
13//! and of XCDR2 collections of non-primitive elements
14//! ([`Encoder::begin_dheader`], [`Decoder::read_dheader`]);
15//! - the member header (EMHEADER) of XCDR2 mutable types
16//! ([`Encoder::begin_member`], [`Decoder::read_member_header`]);
17//! - the parameter headers of XCDR1 mutable types and optional members
18//! ([`Encoder::begin_parameter`], [`Decoder::read_parameter`]).
19//!
20//! Which of them a type uses depends on its extensibility and the
21//! encoding version (Table 35, [`XcdrFormat::new`]); that choice belongs
22//! to the code that knows the type.
23
24use crate::{ByteOrder, Decoder, Encoder, Encoding, Error, Result};
25
26/// The extensibility kind of a type (DDS-XTypes 7.2.2.4.4.4.6, `@final`,
27/// `@appendable`, `@mutable`).
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum Extensibility {
30 /// `@final`.
31 Final,
32 /// `@appendable`, the default.
33 Appendable,
34 /// `@mutable`.
35 Mutable,
36}
37
38/// The format of an XCDR payload: which encoding rules its top-level
39/// object follows (DDS-XTypes Table 35).
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum XcdrFormat {
42 /// PLAIN_CDR: final or appendable types, encoding version 1.
43 PlainCdr,
44 /// PL_CDR: mutable types, encoding version 1.
45 PlCdr,
46 /// PLAIN_CDR2: final types, encoding version 2.
47 PlainCdr2,
48 /// DELIMITED_CDR: appendable types, encoding version 2.
49 DelimitedCdr2,
50 /// PL_CDR2: mutable types, encoding version 2.
51 PlCdr2,
52}
53
54impl XcdrFormat {
55 /// The format of a type of extensibility `kind` written with
56 /// `encoding`, or `None` when that is not an XCDR encoding.
57 pub fn new(encoding: Encoding, kind: Extensibility) -> Option<XcdrFormat> {
58 use Extensibility::*;
59 Some(match (encoding, kind) {
60 (Encoding::Xcdr1, Final | Appendable) => XcdrFormat::PlainCdr,
61 (Encoding::Xcdr1, Mutable) => XcdrFormat::PlCdr,
62 (Encoding::Xcdr2, Final) => XcdrFormat::PlainCdr2,
63 (Encoding::Xcdr2, Appendable) => XcdrFormat::DelimitedCdr2,
64 (Encoding::Xcdr2, Mutable) => XcdrFormat::PlCdr2,
65 _ => return None,
66 })
67 }
68
69 /// The encoding version: [`Encoding::Xcdr1`] or [`Encoding::Xcdr2`].
70 pub fn encoding(self) -> Encoding {
71 match self {
72 XcdrFormat::PlainCdr | XcdrFormat::PlCdr => Encoding::Xcdr1,
73 _ => Encoding::Xcdr2,
74 }
75 }
76}
77
78/// The encapsulation identifier at the start of a payload: a format and a
79/// byte order (DDS-XTypes Table 60, Table 39; DDSI-RTPS 2.5 Table 10.3).
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81pub struct EncapsulationId {
82 /// The format of the top-level object.
83 pub format: XcdrFormat,
84 /// The byte order of the payload.
85 pub order: ByteOrder,
86}
87
88impl EncapsulationId {
89 /// The two octets of the identifier.
90 ///
91 /// The encoding version 2 values are those of DDS-XTypes Table 60,
92 /// the RTPS encapsulation identifiers (`0x06` to `0x0b`). DDS-XTypes
93 /// Table 39 and DDSI-RTPS 2.5 Table 10.3 list other values (`0x10` to
94 /// `0x15`) for the same formats; they are accepted by
95 /// [`from_bytes`](EncapsulationId::from_bytes) but never written, as
96 /// DDS implementations in use (Cyclone DDS 0.10 among them) drop
97 /// payloads that carry them.
98 pub fn to_bytes(self) -> [u8; 2] {
99 let base = match self.format {
100 XcdrFormat::PlainCdr => 0x00,
101 XcdrFormat::PlCdr => 0x02,
102 XcdrFormat::PlainCdr2 => 0x06,
103 XcdrFormat::DelimitedCdr2 => 0x08,
104 XcdrFormat::PlCdr2 => 0x0a,
105 };
106 [0x00, base | self.order.flag()]
107 }
108
109 /// Reads the two octets of an identifier. XML (`0x0004`) and unknown
110 /// identifiers are errors.
111 pub fn from_bytes(bytes: [u8; 2]) -> Result<EncapsulationId> {
112 let [0x00, id] = bytes else {
113 return Err(Error::InvalidXcdr("unknown encapsulation identifier"));
114 };
115 let format = match id & !1 {
116 0x00 => XcdrFormat::PlainCdr,
117 0x02 => XcdrFormat::PlCdr,
118 0x06 | 0x10 => XcdrFormat::PlainCdr2,
119 0x08 | 0x14 => XcdrFormat::DelimitedCdr2,
120 0x0a | 0x12 => XcdrFormat::PlCdr2,
121 _ => return Err(Error::InvalidXcdr("unknown encapsulation identifier")),
122 };
123 // In every identifier the low bit is the byte order.
124 let order = if id & 1 == 0 {
125 ByteOrder::Big
126 } else {
127 ByteOrder::Little
128 };
129 Ok(EncapsulationId { format, order })
130 }
131}
132
133/// The header of a payload read by [`Decoder::xcdr_payload`].
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub struct PayloadHeader {
136 /// The encapsulation identifier.
137 pub id: EncapsulationId,
138 /// The options octets as received. The low two bits of the second are
139 /// the padding after the data, which the decoder leaves out.
140 pub options: [u8; 2],
141}
142
143/// Parameter ID of an extended parameter header (DDS-XTypes Table 34),
144/// with `FLAG_MUST_UNDERSTAND` set as the table requires.
145pub const PID_EXTENDED: u16 = 0x7F01;
146/// Parameter ID that ends an XCDR1 parameter list (DDS-XTypes Table 34),
147/// with `FLAG_MUST_UNDERSTAND` set as the table requires.
148pub const PID_LIST_END: u16 = 0x7F02;
149/// Parameter ID of a parameter every reader ignores (DDS-XTypes Table 34).
150pub const PID_IGNORE: u16 = 0x3F03;
151/// Parameter ID that ends the parameter lists of the RTPS built-in topic
152/// types (DDSI-RTPS 9.4.2.11).
153pub const PID_SENTINEL: u16 = 0x0001;
154/// The implementation-specific flag of a parameter ID.
155pub const FLAG_IMPL_EXTENSION: u16 = 0x8000;
156/// The must-understand flag of a parameter ID.
157pub const FLAG_MUST_UNDERSTAND: u16 = 0x4000;
158
159/// The largest member ID (28 bits), in an EMHEADER or an extended
160/// parameter header.
161pub const MAX_MEMBER_ID: u32 = 0x0FFF_FFFF;
162/// The largest member ID a short parameter header holds (DDS-XTypes
163/// 7.4.1.2.2).
164pub const MAX_SHORT_PID: u32 = 0x3F00;
165
166/// What ends an XCDR1 parameter list.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
168pub enum ListEnd {
169 /// [`PID_LIST_END`], for user types.
170 Xtypes,
171 /// [`PID_SENTINEL`], for the RTPS built-in topic types (whose member
172 /// ID 1 is therefore never used). A reader also accepts
173 /// [`PID_LIST_END`].
174 Rtps,
175}
176
177impl ListEnd {
178 fn pid(self) -> u16 {
179 match self {
180 ListEnd::Xtypes => PID_LIST_END,
181 ListEnd::Rtps => PID_SENTINEL,
182 }
183 }
184}
185
186/// A DHEADER being written; see [`Encoder::begin_dheader`].
187#[derive(Debug)]
188#[must_use = "a DHEADER is written by end_dheader"]
189pub struct DHeaderMark {
190 at: usize,
191 start: usize,
192}
193
194/// A member with an EMHEADER being written; see [`Encoder::begin_member`].
195#[derive(Debug)]
196#[must_use = "a member header is written by end_member"]
197pub struct MemberMark {
198 at: usize,
199 start: usize,
200 header: u32,
201}
202
203/// A parameter being written; see [`Encoder::begin_parameter`].
204#[derive(Debug)]
205#[must_use = "a parameter header is written by end_parameter"]
206pub struct ParameterMark {
207 at: usize,
208 start: usize,
209 id: u32,
210 must_understand: bool,
211 extended: bool,
212 origin: usize,
213}
214
215/// An object read after its DHEADER; see [`Decoder::read_dheader`].
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217#[must_use = "end_dheader skips what was not read"]
218pub struct Delimited {
219 end: usize,
220}
221
222impl Delimited {
223 /// Whether `dec` has not reached the end of the object yet: more
224 /// members of a mutable type, or more of an appendable one that the
225 /// reader may not know.
226 pub fn has_more(&self, dec: &Decoder<'_>) -> bool {
227 dec.pos < self.end
228 }
229
230 /// Bytes of the object left after the position of `dec`.
231 pub fn remaining(&self, dec: &Decoder<'_>) -> usize {
232 self.end.saturating_sub(dec.pos)
233 }
234}
235
236/// A member header read by [`Decoder::read_member_header`].
237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
238#[must_use = "end_member skips what was not read"]
239pub struct MemberHeader {
240 /// The member ID.
241 pub id: u32,
242 /// Whether the member must be understood (`M_FLAG`).
243 pub must_understand: bool,
244 /// The length of the serialized member.
245 pub len: usize,
246 end: usize,
247}
248
249/// A parameter header read by [`Decoder::read_parameter`] or
250/// [`Decoder::read_parameter_header`].
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252#[must_use = "end_parameter skips what was not read and restores the alignment origin"]
253pub struct Parameter {
254 /// The member ID (the low 14 bits of a short parameter ID, or the 28
255 /// bits of an extended header).
256 pub id: u32,
257 /// `FLAG_MUST_UNDERSTAND`.
258 pub must_understand: bool,
259 /// `FLAG_IMPL_EXTENSION`.
260 pub impl_extension: bool,
261 /// The length of the serialized member: 0 for an absent optional
262 /// member.
263 pub len: usize,
264 end: usize,
265 origin: usize,
266}
267
268impl Encoder {
269 /// Starts an RTPS SerializedPayload: the encapsulation identifier of
270 /// `format` and `order`, the options, and alignment counted from the
271 /// byte after them (DDSI-RTPS 2.5 10.2, DDS-XTypes 7.4.3.5.3 rule 1).
272 /// End it with [`finish_xcdr_payload`](Encoder::finish_xcdr_payload).
273 pub fn xcdr_payload(format: XcdrFormat, order: ByteOrder) -> Encoder {
274 let mut enc = Encoder::new(order, format.encoding());
275 enc.write_octets(&EncapsulationId { format, order }.to_bytes());
276 enc.write_octets(&[0, 0]);
277 enc.origin = 4;
278 enc
279 }
280
281 /// Ends a payload started with
282 /// [`xcdr_payload`](Encoder::xcdr_payload): zero padding up to a
283 /// multiple of 4 octets, its length recorded in the options
284 /// (DDS-XTypes 7.6.3.1.2), and the bytes.
285 pub fn finish_xcdr_payload(mut self) -> Vec<u8> {
286 let pad = (4 - self.len() % 4) % 4;
287 self.buf.resize(self.buf.len() + pad, 0);
288 if let Some(options) = self.buf.get_mut(3) {
289 *options = (*options & !3) | pad as u8;
290 }
291 self.into_bytes()
292 }
293
294 fn patch_u32(&mut self, at: usize, value: u32) {
295 let bytes = match self.order {
296 ByteOrder::Big => value.to_be_bytes(),
297 ByteOrder::Little => value.to_le_bytes(),
298 };
299 self.buf[at..at + 4].copy_from_slice(&bytes);
300 }
301
302 fn patch_u16(&mut self, at: usize, value: u16) {
303 let bytes = match self.order {
304 ByteOrder::Big => value.to_be_bytes(),
305 ByteOrder::Little => value.to_le_bytes(),
306 };
307 self.buf[at..at + 2].copy_from_slice(&bytes);
308 }
309
310 fn u16_bytes(&self, value: u16) -> [u8; 2] {
311 match self.order {
312 ByteOrder::Big => value.to_be_bytes(),
313 ByteOrder::Little => value.to_le_bytes(),
314 }
315 }
316
317 fn u32_bytes(&self, value: u32) -> [u8; 4] {
318 match self.order {
319 ByteOrder::Big => value.to_be_bytes(),
320 ByteOrder::Little => value.to_le_bytes(),
321 }
322 }
323
324 /// Writes a DHEADER to be filled in by
325 /// [`end_dheader`](Encoder::end_dheader) with the length of what is
326 /// written in between (DDS-XTypes 7.4.3.4.1).
327 ///
328 /// Marks of [`begin_dheader`](Encoder::begin_dheader),
329 /// [`begin_member`](Encoder::begin_member) and
330 /// [`begin_parameter`](Encoder::begin_parameter) must be ended
331 /// innermost first.
332 pub fn begin_dheader(&mut self) -> DHeaderMark {
333 self.align(4);
334 let at = self.buf.len();
335 self.write_u32(0);
336 DHeaderMark {
337 at,
338 start: self.len(),
339 }
340 }
341
342 /// Fills in the DHEADER of `mark`.
343 pub fn end_dheader(&mut self, mark: DHeaderMark) -> Result<()> {
344 let size = self.len() - mark.start;
345 let size = u32::try_from(size).map_err(|_| Error::LengthOverflow(size))?;
346 self.patch_u32(mark.at, size);
347 Ok(())
348 }
349
350 /// Starts a member of an XCDR2 mutable type: an EMHEADER for member
351 /// `id`, filled in by [`end_member`](Encoder::end_member) with the
352 /// length of what is written in between (DDS-XTypes 7.4.3.4.2, rule
353 /// 22). Only for [`Encoding::Xcdr2`].
354 pub fn begin_member(&mut self, id: u32, must_understand: bool) -> Result<MemberMark> {
355 if self.encoding() != Encoding::Xcdr2 {
356 return Err(Error::InvalidXcdr("EMHEADER outside XCDR2"));
357 }
358 if id > MAX_MEMBER_ID {
359 return Err(Error::InvalidXcdr("member ID larger than 28 bits"));
360 }
361 self.align(4);
362 let at = self.buf.len();
363 // EMHEADER1 and NEXTINT, which end_member drops when a length code
364 // of 0 to 3 is enough.
365 self.write_u32(0);
366 self.write_u32(0);
367 Ok(MemberMark {
368 at,
369 start: self.len(),
370 header: (u32::from(must_understand) << 31) | id,
371 })
372 }
373
374 /// Fills in the EMHEADER of `mark`. A member of 1, 2, 4 or 8 octets
375 /// gets a length code of 0 to 3 and no NEXTINT; any other gets length
376 /// code 4 and its length in NEXTINT. (Length codes 5 to 7, which share
377 /// NEXTINT with the member, are read but not written.)
378 pub fn end_member(&mut self, mark: MemberMark) -> Result<()> {
379 let size = self.len() - mark.start;
380 let lc = match size {
381 1 => Some(0),
382 2 => Some(1),
383 4 => Some(2),
384 8 => Some(3),
385 _ => None,
386 };
387 match lc {
388 // Dropping NEXTINT moves the member back by 4 octets, which
389 // keeps its alignment: XCDR2 aligns to no more than 4.
390 Some(lc) => {
391 self.buf.drain(mark.at + 4..mark.at + 8);
392 self.patch_u32(mark.at, mark.header | (lc << 28));
393 }
394 None => {
395 let size = u32::try_from(size).map_err(|_| Error::LengthOverflow(size))?;
396 self.patch_u32(mark.at, mark.header | (4 << 28));
397 self.patch_u32(mark.at + 4, size);
398 }
399 }
400 Ok(())
401 }
402
403 /// Starts a parameter of an XCDR1 parameter list, or the header of an
404 /// XCDR1 optional member: a parameter header for member `id`, filled
405 /// in by [`end_parameter`](Encoder::end_parameter) with the length of
406 /// what is written in between (DDS-XTypes 7.4.1.2, rules 24 and 25).
407 ///
408 /// The header is a short one (16-bit ID and length) when `id` is at
409 /// most [`MAX_SHORT_PID`], and an extended one ([`PID_EXTENDED`])
410 /// otherwise or when the member turns out longer than 65535 octets.
411 /// Alignment counts from the byte after the header until
412 /// `end_parameter`. An absent optional member is a parameter with
413 /// nothing written in it.
414 pub fn begin_parameter(&mut self, id: u32, must_understand: bool) -> Result<ParameterMark> {
415 if id > MAX_MEMBER_ID {
416 return Err(Error::InvalidXcdr("member ID larger than 28 bits"));
417 }
418 self.align(4);
419 let at = self.buf.len();
420 let extended = id > MAX_SHORT_PID;
421 if extended {
422 self.write_u16(PID_EXTENDED);
423 self.write_u16(8);
424 self.write_u32(extended_header(id, must_understand));
425 self.write_u32(0);
426 } else {
427 let flag = if must_understand {
428 FLAG_MUST_UNDERSTAND
429 } else {
430 0
431 };
432 self.write_u16(flag | id as u16);
433 self.write_u16(0);
434 }
435 let mark = ParameterMark {
436 at,
437 start: self.len(),
438 id,
439 must_understand,
440 extended,
441 origin: self.origin,
442 };
443 self.origin = self.offset();
444 Ok(mark)
445 }
446
447 /// Fills in the parameter header of `mark` and restores the alignment
448 /// origin. The length is that of the member, without padding
449 /// (DDS-XTypes 7.4.1.2).
450 pub fn end_parameter(&mut self, mark: ParameterMark) -> Result<()> {
451 let size = self.len() - mark.start;
452 let size32 = u32::try_from(size).map_err(|_| Error::LengthOverflow(size))?;
453 if mark.extended {
454 self.patch_u32(mark.at + 8, size32);
455 } else if let Ok(short) = u16::try_from(size) {
456 self.patch_u16(mark.at + 2, short);
457 } else {
458 // Too long for a short header: make it an extended one. The
459 // member moves with its alignment origin, so its padding stays
460 // right.
461 let mut header = Vec::with_capacity(12);
462 header.extend_from_slice(&self.u16_bytes(PID_EXTENDED));
463 header.extend_from_slice(&self.u16_bytes(8));
464 header
465 .extend_from_slice(&self.u32_bytes(extended_header(mark.id, mark.must_understand)));
466 header.extend_from_slice(&self.u32_bytes(size32));
467 self.buf.splice(mark.at..mark.at + 4, header);
468 }
469 self.origin = mark.origin;
470 Ok(())
471 }
472
473 /// Ends an XCDR1 parameter list with `end` and a zero length (rule
474 /// 23).
475 pub fn end_parameter_list(&mut self, end: ListEnd) {
476 self.align(4);
477 self.write_u16(end.pid());
478 self.write_u16(0);
479 }
480}
481
482/// The `eMemberHeader` of an extended parameter header: the
483/// must-understand flag (`FLAG_2`) and the member ID.
484fn extended_header(id: u32, must_understand: bool) -> u32 {
485 (u32::from(must_understand) << 30) | id
486}
487
488impl<'a> Decoder<'a> {
489 /// Opens an RTPS SerializedPayload: reads the encapsulation header and
490 /// returns a decoder positioned after it, with alignment counted from
491 /// there, and the header. Padding the options say follows the data is
492 /// left out of the decoder.
493 pub fn xcdr_payload(buf: &'a [u8]) -> Result<(Decoder<'a>, PayloadHeader)> {
494 let [a, b, o1, o2, ..] = *buf else {
495 return Err(Error::UnexpectedEof {
496 needed: 4,
497 remaining: buf.len(),
498 });
499 };
500 let id = EncapsulationId::from_bytes([a, b])?;
501 let pad = usize::from(o2 & 3);
502 let end = buf
503 .len()
504 .checked_sub(pad)
505 .filter(|&end| end >= 4)
506 .ok_or(Error::InvalidXcdr("payload padding longer than the data"))?;
507 let mut dec = Decoder::new(&buf[..end], id.order, id.format.encoding());
508 dec.pos = 4;
509 dec.origin = 4;
510 Ok((
511 dec,
512 PayloadHeader {
513 id,
514 options: [o1, o2],
515 },
516 ))
517 }
518
519 /// Reads a DHEADER (DDS-XTypes 7.4.3.4.1). Read the object, then call
520 /// [`end_dheader`](Decoder::end_dheader), which skips what was not
521 /// read: members that a newer version of an appendable type added.
522 pub fn read_dheader(&mut self) -> Result<Delimited> {
523 let size = self.read_u32()? as usize;
524 if size > self.remaining() {
525 return Err(Error::InvalidXcdr("DHEADER longer than the data"));
526 }
527 Ok(Delimited {
528 end: self.pos + size,
529 })
530 }
531
532 /// Moves to the end of the object of `delimited`. Reading past it is
533 /// an error.
534 pub fn end_dheader(&mut self, delimited: Delimited) -> Result<()> {
535 if self.pos > delimited.end {
536 return Err(Error::InvalidXcdr("object longer than its DHEADER"));
537 }
538 self.pos = delimited.end;
539 Ok(())
540 }
541
542 /// Reads the EMHEADER of a member of an XCDR2 mutable type
543 /// (DDS-XTypes 7.4.3.4.2) and leaves the decoder at the member. Read
544 /// it or not, then call [`end_member`](Decoder::end_member).
545 ///
546 /// With length codes 5 to 7, NEXTINT is also the first 4 octets of the
547 /// member (rule 22), so the decoder is left on it, and the length
548 /// counts it: 4 + NEXTINT, 4 + 4 × NEXTINT or 4 + 8 × NEXTINT octets.
549 pub fn read_member_header(&mut self) -> Result<MemberHeader> {
550 let header = self.read_u32()?;
551 let must_understand = header >> 31 == 1;
552 let lc = (header >> 28) & 7;
553 let id = header & MAX_MEMBER_ID;
554 let len = match lc {
555 0 => 1,
556 1 => 2,
557 2 => 4,
558 3 => 8,
559 _ => {
560 let next = self.read_u32()? as usize;
561 if lc == 4 {
562 next
563 } else {
564 self.pos -= 4;
565 let unit = match lc {
566 5 => 1,
567 6 => 4,
568 _ => 8,
569 };
570 next.checked_mul(unit)
571 .and_then(|n| n.checked_add(4))
572 .ok_or(Error::InvalidXcdr("member longer than the data"))?
573 }
574 }
575 };
576 if len > self.remaining() {
577 return Err(Error::InvalidXcdr("member longer than the data"));
578 }
579 Ok(MemberHeader {
580 id,
581 must_understand,
582 len,
583 end: self.pos + len,
584 })
585 }
586
587 /// Moves to the end of the member of `header`. Reading past it is an
588 /// error.
589 pub fn end_member(&mut self, header: MemberHeader) -> Result<()> {
590 if self.pos > header.end {
591 return Err(Error::InvalidXcdr("member longer than its EMHEADER"));
592 }
593 self.pos = header.end;
594 Ok(())
595 }
596
597 /// Reads a parameter header of XCDR1 (DDS-XTypes 7.4.1.2), short or
598 /// extended, and makes alignment count from the byte after it. Read
599 /// the member or not, then call
600 /// [`end_parameter`](Decoder::end_parameter).
601 ///
602 /// This reads the header in front of an optional member of a final or
603 /// appendable type, where a length of 0 means the member is absent.
604 /// In a parameter list use [`read_parameter`](Decoder::read_parameter),
605 /// which knows its end.
606 pub fn read_parameter_header(&mut self) -> Result<Parameter> {
607 self.align(4)?;
608 let pid = self.read_u16()?;
609 let short_len = self.read_u16()?;
610 let (id, must_understand, impl_extension, len) =
611 if pid & !(FLAG_MUST_UNDERSTAND | FLAG_IMPL_EXTENSION) == PID_EXTENDED & 0x3FFF
612 && pid & FLAG_IMPL_EXTENSION == 0
613 {
614 if short_len != 8 {
615 return Err(Error::InvalidXcdr("PID_EXTENDED length is not 8"));
616 }
617 let header = self.read_u32()?;
618 let len = self.read_u32()? as usize;
619 (
620 header & MAX_MEMBER_ID,
621 header & (1 << 30) != 0,
622 header & (1 << 31) != 0,
623 len,
624 )
625 } else {
626 (
627 u32::from(pid & 0x3FFF),
628 pid & FLAG_MUST_UNDERSTAND != 0,
629 pid & FLAG_IMPL_EXTENSION != 0,
630 usize::from(short_len),
631 )
632 };
633 if len > self.remaining() {
634 return Err(Error::InvalidXcdr("parameter longer than the data"));
635 }
636 let origin = self.origin;
637 self.origin = self.position();
638 Ok(Parameter {
639 id,
640 must_understand,
641 impl_extension,
642 len,
643 end: self.pos + len,
644 origin,
645 })
646 }
647
648 /// Reads the next parameter header of an XCDR1 parameter list, or
649 /// `None` at its end. Parameters with [`PID_IGNORE`] are skipped. The
650 /// list ends with [`PID_LIST_END`] (with any flags), or for
651 /// [`ListEnd::Rtps`] also with [`PID_SENTINEL`].
652 pub fn read_parameter(&mut self, list_end: ListEnd) -> Result<Option<Parameter>> {
653 loop {
654 // The end of the list has a length that is not looked at.
655 self.align(4)?;
656 if let [a, b, ..] = *self.remaining_bytes() {
657 let pid = match self.order {
658 ByteOrder::Big => u16::from_be_bytes([a, b]),
659 ByteOrder::Little => u16::from_le_bytes([a, b]),
660 };
661 if pid & !FLAG_MUST_UNDERSTAND == PID_LIST_END & 0x3FFF
662 || list_end == ListEnd::Rtps && pid == PID_SENTINEL
663 {
664 self.skip(4)?;
665 return Ok(None);
666 }
667 }
668 let param = self.read_parameter_header()?;
669 if !param.impl_extension && param.id == u32::from(PID_IGNORE) {
670 self.end_parameter(param)?;
671 continue;
672 }
673 return Ok(Some(param));
674 }
675 }
676
677 /// Moves to the end of the parameter `param` and restores the
678 /// alignment origin. Reading past it is an error.
679 pub fn end_parameter(&mut self, param: Parameter) -> Result<()> {
680 if self.pos > param.end {
681 return Err(Error::InvalidXcdr("member longer than its parameter"));
682 }
683 self.pos = param.end;
684 self.origin = param.origin;
685 Ok(())
686 }
687}