all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Christoph Heiss <c.heiss@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH proxmox v2 3/8] network-types: add ServiceEndpoint type as host/port tuple abstraction
Date: Fri, 13 Feb 2026 15:35:56 +0100	[thread overview]
Message-ID: <20260213143601.1424613-4-c.heiss@proxmox.com> (raw)
In-Reply-To: <20260213143601.1424613-1-c.heiss@proxmox.com>

Basically a composite data type to provide bit of an better abstraction
to a tuple (host, port).

Signed-off-by: Christoph Heiss <c.heiss@proxmox.com>
---
Changes v1 -> v2:
  * forward to `Display` impl directly where possible

 proxmox-network-types/src/endpoint.rs | 154 ++++++++++++++++++++++++++
 proxmox-network-types/src/lib.rs      |   3 +-
 2 files changed, 156 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-network-types/src/endpoint.rs

diff --git a/proxmox-network-types/src/endpoint.rs b/proxmox-network-types/src/endpoint.rs
new file mode 100644
index 00000000..10f6a813
--- /dev/null
+++ b/proxmox-network-types/src/endpoint.rs
@@ -0,0 +1,154 @@
+//! Implements a wrapper around a (host, port) tuple, where host can either
+//! be a plain IP address or a resolvable hostname.
+
+use std::{
+    fmt::{self, Display},
+    net::IpAddr,
+    str::FromStr,
+};
+
+use serde_with::{DeserializeFromStr, SerializeDisplay};
+
+/// Represents either a resolvable hostname or an IPv4/IPv6 address.
+/// IPv6 address are correctly bracketed on [`Display`], and parsing
+/// automatically tries parsing it as an IP address first, falling back to a
+/// plain hostname in the other case.
+#[derive(Clone, Debug, PartialEq)]
+pub enum HostnameOrIpAddr {
+    Hostname(String),
+    IpAddr(IpAddr),
+}
+
+impl Display for HostnameOrIpAddr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            HostnameOrIpAddr::Hostname(s) => Display::fmt(s, f),
+            HostnameOrIpAddr::IpAddr(addr) => match addr {
+                IpAddr::V4(v4) => Display::fmt(v4, f),
+                IpAddr::V6(v6) => write!(f, "[{v6}]"),
+            },
+        }
+    }
+}
+
+impl<S: Into<String>> From<S> for HostnameOrIpAddr {
+    fn from(value: S) -> Self {
+        let s = value.into();
+        if let Ok(ip_addr) = IpAddr::from_str(&s) {
+            Self::IpAddr(ip_addr)
+        } else {
+            Self::Hostname(s)
+        }
+    }
+}
+
+/// Represents a (host, port) tuple, where the host can either be a resolvable
+/// hostname or an IPv4/IPv6 address.
+#[derive(Clone, Debug, PartialEq, SerializeDisplay, DeserializeFromStr)]
+pub struct ServiceEndpoint {
+    host: HostnameOrIpAddr,
+    port: u16,
+}
+
+impl ServiceEndpoint {
+    pub fn new<S: Into<String>>(host: S, port: u16) -> Self {
+        let s = host.into();
+        Self {
+            host: s.into(),
+            port,
+        }
+    }
+}
+
+impl Display for ServiceEndpoint {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "{}:{}", self.host, self.port)
+    }
+}
+
+#[derive(thiserror::Error, Debug)]
+pub enum ParseError {
+    #[error("host and port must be separated by a colon")]
+    MissingSeparator,
+    #[error("host part missing")]
+    MissingHost,
+    #[error("invalid port: {0}")]
+    InvalidPort(String),
+}
+
+impl FromStr for ServiceEndpoint {
+    type Err = ParseError;
+
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        let (mut host, port) = s.rsplit_once(':').ok_or(Self::Err::MissingSeparator)?;
+
+        if host.is_empty() {
+            return Err(Self::Err::MissingHost);
+        }
+
+        // [ and ] are not valid characters in a hostname, so strip them in case it
+        // is a IPv6 address.
+        host = host.trim_matches(['[', ']']);
+
+        Ok(ServiceEndpoint {
+            host: host.into(),
+            port: port
+                .parse()
+                .map_err(|err: std::num::ParseIntError| Self::Err::InvalidPort(err.to_string()))?,
+        })
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use crate::endpoint::HostnameOrIpAddr;
+
+    use super::ServiceEndpoint;
+
+    #[test]
+    fn display_works() {
+        let s = ServiceEndpoint::new("127.0.0.1", 123);
+        assert_eq!(s.to_string(), "127.0.0.1:123");
+
+        let s = ServiceEndpoint::new("fc00:f00d::4321", 123);
+        assert_eq!(s.to_string(), "[fc00:f00d::4321]:123");
+
+        let s = ServiceEndpoint::new("::", 123);
+        assert_eq!(s.to_string(), "[::]:123");
+
+        let s = ServiceEndpoint::new("fc00::", 123);
+        assert_eq!(s.to_string(), "[fc00::]:123");
+
+        let s = ServiceEndpoint::new("example.com", 123);
+        assert_eq!(s.to_string(), "example.com:123");
+    }
+
+    #[test]
+    fn fromstr_works() {
+        assert_eq!(
+            "127.0.0.1:123".parse::<ServiceEndpoint>().unwrap(),
+            ServiceEndpoint {
+                host: HostnameOrIpAddr::IpAddr([127, 0, 0, 1].into()),
+                port: 123
+            }
+        );
+
+        assert_eq!(
+            "[::1]:123".parse::<ServiceEndpoint>().unwrap(),
+            ServiceEndpoint {
+                host: HostnameOrIpAddr::IpAddr(
+                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1].into()
+                ),
+                port: 123
+            }
+        );
+
+        assert_eq!(
+            "example.com:123".parse::<ServiceEndpoint>().unwrap(),
+            ServiceEndpoint {
+                host: HostnameOrIpAddr::Hostname("example.com".to_owned()),
+                port: 123
+            }
+        );
+    }
+}
diff --git a/proxmox-network-types/src/lib.rs b/proxmox-network-types/src/lib.rs
index ee26b1c1..1bacbaf3 100644
--- a/proxmox-network-types/src/lib.rs
+++ b/proxmox-network-types/src/lib.rs
@@ -1,5 +1,6 @@
 #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
-#![deny(unsafe_op_in_unsafe_fn)]
+#![deny(unsafe_code, unsafe_op_in_unsafe_fn)]
 
+pub mod endpoint;
 pub mod ip_address;
 pub mod mac_address;
-- 
2.52.0





  parent reply	other threads:[~2026-02-13 14:35 UTC|newest]

Thread overview: 9+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-02-13 14:35 [PATCH proxmox v2 0/8] sdn: add wireguard fabric configuration support Christoph Heiss
2026-02-13 14:35 ` [PATCH proxmox v2 1/8] serde: implement ini serializer Christoph Heiss
2026-02-13 14:35 ` [PATCH proxmox v2 2/8] serde: add base64 module for byte arrays Christoph Heiss
2026-02-13 14:35 ` Christoph Heiss [this message]
2026-02-13 14:35 ` [PATCH proxmox v2 4/8] schema: provide integer schema for node ports Christoph Heiss
2026-02-13 14:35 ` [PATCH proxmox v2 5/8] schema: api-types: add ed25519 base64 encoded key schema Christoph Heiss
2026-02-13 14:35 ` [PATCH proxmox v2 6/8] wireguard: init configuration support crate Christoph Heiss
2026-02-13 14:36 ` [PATCH proxmox v2 7/8] wireguard: implement api for PublicKey Christoph Heiss
2026-02-13 14:36 ` [PATCH proxmox v2 8/8] wireguard: make per-peer preshared key optional Christoph Heiss

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260213143601.1424613-4-c.heiss@proxmox.com \
    --to=c.heiss@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal