Skip to main content

bgp_packet/
constants.rs

1use std::fmt::Display;
2
3use eyre::bail;
4use serde_repr::{Deserialize_repr, Serialize_repr};
5
6#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
7#[repr(u16)]
8pub enum AddressFamilyId {
9    Ipv4 = 1,
10    Ipv6 = 2,
11}
12
13impl TryFrom<u16> for AddressFamilyId {
14    type Error = eyre::Error;
15
16    fn try_from(value: u16) -> Result<Self, Self::Error> {
17        Ok(match value {
18            x if x == Self::Ipv4 as u16 => Self::Ipv4,
19            x if x == Self::Ipv6 as u16 => Self::Ipv6,
20            other => bail!("Unknown AddressFamily: {}", other),
21        })
22    }
23}
24
25impl Display for AddressFamilyId {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        match self {
28            AddressFamilyId::Ipv4 => write!(f, "Ipv4"),
29            AddressFamilyId::Ipv6 => write!(f, "Ipv6"),
30        }
31    }
32}
33
34/// Represents a Subsequent Address Family Identifier.
35#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
36#[repr(u8)]
37pub enum SubsequentAfi {
38    Unicast = 1,
39    Multicast = 2,
40    NlriWithMpls = 4,
41    MplsLabelledVpn = 128,
42    MulticastMplsVpn = 129,
43}
44
45impl TryFrom<u8> for SubsequentAfi {
46    type Error = eyre::Error;
47
48    fn try_from(value: u8) -> Result<Self, Self::Error> {
49        Ok(match value {
50            x if x == Self::Unicast as u8 => Self::Unicast,
51            x if x == Self::Multicast as u8 => Self::Multicast,
52            x if x == Self::NlriWithMpls as u8 => Self::NlriWithMpls,
53            x if x == Self::MplsLabelledVpn as u8 => Self::MplsLabelledVpn,
54            x if x == Self::MulticastMplsVpn as u8 => Self::MulticastMplsVpn,
55            other => bail!("Unknown SubsequentAfi: {}", other),
56        })
57    }
58}
59
60/// The implementation try_from for u16 just reuses the u8 implementation since
61/// we don't have any cases where the SAFI is longer than u8::MAX yet.
62impl TryFrom<u16> for SubsequentAfi {
63    type Error = eyre::Error;
64
65    fn try_from(value: u16) -> Result<Self, Self::Error> {
66        TryFrom::<u8>::try_from(value as u8)
67    }
68}
69
70impl Display for SubsequentAfi {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        match self {
73            SubsequentAfi::Unicast => write!(f, "Unicast"),
74            SubsequentAfi::Multicast => write!(f, "Multicast"),
75            SubsequentAfi::NlriWithMpls => write!(f, "NlriWithMpls"),
76            SubsequentAfi::MplsLabelledVpn => write!(f, "MplsLabelledVpn"),
77            SubsequentAfi::MulticastMplsVpn => write!(f, "MulticastMplsVpn"),
78        }
79    }
80}