Skip to main content

rustorb_rtps/
submessage.rs

1//! RTPS submessages (DDSI-RTPS 2.5, 8.3.7, 8.3.8 and 9.4.5).
2//!
3//! Each submessage type here holds the decoded elements. The
4//! EndiannessFlag is not stored: the byte order is chosen when a message
5//! is encoded. Flags marked `X` (unused) in the specification are ignored
6//! when reading and written as zero (9.4.5.1.2).
7
8use crate::Octets;
9use crate::error::{DecodeError, EncodeError};
10use crate::parameter::ParameterList;
11use crate::types::{
12    ChangeCount, Count, EntityId, FragmentNumber, FragmentNumberSet, GroupDigest, GuidPrefix,
13    Locator, LocatorUdpV4, ProtocolVersion, SequenceNumber, SequenceNumberSet, Time, VendorId,
14};
15use crate::wire::{Reader, Writer};
16
17/// Submessage ids (DDSI-RTPS 2.5, 9.4.5.1.1).
18///
19/// Ids `0x80..=0xff` are vendor-specific.
20pub mod submessage_id {
21    /// HeaderExtension.
22    pub const RTPS_HE: u8 = 0x00;
23    /// Pad.
24    pub const PAD: u8 = 0x01;
25    /// AckNack.
26    pub const ACKNACK: u8 = 0x06;
27    /// Heartbeat.
28    pub const HEARTBEAT: u8 = 0x07;
29    /// Gap.
30    pub const GAP: u8 = 0x08;
31    /// InfoTimestamp.
32    pub const INFO_TS: u8 = 0x09;
33    /// InfoSource.
34    pub const INFO_SRC: u8 = 0x0c;
35    /// InfoReplyIp4.
36    pub const INFO_REPLY_IP4: u8 = 0x0d;
37    /// InfoDestination.
38    pub const INFO_DST: u8 = 0x0e;
39    /// InfoReply.
40    pub const INFO_REPLY: u8 = 0x0f;
41    /// NackFrag.
42    pub const NACK_FRAG: u8 = 0x12;
43    /// HeartbeatFrag.
44    pub const HEARTBEAT_FRAG: u8 = 0x13;
45    /// Data.
46    pub const DATA: u8 = 0x15;
47    /// DataFrag.
48    pub const DATA_FRAG: u8 = 0x16;
49}
50
51use submessage_id as id;
52
53/// One submessage.
54#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum Submessage {
56    /// RTPS_HE (8.3.7, 9.4.5.2).
57    HeaderExtension(HeaderExtension),
58    /// PAD (8.3.8.13, 9.4.5.13).
59    Pad(Pad),
60    /// ACKNACK (8.3.8.1, 9.4.5.3).
61    AckNack(AckNack),
62    /// HEARTBEAT (8.3.8.6, 9.4.5.7).
63    Heartbeat(Heartbeat),
64    /// GAP (8.3.8.4, 9.4.5.6).
65    Gap(Gap),
66    /// INFO_TS (8.3.8.11, 9.4.5.12).
67    InfoTimestamp(InfoTimestamp),
68    /// INFO_SRC (8.3.8.10, 9.4.5.11).
69    InfoSource(InfoSource),
70    /// INFO_REPLY_IP4 (9.4.5.15).
71    InfoReplyIp4(InfoReplyIp4),
72    /// INFO_DST (8.3.8.8, 9.4.5.9).
73    InfoDestination(InfoDestination),
74    /// INFO_REPLY (8.3.8.9, 9.4.5.10).
75    InfoReply(InfoReply),
76    /// NACK_FRAG (8.3.8.12, 9.4.5.14).
77    NackFrag(NackFrag),
78    /// HEARTBEAT_FRAG (8.3.8.7, 9.4.5.8).
79    HeartbeatFrag(HeartbeatFrag),
80    /// DATA (8.3.8.2, 9.4.5.4).
81    Data(Data),
82    /// DATA_FRAG (8.3.8.3, 9.4.5.5).
83    DataFrag(DataFrag),
84    /// A submessage this crate does not know: a vendor-specific one, or one
85    /// from a later minor version. Receivers skip these (8.3.4.1 rule 3).
86    Unknown(UnknownSubmessage),
87}
88
89/// The checksum of a HeaderExtension (9.4.2.15, Table 9.8).
90#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
91pub enum Checksum {
92    /// CRC-32C, big-endian (flags C1,C2 = 0,1).
93    Crc32([u8; 4]),
94    /// CRC-64/XZ, big-endian (flags C1,C2 = 1,0).
95    Crc64([u8; 8]),
96    /// MD5 (flags C1,C2 = 1,1).
97    Md5([u8; 16]),
98}
99
100/// RTPS_HE: optional information that belongs to the message header
101/// (8.3.7). It must be the first submessage.
102///
103/// The checksum is carried as received; computing and checking it is not
104/// done here.
105#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct HeaderExtension {
107    /// `messageLength` (flag L).
108    pub message_length: Option<u32>,
109    /// `rtpsSendTimestamp` (flag T).
110    pub send_timestamp: Option<Time>,
111    /// `uExtension4` (flag U).
112    pub u_extension4: Option<[u8; 4]>,
113    /// `wExtension8` (flag W).
114    pub w_extension8: Option<[u8; 8]>,
115    /// `messageChecksum` (flags C1, C2).
116    pub checksum: Option<Checksum>,
117    /// `parameters` (flag P).
118    pub parameters: Option<ParameterList>,
119}
120
121/// PAD: padding with no meaning (8.3.8.13).
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
123pub struct Pad {
124    /// The number of padding octets after the submessage header.
125    pub len: usize,
126}
127
128/// ACKNACK: a reader tells a writer what it has and what it misses
129/// (8.3.8.1).
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub struct AckNack {
132    /// FinalFlag: the reader does not need a HEARTBEAT in reply.
133    pub final_flag: bool,
134    /// The reader.
135    pub reader_id: EntityId,
136    /// The writer.
137    pub writer_id: EntityId,
138    /// Everything before `base` is acknowledged; the members are missing.
139    pub reader_sn_state: SequenceNumberSet,
140    /// Incremented with each new ACKNACK.
141    pub count: Count,
142}
143
144/// The group information of a HEARTBEAT (flag G, 8.3.8.6).
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct HeartbeatGroupInfo {
147    /// `currentGSN`.
148    pub current_gsn: SequenceNumber,
149    /// `firstGSN`.
150    pub first_gsn: SequenceNumber,
151    /// `lastGSN`.
152    pub last_gsn: SequenceNumber,
153    /// `writerSet` and `secureWriterSet`.
154    ///
155    /// Table 8.44 lists these two elements but the wire drawing in 9.4.5.7
156    /// does not. They are read when eight more octets are present and
157    /// written when set. To be checked against other implementations
158    /// (rustorb-dds#8).
159    pub writer_sets: Option<(GroupDigest, GroupDigest)>,
160}
161
162/// HEARTBEAT: a writer tells readers which sequence numbers it has
163/// (8.3.8.6).
164#[derive(Clone, Debug, PartialEq, Eq)]
165pub struct Heartbeat {
166    /// FinalFlag: the reader does not have to reply.
167    pub final_flag: bool,
168    /// LivelinessFlag: the DataWriter asserted its liveliness manually.
169    pub liveliness_flag: bool,
170    /// The reader, or [`EntityId::UNKNOWN`] for all readers.
171    pub reader_id: EntityId,
172    /// The writer.
173    pub writer_id: EntityId,
174    /// The first sequence number still available.
175    pub first_sn: SequenceNumber,
176    /// The last sequence number ever written.
177    pub last_sn: SequenceNumber,
178    /// Incremented with each new HEARTBEAT.
179    pub count: Count,
180    /// Group information (flag G).
181    pub group_info: Option<HeartbeatGroupInfo>,
182}
183
184/// GAP: a writer tells a reader that some changes will not be sent
185/// (8.3.8.4).
186#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct Gap {
188    /// The reader, or [`EntityId::UNKNOWN`] for all matched readers.
189    pub reader_id: EntityId,
190    /// The writer.
191    pub writer_id: EntityId,
192    /// First sequence number of the irrelevant range.
193    pub gap_start: SequenceNumber,
194    /// The range ends at `gap_list.base() - 1`; the members are irrelevant
195    /// too.
196    pub gap_list: SequenceNumberSet,
197    /// `gapStartGSN` and `gapEndGSN` (flag G).
198    pub group_info: Option<(SequenceNumber, SequenceNumber)>,
199    /// `filteredCount` (flag F).
200    pub filtered_count: Option<ChangeCount>,
201}
202
203/// INFO_TS: the source timestamp of the submessages that follow
204/// (8.3.8.11).
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct InfoTimestamp {
207    /// The timestamp, or `None` when the InvalidateFlag is set.
208    pub timestamp: Option<Time>,
209}
210
211/// INFO_SRC: the logical source of the submessages that follow
212/// (8.3.8.10).
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub struct InfoSource {
215    /// The protocol version of the source.
216    pub protocol_version: ProtocolVersion,
217    /// The vendor of the source.
218    pub vendor_id: VendorId,
219    /// The participant of the source.
220    pub guid_prefix: GuidPrefix,
221}
222
223/// INFO_DST: the participant the submessages that follow are for
224/// (8.3.8.8).
225#[derive(Clone, Copy, Debug, PartialEq, Eq)]
226pub struct InfoDestination {
227    /// The destination participant, or [`GuidPrefix::UNKNOWN`] for the
228    /// receiving one.
229    pub guid_prefix: GuidPrefix,
230}
231
232/// INFO_REPLY: where to send replies to the submessages that follow
233/// (8.3.8.9).
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct InfoReply {
236    /// Unicast reply locators.
237    pub unicast_locators: Vec<Locator>,
238    /// Multicast reply locators (flag M).
239    pub multicast_locators: Option<Vec<Locator>>,
240}
241
242/// INFO_REPLY_IP4: the compact UDPv4 form of INFO_REPLY (9.4.5.15).
243#[derive(Clone, Copy, Debug, PartialEq, Eq)]
244pub struct InfoReplyIp4 {
245    /// Unicast reply locator.
246    pub unicast_locator: LocatorUdpV4,
247    /// Multicast reply locator (flag M).
248    pub multicast_locator: Option<LocatorUdpV4>,
249}
250
251/// NACK_FRAG: a reader asks for missing fragments (8.3.8.12).
252#[derive(Clone, Debug, PartialEq, Eq)]
253pub struct NackFrag {
254    /// The reader.
255    pub reader_id: EntityId,
256    /// The writer.
257    pub writer_id: EntityId,
258    /// The change whose fragments are missing.
259    pub writer_sn: SequenceNumber,
260    /// The missing fragments.
261    pub fragment_number_state: FragmentNumberSet,
262    /// Incremented with each new NACK_FRAG.
263    pub count: Count,
264}
265
266/// HEARTBEAT_FRAG: a writer tells readers which fragments it has
267/// (8.3.8.7).
268#[derive(Clone, Debug, PartialEq, Eq)]
269pub struct HeartbeatFrag {
270    /// The reader, or [`EntityId::UNKNOWN`] for all readers.
271    pub reader_id: EntityId,
272    /// The writer.
273    pub writer_id: EntityId,
274    /// The change.
275    pub writer_sn: SequenceNumber,
276    /// All fragments up to this one are available.
277    pub last_fragment_num: FragmentNumber,
278    /// Incremented with each new HEARTBEAT_FRAG.
279    pub count: Count,
280}
281
282/// What a serialized payload holds.
283#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
284pub enum PayloadKind {
285    /// The value of the data object (DataFlag).
286    Data,
287    /// The key of the data object (KeyFlag).
288    Key,
289}
290
291/// The serialized payload of a DATA submessage, kept as octets
292/// (8.3.5.17, 9.4.2.12, clause 10).
293#[derive(Clone, Debug, PartialEq, Eq)]
294pub struct SerializedPayload {
295    /// Value or key.
296    pub kind: PayloadKind,
297    /// The octets, starting with the 4-octet SerializedPayloadHeader.
298    ///
299    /// When read, this runs to the end of the submessage and so may
300    /// include the padding that aligns the next submessage. When written,
301    /// it is padded with zeros to a multiple of four.
302    pub bytes: Octets,
303}
304
305/// DATA: a change to a data object, sent by a writer (8.3.8.2).
306#[derive(Clone, Debug, PartialEq, Eq)]
307pub struct Data {
308    /// The reader, or [`EntityId::UNKNOWN`] for all matched readers.
309    pub reader_id: EntityId,
310    /// The writer.
311    pub writer_id: EntityId,
312    /// The sequence number of the change.
313    pub writer_sn: SequenceNumber,
314    /// In-line QoS (flag Q).
315    pub inline_qos: Option<ParameterList>,
316    /// The payload (flag D or K).
317    pub serialized_payload: Option<SerializedPayload>,
318    /// NonStandardPayloadFlag: the payload is not formatted as in clause
319    /// 10 (for example, it was transformed by DDS-Security).
320    pub non_standard_payload: bool,
321}
322
323/// DATA_FRAG: some fragments of a change (8.3.8.3).
324#[derive(Clone, Debug, PartialEq, Eq)]
325pub struct DataFrag {
326    /// KeyFlag: the fragments are of the key, not the value.
327    pub key_flag: bool,
328    /// NonStandardPayloadFlag.
329    pub non_standard_payload: bool,
330    /// The reader, or [`EntityId::UNKNOWN`].
331    pub reader_id: EntityId,
332    /// The writer.
333    pub writer_id: EntityId,
334    /// The sequence number of the change.
335    pub writer_sn: SequenceNumber,
336    /// The first fragment in this submessage (from 1).
337    pub fragment_starting_num: FragmentNumber,
338    /// How many consecutive fragments this submessage holds.
339    pub fragments_in_submessage: u16,
340    /// The size of each fragment.
341    pub fragment_size: u16,
342    /// The size of the whole serialized data (`sampleSize`, called
343    /// `dataSize` in 8.3.8.3).
344    pub sample_size: u32,
345    /// In-line QoS (flag Q).
346    pub inline_qos: Option<ParameterList>,
347    /// The fragment octets.
348    pub serialized_payload: Octets,
349}
350
351/// A submessage with an id this crate does not handle, kept as octets.
352#[derive(Clone, Debug, PartialEq, Eq)]
353pub struct UnknownSubmessage {
354    /// The submessage id.
355    pub id: u8,
356    /// The flags, including the EndiannessFlag, as received.
357    pub flags: u8,
358    /// The contents after the submessage header.
359    pub body: Vec<u8>,
360}
361
362const TOO_SMALL: &str = "submessageLength too small";
363
364fn invalid(id: u8, reason: &'static str) -> DecodeError {
365    DecodeError::InvalidSubmessage { id, reason }
366}
367
368fn flag(flags: u8, bit: u8) -> bool {
369    flags & bit != 0
370}
371
372impl Submessage {
373    /// The submessage id.
374    pub fn id(&self) -> u8 {
375        match self {
376            Submessage::HeaderExtension(_) => id::RTPS_HE,
377            Submessage::Pad(_) => id::PAD,
378            Submessage::AckNack(_) => id::ACKNACK,
379            Submessage::Heartbeat(_) => id::HEARTBEAT,
380            Submessage::Gap(_) => id::GAP,
381            Submessage::InfoTimestamp(_) => id::INFO_TS,
382            Submessage::InfoSource(_) => id::INFO_SRC,
383            Submessage::InfoReplyIp4(_) => id::INFO_REPLY_IP4,
384            Submessage::InfoDestination(_) => id::INFO_DST,
385            Submessage::InfoReply(_) => id::INFO_REPLY,
386            Submessage::NackFrag(_) => id::NACK_FRAG,
387            Submessage::HeartbeatFrag(_) => id::HEARTBEAT_FRAG,
388            Submessage::Data(_) => id::DATA,
389            Submessage::DataFrag(_) => id::DATA_FRAG,
390            Submessage::Unknown(u) => u.id,
391        }
392    }
393
394    /// Reads the contents of a submessage whose header gave `id` and
395    /// `flags`. `body` is everything after the header up to the next one.
396    pub(crate) fn decode_body(
397        id: u8,
398        flags: u8,
399        body: &[u8],
400        base: Option<&crate::Octets>,
401    ) -> Result<Submessage, DecodeError> {
402        let mut r = Reader::with_base(body, crate::wire::Endianness::from_flags(flags), base);
403        let result = Self::read_body(id, flags, &mut r);
404        result.map_err(|e| match e {
405            DecodeError::UnexpectedEnd => invalid(id, TOO_SMALL),
406            DecodeError::InvalidParameterList(_) => invalid(id, "invalid parameter list"),
407            e => e,
408        })
409    }
410
411    fn read_body(id: u8, flags: u8, r: &mut Reader<'_>) -> Result<Submessage, DecodeError> {
412        Ok(match id {
413            id::RTPS_HE => Submessage::HeaderExtension(HeaderExtension::read(flags, r)?),
414            id::PAD => Submessage::Pad(Pad {
415                len: r.rest().len(),
416            }),
417            id::ACKNACK => Submessage::AckNack(AckNack::read(flags, r)?),
418            id::HEARTBEAT => Submessage::Heartbeat(Heartbeat::read(flags, r)?),
419            id::GAP => Submessage::Gap(Gap::read(flags, r)?),
420            id::INFO_TS => Submessage::InfoTimestamp(InfoTimestamp {
421                timestamp: if flag(flags, 0x02) {
422                    None
423                } else {
424                    Some(Time::read(r)?)
425                },
426            }),
427            id::INFO_SRC => {
428                r.skip(4)?; // unused
429                Submessage::InfoSource(InfoSource {
430                    protocol_version: ProtocolVersion::read(r)?,
431                    vendor_id: VendorId::read(r)?,
432                    guid_prefix: GuidPrefix::read(r)?,
433                })
434            }
435            id::INFO_REPLY_IP4 => Submessage::InfoReplyIp4(InfoReplyIp4 {
436                unicast_locator: LocatorUdpV4::read(r)?,
437                multicast_locator: if flag(flags, 0x02) {
438                    Some(LocatorUdpV4::read(r)?)
439                } else {
440                    None
441                },
442            }),
443            id::INFO_DST => Submessage::InfoDestination(InfoDestination {
444                guid_prefix: GuidPrefix::read(r)?,
445            }),
446            id::INFO_REPLY => Submessage::InfoReply(InfoReply {
447                unicast_locators: read_locator_list(r)?,
448                multicast_locators: if flag(flags, 0x02) {
449                    Some(read_locator_list(r)?)
450                } else {
451                    None
452                },
453            }),
454            id::NACK_FRAG => Submessage::NackFrag(NackFrag::read(r)?),
455            id::HEARTBEAT_FRAG => Submessage::HeartbeatFrag(HeartbeatFrag::read(r)?),
456            id::DATA => Submessage::Data(Data::read(flags, r)?),
457            id::DATA_FRAG => Submessage::DataFrag(DataFrag::read(flags, r)?),
458            _ => Submessage::Unknown(UnknownSubmessage {
459                id,
460                flags,
461                body: r.rest().to_vec(),
462            }),
463        })
464    }
465
466    /// Writes the contents (not the header) and returns the flags to put
467    /// in the header, including the EndiannessFlag.
468    pub(crate) fn write_body(&self, w: &mut Writer<'_>) -> Result<u8, EncodeError> {
469        let e = w.endianness().flag();
470        Ok(match self {
471            Submessage::HeaderExtension(he) => e | he.write(w)?,
472            Submessage::Pad(p) => {
473                w.zeros(p.len);
474                e
475            }
476            Submessage::AckNack(a) => e | a.write(w),
477            Submessage::Heartbeat(h) => e | h.write(w),
478            Submessage::Gap(g) => e | g.write(w),
479            Submessage::InfoTimestamp(ts) => match &ts.timestamp {
480                Some(t) => {
481                    t.write(w);
482                    e
483                }
484                None => e | 0x02,
485            },
486            Submessage::InfoSource(s) => {
487                w.zeros(4);
488                s.protocol_version.write(w);
489                s.vendor_id.write(w);
490                s.guid_prefix.write(w);
491                e
492            }
493            Submessage::InfoReplyIp4(ir) => {
494                ir.unicast_locator.write(w);
495                match &ir.multicast_locator {
496                    Some(m) => {
497                        m.write(w);
498                        e | 0x02
499                    }
500                    None => e,
501                }
502            }
503            Submessage::InfoDestination(d) => {
504                d.guid_prefix.write(w);
505                e
506            }
507            Submessage::InfoReply(ir) => {
508                write_locator_list(w, &ir.unicast_locators)?;
509                match &ir.multicast_locators {
510                    Some(m) => {
511                        write_locator_list(w, m)?;
512                        e | 0x02
513                    }
514                    None => e,
515                }
516            }
517            Submessage::NackFrag(n) => {
518                n.reader_id.write(w);
519                n.writer_id.write(w);
520                n.writer_sn.write(w);
521                n.fragment_number_state.write(w);
522                w.i32(n.count.0);
523                e
524            }
525            Submessage::HeartbeatFrag(h) => {
526                h.reader_id.write(w);
527                h.writer_id.write(w);
528                h.writer_sn.write(w);
529                w.u32(h.last_fragment_num.0);
530                w.i32(h.count.0);
531                e
532            }
533            Submessage::Data(d) => e | d.write(w)?,
534            Submessage::DataFrag(d) => e | d.write(w)?,
535            Submessage::Unknown(u) => {
536                w.bytes(&u.body);
537                u.flags
538            }
539        })
540    }
541}
542
543fn read_locator_list(r: &mut Reader<'_>) -> Result<Vec<Locator>, DecodeError> {
544    let n = r.u32()? as usize;
545    // Check the size first so that a bad count cannot make us allocate.
546    if n > r.remaining() / Locator::WIRE_SIZE {
547        return Err(DecodeError::UnexpectedEnd);
548    }
549    (0..n).map(|_| Locator::read(r)).collect()
550}
551
552fn write_locator_list(w: &mut Writer<'_>, list: &[Locator]) -> Result<(), EncodeError> {
553    w.u32(u32::try_from(list.len()).map_err(|_| EncodeError::TooManyLocators)?);
554    for l in list {
555        l.write(w);
556    }
557    Ok(())
558}
559
560impl HeaderExtension {
561    const L: u8 = 0x02;
562    const T: u8 = 0x04;
563    const U: u8 = 0x08;
564    const W: u8 = 0x10;
565    const C2: u8 = 0x20;
566    const C1: u8 = 0x40;
567    const P: u8 = 0x80;
568
569    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
570        let body_len = r.remaining();
571        let message_length = if flag(flags, Self::L) {
572            Some(r.u32()?)
573        } else {
574            None
575        };
576        let send_timestamp = if flag(flags, Self::T) {
577            Some(Time::read(r)?)
578        } else {
579            None
580        };
581        let u_extension4 = if flag(flags, Self::U) {
582            Some(r.array()?)
583        } else {
584            None
585        };
586        let w_extension8 = if flag(flags, Self::W) {
587            Some(r.array()?)
588        } else {
589            None
590        };
591        let checksum = match (flag(flags, Self::C1), flag(flags, Self::C2)) {
592            (false, false) => None,
593            (false, true) => Some(Checksum::Crc32(r.array()?)),
594            (true, false) => Some(Checksum::Crc64(r.array()?)),
595            (true, true) => Some(Checksum::Md5(r.array()?)),
596        };
597        let parameters = if flag(flags, Self::P) {
598            Some(ParameterList::read(r, false)?)
599        } else {
600            None
601        };
602        // 8.3.7.3: messageLength must fit the Header (20 octets), this
603        // submessage's header (4) and its contents.
604        if let Some(len) = message_length
605            && (len as usize) < 20 + 4 + body_len
606        {
607            return Err(invalid(id::RTPS_HE, "messageLength too small"));
608        }
609        Ok(HeaderExtension {
610            message_length,
611            send_timestamp,
612            u_extension4,
613            w_extension8,
614            checksum,
615            parameters,
616        })
617    }
618
619    fn write(&self, w: &mut Writer<'_>) -> Result<u8, EncodeError> {
620        let mut flags = 0;
621        if let Some(len) = self.message_length {
622            flags |= Self::L;
623            w.u32(len);
624        }
625        if let Some(t) = &self.send_timestamp {
626            flags |= Self::T;
627            t.write(w);
628        }
629        if let Some(u) = &self.u_extension4 {
630            flags |= Self::U;
631            w.bytes(u);
632        }
633        if let Some(x) = &self.w_extension8 {
634            flags |= Self::W;
635            w.bytes(x);
636        }
637        match &self.checksum {
638            None => {}
639            Some(Checksum::Crc32(c)) => {
640                flags |= Self::C2;
641                w.bytes(c);
642            }
643            Some(Checksum::Crc64(c)) => {
644                flags |= Self::C1;
645                w.bytes(c);
646            }
647            Some(Checksum::Md5(c)) => {
648                flags |= Self::C1 | Self::C2;
649                w.bytes(c);
650            }
651        }
652        if let Some(p) = &self.parameters {
653            flags |= Self::P;
654            p.write(w, true)?;
655        }
656        Ok(flags)
657    }
658}
659
660impl AckNack {
661    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
662        Ok(AckNack {
663            final_flag: flag(flags, 0x02),
664            reader_id: EntityId::read(r)?,
665            writer_id: EntityId::read(r)?,
666            // Base 0 with no bits is taken as "nothing yet" for interop;
667            // see `read_allowing_empty_zero`.
668            reader_sn_state: SequenceNumberSet::read_allowing_empty_zero(r, id::ACKNACK)?,
669            count: Count(r.i32()?),
670        })
671    }
672
673    fn write(&self, w: &mut Writer<'_>) -> u8 {
674        self.reader_id.write(w);
675        self.writer_id.write(w);
676        self.reader_sn_state.write(w);
677        w.i32(self.count.0);
678        if self.final_flag { 0x02 } else { 0 }
679    }
680}
681
682impl Heartbeat {
683    const F: u8 = 0x02;
684    const L: u8 = 0x04;
685    const G: u8 = 0x08;
686
687    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
688        let err = |reason| invalid(id::HEARTBEAT, reason);
689        let reader_id = EntityId::read(r)?;
690        let writer_id = EntityId::read(r)?;
691        let first_sn = SequenceNumber::read(r)?;
692        let last_sn = SequenceNumber::read(r)?;
693        let count = Count(r.i32()?);
694        // Validity (8.3.8.6.3).
695        if first_sn.0 <= 0 {
696            return Err(err("firstSN is not positive"));
697        }
698        if last_sn.0 < 0 {
699            return Err(err("lastSN is negative"));
700        }
701        if last_sn.0 < first_sn.0 - 1 {
702            return Err(err("lastSN < firstSN - 1"));
703        }
704        let group_info = if flag(flags, Self::G) {
705            let current_gsn = SequenceNumber::read(r)?;
706            let first_gsn = SequenceNumber::read(r)?;
707            let last_gsn = SequenceNumber::read(r)?;
708            let writer_sets = if r.remaining() >= 8 {
709                Some((GroupDigest(r.array()?), GroupDigest(r.array()?)))
710            } else {
711                None
712            };
713            if current_gsn.0 <= 0 || first_gsn.0 <= 0 {
714                return Err(err("group sequence number is not positive"));
715            }
716            if last_gsn.0 < 0 || last_gsn.0 < first_gsn.0 - 1 {
717                return Err(err("lastGSN < firstGSN - 1"));
718            }
719            if current_gsn.0 < first_gsn.0 {
720                return Err(err("currentGSN < firstGSN"));
721            }
722            // 8.3.8.6.3 also calls "currentGSN > lastGSN" invalid, but
723            // currentGSN is the highest GSN of the whole group, so it is
724            // normally >= lastGSN. That rule is not applied until other
725            // implementations show which reading is meant (rustorb-dds#8).
726            Some(HeartbeatGroupInfo {
727                current_gsn,
728                first_gsn,
729                last_gsn,
730                writer_sets,
731            })
732        } else {
733            None
734        };
735        Ok(Heartbeat {
736            final_flag: flag(flags, Self::F),
737            liveliness_flag: flag(flags, Self::L),
738            reader_id,
739            writer_id,
740            first_sn,
741            last_sn,
742            count,
743            group_info,
744        })
745    }
746
747    fn write(&self, w: &mut Writer<'_>) -> u8 {
748        let mut flags = 0;
749        if self.final_flag {
750            flags |= Self::F;
751        }
752        if self.liveliness_flag {
753            flags |= Self::L;
754        }
755        self.reader_id.write(w);
756        self.writer_id.write(w);
757        self.first_sn.write(w);
758        self.last_sn.write(w);
759        w.i32(self.count.0);
760        if let Some(g) = &self.group_info {
761            flags |= Self::G;
762            g.current_gsn.write(w);
763            g.first_gsn.write(w);
764            g.last_gsn.write(w);
765            if let Some((a, b)) = &g.writer_sets {
766                w.bytes(&a.0);
767                w.bytes(&b.0);
768            }
769        }
770        flags
771    }
772}
773
774impl Gap {
775    const G: u8 = 0x02;
776    const F: u8 = 0x04;
777
778    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
779        let err = |reason| invalid(id::GAP, reason);
780        let reader_id = EntityId::read(r)?;
781        let writer_id = EntityId::read(r)?;
782        let gap_start = SequenceNumber::read(r)?;
783        let gap_list = SequenceNumberSet::read(r, id::GAP)?;
784        if gap_start.0 <= 0 {
785            return Err(err("gapStart is not positive"));
786        }
787        let group_info = if flag(flags, Self::G) {
788            let start = SequenceNumber::read(r)?;
789            let end = SequenceNumber::read(r)?;
790            if start.0 <= 0 || end.0 <= 0 {
791                return Err(err("group sequence number is not positive"));
792            }
793            if end.0 < start.0 - 1 {
794                return Err(err("gapEndGSN < gapStartGSN - 1"));
795            }
796            Some((start, end))
797        } else {
798            None
799        };
800        let filtered_count = if flag(flags, Self::F) {
801            Some(ChangeCount::read(r)?)
802        } else {
803            None
804        };
805        Ok(Gap {
806            reader_id,
807            writer_id,
808            gap_start,
809            gap_list,
810            group_info,
811            filtered_count,
812        })
813    }
814
815    fn write(&self, w: &mut Writer<'_>) -> u8 {
816        let mut flags = 0;
817        self.reader_id.write(w);
818        self.writer_id.write(w);
819        self.gap_start.write(w);
820        self.gap_list.write(w);
821        if let Some((start, end)) = &self.group_info {
822            flags |= Self::G;
823            start.write(w);
824            end.write(w);
825        }
826        if let Some(c) = &self.filtered_count {
827            flags |= Self::F;
828            c.write(w);
829        }
830        flags
831    }
832}
833
834impl NackFrag {
835    fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
836        let reader_id = EntityId::read(r)?;
837        let writer_id = EntityId::read(r)?;
838        let writer_sn = SequenceNumber::read(r)?;
839        let fragment_number_state = FragmentNumberSet::read(r, id::NACK_FRAG)?;
840        let count = Count(r.i32()?);
841        if writer_sn.0 <= 0 {
842            return Err(invalid(id::NACK_FRAG, "writerSN is not positive"));
843        }
844        Ok(NackFrag {
845            reader_id,
846            writer_id,
847            writer_sn,
848            fragment_number_state,
849            count,
850        })
851    }
852}
853
854impl HeartbeatFrag {
855    fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
856        let reader_id = EntityId::read(r)?;
857        let writer_id = EntityId::read(r)?;
858        let writer_sn = SequenceNumber::read(r)?;
859        let last_fragment_num = FragmentNumber(r.u32()?);
860        let count = Count(r.i32()?);
861        if writer_sn.0 <= 0 {
862            return Err(invalid(id::HEARTBEAT_FRAG, "writerSN is not positive"));
863        }
864        if last_fragment_num.0 == 0 {
865            return Err(invalid(id::HEARTBEAT_FRAG, "lastFragmentNum is zero"));
866        }
867        Ok(HeartbeatFrag {
868            reader_id,
869            writer_id,
870            writer_sn,
871            last_fragment_num,
872            count,
873        })
874    }
875}
876
877/// Reads `extraFlags` and `octetsToInlineQos`, then the fixed elements
878/// with `read_fixed`, then skips whatever a later protocol version put
879/// before the in-line QoS (9.4.5.4.3) and reads the in-line QoS.
880fn read_data_common<'a, T>(
881    sub_id: u8,
882    flags: u8,
883    r: &mut Reader<'a>,
884    fixed_len: usize,
885    read_fixed: impl FnOnce(&mut Reader<'a>) -> Result<T, DecodeError>,
886) -> Result<(T, Option<ParameterList>), DecodeError> {
887    let _extra_flags = r.u16()?;
888    let octets_to_inline_qos = r.u16()? as usize;
889    if octets_to_inline_qos < fixed_len {
890        return Err(invalid(sub_id, "octetsToInlineQos too small"));
891    }
892    let fixed = read_fixed(r)?;
893    r.skip(octets_to_inline_qos - fixed_len)?;
894    let inline_qos = if flag(flags, 0x02) {
895        Some(ParameterList::read(r, true).map_err(|_| invalid(sub_id, "invalid inlineQos"))?)
896    } else {
897        None
898    };
899    Ok((fixed, inline_qos))
900}
901
902impl Data {
903    const Q: u8 = 0x02;
904    const D: u8 = 0x04;
905    const K: u8 = 0x08;
906    const N: u8 = 0x10;
907    /// readerId + writerId + writerSN.
908    const FIXED_LEN: usize = 16;
909
910    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
911        let ((reader_id, writer_id, writer_sn), inline_qos) =
912            read_data_common(id::DATA, flags, r, Self::FIXED_LEN, |r| {
913                Ok((
914                    EntityId::read(r)?,
915                    EntityId::read(r)?,
916                    SequenceNumber::read(r)?,
917                ))
918            })?;
919        if writer_sn.0 <= 0 {
920            return Err(invalid(id::DATA, "writerSN is not positive"));
921        }
922        let kind = match (flag(flags, Self::D), flag(flags, Self::K)) {
923            (false, false) => None,
924            (true, false) => Some(PayloadKind::Data),
925            (false, true) => Some(PayloadKind::Key),
926            (true, true) => return Err(invalid(id::DATA, "both DataFlag and KeyFlag set")),
927        };
928        let serialized_payload = kind.map(|kind| SerializedPayload {
929            kind,
930            bytes: {
931                let rest = r.rest();
932                r.share(rest)
933            },
934        });
935        Ok(Data {
936            reader_id,
937            writer_id,
938            writer_sn,
939            inline_qos,
940            serialized_payload,
941            non_standard_payload: flag(flags, Self::N),
942        })
943    }
944
945    fn write(&self, w: &mut Writer<'_>) -> Result<u8, EncodeError> {
946        let mut flags = 0;
947        w.u16(0); // extraFlags
948        w.u16(Self::FIXED_LEN as u16);
949        self.reader_id.write(w);
950        self.writer_id.write(w);
951        self.writer_sn.write(w);
952        if let Some(q) = &self.inline_qos {
953            flags |= Self::Q;
954            q.write(w, true)?;
955        }
956        if let Some(p) = &self.serialized_payload {
957            flags |= match p.kind {
958                PayloadKind::Data => Self::D,
959                PayloadKind::Key => Self::K,
960            };
961            w.bytes(&p.bytes);
962        }
963        if self.non_standard_payload {
964            flags |= Self::N;
965        }
966        Ok(flags)
967    }
968}
969
970impl DataFrag {
971    const Q: u8 = 0x02;
972    const K: u8 = 0x04;
973    const N: u8 = 0x08;
974    /// readerId + writerId + writerSN + fragmentStartingNum +
975    /// fragmentsInSubmessage + fragmentSize + sampleSize.
976    const FIXED_LEN: usize = 28;
977
978    fn read(flags: u8, r: &mut Reader<'_>) -> Result<Self, DecodeError> {
979        let err = |reason| invalid(id::DATA_FRAG, reason);
980        let ((reader_id, writer_id, writer_sn, start, count, size, sample_size), inline_qos) =
981            read_data_common(id::DATA_FRAG, flags, r, Self::FIXED_LEN, |r| {
982                Ok((
983                    EntityId::read(r)?,
984                    EntityId::read(r)?,
985                    SequenceNumber::read(r)?,
986                    FragmentNumber(r.u32()?),
987                    r.u16()?,
988                    r.u16()?,
989                    r.u32()?,
990                ))
991            })?;
992        // Validity (8.3.8.3.3).
993        if writer_sn.0 <= 0 {
994            return Err(err("writerSN is not positive"));
995        }
996        if size == 0 {
997            return Err(err("fragmentSize is zero"));
998        }
999        if size as u32 > sample_size {
1000            return Err(err("fragmentSize exceeds sampleSize"));
1001        }
1002        let total = sample_size.div_ceil(size as u32);
1003        if start.0 == 0 || start.0 > total {
1004            return Err(err("fragmentStartingNum out of range"));
1005        }
1006        let mut payload = r.rest();
1007        // The payload may not be longer than fragmentsInSubmessage *
1008        // fragmentSize. The octets that pad the submessage to a 4-octet
1009        // boundary are allowed on top of that, then dropped, as are octets
1010        // past the end of the sample.
1011        let declared = count as usize * size as usize;
1012        if payload.len() > declared.next_multiple_of(4) {
1013            return Err(err("serializedPayload longer than the fragments"));
1014        }
1015        let offset = (start.0 as u64 - 1) * size as u64;
1016        let left_in_sample = (sample_size as u64).saturating_sub(offset) as usize;
1017        payload = &payload[..payload.len().min(declared).min(left_in_sample)];
1018        Ok(DataFrag {
1019            key_flag: flag(flags, Self::K),
1020            non_standard_payload: flag(flags, Self::N),
1021            reader_id,
1022            writer_id,
1023            writer_sn,
1024            fragment_starting_num: start,
1025            fragments_in_submessage: count,
1026            fragment_size: size,
1027            sample_size,
1028            inline_qos,
1029            serialized_payload: r.share(payload),
1030        })
1031    }
1032
1033    fn write(&self, w: &mut Writer<'_>) -> Result<u8, EncodeError> {
1034        let mut flags = 0;
1035        w.u16(0); // extraFlags
1036        w.u16(Self::FIXED_LEN as u16);
1037        self.reader_id.write(w);
1038        self.writer_id.write(w);
1039        self.writer_sn.write(w);
1040        w.u32(self.fragment_starting_num.0);
1041        w.u16(self.fragments_in_submessage);
1042        w.u16(self.fragment_size);
1043        w.u32(self.sample_size);
1044        if let Some(q) = &self.inline_qos {
1045            flags |= Self::Q;
1046            q.write(w, true)?;
1047        }
1048        w.bytes(&self.serialized_payload);
1049        if self.key_flag {
1050            flags |= Self::K;
1051        }
1052        if self.non_standard_payload {
1053            flags |= Self::N;
1054        }
1055        Ok(flags)
1056    }
1057}