zenoh_codec/core/
zenohid.rs1use 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}