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