From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 86CC51FF0B6 for ; Thu, 12 Nov 2026 18:12:01 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 61CA321714; Thu, 12 Nov 2026 18:11:25 +0100 (CET) From: Stefan Hanreich To: pve-devel@lists.proxmox.com Subject: [PATCH proxmox 3/4] network-types: add types for names reported by the kernel Date: Thu, 12 Nov 2026 18:10:59 +0100 Message-ID: <20261112171102.674232-4-s.hanreich@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261112171102.674232-1-s.hanreich@proxmox.com> References: <20261112171102.674232-1-s.hanreich@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1794503477104 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.226 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) PROLO_LEO2 0.1 Meta Catches all Leo drug variations so far RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: MNDTFETDRUKES7EYBEFLVL5G4HUUUDS4 X-Message-ID-Hash: MNDTFETDRUKES7EYBEFLVL5G4HUUUDS4 X-MailFrom: s.hanreich@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: The kernel accepts a lot more names than the API: any byte except '/', ':', NUL and whitespace, and altnames are only limited in length. So names read from the kernel, e.g. via 'ip link', cannot always be represented by the API types. KernelNetworkInterfaceName and KernelNetworkInterfaceAltname accept exactly what the kernel accepts. This includes treating 0xa0 as whitespace, which also rejects some valid UTF-8 names, e.g. ones containing U+00E0. Names do not have to be valid UTF-8, so the types store bytes. 'ip -json' prints such names unchanged, which only deserializes into bytes, not into a String. The types follow the kernel instead of iproute2, since 'ip' reports names unchanged, but its own checks differ between versions: before 7.0 it rejected altnames with whitespace, which was dropped since the kernel has no such restriction. Names that are created or passed to 'ip' should use the API types instead. The checks are the ones of net-next (v7.4-rc1): dev_valid_name() for names, which is unchanged since Linux 4.17, and only the length for altnames, which is unchanged since altnames were added in Linux 5.5. Serializing a name that is not valid UTF-8 fails, since it cannot be represented as a string, and replacing the invalid bytes would yield the name of another interface. The types are not meant for API parameters, so they have no API schema and do not require the api-types feature. In practice, our stack does not create names that are not valid UTF-8 anyway, the bytes are only needed to read what the kernel reports. Signed-off-by: Stefan Hanreich --- .../src/network_interface.rs | 665 +++++++++++++++++- 1 file changed, 660 insertions(+), 5 deletions(-) diff --git a/proxmox-network-types/src/network_interface.rs b/proxmox-network-types/src/network_interface.rs index fa6d2e37..afa8af2f 100644 --- a/proxmox-network-types/src/network_interface.rs +++ b/proxmox-network-types/src/network_interface.rs @@ -13,6 +13,330 @@ //! * `api_types::NetworkInterfaceAltname`: values that can be a name or an altname, e.g. the //! interface of a firewall rule. Resolve it to the name where only names work, e.g. for //! `iifname` in nftables. +//! +//! * [`KernelNetworkInterfaceName`] and [`KernelNetworkInterfaceAltname`]: names read from the +//! kernel, e.g. via netlink or `ip -json link`. Deserialize them into these types instead of +//! `String`, since they do not have to be valid UTF-8, and convert them into the API types one +//! by one. Not for the API or configuration files, and not for names passed to `ip`, which +//! rejects some altnames that the kernel accepts. + +use std::cmp::Ordering; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::str::{FromStr, Utf8Error}; + +use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser}; +use thiserror::Error; + +/// The size of the kernel buffer for network interface names, including the terminating NUL. +const IFNAMSIZ: usize = 16; + +/// The size of the kernel buffer for altnames, including the terminating NUL. +const ALTIFNAMSIZ: usize = 128; + +/// Errors for names and altnames that the kernel does not accept. +#[derive(Error, Debug, Clone, PartialEq, Eq)] +pub enum KernelNameError { + /// The name is empty. + #[error("the name must not be empty")] + Empty, + /// The name is longer than the kernel accepts. + #[error("the name must have at most {max} bytes, it has {len} bytes")] + TooLong { + /// The length of the name in bytes. + len: usize, + /// The maximum length in bytes. + max: usize, + }, + /// The name is `.` or `..`, which the kernel reserves since names are used as directory names. + #[error("the name must not be '.' or '..'")] + Reserved, + /// The name contains a byte that the kernel rejects. + #[error("the name must not contain the byte {0:#04x}")] + InvalidByte(u8), +} + +/// Returns whether the kernel treats `byte` as whitespace. +/// +/// This includes `0xa0` (no-break space in Latin-1), which is also a UTF-8 continuation byte. So +/// the kernel rejects every code point whose UTF-8 encoding has a 6-bit group of `0x20`, e.g. +/// U+00E0 (`0xc3 0xa0`). +fn is_kernel_space(byte: u8) -> bool { + matches!(byte, b'\t' | b'\n' | 0x0b | 0x0c | b'\r' | b' ' | 0xa0) +} + +/// Checks a network interface name like `dev_valid_name()` of the kernel. +fn check_kernel_name(name: &[u8]) -> Result<(), KernelNameError> { + if name.is_empty() { + return Err(KernelNameError::Empty); + } + + if name.len() >= IFNAMSIZ { + return Err(KernelNameError::TooLong { + len: name.len(), + max: IFNAMSIZ - 1, + }); + } + + if name == b"." || name == b".." { + return Err(KernelNameError::Reserved); + } + + match name + .iter() + .find(|byte| matches!(byte, b'\0' | b'/' | b':') || is_kernel_space(**byte)) + { + Some(byte) => Err(KernelNameError::InvalidByte(*byte)), + None => Ok(()), + } +} + +/// Checks an altname like the kernel, which only limits its length. +fn check_kernel_altname(altname: &[u8]) -> Result<(), KernelNameError> { + if altname.len() >= ALTIFNAMSIZ { + return Err(KernelNameError::TooLong { + len: altname.len(), + max: ALTIFNAMSIZ - 1, + }); + } + + if altname.contains(&b'\0') { + return Err(KernelNameError::InvalidByte(b'\0')); + } + + Ok(()) +} + +/// Implements the traits shared by the kernel name types. It only relies on `as_bytes()`, +/// `TryFrom<&[u8]>` and `TryFrom>`, so it works for both storage layouts. +macro_rules! kernel_name_impls { + ($type:ident, $kind:literal) => { + impl $type { + /// Returns the name as a string, if it is valid UTF-8. + pub fn to_str(&self) -> Result<&str, Utf8Error> { + std::str::from_utf8(self.as_bytes()) + } + } + + impl AsRef<[u8]> for $type { + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } + } + + impl PartialEq for $type { + fn eq(&self, other: &Self) -> bool { + self.as_bytes() == other.as_bytes() + } + } + + impl Eq for $type {} + + impl PartialOrd for $type { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for $type { + fn cmp(&self, other: &Self) -> Ordering { + self.as_bytes().cmp(other.as_bytes()) + } + } + + impl Hash for $type { + fn hash(&self, state: &mut H) { + self.as_bytes().hash(state) + } + } + + impl fmt::Debug for $type { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.to_str() { + Ok(name) => f.debug_tuple(stringify!($type)).field(&name).finish(), + Err(_) => f + .debug_tuple(stringify!($type)) + .field(&format_args!("b\"{}\"", self.as_bytes().escape_ascii())) + .finish(), + } + } + } + + impl TryFrom for $type { + type Error = KernelNameError; + + fn try_from(name: String) -> Result { + Self::try_from(name.into_bytes()) + } + } + + impl FromStr for $type { + type Err = KernelNameError; + + fn from_str(name: &str) -> Result { + Self::try_from(name.as_bytes()) + } + } + + impl Serialize for $type { + fn serialize(&self, serializer: S) -> Result { + match self.to_str() { + Ok(name) => serializer.serialize_str(name), + Err(_) => Err(::custom(format_args!( + "{self:?} is not valid UTF-8" + ))), + } + } + } + + impl<'de> Deserialize<'de> for $type { + fn deserialize>(deserializer: D) -> Result { + struct NameVisitor; + + impl de::Visitor<'_> for NameVisitor { + type Value = $type; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "a {} as a string or byte string", $kind) + } + + fn visit_bytes(self, name: &[u8]) -> Result<$type, E> { + $type::try_from(name).map_err(E::custom) + } + + fn visit_byte_buf(self, name: Vec) -> Result<$type, E> { + $type::try_from(name).map_err(E::custom) + } + + fn visit_str(self, name: &str) -> Result<$type, E> { + self.visit_bytes(name.as_bytes()) + } + + fn visit_string(self, name: String) -> Result<$type, E> { + self.visit_byte_buf(name.into_bytes()) + } + } + + // serde_json passes strings as raw bytes here, so names that are not valid UTF-8 + // work as well + deserializer.deserialize_bytes(NameVisitor) + } + } + }; +} + +/// The name of a network interface as accepted by the kernel. +/// +/// The kernel accepts names of 1 to 15 bytes, except `.` and `..`, without `/`, `:`, NUL and +/// whitespace (including `0xa0`). Names do not have to be valid UTF-8, so this stores bytes. +/// Every value of this type is accepted by the kernel. Unsafe code may rely on a name having 1 to +/// 15 bytes and no NUL byte. +/// +/// Serializing fails for names that are not valid UTF-8, since they cannot be represented as a +/// string. +/// +/// ``` +/// # use proxmox_network_types::network_interface::KernelNetworkInterfaceName; +/// let name: KernelNetworkInterfaceName = "wg*mesh".parse().unwrap(); +/// assert_eq!(name.to_str(), Ok("wg*mesh")); +/// +/// let name = KernelNetworkInterfaceName::try_from(&b"eth\xff"[..]).unwrap(); +/// assert!(name.to_str().is_err()); +/// assert_eq!(format!("{name:?}"), r#"KernelNetworkInterfaceName(b"eth\xff")"#); +/// +/// assert!("eth:0".parse::().is_err()); +/// ``` +#[derive(Clone, Copy)] +pub struct KernelNetworkInterfaceName { + len: u8, + bytes: [u8; IFNAMSIZ - 1], +} + +impl KernelNetworkInterfaceName { + /// # Safety + /// + /// `name` must pass `check_kernel_name()`. + unsafe fn from_bytes_unchecked(name: &[u8]) -> Self { + debug_assert_eq!(check_kernel_name(name), Ok(())); + + let mut bytes = [0; IFNAMSIZ - 1]; + bytes[..name.len()].copy_from_slice(name); + + Self { + len: name.len() as u8, + bytes, + } + } + + /// Returns the name as bytes, without the terminating NUL. + pub fn as_bytes(&self) -> &[u8] { + &self.bytes[..usize::from(self.len)] + } +} + +impl TryFrom<&[u8]> for KernelNetworkInterfaceName { + type Error = KernelNameError; + + fn try_from(name: &[u8]) -> Result { + check_kernel_name(name)?; + // SAFETY: checked above + Ok(unsafe { Self::from_bytes_unchecked(name) }) + } +} + +impl TryFrom> for KernelNetworkInterfaceName { + type Error = KernelNameError; + + fn try_from(name: Vec) -> Result { + Self::try_from(name.as_slice()) + } +} + +kernel_name_impls!(KernelNetworkInterfaceName, "network interface name"); + +/// An alternative name (altname) of a network interface as accepted by the kernel. +/// +/// The kernel only limits altnames to 127 bytes, any byte except NUL is allowed. Every value of +/// this type is accepted by the kernel. Unsafe code may rely on an altname having at most 127 +/// bytes and no NUL byte. Note that `ip` rejects the empty altname, and before iproute2 7.0 also +/// altnames with whitespace or `/`. +#[derive(Clone)] +pub struct KernelNetworkInterfaceAltname(Box<[u8]>); + +impl KernelNetworkInterfaceAltname { + /// # Safety + /// + /// `altname` must pass `check_kernel_altname()`. + unsafe fn from_boxed_unchecked(altname: Box<[u8]>) -> Self { + debug_assert_eq!(check_kernel_altname(&altname), Ok(())); + Self(altname) + } + + /// Returns the altname as bytes, without the terminating NUL. + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } +} + +impl TryFrom<&[u8]> for KernelNetworkInterfaceAltname { + type Error = KernelNameError; + + fn try_from(altname: &[u8]) -> Result { + check_kernel_altname(altname)?; + Ok(Self(altname.into())) + } +} + +impl TryFrom> for KernelNetworkInterfaceAltname { + type Error = KernelNameError; + + fn try_from(altname: Vec) -> Result { + check_kernel_altname(&altname)?; + Ok(Self(altname.into_boxed_slice())) + } +} + +kernel_name_impls!(KernelNetworkInterfaceAltname, "altname"); /// API types for network interface names. /// @@ -42,15 +366,26 @@ /// let name: NetworkInterfaceName = "eth0".parse().unwrap(); /// assert_eq!(NetworkInterfaceAltname::from(name).as_str(), "eth0"); /// ``` +/// +/// The API types convert into the kernel types, the other way around fails for names outside of +/// the API format: +/// +/// ``` +/// # use proxmox_network_types::network_interface::KernelNetworkInterfaceName; +/// # use proxmox_network_types::network_interface::api_types::NetworkInterfaceName; +/// let kernel_name: KernelNetworkInterfaceName = "wg*mesh".parse().unwrap(); +/// assert!(NetworkInterfaceName::try_from(kernel_name).is_err()); +/// +/// let name: NetworkInterfaceName = "wg-mesh".parse().unwrap(); +/// assert_eq!(KernelNetworkInterfaceName::from(name).as_bytes(), b"wg-mesh"); +/// ``` #[cfg(feature = "api-types")] pub mod api_types { - use proxmox_schema::{api, api_string_type, api_types::SAFE_ID_FORMAT}; + use anyhow::{Context, Error}; - /// The size of the kernel buffer for network interface names, including the terminating NUL. - const IFNAMSIZ: usize = 16; + use proxmox_schema::{ApiType, api, api_string_type, api_types::SAFE_ID_FORMAT}; - /// The size of the kernel buffer for altnames, including the terminating NUL. - const ALTIFNAMSIZ: usize = 128; + use super::{ALTIFNAMSIZ, IFNAMSIZ, KernelNetworkInterfaceAltname, KernelNetworkInterfaceName}; api_string_type! { #[api(format: &SAFE_ID_FORMAT, min_length: 1, max_length: IFNAMSIZ - 1)] @@ -87,6 +422,51 @@ pub mod api_types { } } + impl From for KernelNetworkInterfaceName { + fn from(name: NetworkInterfaceName) -> Self { + // SAFETY: the API format is a subset of what the kernel accepts + unsafe { Self::from_bytes_unchecked(name.as_str().as_bytes()) } + } + } + + impl From for KernelNetworkInterfaceAltname { + fn from(altname: NetworkInterfaceAltname) -> Self { + let altname = altname.into_string().into_bytes().into_boxed_slice(); + // SAFETY: the API format is a subset of what the kernel accepts + unsafe { Self::from_boxed_unchecked(altname) } + } + } + + impl TryFrom for NetworkInterfaceName { + type Error = Error; + + fn try_from(name: KernelNetworkInterfaceName) -> Result { + let name = name + .to_str() + .with_context(|| format!("{name:?} is not valid UTF-8"))?; + const { Self::API_SCHEMA.unwrap_string_schema() }.check_constraints(name)?; + + // SAFETY: checked against the schema above + Ok(unsafe { Self::from_string_unchecked(name.to_string()) }) + } + } + + impl TryFrom for NetworkInterfaceAltname { + type Error = Error; + + fn try_from(altname: KernelNetworkInterfaceAltname) -> Result { + let name = altname + .to_str() + .with_context(|| format!("{altname:?} is not valid UTF-8"))?; + const { Self::API_SCHEMA.unwrap_string_schema() }.check_constraints(name)?; + + // SAFETY: valid UTF-8 and checked against the schema above, this reuses the buffer + Ok(unsafe { + Self::from_string_unchecked(String::from_utf8_unchecked(altname.0.into_vec())) + }) + } + } + #[cfg(test)] mod tests { use super::*; @@ -178,5 +558,280 @@ pub mod api_types { assert!(serde_plain::from_str::("eth0:1").is_err()); } + + // the unchecked conversions into the kernel types are checked by a debug assertion + #[test] + fn api_names_are_kernel_names() { + for name in ["a", "eth0", "_x-1.2", "abcdefghijklmno"] { + let name: NetworkInterfaceName = name.parse().expect(name); + let kernel_name = KernelNetworkInterfaceName::from(name.clone()); + assert_eq!(kernel_name.as_bytes(), name.as_str().as_bytes()); + assert_eq!(NetworkInterfaceName::try_from(kernel_name).ok(), Some(name)); + } + } + + #[test] + fn api_altnames_are_kernel_altnames() { + let longest = "a".repeat(ALTIFNAMSIZ - 1); + + for altname in ["eth0", "enx0123456789abcd", longest.as_str()] { + let altname: NetworkInterfaceAltname = altname.parse().expect(altname); + let kernel_altname = KernelNetworkInterfaceAltname::from(altname.clone()); + assert_eq!(kernel_altname.as_bytes(), altname.as_str().as_bytes()); + assert_eq!( + NetworkInterfaceAltname::try_from(kernel_altname).ok(), + Some(altname) + ); + } + } + + #[test] + fn kernel_names_outside_of_the_api_format() { + for name in [ + &b"-eth0"[..], + b"a*b", + b"ctl\x01x", + "abcdefghijklm\u{e9}".as_bytes(), + b"eth\xff", + ] { + let kernel_name = KernelNetworkInterfaceName::try_from(name).expect("kernel name"); + assert!( + NetworkInterfaceName::try_from(kernel_name).is_err(), + "{kernel_name:?}" + ); + } + + for altname in [&b""[..], b"sp ace", b"a/b", b"a\xffb"] { + let kernel_altname = + KernelNetworkInterfaceAltname::try_from(altname).expect("kernel altname"); + assert!( + NetworkInterfaceAltname::try_from(kernel_altname.clone()).is_err(), + "{kernel_altname:?}" + ); + } + } + } +} + +#[cfg(test)] +mod tests { + use serde::de::IntoDeserializer; + use serde::de::value::{BytesDeserializer, Error as ValueError}; + + use super::*; + + #[test] + fn parse_kernel_network_interface_name() { + for name in [ + &b"eth0"[..], + b"wg-mesh", + b"-eth0", + b"a*b", + b"a.b.c", + b"eth0.", + b"ctl\x01x", + // U+00E9 is 0xc3 0xa9, so the name has 15 bytes + "abcdefghijklm\u{e9}".as_bytes(), + // none of their bytes is 0xa0 + "a\u{121}b".as_bytes(), + "a\u{840}b".as_bytes(), + "a\u{1f600}b".as_bytes(), + // names do not have to be valid UTF-8 + b"eth\xff", + b"\xc3", + ] { + let parsed = KernelNetworkInterfaceName::try_from(name).expect("valid name"); + assert_eq!(parsed.as_bytes(), name); + assert_eq!( + KernelNetworkInterfaceName::try_from(name.to_vec()), + Ok(parsed) + ); + } + + for name in [ + &b""[..], + b".", + b"..", + b"eth0/1", + b"eth0:1", + b"eth 0", + b"eth0\t", + b"eth\0", + // the kernel treats 0xa0 as whitespace, U+00E0 is 0xc3 0xa0 + "a\u{e0}b".as_bytes(), + b"a\xa0b", + "a\u{120}b".as_bytes(), + "a\u{160}b".as_bytes(), + "a\u{1e0}b".as_bytes(), + // 0xa0 can also be a middle byte, U+0800 is 0xe0 0xa0 0x80 + "a\u{800}b".as_bytes(), + "a\u{10800}b".as_bytes(), + b"abcdefghijklmnop", + // 16 bytes, but only 15 characters + "abcdefghijklmn\u{e9}".as_bytes(), + ] { + assert!( + KernelNetworkInterfaceName::try_from(name).is_err(), + "{name:?}" + ); + } + + assert_eq!( + "eth0:1".parse::(), + Err(KernelNameError::InvalidByte(b':')) + ); + assert_eq!( + "abcdefghijklmnop".parse::(), + Err(KernelNameError::TooLong { len: 16, max: 15 }) + ); + } + + #[test] + fn kernel_rejects_code_points_with_a_group_of_0x20() { + // the rule described at is_kernel_space(), checked against every code point + for c in (0x80..=char::MAX as u32).filter_map(char::from_u32) { + let code_point = c as u32; + + let groups = match c.len_utf8() { + 2 => vec![code_point & 0x3f], + 3 => vec![code_point & 0x3f, (code_point >> 6) & 0x3f], + _ => vec![ + code_point & 0x3f, + (code_point >> 6) & 0x3f, + (code_point >> 12) & 0x3f, + ], + }; + + let name = format!("a{c}"); + assert_eq!( + name.parse::().is_ok(), + !groups.contains(&0x20), + "U+{code_point:04X}" + ); + } + } + + #[test] + fn parse_kernel_network_interface_altname() { + let longest = "a".repeat(ALTIFNAMSIZ - 1); + // 63 times U+00E9 (2 bytes each) and one 'a' are 127 bytes + let longest_utf8 = format!("{}a", "\u{e9}".repeat(63)); + + for altname in [ + &b""[..], + b"sp ace/x:y", + b"c\x01x", + "a\u{e0}b".as_bytes(), + b"a\xa0b", + b"a\xffb", + longest.as_bytes(), + longest_utf8.as_bytes(), + ] { + let parsed = KernelNetworkInterfaceAltname::try_from(altname).expect("valid altname"); + assert_eq!(parsed.as_bytes(), altname); + assert_eq!( + KernelNetworkInterfaceAltname::try_from(altname.to_vec()), + Ok(parsed) + ); + } + + let too_long = "a".repeat(ALTIFNAMSIZ); + let too_long_utf8 = "\u{e9}".repeat(64); + + for altname in [&b"a\0b"[..], too_long.as_bytes(), too_long_utf8.as_bytes()] { + assert!( + KernelNetworkInterfaceAltname::try_from(altname).is_err(), + "{altname:?}" + ); + } + } + + #[test] + fn debug_kernel_network_interface_name() { + for (name, debug) in [ + (&b"eth0"[..], r#"KernelNetworkInterfaceName("eth0")"#), + ( + "\u{e9}th0".as_bytes(), + "KernelNetworkInterfaceName(\"\u{e9}th0\")", + ), + (b"c\x01\\x", r#"KernelNetworkInterfaceName("c\u{1}\\x")"#), + ( + "x\u{200b}y".as_bytes(), + r#"KernelNetworkInterfaceName("x\u{200b}y")"#, + ), + (b"eth\xff", r#"KernelNetworkInterfaceName(b"eth\xff")"#), + ] { + let name = KernelNetworkInterfaceName::try_from(name).expect("valid name"); + assert_eq!(format!("{name:?}"), debug); + } + } + + #[test] + fn compare_kernel_network_interface_names() { + let names: Vec = ["b", "ab", "a", "eth1", "eth0"] + .into_iter() + .map(|name| name.parse().expect(name)) + .collect(); + + let mut sorted = names.clone(); + sorted.sort(); + assert_eq!( + sorted + .iter() + .map(|name| name.as_bytes()) + .collect::>(), + [&b"a"[..], b"ab", b"b", b"eth0", b"eth1"] + ); + + let set: std::collections::HashSet<_> = names.iter().chain(&names).collect(); + assert_eq!(set.len(), names.len()); + } + + #[test] + fn deserialize_kernel_network_interface_name() { + let name = KernelNetworkInterfaceName::deserialize(BytesDeserializer::::new( + b"eth\xff", + )) + .expect("valid name"); + assert_eq!(name.as_bytes(), b"eth\xff"); + + let name = KernelNetworkInterfaceName::deserialize( + IntoDeserializer::::into_deserializer("c\u{1}x"), + ) + .expect("valid name"); + assert_eq!(name.as_bytes(), b"c\x01x"); + + assert!( + KernelNetworkInterfaceName::deserialize(BytesDeserializer::::new(b"eth:0")) + .is_err() + ); + + let altname = KernelNetworkInterfaceAltname::deserialize( + BytesDeserializer::::new(b"sp ace\xff"), + ) + .expect("valid altname"); + assert_eq!(altname.as_bytes(), b"sp ace\xff"); + } + + #[test] + fn serialize_kernel_network_interface_name() { + let name: KernelNetworkInterfaceName = "c\u{1}x".parse().expect("valid name"); + assert_eq!( + serde_plain::to_string(&name).expect("serializable"), + "c\u{1}x" + ); + + let name = KernelNetworkInterfaceName::try_from(&b"eth\xff"[..]).expect("valid name"); + assert!(serde_plain::to_string(&name).is_err()); + + let altname: KernelNetworkInterfaceAltname = "sp ace".parse().expect("valid altname"); + assert_eq!( + serde_plain::to_string(&altname).expect("serializable"), + "sp ace" + ); + + let altname = + KernelNetworkInterfaceAltname::try_from(&b"a\xffb"[..]).expect("valid altname"); + assert!(serde_plain::to_string(&altname).is_err()); } } -- 2.47.3