use std::borrow::Cow;
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct GuestPort(u16);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HostPort(u16);
impl GuestPort {
#[must_use]
pub const fn new(number: u16) -> GuestPort {
GuestPort(number)
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
impl HostPort {
#[must_use]
pub const fn new(number: u16) -> HostPort {
HostPort(number)
}
#[must_use]
pub const fn get(self) -> u16 {
self.0
}
}
macro_rules! number_schema {
($port:ident) => {
impl schemars::JsonSchema for $port {
fn inline_schema() -> bool {
true
}
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed(stringify!($port))
}
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
u16::json_schema(generator)
}
}
};
}
number_schema!(GuestPort);
number_schema!(HostPort);
impl fmt::Display for GuestPort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for HostPort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_kind_reads_and_writes_as_the_bare_number() {
assert_eq!(serde_json::to_string(&HostPort::new(41873)).unwrap(), "41873");
assert_eq!(serde_json::to_string(&GuestPort::new(80)).unwrap(), "80");
assert_eq!(serde_json::from_str::<HostPort>("8080").unwrap(), HostPort::new(8080));
}
#[test]
fn each_kind_has_the_bare_numbers_schema() {
let number = serde_json::to_value(schemars::schema_for!(u16)).unwrap();
for schema in [schemars::schema_for!(HostPort), schemars::schema_for!(GuestPort)] {
let mut schema = serde_json::to_value(schema).unwrap();
let mut number = number.clone();
for s in [&mut schema, &mut number] {
let fields = s.as_object_mut().unwrap();
fields.remove("title");
fields.remove("description");
}
assert_eq!(schema, number);
}
}
}