Skip to main content

lab_ops_lab_lib/
protocol.rs

1//! Transport protocol enum (TCP / UDP).
2//!
3//! Canonical representation shared across the workspace. Previously defined
4//! in natmap's `models.rs`; extracted here so auto-discover can use it without
5//! depending on natmap.
6
7use std::fmt::Display;
8
9use serde::Deserialize;
10use serde::Serialize;
11
12/// Transport protocol (TCP or UDP).
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash, Default)]
14#[serde(rename_all = "lowercase")]
15pub enum TransportProtocol {
16    #[default]
17    Tcp,
18    Udp,
19}
20
21impl std::str::FromStr for TransportProtocol {
22    type Err = color_eyre::eyre::Error;
23    fn from_str(s: &str) -> Result<Self, Self::Err> {
24        match s {
25            "tcp" => Ok(Self::Tcp),
26            "udp" => Ok(Self::Udp),
27            _ => Err(color_eyre::eyre::eyre!("Invalid transport protocol {s}")),
28        }
29    }
30}
31
32impl TransportProtocol {
33    /// Returns the lowercase protocol name.
34    pub fn to_lowercase(&self) -> &'static str {
35        match self {
36            Self::Tcp => "tcp",
37            Self::Udp => "udp",
38        }
39    }
40}
41
42impl Display for TransportProtocol {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        write!(f, "{}", self.to_lowercase())
45    }
46}