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