Skip to main content

flowparser_sflow/counter_records/
host_adapters.rs

1use mac_address::MacAddress;
2use nom::IResult;
3use nom::number::complete::be_u32;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
7pub struct HostAdapter {
8    pub if_index: u32,
9    pub mac_addresses: Vec<MacAddress>,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct HostAdapters {
14    pub adapters: Vec<HostAdapter>,
15}
16
17fn parse_mac(input: &[u8]) -> IResult<&[u8], MacAddress> {
18    if input.len() < 8 {
19        return Err(nom::Err::Error(nom::error::Error::new(
20            input,
21            nom::error::ErrorKind::Eof,
22        )));
23    }
24    let bytes: [u8; 6] = [input[0], input[1], input[2], input[3], input[4], input[5]];
25    Ok((&input[8..], MacAddress::new(bytes)))
26}
27
28fn parse_host_adapter(input: &[u8]) -> IResult<&[u8], HostAdapter> {
29    let (input, if_index) = be_u32(input)?;
30    let (input, num_macs) = be_u32(input)?;
31    // Each MAC is padded to 8 bytes in sFlow
32    let cap = (num_macs as usize).min(input.len() / 8);
33    let mut mac_addresses = Vec::with_capacity(cap);
34    let mut input = input;
35    for _ in 0..num_macs {
36        let (rest, mac) = parse_mac(input)?;
37        mac_addresses.push(mac);
38        input = rest;
39    }
40
41    Ok((
42        input,
43        HostAdapter {
44            if_index,
45            mac_addresses,
46        },
47    ))
48}
49
50pub(crate) fn parse_host_adapters(input: &[u8]) -> IResult<&[u8], HostAdapters> {
51    let (input, num_adapters) = be_u32(input)?;
52    // Each adapter needs at least 8 bytes (if_index + num_macs)
53    let cap = (num_adapters as usize).min(input.len() / 8);
54    let mut adapters = Vec::with_capacity(cap);
55    let mut input = input;
56    for _ in 0..num_adapters {
57        let (rest, adapter) = parse_host_adapter(input)?;
58        adapters.push(adapter);
59        input = rest;
60    }
61
62    Ok((input, HostAdapters { adapters }))
63}