zenoh_protocol/core/encoding.rs
1//
2// Copyright (c) 2023 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12// ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14use core::fmt::Debug;
15
16use zenoh_buffers::ZSlice;
17
18pub type EncodingId = u16;
19
20/// [`Encoding`] is a metadata that indicates how the data payload should be interpreted.
21/// For wire-efficiency and extensibility purposes, Zenoh defines an [`Encoding`] as
22/// composed of an unsigned integer prefix and a bytes schema. The actual meaning of the
23/// prefix and schema are out-of-scope of the protocol definition. Therefore, Zenoh does not
24/// impose any encoding mapping and users are free to use any mapping they like.
25/// Nevertheless, it is worth highlighting that Zenoh still provides a default mapping as part
26/// of the API as per user convenience. That mapping has no impact on the Zenoh protocol definition.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct Encoding {
29 pub id: EncodingId,
30 pub schema: Option<ZSlice>,
31}
32
33/// # Encoding field
34///
35/// ```text
36/// 7 6 5 4 3 2 1 0
37/// +-+-+-+-+-+-+-+-+
38/// ~ id: z16 |S~
39/// +---------------+
40/// ~schema: <u8;z8>~ -- if S==1
41/// +---------------+
42/// ```
43pub mod flag {
44 pub const S: u32 = 1; // 0x01 Suffix if S==1 then schema is present
45}
46
47impl Encoding {
48 /// Returns a new [`Encoding`] object with default empty prefix ID.
49 pub const fn empty() -> Self {
50 Self {
51 id: 0,
52 schema: None,
53 }
54 }
55}
56
57impl Default for Encoding {
58 fn default() -> Self {
59 Self::empty()
60 }
61}
62
63impl Encoding {
64 #[cfg(feature = "test")]
65 pub fn rand() -> Self {
66 use rand::Rng;
67
68 const MIN: usize = 2;
69 const MAX: usize = 16;
70
71 let mut rng = rand::thread_rng();
72
73 let id: EncodingId = rng.gen();
74 let schema = rng
75 .gen_bool(0.5)
76 .then_some(ZSlice::rand(rng.gen_range(MIN..MAX)));
77 Encoding { id, schema }
78 }
79}