netlink_packet_core/
traits.rs

1// SPDX-License-Identifier: MIT
2
3use crate::{DecodeError, NetlinkHeader};
4
5/// A `NetlinkDeserializable` type can be deserialized from a buffer
6pub trait NetlinkDeserializable: Sized {
7    type Error: std::error::Error + Send + Sync + 'static;
8
9    /// Deserialize the given buffer into `Self`.
10    fn deserialize(
11        header: &NetlinkHeader,
12        payload: &[u8],
13    ) -> Result<Self, Self::Error>;
14}
15
16pub trait NetlinkSerializable {
17    fn message_type(&self) -> u16;
18
19    /// Return the length of the serialized data.
20    ///
21    /// Most netlink messages are encoded following a
22    /// [TLV](https://en.wikipedia.org/wiki/Type-length-value) scheme
23    /// and this library takes advantage of this by pre-allocating
24    /// buffers of the appropriate size when serializing messages,
25    /// which is why `buffer_len` is needed.
26    fn buffer_len(&self) -> usize;
27
28    /// Serialize this types and write the serialized data into the given
29    /// buffer. `buffer`'s length is exactly `InnerMessage::buffer_len()`.
30    /// It means that if `InnerMessage::buffer_len()` is buggy and does not
31    /// return the appropriate length, bad things can happen:
32    ///
33    /// - if `buffer_len()` returns a value _smaller than the actual data_,
34    ///   `emit()` may panics
35    /// - if `buffer_len()` returns a value _bigger than the actual data_, the
36    ///   buffer will contain garbage
37    ///
38    /// # Panic
39    ///
40    /// This method panics if the buffer is not big enough.
41    fn serialize(&self, buffer: &mut [u8]);
42}
43
44/// A type that implements `Emitable` can be serialized.
45pub trait Emitable {
46    /// Return the length of the serialized data.
47    fn buffer_len(&self) -> usize;
48
49    /// Serialize this types and write the serialized data into the given
50    /// buffer.
51    ///
52    /// # Panic
53    ///
54    /// This method panic if the buffer is not big enough. You **must** make
55    /// sure the buffer is big enough before calling this method. You can
56    /// use [`buffer_len()`](trait.Emitable.html#method.buffer_len) to check
57    /// how big the storage needs to be.
58    fn emit(&self, buffer: &mut [u8]);
59}
60
61/// A `Parseable` type can be used to deserialize data from the type `T` for
62/// which it is implemented.
63pub trait Parseable<T>
64where
65    Self: Sized,
66    T: ?Sized,
67{
68    /// Deserialize the current type.
69    fn parse(buf: &T) -> Result<Self, DecodeError>;
70}
71
72/// A `Parseable` type can be used to deserialize data from the type `T` for
73/// which it is implemented.
74pub trait ParseableParametrized<T, P>
75where
76    Self: Sized,
77    T: ?Sized,
78{
79    /// Deserialize the current type.
80    fn parse_with_param(buf: &T, params: P) -> Result<Self, DecodeError>;
81}