From c4a18d91e04779a3db3ada396898e227ec326dcc Mon Sep 17 00:00:00 2001 From: xgbtxy <115146404+xgbtxy@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:40:37 +0800 Subject: [PATCH] fix(uri): make PathAndQuery PartialEq and Hash consistent with as_str and PartialOrd PathAndQuery::as_str(), PartialEq, and PartialOrd already normalize an empty internal buffer to "/", while PartialEq and Hash compared and hashed self.data directly. As a result, an empty PathAndQuery (such as from Uri::builder().path_and_query("") or fragment-only inputs like "#frag") compared PartialOrd::Equal to PathAndQuery::from_static("/") yet returned false for == and produced a different Hash, violating the PartialOrd/PartialEq and Eq/Hash contracts. Use self.as_str() in both PartialEq and Hash implementations and add regression tests covering empty, fragment-only, and builder-constructed values. Signed-off-by: Yan Chen --- src/uri/path.rs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/uri/path.rs b/src/uri/path.rs index f62a6867..cf5350e6 100644 --- a/src/uri/path.rs +++ b/src/uri/path.rs @@ -292,7 +292,7 @@ impl fmt::Display for PathAndQuery { impl hash::Hash for PathAndQuery { fn hash(&self, state: &mut H) { - self.data.hash(state); + self.as_str().hash(state); } } @@ -301,7 +301,7 @@ impl hash::Hash for PathAndQuery { impl PartialEq for PathAndQuery { #[inline] fn eq(&self, other: &PathAndQuery) -> bool { - self.data == other.data + self.as_str() == other.as_str() } } @@ -703,6 +703,41 @@ mod tests { ); } + #[test] + fn empty_and_slash_eq_hash_ord_consistent() { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + fn hash_of(pq: &PathAndQuery) -> u64 { + let mut hasher = DefaultHasher::new(); + pq.hash(&mut hasher); + hasher.finish() + } + + let slash = PathAndQuery::from_static("/"); + let empty = PathAndQuery::empty(); + let frag_only = pq("#frag"); + let built = crate::Uri::builder() + .scheme("http") + .authority("example.com") + .path_and_query("") + .build() + .unwrap(); + let parsed = crate::Uri::from_static("http://example.com/"); + + for other in [&empty, &frag_only, built.path_and_query().unwrap()] { + assert_eq!(other.as_str(), "/"); + assert_eq!(other.partial_cmp(&slash), Some(cmp::Ordering::Equal)); + assert_eq!(slash.partial_cmp(other), Some(cmp::Ordering::Equal)); + assert_eq!(other, &slash); + assert_eq!(&slash, other); + assert_eq!(hash_of(other), hash_of(&slash)); + } + + assert_eq!(built, parsed); + assert_eq!(built.path_and_query(), parsed.path_and_query()); + } + fn pq(s: &str) -> PathAndQuery { s.parse().expect(&format!("parsing {}", s)) }