Skip to main content

rustorb_rtps/
types.rs

1//! The basic RTPS types and submessage elements
2//! (DDSI-RTPS 2.5, 8.3.5, 9.3 and 9.4.2).
3
4use std::fmt;
5use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
6
7use crate::error::DecodeError;
8use crate::wire::{Endianness, Reader, Writer};
9
10/// The 12-octet prefix shared by the GUIDs of all entities of one
11/// participant (DDSI-RTPS 2.5, 9.3.1.1).
12///
13/// The first two octets must be the vendor id of the implementation
14/// (9.3.1.5).
15#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
16pub struct GuidPrefix(pub [u8; 12]);
17
18impl GuidPrefix {
19    /// `GUIDPREFIX_UNKNOWN`: all zeros.
20    pub const UNKNOWN: GuidPrefix = GuidPrefix([0; 12]);
21
22    /// Makes a prefix that is very likely unique in the domain: the vendor
23    /// id in the first two octets (9.3.1.5), then ten octets mixed from
24    /// the process id, the time, a counter and the standard library's
25    /// random hash keys.
26    pub fn generate(vendor_id: VendorId) -> GuidPrefix {
27        use std::collections::hash_map::RandomState;
28        use std::hash::{BuildHasher, Hasher};
29        use std::sync::atomic::{AtomicU64, Ordering};
30        static COUNTER: AtomicU64 = AtomicU64::new(0);
31
32        let mut h = RandomState::new().build_hasher();
33        h.write_u32(std::process::id());
34        h.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
35        if let Ok(d) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
36            h.write_u128(d.as_nanos());
37        }
38        let a = h.finish();
39        h.write_u64(a);
40        let b = h.finish();
41        let mut out = [0u8; 12];
42        out[..2].copy_from_slice(&vendor_id.0);
43        out[2..10].copy_from_slice(&a.to_be_bytes());
44        out[10..].copy_from_slice(&b.to_be_bytes()[..2]);
45        GuidPrefix(out)
46    }
47
48    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
49        r.array().map(GuidPrefix)
50    }
51
52    pub(crate) fn write(&self, w: &mut Writer<'_>) {
53        w.bytes(&self.0);
54    }
55}
56
57impl fmt::Debug for GuidPrefix {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        write!(f, "GuidPrefix(")?;
60        for (i, b) in self.0.iter().enumerate() {
61            if i > 0 && i % 4 == 0 {
62                f.write_str(".")?;
63            }
64            write!(f, "{b:02x}")?;
65        }
66        f.write_str(")")
67    }
68}
69
70/// The identifier of an entity within its participant
71/// (DDSI-RTPS 2.5, 9.3.1.2).
72#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
73pub struct EntityId {
74    /// The three-octet key. Chosen by the implementation unless the entity
75    /// is a predefined one.
76    pub entity_key: [u8; 3],
77    /// The kind of entity; see [`entity_kind`].
78    pub entity_kind: u8,
79}
80
81/// Values of [`EntityId::entity_kind`] (DDSI-RTPS 2.5, Table 9.1).
82///
83/// The two most significant bits say who defined the entity: `00` user,
84/// `11` built-in, `01` vendor-specific (9.3.1.2).
85pub mod entity_kind {
86    /// Unknown, user-defined.
87    pub const USER_UNKNOWN: u8 = 0x00;
88    /// Writer with a key, user-defined.
89    pub const USER_WRITER_WITH_KEY: u8 = 0x02;
90    /// Writer without a key, user-defined.
91    pub const USER_WRITER_NO_KEY: u8 = 0x03;
92    /// Reader without a key, user-defined.
93    pub const USER_READER_NO_KEY: u8 = 0x04;
94    /// Reader with a key, user-defined.
95    pub const USER_READER_WITH_KEY: u8 = 0x07;
96    /// Writer group, user-defined.
97    pub const USER_WRITER_GROUP: u8 = 0x08;
98    /// Reader group, user-defined.
99    pub const USER_READER_GROUP: u8 = 0x09;
100    /// Unknown, built-in.
101    pub const BUILTIN_UNKNOWN: u8 = 0xc0;
102    /// Participant (always built-in).
103    pub const BUILTIN_PARTICIPANT: u8 = 0xc1;
104    /// Writer with a key, built-in.
105    pub const BUILTIN_WRITER_WITH_KEY: u8 = 0xc2;
106    /// Writer without a key, built-in.
107    pub const BUILTIN_WRITER_NO_KEY: u8 = 0xc3;
108    /// Reader without a key, built-in.
109    pub const BUILTIN_READER_NO_KEY: u8 = 0xc4;
110    /// Reader with a key, built-in.
111    pub const BUILTIN_READER_WITH_KEY: u8 = 0xc7;
112    /// Writer group, built-in.
113    pub const BUILTIN_WRITER_GROUP: u8 = 0xc8;
114    /// Reader group, built-in.
115    pub const BUILTIN_READER_GROUP: u8 = 0xc9;
116}
117
118impl EntityId {
119    const fn new(key: [u8; 3], kind: u8) -> Self {
120        EntityId {
121            entity_key: key,
122            entity_kind: kind,
123        }
124    }
125
126    /// `ENTITYID_UNKNOWN`.
127    pub const UNKNOWN: EntityId = EntityId::new([0, 0, 0], 0x00);
128    /// `ENTITYID_PARTICIPANT` (Table 9.2).
129    pub const PARTICIPANT: EntityId = EntityId::new([0, 0, 1], 0xc1);
130    /// `ENTITYID_SEDP_BUILTIN_TOPICS_ANNOUNCER`.
131    pub const SEDP_BUILTIN_TOPICS_ANNOUNCER: EntityId = EntityId::new([0, 0, 2], 0xc2);
132    /// `ENTITYID_SEDP_BUILTIN_TOPICS_DETECTOR`.
133    pub const SEDP_BUILTIN_TOPICS_DETECTOR: EntityId = EntityId::new([0, 0, 2], 0xc7);
134    /// `ENTITYID_SEDP_BUILTIN_PUBLICATIONS_ANNOUNCER`.
135    pub const SEDP_BUILTIN_PUBLICATIONS_ANNOUNCER: EntityId = EntityId::new([0, 0, 3], 0xc2);
136    /// `ENTITYID_SEDP_BUILTIN_PUBLICATIONS_DETECTOR`.
137    pub const SEDP_BUILTIN_PUBLICATIONS_DETECTOR: EntityId = EntityId::new([0, 0, 3], 0xc7);
138    /// `ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_ANNOUNCER`.
139    pub const SEDP_BUILTIN_SUBSCRIPTIONS_ANNOUNCER: EntityId = EntityId::new([0, 0, 4], 0xc2);
140    /// `ENTITYID_SEDP_BUILTIN_SUBSCRIPTIONS_DETECTOR`.
141    pub const SEDP_BUILTIN_SUBSCRIPTIONS_DETECTOR: EntityId = EntityId::new([0, 0, 4], 0xc7);
142    /// `ENTITYID_SPDP_BUILTIN_PARTICIPANT_ANNOUNCER`.
143    pub const SPDP_BUILTIN_PARTICIPANT_ANNOUNCER: EntityId = EntityId::new([0, 1, 0], 0xc2);
144    /// `ENTITYID_SPDP_BUILTIN_PARTICIPANT_DETECTOR`.
145    pub const SPDP_BUILTIN_PARTICIPANT_DETECTOR: EntityId = EntityId::new([0, 1, 0], 0xc7);
146    /// `ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER`.
147    pub const P2P_BUILTIN_PARTICIPANT_MESSAGE_WRITER: EntityId = EntityId::new([0, 2, 0], 0xc2);
148    /// `ENTITYID_P2P_BUILTIN_PARTICIPANT_MESSAGE_READER`.
149    pub const P2P_BUILTIN_PARTICIPANT_MESSAGE_READER: EntityId = EntityId::new([0, 2, 0], 0xc7);
150    /// `ENTITYID_TL_SVC_REQ_WRITER` (DDS-XTypes 1.3 Table 61).
151    pub const TL_SVC_REQ_WRITER: EntityId = EntityId::new([0, 3, 0], 0xc3);
152    /// `ENTITYID_TL_SVC_REQ_READER`.
153    pub const TL_SVC_REQ_READER: EntityId = EntityId::new([0, 3, 0], 0xc4);
154    /// `ENTITYID_TL_SVC_REPLY_WRITER`.
155    pub const TL_SVC_REPLY_WRITER: EntityId = EntityId::new([0, 3, 1], 0xc3);
156    /// `ENTITYID_TL_SVC_REPLY_READER`.
157    pub const TL_SVC_REPLY_READER: EntityId = EntityId::new([0, 3, 1], 0xc4);
158    /// SEDPbuiltinPublicationsSecureWriter (DDS Security 1.2, Table 9).
159    pub const SEDP_BUILTIN_PUBLICATIONS_SECURE_WRITER: EntityId = EntityId::new([0xff, 0, 3], 0xc2);
160    /// SEDPbuiltinPublicationsSecureReader.
161    pub const SEDP_BUILTIN_PUBLICATIONS_SECURE_READER: EntityId = EntityId::new([0xff, 0, 3], 0xc7);
162    /// SEDPbuiltinSubscriptionsSecureWriter.
163    pub const SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_WRITER: EntityId =
164        EntityId::new([0xff, 0, 4], 0xc2);
165    /// SEDPbuiltinSubscriptionsSecureReader.
166    pub const SEDP_BUILTIN_SUBSCRIPTIONS_SECURE_READER: EntityId =
167        EntityId::new([0xff, 0, 4], 0xc7);
168    /// BuiltinParticipantMessageSecureWriter.
169    pub const P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_WRITER: EntityId =
170        EntityId::new([0xff, 2, 0], 0xc2);
171    /// BuiltinParticipantMessageSecureReader.
172    pub const P2P_BUILTIN_PARTICIPANT_MESSAGE_SECURE_READER: EntityId =
173        EntityId::new([0xff, 2, 0], 0xc7);
174    /// BuiltinParticipantStatelessMessageWriter.
175    pub const P2P_BUILTIN_PARTICIPANT_STATELESS_WRITER: EntityId = EntityId::new([0, 2, 1], 0xc3);
176    /// BuiltinParticipantStatelessMessageReader.
177    pub const P2P_BUILTIN_PARTICIPANT_STATELESS_READER: EntityId = EntityId::new([0, 2, 1], 0xc4);
178    /// BuiltinParticipantVolatileMessageSecureWriter.
179    pub const P2P_BUILTIN_PARTICIPANT_VOLATILE_SECURE_WRITER: EntityId =
180        EntityId::new([0xff, 2, 2], 0xc3);
181    /// BuiltinParticipantVolatileMessageSecureReader.
182    pub const P2P_BUILTIN_PARTICIPANT_VOLATILE_SECURE_READER: EntityId =
183        EntityId::new([0xff, 2, 2], 0xc4);
184    /// SPDPbuiltinParticipantsSecureWriter.
185    pub const SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_WRITER: EntityId =
186        EntityId::new([0xff, 1, 1], 0xc2);
187    /// SPDPbuiltinParticipantsSecureReader.
188    pub const SPDP_RELIABLE_BUILTIN_PARTICIPANT_SECURE_READER: EntityId =
189        EntityId::new([0xff, 1, 1], 0xc7);
190
191    /// Makes a user-defined entity id from a key and a kind.
192    pub const fn user(entity_key: [u8; 3], entity_kind: u8) -> Self {
193        EntityId::new(entity_key, entity_kind)
194    }
195
196    /// The four octets as they appear on the wire.
197    pub const fn to_bytes(self) -> [u8; 4] {
198        let k = self.entity_key;
199        [k[0], k[1], k[2], self.entity_kind]
200    }
201
202    /// Builds an entity id from its four wire octets.
203    pub const fn from_bytes(b: [u8; 4]) -> Self {
204        EntityId::new([b[0], b[1], b[2]], b[3])
205    }
206
207    /// Whether the kind marks a built-in entity (top bits `11`).
208    pub const fn is_builtin(self) -> bool {
209        self.entity_kind & 0xc0 == 0xc0
210    }
211
212    /// Whether the kind marks a vendor-specific entity (top bits `01`).
213    pub const fn is_vendor_specific(self) -> bool {
214        self.entity_kind & 0xc0 == 0x40
215    }
216
217    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
218        r.array().map(EntityId::from_bytes)
219    }
220
221    pub(crate) fn write(&self, w: &mut Writer<'_>) {
222        w.bytes(&self.to_bytes());
223    }
224}
225
226impl fmt::Debug for EntityId {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        let [a, b, c, d] = self.to_bytes();
229        write!(f, "EntityId({a:02x}{b:02x}{c:02x}.{d:02x})")
230    }
231}
232
233/// A globally unique identifier of an entity (DDSI-RTPS 2.5, 9.3.1.5).
234#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
235pub struct Guid {
236    /// The participant part.
237    pub prefix: GuidPrefix,
238    /// The entity part.
239    pub entity_id: EntityId,
240}
241
242impl Guid {
243    /// `GUID_UNKNOWN`.
244    pub const UNKNOWN: Guid = Guid {
245        prefix: GuidPrefix::UNKNOWN,
246        entity_id: EntityId::UNKNOWN,
247    };
248
249    /// Joins a prefix and an entity id.
250    pub const fn new(prefix: GuidPrefix, entity_id: EntityId) -> Self {
251        Guid { prefix, entity_id }
252    }
253
254    /// The 16 octets: the prefix followed by the entity id.
255    pub fn to_bytes(self) -> [u8; 16] {
256        let mut out = [0u8; 16];
257        out[..12].copy_from_slice(&self.prefix.0);
258        out[12..].copy_from_slice(&self.entity_id.to_bytes());
259        out
260    }
261
262    /// From the 16 octets of [`to_bytes`](Self::to_bytes).
263    pub fn from_bytes(b: [u8; 16]) -> Self {
264        let mut prefix = [0u8; 12];
265        prefix.copy_from_slice(&b[..12]);
266        Guid::new(
267            GuidPrefix(prefix),
268            EntityId::from_bytes([b[12], b[13], b[14], b[15]]),
269        )
270    }
271}
272
273/// The vendor of an RTPS implementation (DDSI-RTPS 2.5, 8.3.3.1.3).
274///
275/// Values are assigned by the OMG.
276#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
277pub struct VendorId(pub [u8; 2]);
278
279impl VendorId {
280    /// `VENDORID_UNKNOWN`.
281    pub const UNKNOWN: VendorId = VendorId([0, 0]);
282
283    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
284        r.array().map(VendorId)
285    }
286
287    pub(crate) fn write(&self, w: &mut Writer<'_>) {
288        w.bytes(&self.0);
289    }
290}
291
292/// An RTPS protocol version (DDSI-RTPS 2.5, 9.4.2.4).
293#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
294pub struct ProtocolVersion {
295    /// Major version.
296    pub major: u8,
297    /// Minor version.
298    pub minor: u8,
299}
300
301impl ProtocolVersion {
302    /// 1.0
303    pub const V1_0: ProtocolVersion = ProtocolVersion { major: 1, minor: 0 };
304    /// 1.1
305    pub const V1_1: ProtocolVersion = ProtocolVersion { major: 1, minor: 1 };
306    /// 2.0
307    pub const V2_0: ProtocolVersion = ProtocolVersion { major: 2, minor: 0 };
308    /// 2.1
309    pub const V2_1: ProtocolVersion = ProtocolVersion { major: 2, minor: 1 };
310    /// 2.2
311    pub const V2_2: ProtocolVersion = ProtocolVersion { major: 2, minor: 2 };
312    /// 2.3
313    pub const V2_3: ProtocolVersion = ProtocolVersion { major: 2, minor: 3 };
314    /// 2.4
315    pub const V2_4: ProtocolVersion = ProtocolVersion { major: 2, minor: 4 };
316    /// 2.5
317    pub const V2_5: ProtocolVersion = ProtocolVersion { major: 2, minor: 5 };
318    /// `PROTOCOLVERSION`: the version this crate implements, 2.5.
319    pub const CURRENT: ProtocolVersion = ProtocolVersion::V2_5;
320
321    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
322        let [major, minor] = r.array()?;
323        Ok(ProtocolVersion { major, minor })
324    }
325
326    pub(crate) fn write(&self, w: &mut Writer<'_>) {
327        w.bytes(&[self.major, self.minor]);
328    }
329}
330
331/// A 64-bit signed sequence number (DDSI-RTPS 2.5, 8.3.5.4 and 9.3.2.10).
332///
333/// On the wire it is `{ long high; unsigned long low; }` and the value is
334/// `high * 2^32 + low`. Sequence numbers start at 1.
335#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
336pub struct SequenceNumber(pub i64);
337
338impl SequenceNumber {
339    /// `SEQUENCENUMBER_UNKNOWN`: high = -1, low = 0.
340    pub const UNKNOWN: SequenceNumber = SequenceNumber(-(1 << 32));
341
342    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
343        let high = r.i32()?;
344        let low = r.u32()?;
345        Ok(SequenceNumber(((high as i64) << 32) | low as i64))
346    }
347
348    pub(crate) fn write(&self, w: &mut Writer<'_>) {
349        w.i32((self.0 >> 32) as i32);
350        w.u32(self.0 as u32);
351    }
352}
353
354/// The identity of a sample: its writer and its sequence number
355/// (`SampleIdentity`, DDS-RPC 1.0, 7.5.1.1.1). A reply carries that of
356/// its request in-line, as `PID_RELATED_SAMPLE_IDENTITY` (7.8.2).
357#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
358pub struct SampleIdentity {
359    /// `writer_guid`.
360    pub writer_guid: Guid,
361    /// `sequence_number`.
362    pub sequence_number: SequenceNumber,
363}
364
365impl SampleIdentity {
366    /// `RELATED_SAMPLE_IDENTITY_INVALID`: `GUID_UNKNOWN` and
367    /// `SEQUENCENUMBER_UNKNOWN`.
368    pub const INVALID: SampleIdentity = SampleIdentity {
369        writer_guid: Guid::UNKNOWN,
370        sequence_number: SequenceNumber::UNKNOWN,
371    };
372
373    /// The CDR serialization (24 octets) in `endianness`.
374    pub fn to_bytes(&self, endianness: Endianness) -> Vec<u8> {
375        let mut out = Vec::with_capacity(24);
376        let mut w = Writer::new(&mut out, endianness);
377        w.bytes(&self.writer_guid.to_bytes());
378        self.sequence_number.write(&mut w);
379        out
380    }
381
382    /// Reads the CDR serialization in `endianness`.
383    pub fn from_bytes(bytes: &[u8], endianness: Endianness) -> Result<Self, DecodeError> {
384        let mut r = Reader::new(bytes, endianness);
385        let prefix = GuidPrefix::read(&mut r)?;
386        let entity_id = EntityId::read(&mut r)?;
387        Ok(SampleIdentity {
388            writer_guid: Guid::new(prefix, entity_id),
389            sequence_number: SequenceNumber::read(&mut r)?,
390        })
391    }
392}
393
394/// A 32-bit fragment number, starting at 1 (DDSI-RTPS 2.5, 8.3.5.6).
395#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
396pub struct FragmentNumber(pub u32);
397
398/// The bitmap shared by [`SequenceNumberSet`] and [`FragmentNumberSet`]
399/// (DDSI-RTPS 2.5, 9.4.2.6): up to 256 bits, the first bit is the most
400/// significant bit of the first 32-bit word.
401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
402struct Bitmap {
403    num_bits: u32,
404    words: [u32; 8],
405}
406
407impl Bitmap {
408    const MAX_BITS: u32 = 256;
409
410    fn new(num_bits: u32) -> Option<Self> {
411        (num_bits <= Self::MAX_BITS).then_some(Bitmap {
412            num_bits,
413            words: [0; 8],
414        })
415    }
416
417    fn get(&self, offset: u32) -> bool {
418        offset < self.num_bits
419            && self.words[(offset / 32) as usize] & (1 << (31 - offset % 32)) != 0
420    }
421
422    fn set(&mut self, offset: u32) -> bool {
423        if offset >= self.num_bits {
424            return false;
425        }
426        self.words[(offset / 32) as usize] |= 1 << (31 - offset % 32);
427        true
428    }
429
430    fn ones(&self) -> impl Iterator<Item = u32> + '_ {
431        (0..self.num_bits).filter(|&i| self.get(i))
432    }
433
434    fn word_count(&self) -> usize {
435        self.num_bits.div_ceil(32) as usize
436    }
437
438    /// Reads `numBits` and the words. Bits past `numBits` are cleared, as
439    /// they carry no meaning.
440    fn read(r: &mut Reader<'_>, invalid: DecodeError) -> Result<Self, DecodeError> {
441        let num_bits = r.u32()?;
442        let mut bitmap = Bitmap::new(num_bits).ok_or(invalid)?;
443        for i in 0..bitmap.word_count() {
444            bitmap.words[i] = r.u32()?;
445        }
446        let rem = num_bits % 32;
447        if rem != 0 {
448            let last = bitmap.word_count() - 1;
449            bitmap.words[last] &= !(u32::MAX >> rem);
450        }
451        Ok(bitmap)
452    }
453
454    fn write(&self, w: &mut Writer<'_>) {
455        w.u32(self.num_bits);
456        for word in &self.words[..self.word_count()] {
457            w.u32(*word);
458        }
459    }
460}
461
462/// A set of up to 256 sequence numbers starting at `base`
463/// (DDSI-RTPS 2.5, 8.3.5.5 and 9.4.2.6).
464#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
465pub struct SequenceNumberSet {
466    base: SequenceNumber,
467    bitmap: Bitmap,
468}
469
470impl SequenceNumberSet {
471    /// An empty set covering `base .. base + num_bits`.
472    ///
473    /// Returns `None` if `base` is less than 1 or `num_bits` is more than
474    /// 256.
475    pub fn new(base: SequenceNumber, num_bits: u32) -> Option<Self> {
476        if base.0 < 1 {
477            return None;
478        }
479        Some(SequenceNumberSet {
480            base,
481            bitmap: Bitmap::new(num_bits)?,
482        })
483    }
484
485    /// The first sequence number the set can hold (`bitmapBase`).
486    pub fn base(&self) -> SequenceNumber {
487        self.base
488    }
489
490    /// How many sequence numbers, from `base`, the set covers (`numBits`).
491    pub fn num_bits(&self) -> u32 {
492        self.bitmap.num_bits
493    }
494
495    /// Adds `sn`. Returns false, and leaves the set as it is, when `sn` is
496    /// outside `base .. base + num_bits`.
497    pub fn insert(&mut self, sn: SequenceNumber) -> bool {
498        match sn.0.checked_sub(self.base.0) {
499            Some(d) if (0..self.bitmap.num_bits as i64).contains(&d) => self.bitmap.set(d as u32),
500            _ => false,
501        }
502    }
503
504    /// Whether `sn` is in the set.
505    pub fn contains(&self, sn: SequenceNumber) -> bool {
506        match sn.0.checked_sub(self.base.0) {
507            Some(d) if (0..self.bitmap.num_bits as i64).contains(&d) => self.bitmap.get(d as u32),
508            _ => false,
509        }
510    }
511
512    /// The sequence numbers in the set, in increasing order.
513    pub fn iter(&self) -> impl Iterator<Item = SequenceNumber> + '_ {
514        self.bitmap
515            .ones()
516            .map(move |d| SequenceNumber(self.base.0 + d as i64))
517    }
518
519    pub(crate) fn read(r: &mut Reader<'_>, id: u8) -> Result<Self, DecodeError> {
520        let invalid = DecodeError::InvalidSubmessage {
521            id,
522            reason: "invalid SequenceNumberSet",
523        };
524        let base = SequenceNumber::read(r)?;
525        if base.0 < 1 {
526            return Err(invalid);
527        }
528        let bitmap = Bitmap::read(r, invalid)?;
529        Ok(SequenceNumberSet { base, bitmap })
530    }
531
532    /// Like `read`, but also takes an empty set with base 0 and returns
533    /// it as an empty set with base 1. Base 0 is invalid (8.3.5.5), but
534    /// some implementations send it in an ACKNACK to say that nothing was
535    /// received yet; "everything before 0" and "everything before 1"
536    /// acknowledge the same nothing.
537    pub(crate) fn read_allowing_empty_zero(
538        r: &mut Reader<'_>,
539        id: u8,
540    ) -> Result<Self, DecodeError> {
541        let invalid = DecodeError::InvalidSubmessage {
542            id,
543            reason: "invalid SequenceNumberSet",
544        };
545        let base = SequenceNumber::read(r)?;
546        let bitmap = Bitmap::read(r, invalid.clone())?;
547        if base.0 >= 1 {
548            Ok(SequenceNumberSet { base, bitmap })
549        } else if base.0 == 0 && bitmap.num_bits == 0 {
550            Ok(SequenceNumberSet {
551                base: SequenceNumber(1),
552                bitmap,
553            })
554        } else {
555            Err(invalid)
556        }
557    }
558
559    pub(crate) fn write(&self, w: &mut Writer<'_>) {
560        self.base.write(w);
561        self.bitmap.write(w);
562    }
563}
564
565/// A set of up to 256 fragment numbers starting at `base`
566/// (DDSI-RTPS 2.5, 8.3.5.7 and 9.4.2.8).
567#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
568pub struct FragmentNumberSet {
569    base: FragmentNumber,
570    bitmap: Bitmap,
571}
572
573impl FragmentNumberSet {
574    /// An empty set covering `base .. base + num_bits`.
575    ///
576    /// Returns `None` if `base` is 0 or `num_bits` is more than 256.
577    pub fn new(base: FragmentNumber, num_bits: u32) -> Option<Self> {
578        if base.0 < 1 {
579            return None;
580        }
581        Some(FragmentNumberSet {
582            base,
583            bitmap: Bitmap::new(num_bits)?,
584        })
585    }
586
587    /// The first fragment number the set can hold (`bitmapBase`).
588    pub fn base(&self) -> FragmentNumber {
589        self.base
590    }
591
592    /// How many fragment numbers, from `base`, the set covers (`numBits`).
593    pub fn num_bits(&self) -> u32 {
594        self.bitmap.num_bits
595    }
596
597    /// Adds `n`. Returns false when `n` is outside the range of the set.
598    pub fn insert(&mut self, n: FragmentNumber) -> bool {
599        match n.0.checked_sub(self.base.0) {
600            Some(d) => self.bitmap.set(d),
601            None => false,
602        }
603    }
604
605    /// Whether `n` is in the set.
606    pub fn contains(&self, n: FragmentNumber) -> bool {
607        match n.0.checked_sub(self.base.0) {
608            Some(d) => self.bitmap.get(d),
609            None => false,
610        }
611    }
612
613    /// The fragment numbers in the set, in increasing order.
614    pub fn iter(&self) -> impl Iterator<Item = FragmentNumber> + '_ {
615        self.bitmap
616            .ones()
617            .map(move |d| FragmentNumber(self.base.0 + d))
618    }
619
620    pub(crate) fn read(r: &mut Reader<'_>, id: u8) -> Result<Self, DecodeError> {
621        let invalid = DecodeError::InvalidSubmessage {
622            id,
623            reason: "invalid FragmentNumberSet",
624        };
625        let base = FragmentNumber(r.u32()?);
626        if base.0 < 1 {
627            return Err(invalid);
628        }
629        let bitmap = Bitmap::read(r, invalid)?;
630        Ok(FragmentNumberSet { base, bitmap })
631    }
632
633    pub(crate) fn write(&self, w: &mut Writer<'_>) {
634        w.u32(self.base.0);
635        self.bitmap.write(w);
636    }
637}
638
639/// A point in time in NTP format: `seconds + fraction / 2^32`
640/// (DDSI-RTPS 2.5, 9.3.2.1 and 9.3.2.2).
641///
642/// The IDL in 9.3.2.1 makes `seconds` an `unsigned long`, and the special
643/// values use `0xffffffff`, so it is held as `u32` here. (The drawing in
644/// 9.4.2.9 labels it `long`; the bits are the same.)
645#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
646pub struct Time {
647    /// Whole seconds.
648    pub seconds: u32,
649    /// Fraction of a second in units of 2^-32 s.
650    pub fraction: u32,
651}
652
653impl Time {
654    /// `TIME_ZERO`.
655    pub const ZERO: Time = Time {
656        seconds: 0,
657        fraction: 0,
658    };
659    /// `TIME_INVALID`.
660    pub const INVALID: Time = Time {
661        seconds: 0xffff_ffff,
662        fraction: 0xffff_ffff,
663    };
664    /// `TIME_INFINITE`.
665    pub const INFINITE: Time = Time {
666        seconds: 0xffff_ffff,
667        fraction: 0xffff_fffe,
668    };
669
670    /// The current time, counted from the UNIX epoch.
671    ///
672    /// DDSI-RTPS does not fix the origin of `Time_t`; the UNIX epoch is
673    /// assumed here and is to be checked against other implementations
674    /// (rustorb-dds#8).
675    pub fn now() -> Time {
676        let d = std::time::SystemTime::now()
677            .duration_since(std::time::UNIX_EPOCH)
678            .unwrap_or_default();
679        Time {
680            seconds: d.as_secs() as u32,
681            fraction: ((u64::from(d.subsec_nanos()) << 32) / 1_000_000_000) as u32,
682        }
683    }
684
685    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
686        Ok(Time {
687            seconds: r.u32()?,
688            fraction: r.u32()?,
689        })
690    }
691
692    pub(crate) fn write(&self, w: &mut Writer<'_>) {
693        w.u32(self.seconds);
694        w.u32(self.fraction);
695    }
696}
697
698/// A counter used to detect duplicate submessages
699/// (DDSI-RTPS 2.5, 8.3.5.10 and 9.4.2.13).
700#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
701pub struct Count(pub i32);
702
703/// A 64-bit count of changes, used in GAP
704/// (DDSI-RTPS 2.5, 8.3.5.11 and 9.3.2.11).
705#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
706pub struct ChangeCount(pub i64);
707
708impl ChangeCount {
709    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
710        SequenceNumber::read(r).map(|s| ChangeCount(s.0))
711    }
712
713    pub(crate) fn write(&self, w: &mut Writer<'_>) {
714        SequenceNumber(self.0).write(w);
715    }
716}
717
718/// Four octets that stand for a group of entities
719/// (DDSI-RTPS 2.5, 9.3.2.5).
720#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
721pub struct GroupDigest(pub [u8; 4]);
722
723/// A transport address (DDSI-RTPS 2.5, 9.3.2.4).
724#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
725pub struct Locator {
726    /// The transport; see the `KIND_*` constants.
727    pub kind: i32,
728    /// The port.
729    pub port: u32,
730    /// The address. IPv4 addresses use the last four octets.
731    pub address: [u8; 16],
732}
733
734impl Locator {
735    /// `LOCATOR_KIND_INVALID`.
736    pub const KIND_INVALID: i32 = -1;
737    /// `LOCATOR_KIND_RESERVED`.
738    pub const KIND_RESERVED: i32 = 0;
739    /// `LOCATOR_KIND_UDPv4`.
740    pub const KIND_UDPV4: i32 = 1;
741    /// `LOCATOR_KIND_UDPv6`.
742    pub const KIND_UDPV6: i32 = 2;
743    /// The shared memory transport of rustorb-dds (a vendor kind, "RD"
744    /// and 1): the address holds the host and the segment, the port the
745    /// traffic (see the module `shm`).
746    pub const KIND_SHM: i32 = 0x5244_0001;
747    /// `LOCATOR_PORT_INVALID`.
748    pub const PORT_INVALID: u32 = 0;
749    /// `LOCATOR_ADDRESS_INVALID`.
750    pub const ADDRESS_INVALID: [u8; 16] = [0; 16];
751    /// `LOCATOR_INVALID`.
752    pub const INVALID: Locator = Locator {
753        kind: Locator::KIND_INVALID,
754        port: Locator::PORT_INVALID,
755        address: Locator::ADDRESS_INVALID,
756    };
757
758    /// The size of a locator on the wire.
759    pub(crate) const WIRE_SIZE: usize = 24;
760
761    /// A UDPv4 locator.
762    pub fn udpv4(addr: SocketAddrV4) -> Self {
763        let mut address = [0u8; 16];
764        address[12..].copy_from_slice(&addr.ip().octets());
765        Locator {
766            kind: Locator::KIND_UDPV4,
767            port: addr.port() as u32,
768            address,
769        }
770    }
771
772    /// A UDPv6 locator.
773    pub fn udpv6(addr: SocketAddrV6) -> Self {
774        Locator {
775            kind: Locator::KIND_UDPV6,
776            port: addr.port() as u32,
777            address: addr.ip().octets(),
778        }
779    }
780
781    /// The UDP socket address, if this is a UDPv4 or UDPv6 locator whose
782    /// port fits in 16 bits.
783    pub fn to_socket_addr(&self) -> Option<SocketAddr> {
784        let port = u16::try_from(self.port).ok()?;
785        match self.kind {
786            Locator::KIND_UDPV4 => {
787                let a = &self.address;
788                let ip = Ipv4Addr::new(a[12], a[13], a[14], a[15]);
789                Some(SocketAddr::V4(SocketAddrV4::new(ip, port)))
790            }
791            Locator::KIND_UDPV6 => Some(SocketAddr::V6(SocketAddrV6::new(
792                Ipv6Addr::from(self.address),
793                port,
794                0,
795                0,
796            ))),
797            _ => None,
798        }
799    }
800
801    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
802        Ok(Locator {
803            kind: r.i32()?,
804            port: r.u32()?,
805            address: r.array()?,
806        })
807    }
808
809    pub(crate) fn write(&self, w: &mut Writer<'_>) {
810        w.i32(self.kind);
811        w.u32(self.port);
812        w.bytes(&self.address);
813    }
814}
815
816/// The compact UDPv4 locator of INFO_REPLY_IP4
817/// (DDSI-RTPS 2.5, 9.4.3.1).
818///
819/// The specification gives both fields as `unsigned long` and does not say
820/// how `address` maps to dotted notation. [`LocatorUdpV4::ip`] reads it
821/// with `a` as the most significant octet; this needs to be checked
822/// against other implementations (rustorb-dds#8).
823#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
824pub struct LocatorUdpV4 {
825    /// The IPv4 address as a 32-bit number.
826    pub address: u32,
827    /// The port.
828    pub port: u32,
829}
830
831impl LocatorUdpV4 {
832    /// The address as an [`Ipv4Addr`], `a` being the most significant
833    /// octet of `address`.
834    pub fn ip(&self) -> Ipv4Addr {
835        Ipv4Addr::from(self.address)
836    }
837
838    pub(crate) fn read(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
839        Ok(LocatorUdpV4 {
840            address: r.u32()?,
841            port: r.u32()?,
842        })
843    }
844
845    pub(crate) fn write(&self, w: &mut Writer<'_>) {
846        w.u32(self.address);
847        w.u32(self.port);
848    }
849}
850
851/// A length of time in NTP format: `seconds + fraction / 2^32`
852/// (DDSI-RTPS 2.5, 9.3.2.1 and 9.3.2.3).
853#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
854pub struct Duration {
855    /// Whole seconds.
856    pub seconds: i32,
857    /// Fraction of a second in units of 2^-32 s.
858    pub fraction: u32,
859}
860
861impl Duration {
862    /// `DURATION_ZERO`.
863    pub const ZERO: Duration = Duration {
864        seconds: 0,
865        fraction: 0,
866    };
867    /// `DURATION_INFINITE`.
868    pub const INFINITE: Duration = Duration {
869        seconds: 0x7fff_ffff,
870        fraction: 0xffff_ffff,
871    };
872
873    /// Whole seconds.
874    pub const fn from_secs(seconds: i32) -> Duration {
875        Duration {
876            seconds,
877            fraction: 0,
878        }
879    }
880
881    /// Converts to a [`std::time::Duration`]. Negative values give zero;
882    /// [`Duration::INFINITE`] gives `None`.
883    pub fn to_std(self) -> Option<std::time::Duration> {
884        if self == Duration::INFINITE {
885            return None;
886        }
887        if self.seconds < 0 {
888            return Some(std::time::Duration::ZERO);
889        }
890        let nanos = (u64::from(self.fraction) * 1_000_000_000) >> 32;
891        Some(std::time::Duration::new(self.seconds as u64, nanos as u32))
892    }
893
894    /// Converts from a [`std::time::Duration`], saturating at the largest
895    /// finite value.
896    pub fn from_std(d: std::time::Duration) -> Duration {
897        let Ok(seconds) = i32::try_from(d.as_secs()) else {
898            return Duration {
899                seconds: i32::MAX,
900                fraction: 0xffff_fffe,
901            };
902        };
903        Duration {
904            seconds,
905            fraction: ((u64::from(d.subsec_nanos()) << 32) / 1_000_000_000) as u32,
906        }
907    }
908}
909
910/// The built-in endpoints a participant has (DDSI-RTPS 2.5, 9.3.2.12).
911#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
912pub struct BuiltinEndpointSet(pub u32);
913
914impl BuiltinEndpointSet {
915    /// `DISC_BUILTIN_ENDPOINT_PARTICIPANT_ANNOUNCER`.
916    pub const PARTICIPANT_ANNOUNCER: u32 = 1 << 0;
917    /// `DISC_BUILTIN_ENDPOINT_PARTICIPANT_DETECTOR`.
918    pub const PARTICIPANT_DETECTOR: u32 = 1 << 1;
919    /// `DISC_BUILTIN_ENDPOINT_PUBLICATIONS_ANNOUNCER`.
920    pub const PUBLICATIONS_ANNOUNCER: u32 = 1 << 2;
921    /// `DISC_BUILTIN_ENDPOINT_PUBLICATIONS_DETECTOR`.
922    pub const PUBLICATIONS_DETECTOR: u32 = 1 << 3;
923    /// `DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_ANNOUNCER`.
924    pub const SUBSCRIPTIONS_ANNOUNCER: u32 = 1 << 4;
925    /// `DISC_BUILTIN_ENDPOINT_SUBSCRIPTIONS_DETECTOR`.
926    pub const SUBSCRIPTIONS_DETECTOR: u32 = 1 << 5;
927    /// `BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_WRITER`.
928    pub const PARTICIPANT_MESSAGE_DATA_WRITER: u32 = 1 << 10;
929    /// `BUILTIN_ENDPOINT_PARTICIPANT_MESSAGE_DATA_READER`.
930    pub const PARTICIPANT_MESSAGE_DATA_READER: u32 = 1 << 11;
931    /// TypeLookupServiceRequestDataWriter (DDS-XTypes 1.3 Table 62).
932    pub const TYPE_LOOKUP_REQUEST_WRITER: u32 = 1 << 12;
933    /// TypeLookupServiceRequestDataReader.
934    pub const TYPE_LOOKUP_REQUEST_READER: u32 = 1 << 13;
935    /// TypeLookupServiceReplyDataWriter.
936    pub const TYPE_LOOKUP_REPLY_WRITER: u32 = 1 << 14;
937    /// TypeLookupServiceReplyDataReader.
938    pub const TYPE_LOOKUP_REPLY_READER: u32 = 1 << 15;
939    /// `DISC_BUILTIN_ENDPOINT_TOPICS_ANNOUNCER`.
940    /// SEDPbuiltinPublicationsSecureWriter (DDS Security 1.2, Table 11).
941    pub const PUBLICATIONS_SECURE_WRITER: u32 = 1 << 16;
942    /// SEDPbuiltinPublicationsSecureReader.
943    pub const PUBLICATIONS_SECURE_READER: u32 = 1 << 17;
944    /// SEDPbuiltinSubscriptionsSecureWriter.
945    pub const SUBSCRIPTIONS_SECURE_WRITER: u32 = 1 << 18;
946    /// SEDPbuiltinSubscriptionsSecureReader.
947    pub const SUBSCRIPTIONS_SECURE_READER: u32 = 1 << 19;
948    /// BuiltinParticipantMessageSecureWriter.
949    pub const PARTICIPANT_MESSAGE_SECURE_WRITER: u32 = 1 << 20;
950    /// BuiltinParticipantMessageSecureReader.
951    pub const PARTICIPANT_MESSAGE_SECURE_READER: u32 = 1 << 21;
952    /// BuiltinParticipantStatelessMessageWriter.
953    pub const PARTICIPANT_STATELESS_MESSAGE_WRITER: u32 = 1 << 22;
954    /// BuiltinParticipantStatelessMessageReader.
955    pub const PARTICIPANT_STATELESS_MESSAGE_READER: u32 = 1 << 23;
956    /// BuiltinParticipantVolatileMessageSecureWriter.
957    pub const PARTICIPANT_VOLATILE_MESSAGE_SECURE_WRITER: u32 = 1 << 24;
958    /// BuiltinParticipantVolatileMessageSecureReader.
959    pub const PARTICIPANT_VOLATILE_MESSAGE_SECURE_READER: u32 = 1 << 25;
960    /// SPDPbuiltinParticipantsSecureWriter.
961    pub const PARTICIPANT_SECURE_WRITER: u32 = 1 << 26;
962    /// SPDPbuiltinParticipantsSecureReader.
963    pub const PARTICIPANT_SECURE_READER: u32 = 1 << 27;
964    /// TOPICS_ANNOUNCER.
965    pub const TOPICS_ANNOUNCER: u32 = 1 << 28;
966    /// `DISC_BUILTIN_ENDPOINT_TOPICS_DETECTOR`.
967    pub const TOPICS_DETECTOR: u32 = 1 << 29;
968
969    /// Whether all the given bits are set.
970    pub const fn contains(self, bits: u32) -> bool {
971        self.0 & bits == bits
972    }
973}
974
975#[cfg(test)]
976mod sample_identity_tests {
977    use super::*;
978
979    #[test]
980    fn sample_identity_round_trip() {
981        let id = SampleIdentity {
982            writer_guid: Guid::new(GuidPrefix([1; 12]), EntityId::PARTICIPANT),
983            sequence_number: SequenceNumber((2 << 32) | 3),
984        };
985        let le = id.to_bytes(Endianness::Little);
986        assert_eq!(&le[16..], &[2, 0, 0, 0, 3, 0, 0, 0]);
987        assert_eq!(
988            SampleIdentity::from_bytes(&le, Endianness::Little).unwrap(),
989            id
990        );
991        let be = id.to_bytes(Endianness::Big);
992        assert_eq!(&be[16..], &[0, 0, 0, 2, 0, 0, 0, 3]);
993        assert_eq!(
994            SampleIdentity::from_bytes(&be, Endianness::Big).unwrap(),
995            id
996        );
997        assert!(SampleIdentity::from_bytes(&be[..20], Endianness::Big).is_err());
998    }
999}