zenoh_codec/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 zenoh_buffers::{
15    reader::{DidntRead, Reader},
16    writer::{DidntWrite, Writer},
17};
18use zenoh_protocol::{
19    common::imsg,
20    core::encoding::{flag, Encoding, EncodingId},
21};
22
23use crate::{LCodec, RCodec, WCodec, Zenoh080, Zenoh080Bounded};
24
25impl LCodec<&Encoding> for Zenoh080 {
26    fn w_len(self, x: &Encoding) -> usize {
27        let mut len = self.w_len((x.id as u32) << 1);
28        if let Some(schema) = x.schema.as_ref() {
29            len += self.w_len(schema.as_slice());
30        }
31        len
32    }
33}
34
35impl<W> WCodec<&Encoding, &mut W> for Zenoh080
36where
37    W: Writer,
38{
39    type Output = Result<(), DidntWrite>;
40
41    fn write(self, writer: &mut W, x: &Encoding) -> Self::Output {
42        let mut id = (x.id as u32) << 1;
43
44        if x.schema.is_some() {
45            id |= flag::S;
46        }
47        let zodec = Zenoh080Bounded::<u32>::new();
48        zodec.write(&mut *writer, id)?;
49        if let Some(schema) = x.schema.as_ref() {
50            let zodec = Zenoh080Bounded::<u8>::new();
51            zodec.write(&mut *writer, schema)?;
52        }
53        Ok(())
54    }
55}
56
57impl<R> RCodec<Encoding, &mut R> for Zenoh080
58where
59    R: Reader,
60{
61    type Error = DidntRead;
62
63    fn read(self, reader: &mut R) -> Result<Encoding, Self::Error> {
64        let zodec = Zenoh080Bounded::<u32>::new();
65        let id: u32 = zodec.read(&mut *reader)?;
66        let (id, has_schema) = (
67            (id >> 1) as EncodingId,
68            imsg::has_flag(id as u8, flag::S as u8),
69        );
70
71        let mut schema = None;
72        if has_schema {
73            let zodec = Zenoh080Bounded::<u8>::new();
74            schema = Some(zodec.read(&mut *reader)?);
75        }
76
77        let encoding = Encoding { id, schema };
78        Ok(encoding)
79    }
80}