zenoh_codec/core/
zenohid.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::convert::TryFrom;
15
16use zenoh_buffers::{
17    reader::{DidntRead, Reader},
18    writer::{DidntWrite, Writer},
19};
20use zenoh_protocol::core::ZenohIdProto;
21
22use crate::{LCodec, RCodec, WCodec, Zenoh080, Zenoh080Length};
23
24impl LCodec<&ZenohIdProto> for Zenoh080 {
25    fn w_len(self, x: &ZenohIdProto) -> usize {
26        x.size()
27    }
28}
29
30impl<W> WCodec<&ZenohIdProto, &mut W> for Zenoh080
31where
32    W: Writer,
33{
34    type Output = Result<(), DidntWrite>;
35
36    fn write(self, writer: &mut W, x: &ZenohIdProto) -> Self::Output {
37        self.write(&mut *writer, &x.to_le_bytes()[..x.size()])
38    }
39}
40
41impl<R> RCodec<ZenohIdProto, &mut R> for Zenoh080
42where
43    R: Reader,
44{
45    type Error = DidntRead;
46
47    fn read(self, reader: &mut R) -> Result<ZenohIdProto, Self::Error> {
48        let size: usize = self.read(&mut *reader)?;
49        if size > ZenohIdProto::MAX_SIZE {
50            return Err(DidntRead);
51        }
52        let mut id = [0; ZenohIdProto::MAX_SIZE];
53        reader.read_exact(&mut id[..size])?;
54        ZenohIdProto::try_from(&id[..size]).map_err(|_| DidntRead)
55    }
56}
57
58impl<W> WCodec<&ZenohIdProto, &mut W> for Zenoh080Length
59where
60    W: Writer,
61{
62    type Output = Result<(), DidntWrite>;
63
64    fn write(self, writer: &mut W, x: &ZenohIdProto) -> Self::Output {
65        if self.length > ZenohIdProto::MAX_SIZE {
66            return Err(DidntWrite);
67        }
68        writer.write_exact(&x.to_le_bytes()[..x.size()])
69    }
70}
71
72impl<R> RCodec<ZenohIdProto, &mut R> for Zenoh080Length
73where
74    R: Reader,
75{
76    type Error = DidntRead;
77
78    fn read(self, reader: &mut R) -> Result<ZenohIdProto, Self::Error> {
79        if self.length > ZenohIdProto::MAX_SIZE {
80            return Err(DidntRead);
81        }
82        let mut id = [0; ZenohIdProto::MAX_SIZE];
83        reader.read_exact(&mut id[..self.length])?;
84        ZenohIdProto::try_from(&id[..self.length]).map_err(|_| DidntRead)
85    }
86}