netlink_packet_route/rule/
port_range.rs

1// SPDX-License-Identifier: MIT
2
3use crate::rule::RuleError;
4use netlink_packet_utils::Emitable;
5
6const RULE_PORT_RANGE_LEN: usize = 4;
7
8#[derive(Clone, Eq, PartialEq, Debug, Copy)]
9pub struct RulePortRange {
10    pub start: u16,
11    pub end: u16,
12}
13
14impl RulePortRange {
15    pub(crate) fn parse(buf: &[u8]) -> Result<Self, RuleError> {
16        if buf.len() == RULE_PORT_RANGE_LEN {
17            Ok(Self {
18                start: u16::from_ne_bytes([buf[0], buf[1]]),
19                end: u16::from_ne_bytes([buf[2], buf[3]]),
20            })
21        } else {
22            Err(RuleError::ParsePortRange { expected: RULE_PORT_RANGE_LEN, got: buf.len() })
23        }
24    }
25}
26
27impl Emitable for RulePortRange {
28    fn buffer_len(&self) -> usize {
29        RULE_PORT_RANGE_LEN
30    }
31
32    fn emit(&self, buffer: &mut [u8]) {
33        buffer[0..2].copy_from_slice(&self.start.to_ne_bytes());
34        buffer[2..4].copy_from_slice(&self.end.to_ne_bytes());
35    }
36}