Просмотр исходного кода

Generalize PartialEq impl for Host

This allows `Host<String>` to be compared with a `Host<&str>`.
Matt Brubeck 5 лет назад
Родитель
Сommit
31bc0da54c
2 измененных файлов с 18 добавлено и 1 удалено
  1. 15 1
      url/src/host.rs
  2. 3 0
      url/tests/unit.rs

+ 15 - 1
url/src/host.rs

@@ -38,7 +38,7 @@ impl From<Host<String>> for HostInternal {
 
 /// The host name of an URL.
 #[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
-#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
+#[derive(Clone, Debug, Eq, Ord, PartialOrd, Hash)]
 pub enum Host<S = String> {
     /// A DNS domain name, as '.' dot-separated labels.
     /// Non-ASCII labels are encoded in punycode per IDNA if this is the host of
@@ -172,6 +172,20 @@ impl<S: AsRef<str>> fmt::Display for Host<S> {
     }
 }
 
+impl<S, T> PartialEq<Host<T>> for Host<S>
+where
+    S: PartialEq<T>,
+{
+    fn eq(&self, other: &Host<T>) -> bool {
+        match (self, other) {
+            (Host::Domain(a), Host::Domain(b)) => a == b,
+            (Host::Ipv4(a), Host::Ipv4(b)) => a == b,
+            (Host::Ipv6(a), Host::Ipv6(b)) => a == b,
+            (_, _) => false,
+        }
+    }
+}
+
 fn write_ipv6(addr: &Ipv6Addr, f: &mut Formatter<'_>) -> fmt::Result {
     let segments = addr.segments();
     let (compress_start, compress_end) = longest_zero_sequence(&segments);

+ 3 - 0
url/tests/unit.rs

@@ -274,6 +274,9 @@ fn host() {
     assert_host("http://2..2.3", Host::Domain("2..2.3"));
     assert!(Url::parse("http://42.0x1232131").is_err());
     assert!(Url::parse("http://192.168.0.257").is_err());
+
+    assert_eq!(Host::Domain("foo"), Host::Domain("foo").to_owned());
+    assert_ne!(Host::Domain("foo"), Host::Domain("bar").to_owned());
 }
 
 #[test]