netlink_packet_route/prefix/
attribute.rs1use std::net::Ipv6Addr;
4
5use netlink_packet_core::{
6 DecodeError, DefaultNla, Emitable, ErrorContext, Nla, NlaBuffer, Parseable,
7};
8
9use super::cache_info::{CacheInfo, CacheInfoBuffer};
10
11const PREFIX_ADDRESS: u16 = 1;
12const PREFIX_CACHEINFO: u16 = 2;
13
14#[derive(Debug, PartialEq, Eq, Clone)]
15pub enum PrefixAttribute {
16 Address(Ipv6Addr),
17 CacheInfo(CacheInfo),
18 Other(DefaultNla),
19}
20
21impl Nla for PrefixAttribute {
22 fn value_len(&self) -> usize {
23 match *self {
24 Self::Address(_) => 16,
25 Self::CacheInfo(ref cache_info) => cache_info.buffer_len(),
26 Self::Other(ref attr) => attr.value_len(),
27 }
28 }
29
30 fn emit_value(&self, buffer: &mut [u8]) {
31 match *self {
32 Self::Address(ref addr) => buffer.copy_from_slice(&addr.octets()),
33 Self::CacheInfo(ref cache_info) => cache_info.emit(buffer),
34 Self::Other(ref attr) => attr.emit_value(buffer),
35 }
36 }
37
38 fn kind(&self) -> u16 {
39 match *self {
40 Self::Address(_) => PREFIX_ADDRESS,
41 Self::CacheInfo(_) => PREFIX_CACHEINFO,
42 Self::Other(ref nla) => nla.kind(),
43 }
44 }
45}
46
47impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>>
48 for PrefixAttribute
49{
50 fn parse(buf: &NlaBuffer<&'a T>) -> Result<Self, DecodeError> {
51 let payload = buf.value();
52 match buf.kind() {
53 PREFIX_ADDRESS => {
54 if let Ok(payload) = TryInto::<[u8; 16]>::try_into(payload) {
55 Ok(Self::Address(Ipv6Addr::from(payload)))
56 } else {
57 Err(DecodeError::from(format!(
58 "Invalid PREFIX_ADDRESS, unexpected payload length: \
59 {payload:?}"
60 )))
61 }
62 }
63 PREFIX_CACHEINFO => Ok(Self::CacheInfo(
64 CacheInfo::parse(&CacheInfoBuffer::new(payload)).context(
65 format!("Invalid PREFIX_CACHEINFO: {payload:?}"),
66 )?,
67 )),
68 _ => Ok(Self::Other(DefaultNla::parse(buf)?)),
69 }
70 }
71}