ntp_proto/protocol/traits.rs
1#[cfg(feature = "std")]
2use byteorder::{ReadBytesExt, WriteBytesExt};
3#[cfg(feature = "std")]
4use std::io;
5
6use crate::error::ParseError;
7
8/// A trait for writing any of the Network Time Protocol types to network-endian bytes.
9///
10/// A blanket implementation is provided for all types that implement `byteorder::WriteBytesExt`.
11/// Requires the `std` feature.
12#[cfg(feature = "std")]
13pub trait WriteBytes {
14 /// Writes an NTP protocol type to this writer in network byte order.
15 fn write_bytes<P: WriteToBytes>(&mut self, protocol: P) -> io::Result<()>;
16}
17
18/// A trait for reading any of the Network Time Protocol types from network-endian bytes.
19///
20/// A blanket implementation is provided for all types that implement `byteorder::ReadBytesExt`.
21/// Requires the `std` feature.
22#[cfg(feature = "std")]
23pub trait ReadBytes {
24 /// Reads an NTP protocol type from this reader in network byte order.
25 fn read_bytes<P: ReadFromBytes>(&mut self) -> io::Result<P>;
26}
27
28/// Network Time Protocol types that may be written to network endian bytes.
29/// Requires the `std` feature.
30#[cfg(feature = "std")]
31pub trait WriteToBytes {
32 /// Write the command to bytes.
33 fn write_to_bytes<W: WriteBytesExt>(&self, writer: W) -> io::Result<()>;
34}
35
36/// Network Time Protocol types that may be read from network endian bytes.
37/// Requires the `std` feature.
38#[cfg(feature = "std")]
39pub trait ReadFromBytes: Sized {
40 /// Read the command from bytes.
41 fn read_from_bytes<R: ReadBytesExt>(reader: R) -> io::Result<Self>;
42}
43
44/// Types that have a constant size when written to or read from bytes.
45pub trait ConstPackedSizeBytes {
46 /// The constant size in bytes when this type is packed for network transmission.
47 const PACKED_SIZE_BYTES: usize;
48}
49
50/// Parse a type from a byte slice, returning the parsed value and the number
51/// of bytes consumed.
52///
53/// Unlike [`ReadFromBytes`], this trait does not require `std::io` or the `byteorder` crate.
54/// It operates directly on `&[u8]` slices, making it suitable for `no_std` environments
55/// and packet capture analysis.
56pub trait FromBytes: Sized {
57 /// Parse from the given byte slice. Returns the parsed value and the
58 /// number of bytes consumed from the front of `buf`.
59 fn from_bytes(buf: &[u8]) -> Result<(Self, usize), ParseError>;
60}
61
62/// Serialize a type into a byte slice, returning the number of bytes written.
63///
64/// Unlike [`WriteToBytes`], this trait does not require `std::io` or the `byteorder` crate.
65/// It operates directly on `&mut [u8]` slices, making it suitable for `no_std` environments.
66pub trait ToBytes {
67 /// Write this value into the given byte slice. Returns the number of bytes
68 /// written. Fails with [`ParseError::BufferTooShort`] if `buf` is too short.
69 fn to_bytes(&self, buf: &mut [u8]) -> Result<usize, ParseError>;
70}