zenoh_codec/core/
zslice.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    ZSlice,
18};
19
20use crate::{RCodec, WCodec, Zenoh080, Zenoh080Bounded};
21
22// ZSlice - Bounded
23macro_rules! zslice_impl {
24    ($bound:ty) => {
25        impl<W> WCodec<&ZSlice, &mut W> for Zenoh080Bounded<$bound>
26        where
27            W: Writer,
28        {
29            type Output = Result<(), DidntWrite>;
30
31            fn write(self, writer: &mut W, x: &ZSlice) -> Self::Output {
32                self.write(&mut *writer, x.len())?;
33                writer.write_zslice(x)?;
34                Ok(())
35            }
36        }
37
38        impl<R> RCodec<ZSlice, &mut R> for Zenoh080Bounded<$bound>
39        where
40            R: Reader,
41        {
42            type Error = DidntRead;
43
44            #[allow(clippy::uninit_vec)]
45            fn read(self, reader: &mut R) -> Result<ZSlice, Self::Error> {
46                let len: usize = self.read(&mut *reader)?;
47                let zslice = reader.read_zslice(len)?;
48                Ok(zslice)
49            }
50        }
51    };
52}
53
54zslice_impl!(u8);
55zslice_impl!(u16);
56zslice_impl!(u32);
57zslice_impl!(u64);
58zslice_impl!(usize);
59
60// ZSlice
61impl<W> WCodec<&ZSlice, &mut W> for Zenoh080
62where
63    W: Writer,
64{
65    type Output = Result<(), DidntWrite>;
66
67    fn write(self, writer: &mut W, x: &ZSlice) -> Self::Output {
68        let zodec = Zenoh080Bounded::<usize>::new();
69        zodec.write(&mut *writer, x)
70    }
71}
72
73impl<R> RCodec<ZSlice, &mut R> for Zenoh080
74where
75    R: Reader,
76{
77    type Error = DidntRead;
78
79    fn read(self, reader: &mut R) -> Result<ZSlice, Self::Error> {
80        let zodec = Zenoh080Bounded::<usize>::new();
81        zodec.read(&mut *reader)
82    }
83}