netlink_packet_route/neighbour/
address.rs

1// SPDX-License-Identifier: MIT
2
3use std::net::{Ipv4Addr, Ipv6Addr};
4
5use netlink_packet_utils::{DecodeError, Emitable};
6
7use crate::ip::{
8    emit_ip_to_buffer, parse_ipv4_addr, parse_ipv6_addr, IPV4_ADDR_LEN, IPV6_ADDR_LEN,
9};
10use crate::AddressFamily;
11
12#[derive(Debug, PartialEq, Eq, Clone)]
13#[non_exhaustive]
14pub enum NeighbourAddress {
15    Inet(Ipv4Addr),
16    Inet6(Ipv6Addr),
17    Other(Vec<u8>),
18}
19
20impl NeighbourAddress {
21    pub(crate) fn parse_with_param(
22        address_family: AddressFamily,
23        payload: &[u8],
24    ) -> Result<Self, DecodeError> {
25        Ok(match address_family {
26            AddressFamily::Inet => Self::Inet(parse_ipv4_addr(payload)?),
27            AddressFamily::Inet6 => Self::Inet6(parse_ipv6_addr(payload)?),
28            _ => Self::Other(payload.to_vec()),
29        })
30    }
31}
32
33impl Emitable for NeighbourAddress {
34    fn buffer_len(&self) -> usize {
35        match self {
36            Self::Inet(_) => IPV4_ADDR_LEN,
37            Self::Inet6(_) => IPV6_ADDR_LEN,
38            Self::Other(v) => v.len(),
39        }
40    }
41
42    fn emit(&self, buffer: &mut [u8]) {
43        match self {
44            Self::Inet(v) => emit_ip_to_buffer(&((*v).into()), buffer),
45            Self::Inet6(v) => emit_ip_to_buffer(&((*v).into()), buffer),
46            Self::Other(v) => buffer.copy_from_slice(v.as_slice()),
47        }
48    }
49}
50
51impl From<Ipv4Addr> for NeighbourAddress {
52    fn from(v: Ipv4Addr) -> Self {
53        Self::Inet(v)
54    }
55}
56
57impl From<Ipv6Addr> for NeighbourAddress {
58    fn from(v: Ipv6Addr) -> Self {
59        Self::Inet6(v)
60    }
61}