Skip to main content

web_url/url/
compare.rs

1use std::cmp::Ordering;
2use std::hash::{Hash, Hasher};
3
4use crate::WebUrl;
5
6impl Ord for WebUrl {
7    fn cmp(&self, other: &Self) -> Ordering {
8        self.url.cmp(&other.url)
9    }
10}
11
12impl PartialOrd for WebUrl {
13    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
14        Some(self.cmp(other))
15    }
16}
17
18impl Eq for WebUrl {}
19
20impl PartialEq for WebUrl {
21    fn eq(&self, other: &Self) -> bool {
22        self.url.eq(&other.url)
23    }
24}
25
26impl Hash for WebUrl {
27    fn hash<H: Hasher>(&self, state: &mut H) {
28        self.url.hash(state)
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use std::collections::hash_map::DefaultHasher;
35    use std::hash::{Hash, Hasher};
36    use std::str::FromStr;
37
38    use crate::WebUrl;
39
40    fn hash_of(url: &WebUrl) -> u64 {
41        let mut hasher = DefaultHasher::new();
42        url.hash(&mut hasher);
43        hasher.finish()
44    }
45
46    #[test]
47    fn eq() {
48        let a = WebUrl::from_str("https://example.com").unwrap();
49        let b = WebUrl::from_str("https://example.com").unwrap();
50        let c = WebUrl::from_str("https://other.com").unwrap();
51
52        assert_eq!(a, b);
53        assert_ne!(a, c);
54    }
55
56    #[test]
57    fn ord() {
58        let a = WebUrl::from_str("https://aaa.com").unwrap();
59        let b = WebUrl::from_str("https://bbb.com").unwrap();
60
61        assert!(a < b);
62        assert!(b > a);
63        assert_eq!(a.partial_cmp(&b), Some(std::cmp::Ordering::Less));
64    }
65
66    #[test]
67    fn hash() {
68        let a = WebUrl::from_str("https://example.com").unwrap();
69        let b = WebUrl::from_str("https://example.com").unwrap();
70
71        assert_eq!(hash_of(&a), hash_of(&b));
72    }
73}