netlink_packet_core/
traits.rs

1// SPDX-License-Identifier: MIT
2
3use crate::NetlinkHeader;
4use std::error::Error;
5
6/// A `NetlinkDeserializable` type can be deserialized from a buffer
7pub trait NetlinkDeserializable: Sized {
8    type Error: Error + Send + Sync + 'static;
9
10    /// Deserialize the given buffer into `Self`.
11    fn deserialize(header: &NetlinkHeader, payload: &[u8]) -> Result<Self, Self::Error>;
12}
13
14pub trait NetlinkSerializable {
15    fn message_type(&self) -> u16;
16
17    /// Return the length of the serialized data.
18    ///
19    /// Most netlink messages are encoded following a
20    /// [TLV](https://en.wikipedia.org/wiki/Type-length-value) scheme
21    /// and this library takes advantage of this by pre-allocating
22    /// buffers of the appropriate size when serializing messages,
23    /// which is why `buffer_len` is needed.
24    fn buffer_len(&self) -> usize;
25
26    /// Serialize this types and write the serialized data into the given
27    /// buffer. `buffer`'s length is exactly `InnerMessage::buffer_len()`.
28    /// It means that if `InnerMessage::buffer_len()` is buggy and does not
29    /// return the appropriate length, bad things can happen:
30    ///
31    /// - if `buffer_len()` returns a value _smaller than the actual data_,
32    ///   `emit()` may panics
33    /// - if `buffer_len()` returns a value _bigger than the actual data_, the
34    ///   buffer will contain garbage
35    ///
36    /// # Panic
37    ///
38    /// This method panics if the buffer is not big enough.
39    fn serialize(&self, buffer: &mut [u8]);
40}