zenoh_codec/core/
locator.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 alloc::{string::String, vec::Vec};
15use core::convert::TryFrom;
16
17use zenoh_buffers::{
18    reader::{DidntRead, Reader},
19    writer::{DidntWrite, Writer},
20};
21use zenoh_protocol::core::Locator;
22
23use crate::{RCodec, WCodec, Zenoh080, Zenoh080Bounded};
24
25impl<W> WCodec<&Locator, &mut W> for Zenoh080
26where
27    W: Writer,
28{
29    type Output = Result<(), DidntWrite>;
30
31    fn write(self, writer: &mut W, x: &Locator) -> Self::Output {
32        let zodec = Zenoh080Bounded::<u8>::new();
33        zodec.write(writer, x.as_str())
34    }
35}
36
37impl<R> RCodec<Locator, &mut R> for Zenoh080
38where
39    R: Reader,
40{
41    type Error = DidntRead;
42
43    fn read(self, reader: &mut R) -> Result<Locator, Self::Error> {
44        let zodec = Zenoh080Bounded::<u8>::new();
45        let loc: String = zodec.read(reader)?;
46        Locator::try_from(loc).map_err(|_| DidntRead)
47    }
48}
49
50impl<W> WCodec<&[Locator], &mut W> for Zenoh080
51where
52    W: Writer,
53{
54    type Output = Result<(), DidntWrite>;
55
56    fn write(self, writer: &mut W, x: &[Locator]) -> Self::Output {
57        self.write(&mut *writer, x.len())?;
58        for l in x {
59            self.write(&mut *writer, l)?;
60        }
61        Ok(())
62    }
63}
64
65impl<R> RCodec<Vec<Locator>, &mut R> for Zenoh080
66where
67    R: Reader,
68{
69    type Error = DidntRead;
70
71    fn read(self, reader: &mut R) -> Result<Vec<Locator>, Self::Error> {
72        let len = self.read(&mut *reader)?;
73        let mut vec: Vec<Locator> = Vec::with_capacity(len);
74        for _ in 0..len {
75            vec.push(self.read(&mut *reader)?);
76        }
77        Ok(vec)
78    }
79}