hiroz 0.2.0

Native Rust ROS 2 implementation using Zenoh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
use std::fmt;
use std::num::NonZeroUsize;

#[non_exhaustive]
#[derive(Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
pub enum QosReliability {
    #[default]
    Reliable,
    BestEffort,
}

impl fmt::Display for QosReliability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Reliable => write!(f, "Reliable"),
            Self::BestEffort => write!(f, "Best Effort"),
        }
    }
}

/// Default depth for `KeepLast` when SYSTEM_DEFAULT (depth=0) is used.
/// Matches rclcpp's default of 10. Note this is distinct from
/// [`KEEP_ALL_CACHE_DEPTH`] below, which is the rmw_zenoh-aligned cap
/// applied to `KeepAll` when mapped to zenoh-ext's `cache.max_samples`.
pub const DEFAULT_HISTORY_DEPTH: usize = 10;

/// Cache/history depth used when a TransientLocal endpoint carries
/// `QosHistory::KeepAll` (no inherent depth) or `KeepLast(0)`.
///
/// Matches rmw_zenoh_cpp's `RMW_ZENOH_DEFAULT_HISTORY_DEPTH = 42`
/// (`rmw_zenoh_cpp/src/detail/qos.cpp:27`), which is the value
/// rmw_zenoh's `best_available_qos` substitutes for a zero-valued
/// `qos.depth` before passing it to
/// `AdvancedPublisherOptions::CacheOptions::max_samples`.
///
/// This is intentionally a *finite* cap that mirrors rmw_zenoh's
/// pragmatic behaviour rather than the DDS KEEP_ALL spec's "keep
/// everything" semantics.
pub const KEEP_ALL_CACHE_DEPTH: usize = 42;

#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub enum QosHistory {
    KeepLast(NonZeroUsize),
    KeepAll,
}

impl Default for QosHistory {
    fn default() -> Self {
        Self::KeepLast(NonZeroUsize::new(DEFAULT_HISTORY_DEPTH).unwrap())
    }
}

impl QosHistory {
    /// Normalize depth by replacing 0 with the default depth
    /// Used when converting from RMW QoS (which allows depth=0 for SYSTEM_DEFAULT)
    pub fn from_depth(depth: usize) -> Self {
        let normalized_depth = if depth == 0 {
            DEFAULT_HISTORY_DEPTH
        } else {
            depth
        };
        Self::KeepLast(
            NonZeroUsize::new(normalized_depth)
                .unwrap_or_else(|| NonZeroUsize::new(DEFAULT_HISTORY_DEPTH).unwrap()),
        )
    }
}

impl fmt::Display for QosHistory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::KeepLast(depth) => write!(f, "Keep Last ({})", depth),
            Self::KeepAll => write!(f, "Keep All"),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
pub enum QosDurability {
    TransientLocal,
    #[default]
    Volatile,
}

impl fmt::Display for QosDurability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TransientLocal => write!(f, "Transient Local"),
            Self::Volatile => write!(f, "Volatile"),
        }
    }
}

#[non_exhaustive]
#[derive(Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
pub enum QosLiveliness {
    #[default]
    Automatic,
    ManualByNode,
    ManualByTopic,
}

impl fmt::Display for QosLiveliness {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Automatic => write!(f, "Automatic"),
            Self::ManualByNode => write!(f, "Manual by Node"),
            Self::ManualByTopic => write!(f, "Manual by Topic"),
        }
    }
}

/// Represents a QoS duration in seconds and nanoseconds.
///
/// This is distinct from [`std::time::Duration`] and is used exclusively for
/// configuring QoS deadline, lifespan, and liveliness lease duration.
/// Use [`QosDuration::INFINITE`] (the default) to disable a QoS time constraint.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
pub struct QosDuration {
    pub sec: u64,
    pub nsec: u64,
}

impl QosDuration {
    pub const INFINITE: QosDuration = QosDuration {
        sec: 9223372036,
        nsec: 854775807,
    };
}

impl Default for QosDuration {
    fn default() -> Self {
        Self::INFINITE
    }
}

impl From<std::time::Duration> for QosDuration {
    fn from(d: std::time::Duration) -> Self {
        Self {
            sec: d.as_secs(),
            nsec: d.subsec_nanos() as u64,
        }
    }
}

impl fmt::Display for QosDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if *self == Self::INFINITE {
            write!(f, "Infinite")
        } else if self.nsec == 0 {
            write!(f, "{}s", self.sec)
        } else {
            write!(f, "{}s {}ns", self.sec, self.nsec)
        }
    }
}

#[derive(Debug, Default, Hash, PartialEq, Eq, Clone, Copy)]
pub struct QosProfile {
    pub reliability: QosReliability,
    pub durability: QosDurability,
    pub history: QosHistory,
    pub deadline: QosDuration,
    pub lifespan: QosDuration,
    pub liveliness: QosLiveliness,
    pub liveliness_lease_duration: QosDuration,
}

impl QosProfile {
    /// Convert to hiroz-protocol's QosProfile for key expression generation
    pub fn to_protocol_qos(&self) -> hiroz_protocol::qos::QosProfile {
        hiroz_protocol::qos::QosProfile {
            reliability: match self.reliability {
                QosReliability::Reliable => hiroz_protocol::qos::QosReliability::Reliable,
                QosReliability::BestEffort => hiroz_protocol::qos::QosReliability::BestEffort,
            },
            durability: match self.durability {
                QosDurability::TransientLocal => hiroz_protocol::qos::QosDurability::TransientLocal,
                QosDurability::Volatile => hiroz_protocol::qos::QosDurability::Volatile,
            },
            history: match self.history {
                QosHistory::KeepLast(depth) => {
                    hiroz_protocol::qos::QosHistory::KeepLast(depth.get())
                }
                QosHistory::KeepAll => hiroz_protocol::qos::QosHistory::KeepAll,
            },
        }
    }
}

impl fmt::Display for QosProfile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "QoS({}, {}, {}",
            self.reliability, self.durability, self.history
        )?;
        if self.deadline != QosDuration::INFINITE {
            write!(f, ", deadline={}", self.deadline)?;
        }
        if self.lifespan != QosDuration::INFINITE {
            write!(f, ", lifespan={}", self.lifespan)?;
        }
        if self.liveliness != QosLiveliness::Automatic {
            write!(f, ", liveliness={}", self.liveliness)?;
        }
        if self.liveliness_lease_duration != QosDuration::INFINITE {
            write!(f, ", lease={}", self.liveliness_lease_duration)?;
        }
        write!(f, ")")
    }
}

const QOS_DELIMITER: &str = ":";

#[derive(Debug)]
pub enum QosDecodeError {
    IncompleteQos,
    InvalidReliability,
    InvalidDurability,
    InvalidHistory,
    InvalidHistoryDepth,
}

impl std::fmt::Display for QosDecodeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::IncompleteQos => write!(f, "Incomplete QoS string"),
            Self::InvalidReliability => write!(f, "Invalid reliability value in QoS"),
            Self::InvalidDurability => write!(f, "Invalid durability value in QoS"),
            Self::InvalidHistory => write!(f, "Invalid history value in QoS"),
            Self::InvalidHistoryDepth => write!(f, "Invalid history depth value in QoS"),
        }
    }
}

impl std::error::Error for QosDecodeError {}

impl QosProfile {
    // This format comes from rmw_zenoh
    // <ReliabilityKind>:<DurabilityKind>:<HistoryKind>,<HistoryDepth>:<DeadlineSec, DeadlineNSec>:<LifespanSec, LifespanNSec>:<Liveliness, LivelinessSec, LivelinessNSec>"
    pub fn encode(&self) -> String {
        let default_qos = Self::default();

        // Reliability - empty if default
        let reliability = if self.reliability != default_qos.reliability {
            match self.reliability {
                QosReliability::Reliable => "1",
                QosReliability::BestEffort => "2",
            }
        } else {
            ""
        };

        // Durability - empty if default
        let durability = if self.durability != default_qos.durability {
            match self.durability {
                QosDurability::TransientLocal => "1",
                QosDurability::Volatile => "2",
            }
        } else {
            ""
        };

        // History format: <history_kind>,<depth>
        // Only include kind if it's non-default
        // Always include depth (even if default)
        let history = match self.history {
            QosHistory::KeepLast(depth) => {
                if self.history != default_qos.history {
                    // Non-default history kind - include both kind and depth
                    format!("1,{}", depth.get())
                } else {
                    // Default history kind - only include depth
                    format!(",{}", depth.get())
                }
            }
            QosHistory::KeepAll => "2,".to_string(),
        };

        // Deadline - empty if default (infinite)
        let deadline = if self.deadline != default_qos.deadline {
            format!("{},{}", self.deadline.sec, self.deadline.nsec)
        } else {
            ",".to_string()
        };

        // Lifespan - empty if default (infinite)
        let lifespan = if self.lifespan != default_qos.lifespan {
            format!("{},{}", self.lifespan.sec, self.lifespan.nsec)
        } else {
            ",".to_string()
        };

        // Liveliness - format: <liveliness_kind>,<lease_sec>,<lease_nsec>
        let liveliness = if self.liveliness != default_qos.liveliness
            || self.liveliness_lease_duration != default_qos.liveliness_lease_duration
        {
            let kind = match self.liveliness {
                QosLiveliness::Automatic => "1",
                QosLiveliness::ManualByNode => "2",
                QosLiveliness::ManualByTopic => "3",
            };
            format!(
                "{},{},{}",
                kind, self.liveliness_lease_duration.sec, self.liveliness_lease_duration.nsec
            )
        } else {
            ",,".to_string()
        };

        format!(
            "{}:{}:{}:{}:{}:{}",
            reliability, durability, history, deadline, lifespan, liveliness
        )
    }

    pub fn decode(encoded: impl AsRef<str>) -> Result<Self, QosDecodeError> {
        let mut fields = encoded.as_ref().split(QOS_DELIMITER);
        let reliability = match fields.next() {
            Some(x) => match x {
                "0" | "" => QosReliability::default(),
                "1" => QosReliability::Reliable,
                "2" => QosReliability::BestEffort,
                _ => return Err(QosDecodeError::InvalidReliability),
            },
            None => return Err(QosDecodeError::IncompleteQos),
        };
        let durability = match fields.next() {
            Some(x) => match x {
                "0" | "" => QosDurability::default(),
                "1" => QosDurability::TransientLocal,
                "2" => QosDurability::Volatile,
                _ => return Err(QosDecodeError::InvalidDurability),
            },
            None => return Err(QosDecodeError::IncompleteQos),
        };
        let history = match fields.next() {
            Some(x) => match x {
                "," | "" => QosHistory::default(),
                x => {
                    let mut iter = x.split(",");
                    let Some(kind) = iter.next() else {
                        return Err(QosDecodeError::IncompleteQos);
                    };
                    let Some(depth) = iter.next() else {
                        return Err(QosDecodeError::IncompleteQos);
                    };
                    match (kind, depth) {
                        ("", d) | ("0", d) | ("1", d) => {
                            let depth_usize: usize =
                                d.parse().map_err(|_| QosDecodeError::InvalidHistory)?;
                            let non_zero_depth = NonZeroUsize::new(depth_usize)
                                .ok_or(QosDecodeError::InvalidHistoryDepth)?;
                            QosHistory::KeepLast(non_zero_depth)
                        }
                        ("2", _) => QosHistory::KeepAll,
                        _ => return Err(QosDecodeError::InvalidHistory),
                    }
                }
            },
            None => return Err(QosDecodeError::IncompleteQos),
        };

        // Deadline - format: <sec>,<nsec>
        let deadline = match fields.next() {
            Some(x) if x.is_empty() || x == "," => QosDuration::default(),
            Some(x) => {
                let mut iter = x.split(",");
                let sec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.sec);
                let nsec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.nsec);
                QosDuration { sec, nsec }
            }
            None => QosDuration::default(),
        };

        // Lifespan - format: <sec>,<nsec>
        let lifespan = match fields.next() {
            Some(x) if x.is_empty() || x == "," => QosDuration::default(),
            Some(x) => {
                let mut iter = x.split(",");
                let sec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.sec);
                let nsec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.nsec);
                QosDuration { sec, nsec }
            }
            None => QosDuration::default(),
        };

        // Liveliness - format: <kind>,<lease_sec>,<lease_nsec>
        let (liveliness, liveliness_lease_duration) = match fields.next() {
            Some(x) if x.is_empty() || x == ",," => {
                (QosLiveliness::default(), QosDuration::default())
            }
            Some(x) => {
                let mut iter = x.split(",");
                let kind = match iter.next().unwrap_or("") {
                    "" | "0" | "1" => QosLiveliness::Automatic,
                    "2" => QosLiveliness::ManualByNode,
                    "3" => QosLiveliness::ManualByTopic,
                    _ => QosLiveliness::default(),
                };
                let sec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.sec);
                let nsec = iter
                    .next()
                    .unwrap_or("")
                    .parse()
                    .unwrap_or(QosDuration::INFINITE.nsec);
                (kind, QosDuration { sec, nsec })
            }
            None => (QosLiveliness::default(), QosDuration::default()),
        };

        Ok(Self {
            reliability,
            durability,
            history,
            deadline,
            lifespan,
            liveliness,
            liveliness_lease_duration,
        })
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;

    use super::*;

    // -----------------------------------------------------------------------
    // Reliability mapping: QosReliability → protocol::QosReliability
    // -----------------------------------------------------------------------

    #[test]
    fn test_reliable_maps_to_protocol_reliable() {
        let qos = QosProfile {
            reliability: QosReliability::Reliable,
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(
            proto.reliability,
            hiroz_protocol::qos::QosReliability::Reliable
        );
    }

    #[test]
    fn test_best_effort_maps_to_protocol_best_effort() {
        let qos = QosProfile {
            reliability: QosReliability::BestEffort,
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(
            proto.reliability,
            hiroz_protocol::qos::QosReliability::BestEffort
        );
    }

    // -----------------------------------------------------------------------
    // Durability mapping
    // -----------------------------------------------------------------------

    #[test]
    fn test_volatile_maps_to_protocol_volatile() {
        let qos = QosProfile {
            durability: QosDurability::Volatile,
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(
            proto.durability,
            hiroz_protocol::qos::QosDurability::Volatile
        );
    }

    #[test]
    fn test_transient_local_maps_to_protocol_transient_local() {
        let qos = QosProfile {
            durability: QosDurability::TransientLocal,
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(
            proto.durability,
            hiroz_protocol::qos::QosDurability::TransientLocal
        );
    }

    // -----------------------------------------------------------------------
    // History mapping: depth is preserved
    // -----------------------------------------------------------------------

    #[test]
    fn test_keep_last_depth_is_preserved() {
        let depth = NonZeroUsize::new(7).unwrap();
        let qos = QosProfile {
            history: QosHistory::KeepLast(depth),
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(proto.history, hiroz_protocol::qos::QosHistory::KeepLast(7));
    }

    #[test]
    fn test_keep_all_maps_to_protocol_keep_all() {
        let qos = QosProfile {
            history: QosHistory::KeepAll,
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(proto.history, hiroz_protocol::qos::QosHistory::KeepAll);
    }

    #[test]
    fn test_keep_last_depth_1_is_preserved() {
        let depth = NonZeroUsize::new(1).unwrap();
        let qos = QosProfile {
            history: QosHistory::KeepLast(depth),
            ..Default::default()
        };
        let proto = qos.to_protocol_qos();
        assert_eq!(proto.history, hiroz_protocol::qos::QosHistory::KeepLast(1));
    }

    // -----------------------------------------------------------------------
    // QoS encode/decode roundtrip (pure string logic, no Zenoh session)
    // -----------------------------------------------------------------------

    #[test]
    fn test_encode_decode_reliable_volatile_keep_last() {
        let qos = QosProfile {
            reliability: QosReliability::Reliable,
            durability: QosDurability::Volatile,
            history: QosHistory::KeepLast(NonZeroUsize::new(10).unwrap()),
            ..Default::default()
        };
        let encoded = qos.encode();
        let decoded = QosProfile::decode(&encoded).expect("decode");
        assert_eq!(decoded.reliability, qos.reliability);
        assert_eq!(decoded.durability, qos.durability);
        assert_eq!(decoded.history, qos.history);
    }

    #[test]
    fn test_encode_decode_best_effort_transient_keep_last() {
        let qos = QosProfile {
            reliability: QosReliability::BestEffort,
            durability: QosDurability::TransientLocal,
            history: QosHistory::KeepLast(NonZeroUsize::new(5).unwrap()),
            ..Default::default()
        };
        let encoded = qos.encode();
        let decoded = QosProfile::decode(&encoded).expect("decode");
        assert_eq!(decoded.reliability, qos.reliability);
        assert_eq!(decoded.durability, qos.durability);
        assert_eq!(decoded.history, qos.history);
    }

    // -----------------------------------------------------------------------
    // QosHistory::from_depth normalizes depth=0 to DEFAULT_HISTORY_DEPTH
    // -----------------------------------------------------------------------

    #[test]
    fn test_from_depth_zero_uses_default() {
        let h = QosHistory::from_depth(0);
        assert_eq!(
            h,
            QosHistory::KeepLast(NonZeroUsize::new(DEFAULT_HISTORY_DEPTH).unwrap())
        );
    }

    #[test]
    fn test_from_depth_nonzero_preserved() {
        let h = QosHistory::from_depth(3);
        assert_eq!(h, QosHistory::KeepLast(NonZeroUsize::new(3).unwrap()));
    }

    #[test]
    fn test_qos_duration_from_std_duration() {
        let d = std::time::Duration::new(3, 500_000_000);
        let qd = QosDuration::from(d);
        assert_eq!(qd.sec, 3);
        assert_eq!(qd.nsec, 500_000_000);
    }

    #[test]
    fn test_qos_duration_from_std_duration_zero() {
        let d = std::time::Duration::ZERO;
        let qd = QosDuration::from(d);
        assert_eq!(qd.sec, 0);
        assert_eq!(qd.nsec, 0);
    }
}