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)]
28#[cfg_attr(feature = "std", derive(Hash))]
29pub struct Encoding {
30    pub id: EncodingId,
31    pub schema: Option<ZSlice>,
32}
33
34/// # Encoding field
35///
36/// ```text
37///  7 6 5 4 3 2 1 0
38/// +-+-+-+-+-+-+-+-+
39/// ~   id: z16   |S~
40/// +---------------+
41/// ~schema: <u8;z8>~  -- if S==1
42/// +---------------+
43/// ```
44pub mod flag {
45    pub const S: u32 = 1; // 0x01 Suffix    if S==1 then schema is present
46}
47
48impl Encoding {
49    /// Returns a new [`Encoding`] object with default empty prefix ID.
50    pub const fn empty() -> Self {
51        Self {
52            id: 0,
53            schema: None,
54        }
55    }
56}
57
58impl Default for Encoding {
59    fn default() -> Self {
60        Self::empty()
61    }
62}
63
64impl Encoding {
65    #[cfg(feature = "test")]
66    pub fn rand() -> Self {
67        use rand::Rng;
68
69        const MIN: usize = 2;
70        const MAX: usize = 16;
71
72        let mut rng = rand::thread_rng();
73
74        let id: EncodingId = rng.gen();
75        let schema = rng
76            .gen_bool(0.5)
77            .then_some(ZSlice::rand(rng.gen_range(MIN..MAX)));
78        Encoding { id, schema }
79    }
80}