1use crate::error::DecodeError;
12use crate::parameter::Parameter;
13use crate::pl::{PlBuilder, PlValues, pid};
14use crate::types::Duration;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
20pub enum ReliabilityKind {
21 BestEffort,
23 Reliable,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29pub struct Reliability {
30 pub kind: ReliabilityKind,
32 pub max_blocking_time: Duration,
34}
35
36impl Reliability {
37 pub fn default_max_blocking_time() -> Duration {
39 Duration::from_std(std::time::Duration::from_millis(100))
40 }
41
42 pub fn writer_default() -> Self {
44 Reliability {
45 kind: ReliabilityKind::Reliable,
46 max_blocking_time: Self::default_max_blocking_time(),
47 }
48 }
49
50 pub fn reader_default() -> Self {
53 Reliability {
54 kind: ReliabilityKind::BestEffort,
55 max_blocking_time: Self::default_max_blocking_time(),
56 }
57 }
58
59 pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
64 let bad = DecodeError::InvalidParameterValue(p.id);
65 let kind = match v.u32(p)? {
66 1 => ReliabilityKind::BestEffort,
67 2 => ReliabilityKind::Reliable,
68 _ => return Err(bad),
69 };
70 let max_blocking_time = if p.value.len() >= 12 {
71 let rest = Parameter::new(p.id, p.value[4..12].to_vec());
72 v.duration(&rest)?
73 } else {
74 Self::default_max_blocking_time()
75 };
76 Ok(Reliability {
77 kind,
78 max_blocking_time,
79 })
80 }
81
82 pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
84 let kind: u32 = match self.kind {
85 ReliabilityKind::BestEffort => 1,
86 ReliabilityKind::Reliable => 2,
87 };
88 let mut value = b.u32(pid::RELIABILITY, kind).value;
89 value.extend(b.duration(pid::RELIABILITY, self.max_blocking_time).value);
90 Parameter::new(pid::RELIABILITY, value)
91 }
92}
93
94#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
98pub enum DurabilityKind {
99 #[default]
101 Volatile,
102 TransientLocal,
104 Transient,
106 Persistent,
108}
109
110impl DurabilityKind {
111 pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
114 Ok(match v.u32(p)? {
115 0 => DurabilityKind::Volatile,
116 1 => DurabilityKind::TransientLocal,
117 2 => DurabilityKind::Transient,
118 3 => DurabilityKind::Persistent,
119 _ => return Err(DecodeError::InvalidParameterValue(p.id)),
120 })
121 }
122
123 pub fn to_parameter(self, b: &PlBuilder) -> Parameter {
125 b.u32(pid::DURABILITY, self as u32)
126 }
127}
128
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
134pub struct DurabilityService {
135 pub service_cleanup_delay: Duration,
137 pub history_kind: u32,
139 pub history_depth: i32,
141 pub max_samples: i32,
143 pub max_instances: i32,
145 pub max_samples_per_instance: i32,
147}
148
149impl Default for DurabilityService {
150 fn default() -> Self {
152 DurabilityService {
153 service_cleanup_delay: Duration::ZERO,
154 history_kind: 0,
155 history_depth: 1,
156 max_samples: -1,
157 max_instances: -1,
158 max_samples_per_instance: -1,
159 }
160 }
161}
162
163impl DurabilityService {
164 pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
169 if p.value.len() < 28 {
170 return Err(DecodeError::InvalidParameterValue(p.id));
171 }
172 let at = |i: usize| v.u32(&Parameter::new(p.id, p.value[i..i + 4].to_vec()));
173 Ok(DurabilityService {
174 service_cleanup_delay: v.duration(&Parameter::new(p.id, p.value[..8].to_vec()))?,
175 history_kind: at(8)?,
176 history_depth: at(12)? as i32,
177 max_samples: at(16)? as i32,
178 max_instances: at(20)? as i32,
179 max_samples_per_instance: at(24)? as i32,
180 })
181 }
182
183 pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
185 let id = pid::DURABILITY_SERVICE;
186 let mut value = b.duration(id, self.service_cleanup_delay).value;
187 for n in [
188 self.history_kind,
189 self.history_depth as u32,
190 self.max_samples as u32,
191 self.max_instances as u32,
192 self.max_samples_per_instance as u32,
193 ] {
194 value.extend(b.u32(id, n).value);
195 }
196 Parameter::new(id, value)
197 }
198}
199
200#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
204pub enum LivelinessKind {
205 #[default]
208 Automatic,
209 ManualByParticipant,
212 ManualByTopic,
215}
216
217#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
219pub struct Liveliness {
220 pub kind: LivelinessKind,
222 pub lease_duration: Duration,
224}
225
226impl Default for Liveliness {
227 fn default() -> Self {
229 Liveliness {
230 kind: LivelinessKind::Automatic,
231 lease_duration: Duration::INFINITE,
232 }
233 }
234}
235
236impl Liveliness {
237 pub fn from_parameter(v: &PlValues, p: &Parameter) -> Result<Self, DecodeError> {
240 let kind = match v.u32(p)? {
241 0 => LivelinessKind::Automatic,
242 1 => LivelinessKind::ManualByParticipant,
243 2 => LivelinessKind::ManualByTopic,
244 _ => return Err(DecodeError::InvalidParameterValue(p.id)),
245 };
246 let lease_duration = if p.value.len() >= 12 {
247 v.duration(&Parameter::new(p.id, p.value[4..12].to_vec()))?
248 } else {
249 Duration::INFINITE
250 };
251 Ok(Liveliness {
252 kind,
253 lease_duration,
254 })
255 }
256
257 pub fn to_parameter(&self, b: &PlBuilder) -> Parameter {
259 let mut value = b.u32(pid::LIVELINESS, self.kind as u32).value;
260 value.extend(b.duration(pid::LIVELINESS, self.lease_duration).value);
261 Parameter::new(pid::LIVELINESS, value)
262 }
263}
264
265#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
268pub struct QosPolicyId(pub u32);
269
270impl QosPolicyId {
271 pub const DURABILITY: QosPolicyId = QosPolicyId(2);
273 pub const DEADLINE: QosPolicyId = QosPolicyId(4);
275 pub const LIVELINESS: QosPolicyId = QosPolicyId(8);
277 pub const RELIABILITY: QosPolicyId = QosPolicyId(11);
279}
280
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
283pub struct RxO {
284 pub reliability: ReliabilityKind,
286 pub durability: DurabilityKind,
288 pub deadline: Duration,
290 pub liveliness: Liveliness,
292}
293
294pub fn incompatible_policies(offered: &RxO, requested: &RxO) -> Vec<QosPolicyId> {
300 let mut out = Vec::new();
301 if offered.durability < requested.durability {
302 out.push(QosPolicyId::DURABILITY);
303 }
304 if offered.deadline > requested.deadline {
305 out.push(QosPolicyId::DEADLINE);
306 }
307 if offered.liveliness.kind < requested.liveliness.kind
308 || offered.liveliness.lease_duration > requested.liveliness.lease_duration
309 {
310 out.push(QosPolicyId::LIVELINESS);
311 }
312 if offered.reliability < requested.reliability {
313 out.push(QosPolicyId::RELIABILITY);
314 }
315 out
316}
317
318pub fn partitions_match(a: &[String], b: &[String]) -> bool {
325 let default = [String::new()];
326 let a = if a.is_empty() { &default[..] } else { a };
327 let b = if b.is_empty() { &default[..] } else { b };
328 a.iter()
329 .any(|x| b.iter().any(|y| partition_names_match(x, y)))
330}
331
332fn partition_names_match(a: &str, b: &str) -> bool {
333 match (has_wildcard(a), has_wildcard(b)) {
334 (false, false) => a == b,
335 (true, false) => fnmatch(a.as_bytes(), b.as_bytes()),
336 (false, true) => fnmatch(b.as_bytes(), a.as_bytes()),
337 (true, true) => false,
338 }
339}
340
341fn has_wildcard(s: &str) -> bool {
342 s.bytes().any(|c| matches!(c, b'*' | b'?' | b'['))
343}
344
345fn fnmatch(pattern: &[u8], name: &[u8]) -> bool {
349 match pattern.first() {
350 None => name.is_empty(),
351 Some(b'*') => {
352 (0..=name.len()).any(|i| fnmatch(&pattern[1..], &name[i..]))
354 }
355 Some(b'?') => !name.is_empty() && fnmatch(&pattern[1..], &name[1..]),
356 Some(b'[') => {
357 let Some((&c, rest)) = name.split_first() else {
358 return false;
359 };
360 match bracket(&pattern[1..], c) {
361 Some((matched, after)) => matched && fnmatch(after, rest),
362 None => c == b'[' && fnmatch(&pattern[1..], rest),
364 }
365 }
366 Some(b'\\') if pattern.len() > 1 => {
367 name.first() == Some(&pattern[1]) && fnmatch(&pattern[2..], &name[1..])
368 }
369 Some(&p) => name.first() == Some(&p) && fnmatch(&pattern[1..], &name[1..]),
370 }
371}
372
373fn bracket(p: &[u8], c: u8) -> Option<(bool, &[u8])> {
377 let (negate, mut i) = match p.first() {
378 Some(b'!') => (true, 1),
379 _ => (false, 0),
380 };
381 let mut matched = false;
382 let mut first = true;
383 loop {
384 let lo = *p.get(i)?;
385 if lo == b']' && !first {
386 return Some((matched != negate, &p[i + 1..]));
387 }
388 first = false;
389 if p.get(i + 1) == Some(&b'-') && p.get(i + 2).is_some_and(|h| *h != b']') {
390 let hi = p[i + 2];
391 matched |= lo <= c && c <= hi;
392 i += 3;
393 } else {
394 matched |= lo == c;
395 i += 1;
396 }
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403 use crate::wire::Endianness;
404
405 #[test]
406 fn reliability_wire() {
407 for e in [Endianness::Big, Endianness::Little] {
408 let b = PlBuilder::new(e);
409 let v = PlValues::new(e);
410 for r in [Reliability::writer_default(), Reliability::reader_default()] {
411 let p = r.to_parameter(&b);
412 assert_eq!(p.id, pid::RELIABILITY);
413 assert_eq!(p.value.len(), 12);
414 assert_eq!(Reliability::from_parameter(&v, &p).unwrap(), r);
415 }
416 }
417 let v = PlValues::new(Endianness::Little);
418 let p = Parameter::new(pid::RELIABILITY, [2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]);
420 let r = Reliability::from_parameter(&v, &p).unwrap();
421 assert_eq!(r.kind, ReliabilityKind::Reliable);
422 assert_eq!(r.max_blocking_time, Duration::from_secs(1));
423 let p = Parameter::new(pid::RELIABILITY, [1, 0, 0, 0]);
425 assert_eq!(
426 Reliability::from_parameter(&v, &p).unwrap(),
427 Reliability::reader_default()
428 );
429 let p = Parameter::new(pid::RELIABILITY, [0, 0, 0, 0]);
430 assert!(Reliability::from_parameter(&v, &p).is_err());
431 }
432
433 #[test]
434 fn durability_wire() {
435 let b = PlBuilder::new(Endianness::Big);
436 let v = PlValues::new(Endianness::Big);
437 for k in [
438 DurabilityKind::Volatile,
439 DurabilityKind::TransientLocal,
440 DurabilityKind::Transient,
441 DurabilityKind::Persistent,
442 ] {
443 assert_eq!(
444 DurabilityKind::from_parameter(&v, &k.to_parameter(&b)).unwrap(),
445 k
446 );
447 }
448 assert_eq!(
449 DurabilityKind::TransientLocal.to_parameter(&b).value,
450 [0, 0, 0, 1]
451 );
452 let p = Parameter::new(pid::DURABILITY, [0, 0, 0, 4]);
453 assert!(DurabilityKind::from_parameter(&v, &p).is_err());
454 }
455
456 #[test]
457 fn liveliness_wire() {
458 for e in [Endianness::Big, Endianness::Little] {
459 let b = PlBuilder::new(e);
460 let v = PlValues::new(e);
461 for l in [
462 Liveliness::default(),
463 Liveliness {
464 kind: LivelinessKind::ManualByTopic,
465 lease_duration: Duration::from_secs(3),
466 },
467 ] {
468 let p = l.to_parameter(&b);
469 assert_eq!(p.value.len(), 12);
470 assert_eq!(Liveliness::from_parameter(&v, &p).unwrap(), l);
471 }
472 }
473 let v = PlValues::new(Endianness::Little);
474 let p = Parameter::new(pid::LIVELINESS, [1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
475 assert_eq!(
476 Liveliness::from_parameter(&v, &p).unwrap(),
477 Liveliness {
478 kind: LivelinessKind::ManualByParticipant,
479 lease_duration: Duration::from_secs(2),
480 }
481 );
482 let p = Parameter::new(pid::LIVELINESS, [3, 0, 0, 0]);
483 assert!(Liveliness::from_parameter(&v, &p).is_err());
484 }
485
486 #[test]
487 fn matching_rules() {
488 use DurabilityKind::*;
489 use ReliabilityKind::*;
490 let rxo = |reliability, durability| RxO {
491 reliability,
492 durability,
493 deadline: Duration::INFINITE,
494 liveliness: Liveliness::default(),
495 };
496 let none: Vec<QosPolicyId> = Vec::new();
497 assert_eq!(
498 incompatible_policies(&rxo(Reliable, Volatile), &rxo(BestEffort, Volatile)),
499 none
500 );
501 assert_eq!(
502 incompatible_policies(&rxo(Reliable, TransientLocal), &rxo(Reliable, Volatile)),
503 none
504 );
505 assert_eq!(
506 incompatible_policies(&rxo(BestEffort, Volatile), &rxo(Reliable, TransientLocal)),
507 [QosPolicyId::DURABILITY, QosPolicyId::RELIABILITY]
508 );
509 let mut w = rxo(Reliable, Volatile);
511 let mut r = rxo(Reliable, Volatile);
512 r.deadline = Duration::from_secs(1);
513 assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::DEADLINE]);
514 w.deadline = Duration::from_secs(1);
515 assert_eq!(incompatible_policies(&w, &r), none);
516 r.liveliness = Liveliness {
518 kind: LivelinessKind::ManualByParticipant,
519 lease_duration: Duration::from_secs(5),
520 };
521 assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::LIVELINESS]);
522 w.liveliness = Liveliness {
523 kind: LivelinessKind::ManualByTopic,
524 lease_duration: Duration::from_secs(10),
525 };
526 assert_eq!(incompatible_policies(&w, &r), [QosPolicyId::LIVELINESS]);
527 w.liveliness.lease_duration = Duration::from_secs(5);
528 assert_eq!(incompatible_policies(&w, &r), none);
529 }
530
531 #[test]
532 fn partitions() {
533 let s = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
534 assert!(partitions_match(&[], &[]));
535 assert!(partitions_match(&[], &s(&[""])));
536 assert!(!partitions_match(&[], &s(&["a"])));
537 assert!(partitions_match(&s(&["a", "b"]), &s(&["b"])));
538 assert!(partitions_match(&s(&["sensors/*"]), &s(&["sensors/front"])));
540 assert!(partitions_match(&s(&["sensors/front"]), &s(&["sensors/*"])));
541 assert!(!partitions_match(&s(&["sensors/*"]), &s(&["sensors/*"])));
542 assert!(!partitions_match(&s(&["sensors/*"]), &s(&["robot/1"])));
543 assert!(partitions_match(&s(&["*"]), &[]));
544 }
545
546 #[test]
547 fn fnmatch_rules() {
548 let m = |p: &str, n: &str| fnmatch(p.as_bytes(), n.as_bytes());
549 assert!(m("*", ""));
550 assert!(m("a*c", "abbbc"));
551 assert!(!m("a*c", "abbbd"));
552 assert!(m("a?c", "abc"));
553 assert!(!m("a?c", "ac"));
554 assert!(m("[abc]x", "bx"));
555 assert!(!m("[abc]x", "dx"));
556 assert!(m("[a-c]x", "bx"));
557 assert!(m("[!a-c]x", "dx"));
558 assert!(!m("[!a-c]x", "bx"));
559 assert!(m("[]]", "]"));
560 assert!(m("[a-]", "-"));
561 assert!(m("\\*", "*"));
562 assert!(!m("\\*", "a"));
563 assert!(m("[ab", "[ab"));
565 }
566}