1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
45use md5::{Digest, Md5};
6use url::{Host, Url};
78pub type UrlHash = [u8; 16];
910/// Given a URL, extract the part of it that we want to use to identify it.
11pub fn url_hash_source(url: &str) -> Option<String> {
12// We currently use the final 2 components of the URL domain.
13const URL_COMPONENTS_TO_USE: usize = 2;
1415let url = Url::parse(url).ok()?;
16let domain = match url.host() {
17Some(Host::Domain(d)) => d,
18_ => return None,
19 };
20// This will store indexes of `.` chars as we search backwards.
21let mut pos = domain.len();
22for _ in 0..URL_COMPONENTS_TO_USE {
23match domain[0..pos].rfind('.') {
24Some(p) => pos = p,
25// The domain has less than 3 dots, return it all
26None => return Some(domain.to_owned()),
27 }
28 }
29Some(domain[pos + 1..].to_owned())
30}
3132pub fn hash_url(url: &str) -> Option<UrlHash> {
33 url_hash_source(url).map(|hash_source| {
34let mut hasher = Md5::new();
35 hasher.update(hash_source);
36let result = hasher.finalize();
37 result.into()
38 })
39}
4041#[cfg(test)]
42mod test {
43use super::*;
4445#[test]
46fn test_url_hash_source() {
47let table = [
48 ("http://example.com/some-path", Some("example.com")),
49 ("http://foo.example.com/some-path", Some("example.com")),
50 (
51"http://foo.bar.baz.example.com/some-path",
52Some("example.com"),
53 ),
54 ("http://foo.com.uk/some-path", Some("com.uk")),
55 ("http://amazon.com/some-path", Some("amazon.com")),
56 ("http://192.168.0.1/some-path", None),
57 ];
58for (url, expected) in table {
59assert_eq!(url_hash_source(url).as_deref(), expected)
60 }
61 }
62}