1use alloc::{
16 boxed::Box,
17 format,
18 string::{String, ToString},
19};
20use core::{
21 convert::{From, TryFrom, TryInto},
22 fmt::{self, Display},
23 hash::Hash,
24 ops::{Deref, RangeInclusive},
25 str::FromStr,
26};
27
28use serde::{Deserialize, Serialize};
29pub use uhlc::{Timestamp, NTP64};
30use zenoh_keyexpr::OwnedKeyExpr;
31use zenoh_result::{bail, zerror};
32
33pub type TimestampId = uhlc::ID;
35
36pub mod whatami;
38pub use whatami::*;
39pub use zenoh_keyexpr::key_expr;
40
41pub mod wire_expr;
42pub use wire_expr::*;
43
44mod cowstr;
45pub use cowstr::CowStr;
46pub mod encoding;
47pub use encoding::{Encoding, EncodingId};
48
49pub mod locator;
50pub use locator::*;
51
52pub mod endpoint;
53pub use endpoint::*;
54
55pub mod resolution;
56pub use resolution::*;
57
58pub mod parameters;
59pub use parameters::Parameters;
60
61#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
63#[repr(transparent)]
64pub struct ZenohIdProto(uhlc::ID);
65
66impl ZenohIdProto {
67 pub const MAX_SIZE: usize = 16;
68
69 #[inline]
70 pub fn size(&self) -> usize {
71 self.0.size()
72 }
73
74 #[inline]
75 pub fn to_le_bytes(&self) -> [u8; uhlc::ID::MAX_SIZE] {
76 self.0.to_le_bytes()
77 }
78
79 #[doc(hidden)]
80 pub fn rand() -> ZenohIdProto {
81 ZenohIdProto(uhlc::ID::rand())
82 }
83
84 pub fn into_keyexpr(self) -> OwnedKeyExpr {
85 self.into()
86 }
87}
88
89impl Default for ZenohIdProto {
90 fn default() -> Self {
91 Self::rand()
92 }
93}
94
95#[derive(Debug, Clone, Copy)]
97pub struct SizeError(usize);
98
99#[cfg(feature = "std")]
100impl std::error::Error for SizeError {}
101#[cfg(not(feature = "std"))]
102impl zenoh_result::IError for SizeError {}
103
104impl From<uhlc::SizeError> for SizeError {
105 fn from(val: uhlc::SizeError) -> Self {
106 Self(val.0)
107 }
108}
109
110impl fmt::Display for SizeError {
112 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113 write!(
114 f,
115 "Maximum ID size ({} bytes) exceeded: {}",
116 uhlc::ID::MAX_SIZE,
117 self.0
118 )
119 }
120}
121
122macro_rules! derive_tryfrom {
123 ($T: ty) => {
124 impl TryFrom<$T> for ZenohIdProto {
125 type Error = zenoh_result::Error;
126 fn try_from(val: $T) -> Result<Self, Self::Error> {
127 match val.try_into() {
128 Ok(ok) => Ok(Self(ok)),
129 Err(err) => Err(Box::<SizeError>::new(err.into())),
130 }
131 }
132 }
133 };
134}
135derive_tryfrom!([u8; 1]);
136derive_tryfrom!(&[u8; 1]);
137derive_tryfrom!([u8; 2]);
138derive_tryfrom!(&[u8; 2]);
139derive_tryfrom!([u8; 3]);
140derive_tryfrom!(&[u8; 3]);
141derive_tryfrom!([u8; 4]);
142derive_tryfrom!(&[u8; 4]);
143derive_tryfrom!([u8; 5]);
144derive_tryfrom!(&[u8; 5]);
145derive_tryfrom!([u8; 6]);
146derive_tryfrom!(&[u8; 6]);
147derive_tryfrom!([u8; 7]);
148derive_tryfrom!(&[u8; 7]);
149derive_tryfrom!([u8; 8]);
150derive_tryfrom!(&[u8; 8]);
151derive_tryfrom!([u8; 9]);
152derive_tryfrom!(&[u8; 9]);
153derive_tryfrom!([u8; 10]);
154derive_tryfrom!(&[u8; 10]);
155derive_tryfrom!([u8; 11]);
156derive_tryfrom!(&[u8; 11]);
157derive_tryfrom!([u8; 12]);
158derive_tryfrom!(&[u8; 12]);
159derive_tryfrom!([u8; 13]);
160derive_tryfrom!(&[u8; 13]);
161derive_tryfrom!([u8; 14]);
162derive_tryfrom!(&[u8; 14]);
163derive_tryfrom!([u8; 15]);
164derive_tryfrom!(&[u8; 15]);
165derive_tryfrom!([u8; 16]);
166derive_tryfrom!(&[u8; 16]);
167derive_tryfrom!(&[u8]);
168
169impl FromStr for ZenohIdProto {
170 type Err = zenoh_result::Error;
171
172 fn from_str(s: &str) -> Result<Self, Self::Err> {
173 if s.contains(|c: char| c.is_ascii_uppercase()) {
174 bail!(
175 "Invalid id: {} - uppercase hexadecimal is not accepted, use lowercase",
176 s
177 );
178 }
179 let u: uhlc::ID = s
180 .parse()
181 .map_err(|e: uhlc::ParseIDError| zerror!("Invalid id: {} - {}", s, e.cause))?;
182 Ok(ZenohIdProto(u))
183 }
184}
185
186impl fmt::Debug for ZenohIdProto {
187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188 write!(f, "{}", self.0)
189 }
190}
191
192impl fmt::Display for ZenohIdProto {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 fmt::Debug::fmt(self, f)
195 }
196}
197
198impl From<&ZenohIdProto> for uhlc::ID {
200 fn from(zid: &ZenohIdProto) -> Self {
201 zid.0
202 }
203}
204
205impl From<ZenohIdProto> for uhlc::ID {
206 fn from(zid: ZenohIdProto) -> Self {
207 zid.0
208 }
209}
210
211impl From<ZenohIdProto> for OwnedKeyExpr {
212 fn from(zid: ZenohIdProto) -> Self {
213 unsafe { OwnedKeyExpr::from_string_unchecked(zid.to_string()) }
218 }
219}
220
221impl From<&ZenohIdProto> for OwnedKeyExpr {
222 fn from(zid: &ZenohIdProto) -> Self {
223 (*zid).into()
224 }
225}
226
227impl serde::Serialize for ZenohIdProto {
228 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
229 where
230 S: serde::Serializer,
231 {
232 serializer.serialize_str(self.to_string().as_str())
233 }
234}
235
236impl<'de> serde::Deserialize<'de> for ZenohIdProto {
237 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
238 where
239 D: serde::Deserializer<'de>,
240 {
241 struct ZenohIdVisitor;
242
243 impl<'de> serde::de::Visitor<'de> for ZenohIdVisitor {
244 type Value = ZenohIdProto;
245
246 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
247 formatter.write_str(&format!(
248 "An hex string of 1-{} bytes",
249 ZenohIdProto::MAX_SIZE
250 ))
251 }
252
253 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
254 where
255 E: serde::de::Error,
256 {
257 v.parse().map_err(serde::de::Error::custom)
258 }
259
260 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
261 where
262 E: serde::de::Error,
263 {
264 self.visit_str(v)
265 }
266
267 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
268 where
269 E: serde::de::Error,
270 {
271 self.visit_str(&v)
272 }
273 }
274
275 deserializer.deserialize_str(ZenohIdVisitor)
276 }
277}
278
279pub type EntityId = u32;
281
282#[derive(Debug, Default, Copy, Clone, Eq, Hash, PartialEq)]
284pub struct EntityGlobalIdProto {
285 pub zid: ZenohIdProto,
286 pub eid: EntityId,
287}
288
289impl EntityGlobalIdProto {
290 #[cfg(feature = "test")]
291 #[doc(hidden)]
292 pub fn rand() -> Self {
293 use rand::Rng;
294 Self {
295 zid: ZenohIdProto::rand(),
296 eid: rand::thread_rng().gen(),
297 }
298 }
299}
300
301#[repr(u8)]
302#[derive(Debug, Default, Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
303pub enum Priority {
304 Control = 0,
305 RealTime = 1,
306 InteractiveHigh = 2,
307 InteractiveLow = 3,
308 DataHigh = 4,
309 #[default]
310 Data = 5,
311 DataLow = 6,
312 Background = 7,
313}
314
315#[derive(Debug, Clone, Eq, Hash, PartialEq, Serialize)]
316pub struct PriorityRange(RangeInclusive<Priority>);
318
319impl Deref for PriorityRange {
320 type Target = RangeInclusive<Priority>;
321
322 fn deref(&self) -> &Self::Target {
323 &self.0
324 }
325}
326
327impl PriorityRange {
328 pub fn new(range: RangeInclusive<Priority>) -> Self {
329 Self(range)
330 }
331
332 pub fn includes(&self, other: &PriorityRange) -> bool {
334 self.start() <= other.start() && other.end() <= self.end()
335 }
336
337 pub fn len(&self) -> usize {
338 *self.end() as usize - *self.start() as usize + 1
339 }
340
341 pub fn is_empty(&self) -> bool {
342 false
343 }
344
345 #[cfg(feature = "test")]
346 #[doc(hidden)]
347 pub fn rand() -> Self {
348 use rand::Rng;
349 let mut rng = rand::thread_rng();
350 let start = rng.gen_range(Priority::MAX as u8..Priority::MIN as u8);
351 let end = rng.gen_range((start + 1)..=Priority::MIN as u8);
352
353 Self(Priority::try_from(start).unwrap()..=Priority::try_from(end).unwrap())
354 }
355}
356
357impl Display for PriorityRange {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 write!(f, "{}-{}", *self.start() as u8, *self.end() as u8)
360 }
361}
362
363#[derive(Debug, PartialEq)]
364pub enum InvalidPriorityRange {
365 InvalidSyntax { found: String },
366 InvalidBound { message: String },
367}
368
369impl Display for InvalidPriorityRange {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 match self {
372 InvalidPriorityRange::InvalidSyntax { found } => write!(f, "invalid priority range string, expected an range of the form `start-end` but found {found}"),
373 InvalidPriorityRange::InvalidBound { message } => write!(f, "invalid priority range bound: {message}"),
374 }
375 }
376}
377
378#[cfg(feature = "std")]
379impl std::error::Error for InvalidPriorityRange {}
380
381impl FromStr for PriorityRange {
382 type Err = InvalidPriorityRange;
383
384 fn from_str(s: &str) -> Result<Self, Self::Err> {
385 const SEPARATOR: &str = "-";
386 let mut metadata = s.split(SEPARATOR);
387
388 let start = metadata
389 .next()
390 .ok_or_else(|| InvalidPriorityRange::InvalidSyntax {
391 found: s.to_string(),
392 })?
393 .parse::<u8>()
394 .map(Priority::try_from)
395 .map_err(|err| InvalidPriorityRange::InvalidBound {
396 message: err.to_string(),
397 })?
398 .map_err(|err| InvalidPriorityRange::InvalidBound {
399 message: err.to_string(),
400 })?;
401
402 match metadata.next() {
403 Some(slice) => {
404 let end = slice
405 .parse::<u8>()
406 .map(Priority::try_from)
407 .map_err(|err| InvalidPriorityRange::InvalidBound {
408 message: err.to_string(),
409 })?
410 .map_err(|err| InvalidPriorityRange::InvalidBound {
411 message: err.to_string(),
412 })?;
413
414 if metadata.next().is_some() {
415 return Err(InvalidPriorityRange::InvalidSyntax {
416 found: s.to_string(),
417 });
418 };
419
420 Ok(PriorityRange::new(start..=end))
421 }
422 None => Ok(PriorityRange::new(start..=start)),
423 }
424 }
425}
426
427impl Priority {
428 pub const DEFAULT: Self = Self::Data;
430 pub const MIN: Self = Self::Background;
432 pub const MAX: Self = Self::Control;
434 pub const NUM: usize = 1 + Self::MIN as usize - Self::MAX as usize;
436}
437
438impl TryFrom<u8> for Priority {
439 type Error = zenoh_result::Error;
440
441 fn try_from(v: u8) -> Result<Self, Self::Error> {
442 match v {
443 0 => Ok(Priority::Control),
444 1 => Ok(Priority::RealTime),
445 2 => Ok(Priority::InteractiveHigh),
446 3 => Ok(Priority::InteractiveLow),
447 4 => Ok(Priority::DataHigh),
448 5 => Ok(Priority::Data),
449 6 => Ok(Priority::DataLow),
450 7 => Ok(Priority::Background),
451 unknown => bail!(
452 "{} is not a valid priority value. Admitted values are: [{}-{}].",
453 unknown,
454 Self::MAX as u8,
455 Self::MIN as u8
456 ),
457 }
458 }
459}
460
461#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
463#[repr(u8)]
464pub enum Reliability {
465 BestEffort = 0,
467 #[default]
469 Reliable = 1,
470}
471
472impl Reliability {
473 pub const DEFAULT: Self = Self::Reliable;
474
475 #[cfg(feature = "test")]
476 #[doc(hidden)]
477 pub fn rand() -> Self {
478 use rand::Rng;
479
480 let mut rng = rand::thread_rng();
481
482 if rng.gen_bool(0.5) {
483 Reliability::Reliable
484 } else {
485 Reliability::BestEffort
486 }
487 }
488}
489
490impl From<bool> for Reliability {
491 fn from(value: bool) -> Self {
492 if value {
493 Reliability::Reliable
494 } else {
495 Reliability::BestEffort
496 }
497 }
498}
499
500impl From<Reliability> for bool {
501 fn from(value: Reliability) -> Self {
502 match value {
503 Reliability::BestEffort => false,
504 Reliability::Reliable => true,
505 }
506 }
507}
508
509impl Display for Reliability {
510 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
511 write!(f, "{}", *self as u8)
512 }
513}
514
515#[derive(Debug)]
516pub struct InvalidReliability {
517 found: String,
518}
519
520impl Display for InvalidReliability {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 write!(
523 f,
524 "invalid Reliability string, expected `{}` or `{}` but found {}",
525 Reliability::Reliable as u8,
526 Reliability::BestEffort as u8,
527 self.found
528 )
529 }
530}
531
532#[cfg(feature = "std")]
533impl std::error::Error for InvalidReliability {}
534
535impl FromStr for Reliability {
536 type Err = InvalidReliability;
537
538 fn from_str(s: &str) -> Result<Self, Self::Err> {
539 let Ok(desc) = s.parse::<u8>() else {
540 return Err(InvalidReliability {
541 found: s.to_string(),
542 });
543 };
544
545 if desc == Reliability::BestEffort as u8 {
546 Ok(Reliability::BestEffort)
547 } else if desc == Reliability::Reliable as u8 {
548 Ok(Reliability::Reliable)
549 } else {
550 Err(InvalidReliability {
551 found: s.to_string(),
552 })
553 }
554 }
555}
556
557#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
558pub struct Channel {
559 pub priority: Priority,
560 pub reliability: Reliability,
561}
562
563impl Channel {
564 pub const DEFAULT: Self = Self {
565 priority: Priority::DEFAULT,
566 reliability: Reliability::DEFAULT,
567 };
568}
569
570#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Deserialize)]
572#[repr(u8)]
573pub enum CongestionControl {
574 #[default]
575 Drop = 0,
577 Block = 1,
580 #[cfg(feature = "unstable")]
581 BlockFirst = 2,
585}
586
587impl CongestionControl {
588 pub const DEFAULT: Self = Self::Drop;
589
590 #[cfg(feature = "internal")]
591 pub const DEFAULT_PUSH: Self = Self::Drop;
592 #[cfg(not(feature = "internal"))]
593 pub(crate) const DEFAULT_PUSH: Self = Self::Drop;
594
595 #[cfg(feature = "internal")]
596 pub const DEFAULT_REQUEST: Self = Self::Block;
597 #[cfg(not(feature = "internal"))]
598 pub(crate) const DEFAULT_REQUEST: Self = Self::Block;
599
600 #[cfg(feature = "internal")]
601 pub const DEFAULT_RESPONSE: Self = Self::Block;
602 #[cfg(not(feature = "internal"))]
603 pub(crate) const DEFAULT_RESPONSE: Self = Self::Block;
604
605 #[cfg(feature = "internal")]
606 pub const DEFAULT_DECLARE: Self = Self::Block;
607 #[cfg(not(feature = "internal"))]
608 pub(crate) const DEFAULT_DECLARE: Self = Self::Block;
609
610 #[cfg(feature = "internal")]
611 pub const DEFAULT_OAM: Self = Self::Block;
612 #[cfg(not(feature = "internal"))]
613 pub(crate) const DEFAULT_OAM: Self = Self::Block;
614}
615
616#[cfg(test)]
617mod tests {
618 use core::str::FromStr;
619
620 use crate::core::{Priority, PriorityRange};
621
622 #[test]
623 fn test_priority_range() {
624 assert_eq!(
625 PriorityRange::from_str("2-3"),
626 Ok(PriorityRange::new(
627 Priority::InteractiveHigh..=Priority::InteractiveLow
628 ))
629 );
630
631 assert_eq!(
632 PriorityRange::from_str("7"),
633 Ok(PriorityRange::new(
634 Priority::Background..=Priority::Background
635 ))
636 );
637
638 assert!(PriorityRange::from_str("1-").is_err());
639 assert!(PriorityRange::from_str("-5").is_err());
640 }
641}