Skip to main content

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        let parsed = Locator::try_from(loc.clone()).map_err(|_| DidntRead)?;
47        // `Locator::try_from()` first parses the input as an `EndPoint`, and
48        // `EndPoint` accepts `#...` config. Converting that `EndPoint` back to
49        // a `Locator` drops the config part, so decode would accept one string
50        // and re-encode a different one. Rechecking the parsed locator string
51        // against the original wire bytes keeps decode/re-encode consistent.
52        if parsed.as_str() != loc {
53            return Err(DidntRead);
54        }
55        Ok(parsed)
56    }
57}
58
59impl<W> WCodec<&[Locator], &mut W> for Zenoh080
60where
61    W: Writer,
62{
63    type Output = Result<(), DidntWrite>;
64
65    fn write(self, writer: &mut W, x: &[Locator]) -> Self::Output {
66        self.write(&mut *writer, x.len())?;
67        for l in x {
68            self.write(&mut *writer, l)?;
69        }
70        Ok(())
71    }
72}
73
74impl<R> RCodec<Vec<Locator>, &mut R> for Zenoh080
75where
76    R: Reader,
77{
78    type Error = DidntRead;
79
80    fn read(self, reader: &mut R) -> Result<Vec<Locator>, Self::Error> {
81        let len: usize = self.read(&mut *reader)?;
82        let mut vec = Vec::new();
83        for _ in 0..len {
84            vec.push(self.read(&mut *reader)?);
85        }
86        Ok(vec)
87    }
88}