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