Skip to content

Commit 4260325

Browse files
committed
derive hash trait for Origin
1 parent cb8330d commit 4260325

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/origin.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ pub fn url_origin(url: &Url) -> Origin {
5050
/// the URL does not have the same origin as any other URL.
5151
///
5252
/// For more information see https://url.spec.whatwg.org/#origin
53-
#[derive(PartialEq, Eq, Clone, Debug)]
53+
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
5454
pub enum Origin {
5555
/// A globally unique identifier
5656
Opaque(OpaqueOrigin),
@@ -123,7 +123,7 @@ impl Origin {
123123
}
124124

125125
/// Opaque identifier for URLs that have file or other schemes
126-
#[derive(Eq, PartialEq, Clone, Debug)]
126+
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
127127
pub struct OpaqueOrigin(usize);
128128

129129
#[cfg(feature = "heapsize")]

tests/unit.rs

+42
Original file line numberDiff line numberDiff line change
@@ -372,3 +372,45 @@ fn define_encode_set_scopes() {
372372

373373
m::test();
374374
}
375+
376+
#[test]
377+
/// https://github.com/servo/rust-url/issues/302
378+
fn test_origin_hash() {
379+
use std::hash::{Hash,Hasher};
380+
use std::collections::hash_map::DefaultHasher;
381+
382+
fn hash<T: Hash>(value: &T) -> u64 {
383+
let mut hasher = DefaultHasher::new();
384+
value.hash(&mut hasher);
385+
hasher.finish()
386+
}
387+
388+
let origin = &Url::parse("http://example.net/").unwrap().origin();
389+
390+
let origins_to_compare = [
391+
Url::parse("http://example.net:80/").unwrap().origin(),
392+
Url::parse("http://example.net:81/").unwrap().origin(),
393+
Url::parse("http://example.net").unwrap().origin(),
394+
Url::parse("http://example.net/hello").unwrap().origin(),
395+
Url::parse("https://example.net").unwrap().origin(),
396+
Url::parse("ftp://example.net").unwrap().origin(),
397+
Url::parse("file://example.net").unwrap().origin(),
398+
Url::parse("http://user@example.net/").unwrap().origin(),
399+
Url::parse("http://user:pass@example.net/").unwrap().origin(),
400+
];
401+
402+
for origin_to_compare in &origins_to_compare {
403+
if origin == origin_to_compare {
404+
assert_eq!(hash(origin), hash(origin_to_compare));
405+
} else {
406+
assert_ne!(hash(origin), hash(origin_to_compare));
407+
}
408+
}
409+
410+
let opaque_origin = Url::parse("file://example.net").unwrap().origin();
411+
let same_opaque_origin = Url::parse("file://example.net").unwrap().origin();
412+
let other_opaque_origin = Url::parse("file://other").unwrap().origin();
413+
414+
assert_ne!(hash(&opaque_origin), hash(&same_opaque_origin));
415+
assert_ne!(hash(&opaque_origin), hash(&other_opaque_origin));
416+
}

0 commit comments

Comments
 (0)