1use std::borrow::Cow;
16use std::fmt;
17
18use serde::{Deserialize, Serialize};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
23#[serde(transparent)]
24pub struct GuestPort(u16);
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
30#[serde(transparent)]
31pub struct HostPort(u16);
32
33impl GuestPort {
34 #[must_use]
36 pub const fn new(number: u16) -> GuestPort {
37 GuestPort(number)
38 }
39
40 #[must_use]
42 pub const fn get(self) -> u16 {
43 self.0
44 }
45}
46
47impl HostPort {
48 #[must_use]
50 pub const fn new(number: u16) -> HostPort {
51 HostPort(number)
52 }
53
54 #[must_use]
56 pub const fn get(self) -> u16 {
57 self.0
58 }
59}
60
61macro_rules! number_schema {
64 ($port:ident) => {
65 impl schemars::JsonSchema for $port {
66 fn inline_schema() -> bool {
67 true
68 }
69
70 fn schema_name() -> Cow<'static, str> {
71 Cow::Borrowed(stringify!($port))
72 }
73
74 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
75 u16::json_schema(generator)
76 }
77 }
78 };
79}
80
81number_schema!(GuestPort);
82number_schema!(HostPort);
83
84impl fmt::Display for GuestPort {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 self.0.fmt(f)
87 }
88}
89
90impl fmt::Display for HostPort {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 self.0.fmt(f)
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn each_kind_reads_and_writes_as_the_bare_number() {
102 assert_eq!(serde_json::to_string(&HostPort::new(41873)).unwrap(), "41873");
103 assert_eq!(serde_json::to_string(&GuestPort::new(80)).unwrap(), "80");
104 assert_eq!(serde_json::from_str::<HostPort>("8080").unwrap(), HostPort::new(8080));
105 }
106
107 #[test]
108 fn each_kind_has_the_bare_numbers_schema() {
109 let number = serde_json::to_value(schemars::schema_for!(u16)).unwrap();
110 for schema in [schemars::schema_for!(HostPort), schemars::schema_for!(GuestPort)] {
111 let mut schema = serde_json::to_value(schema).unwrap();
112 let mut number = number.clone();
113 for s in [&mut schema, &mut number] {
114 let fields = s.as_object_mut().unwrap();
115 fields.remove("title");
116 fields.remove("description");
117 }
118 assert_eq!(schema, number);
119 }
120 }
121}