zenoh_codec/core/
timestamp.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::{Timestamp, ZenohIdProto};
21
22use crate::{LCodec, RCodec, WCodec, Zenoh080};
23
24impl LCodec<&Timestamp> for Zenoh080 {
25    fn w_len(self, x: &Timestamp) -> usize {
26        let id = x.get_id();
27        self.w_len(x.get_time().as_u64()) + self.w_len(&id.to_le_bytes()[..id.size()])
28    }
29}
30
31impl<W> WCodec<&Timestamp, &mut W> for Zenoh080
32where
33    W: Writer,
34{
35    type Output = Result<(), DidntWrite>;
36
37    fn write(self, writer: &mut W, x: &Timestamp) -> Self::Output {
38        self.write(&mut *writer, x.get_time().as_u64())?;
39        let id = x.get_id();
40        self.write(&mut *writer, &id.to_le_bytes()[..id.size()])?;
41        Ok(())
42    }
43}
44
45impl<R> RCodec<Timestamp, &mut R> for Zenoh080
46where
47    R: Reader,
48{
49    type Error = DidntRead;
50
51    fn read(self, reader: &mut R) -> Result<Timestamp, Self::Error> {
52        let time: u64 = self.read(&mut *reader)?;
53        let size: usize = self.read(&mut *reader)?;
54        if size > (uhlc::ID::MAX_SIZE) {
55            return Err(DidntRead);
56        }
57        let mut id = [0_u8; ZenohIdProto::MAX_SIZE];
58        reader.read_exact(&mut id[..size])?;
59
60        let time = uhlc::NTP64(time);
61        let id = uhlc::ID::try_from(&id[..size]).map_err(|_| DidntRead)?;
62        Ok(Timestamp::new(time, id))
63    }
64}