netlink_packet_route/route/
realm.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// SPDX-License-Identifier: MIT

use super::RouteError;
use netlink_packet_utils::Emitable;

const RULE_REALM_LEN: usize = 4;

#[derive(Clone, Eq, PartialEq, Debug, Copy)]
pub struct RouteRealm {
    pub source: u16,
    pub destination: u16,
}

impl RouteRealm {
    pub(crate) fn parse(buf: &[u8]) -> Result<Self, RouteError> {
        let all = u32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]);
        if buf.len() == RULE_REALM_LEN {
            Ok(Self { source: (all >> 16) as u16, destination: (all & 0xFFFF) as u16 })
        } else {
            Err(RouteError::InvalidRulePortRange { expected: RULE_REALM_LEN, got: buf.len() })
        }
    }
}

impl Emitable for RouteRealm {
    fn buffer_len(&self) -> usize {
        RULE_REALM_LEN
    }

    fn emit(&self, buffer: &mut [u8]) {
        let all = (self.source as u32) << 16 | self.destination as u32;
        buffer.copy_from_slice(&all.to_ne_bytes());
    }
}