async_dnssd/
interface.rs

1use std::fmt;
2
3use crate::ffi;
4
5/// Network interface index
6///
7/// Identifies a single interface by index.
8#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct InterfaceIndex(u32);
10
11impl InterfaceIndex {
12	/// Construct new `InterfaceIndex` from raw index and makes sure
13	/// not to use the special reserved values.
14	pub fn from_raw(ndx: u32) -> Option<Self> {
15		match ndx {
16			ffi::INTERFACE_INDEX_ANY => None,
17			ffi::INTERFACE_INDEX_LOCAL_ONLY => None,
18			ffi::INTERFACE_INDEX_UNICAST => None,
19			ffi::INTERFACE_INDEX_P2P => None,
20			_ => Some(Self(ndx)),
21		}
22	}
23
24	/// raw index
25	pub fn into_raw(self) -> u32 {
26		self.0
27	}
28}
29
30impl From<InterfaceIndex> for u32 {
31	fn from(ndx: InterfaceIndex) -> Self {
32		ndx.into_raw()
33	}
34}
35
36impl fmt::Debug for InterfaceIndex {
37	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38		fmt::Debug::fmt(&self.0, f)
39	}
40}
41
42/// Network interface
43///
44/// Either identifies a single interface (by index) or the special "Any"
45/// or "LocalOnly" interfaces.
46#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
47#[non_exhaustive]
48pub enum Interface {
49	/// Any interface; depending on domain name this means either
50	/// multicast or unicast
51	Any,
52	/// Single interface
53	Index(InterfaceIndex),
54	/// Local machine only
55	LocalOnly,
56	/// See [`kDNSServiceInterfaceIndexUnicast`](https://developer.apple.com/documentation/dnssd/kdnsserviceinterfaceindexunicast)
57	Unicast,
58	/// See [`kDNSServiceInterfaceIndexP2P`](https://developer.apple.com/documentation/dnssd/kdnsserviceinterfaceindexp2p)
59	PeerToPeer,
60}
61
62impl Default for Interface {
63	fn default() -> Self {
64		Self::Any
65	}
66}
67
68impl Interface {
69	/// Construct from raw value
70	pub fn from_raw(raw: u32) -> Self {
71		match raw {
72			ffi::INTERFACE_INDEX_ANY => Self::Any,
73			ffi::INTERFACE_INDEX_LOCAL_ONLY => Self::LocalOnly,
74			ffi::INTERFACE_INDEX_UNICAST => Self::Unicast,
75			ffi::INTERFACE_INDEX_P2P => Self::PeerToPeer,
76			_ => Self::Index(InterfaceIndex(raw)),
77		}
78	}
79
80	/// Convert to raw value
81	pub fn into_raw(self) -> u32 {
82		match self {
83			Self::Any => ffi::INTERFACE_INDEX_ANY,
84			Self::Index(InterfaceIndex(raw)) => raw,
85			Self::LocalOnly => ffi::INTERFACE_INDEX_LOCAL_ONLY,
86			Self::Unicast => ffi::INTERFACE_INDEX_UNICAST,
87			Self::PeerToPeer => ffi::INTERFACE_INDEX_P2P,
88		}
89	}
90
91	/// Extract scope id / interface index
92	///
93	/// Returns the interface index (or zero if not a single interface is selected)
94	pub fn scope_id(self) -> u32 {
95		match self {
96			Self::Index(InterfaceIndex(scope_id)) => scope_id,
97			_ => 0,
98		}
99	}
100}
101
102impl From<Interface> for u32 {
103	fn from(i: Interface) -> u32 {
104		i.into_raw()
105	}
106}