From 6650e9aeeb3b61e9150f09d897035fc916e1325a Mon Sep 17 00:00:00 2001 From: Josh Leeb-du Toit Date: Thu, 20 Sep 2018 21:53:02 +1000 Subject: [PATCH] Add trait impls for uri::Port --- src/uri/port.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 46 insertions(+), 4 deletions(-) diff --git a/src/uri/port.rs b/src/uri/port.rs index 76501b93..88ddb0b0 100644 --- a/src/uri/port.rs +++ b/src/uri/port.rs @@ -20,7 +20,7 @@ impl<'a> Port<'a> { /// /// # Examples /// - /// Port as `u16` + /// Port as `u16`. /// /// ``` /// # use http::uri::Authority; @@ -51,14 +51,56 @@ impl<'a> Port<'a> { } } +impl<'a> fmt::Display for Port<'a> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}", self.bytes) + } +} + +impl<'a> From> for u16 { + fn from(port: Port) -> Self { + port.as_u16() + } +} + +impl<'a> AsRef for Port<'a> { + fn as_ref(&self) -> &str { + self.as_str() + } +} + impl<'a> PartialEq for Port<'a> { fn eq(&self, other: &Self) -> bool { self.port == other.port } } -impl<'a> fmt::Display for Port<'a> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "{}", self.bytes) +impl<'a> PartialEq for Port<'a> { + fn eq(&self, other: &u16) -> bool { + self.port == *other + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn partialeq_port() { + let port_a = Port::from_str("8080").unwrap(); + let port_b = Port::from_str("8080").unwrap(); + assert_eq!(port_a, port_b); + } + + #[test] + fn partialeq_u16() { + let port = Port::from_str("8080").unwrap(); + assert_eq!(port, 8080u16); + } + + #[test] + fn u16_from_port() { + let port = Port::from_str("8080").unwrap(); + assert_eq!(8080, u16::from(port)); } }