netlink_packet_route/route/
realm.rs

1// SPDX-License-Identifier: MIT
2
3use netlink_packet_core::{DecodeError, Emitable};
4
5const RULE_REALM_LEN: usize = 4;
6
7#[derive(Clone, Eq, PartialEq, Debug, Copy)]
8pub struct RouteRealm {
9    pub source: u16,
10    pub destination: u16,
11}
12
13impl RouteRealm {
14    pub(crate) fn parse(buf: &[u8]) -> Result<Self, DecodeError> {
15        let all = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]);
16        if buf.len() == RULE_REALM_LEN {
17            Ok(Self {
18                source: (all >> 16) as u16,
19                destination: (all & 0xFFFF) as u16,
20            })
21        } else {
22            Err(DecodeError::from(format!(
23                "Invalid rule port range data, expecting {RULE_REALM_LEN} u8 \
24                 array, but got {buf:?}"
25            )))
26        }
27    }
28}
29
30impl Emitable for RouteRealm {
31    fn buffer_len(&self) -> usize {
32        RULE_REALM_LEN
33    }
34
35    fn emit(&self, buffer: &mut [u8]) {
36        let all = ((self.source as u32) << 16) | self.destination as u32;
37        buffer.copy_from_slice(&all.to_ne_bytes());
38    }
39}