netlink_packet_route/link/af_spec/
unspec.rsuse anyhow::Context;
use netlink_packet_utils::nla::{DefaultNla, Nla, NlaBuffer, NlasIterator};
use netlink_packet_utils::traits::{Emitable, Parseable};
use netlink_packet_utils::DecodeError;
use crate::link::af_spec::{VecAfSpecInet, VecAfSpecInet6};
use crate::link::{AfSpecInet, AfSpecInet6};
use crate::AddressFamily;
#[derive(Clone, Eq, PartialEq, Debug)]
#[non_exhaustive]
pub enum AfSpecUnspec {
Inet(Vec<AfSpecInet>),
Inet6(Vec<AfSpecInet6>),
Other(DefaultNla),
}
pub(crate) struct VecAfSpecUnspec(pub(crate) Vec<AfSpecUnspec>);
impl<'a, T: AsRef<[u8]> + ?Sized> Parseable<NlaBuffer<&'a T>> for VecAfSpecUnspec {
type Error = DecodeError;
fn parse(buf: &NlaBuffer<&'a T>) -> Result<Self, DecodeError> {
let mut nlas = vec![];
let err = "Invalid NLA for IFLA_AF_SPEC(AF_UNSPEC)";
for nla in NlasIterator::new(buf.into_inner()) {
let nla = nla.context(err)?;
nlas.push(match nla.kind() {
k if k == u8::from(AddressFamily::Inet) as u16 => AfSpecUnspec::Inet(
VecAfSpecInet::parse(&NlaBuffer::new_checked(&nla.value()).context(err)?)
.context(err)?
.0,
),
k if k == u8::from(AddressFamily::Inet6) as u16 => AfSpecUnspec::Inet6(
VecAfSpecInet6::parse(&NlaBuffer::new_checked(&nla.value()).context(err)?)
.context(err)?
.0,
),
kind => {
AfSpecUnspec::Other(DefaultNla::parse(&nla).context(format!(
"Unknown AF_XXX type {kind} for IFLA_AF_SPEC(AF_UNSPEC)"
))?)
}
})
}
Ok(Self(nlas))
}
}
impl Nla for AfSpecUnspec {
fn value_len(&self) -> usize {
match *self {
Self::Inet(ref nlas) => nlas.as_slice().buffer_len(),
Self::Inet6(ref nlas) => nlas.as_slice().buffer_len(),
Self::Other(ref nla) => nla.value_len(),
}
}
fn emit_value(&self, buffer: &mut [u8]) {
match *self {
Self::Inet(ref nlas) => nlas.as_slice().emit(buffer),
Self::Inet6(ref nlas) => nlas.as_slice().emit(buffer),
Self::Other(ref nla) => nla.emit_value(buffer),
}
}
fn kind(&self) -> u16 {
match *self {
Self::Inet(_) => u8::from(AddressFamily::Inet) as u16,
Self::Inet6(_) => u8::from(AddressFamily::Inet6) as u16,
Self::Other(ref nla) => nla.kind(),
}
}
}