Debian Codegraph @

examples/tldextract.rs

raw symbols SCIP
1 use psl_types::List;
2
3 pub trait TldExtract {
4 fn extract<'a>(&self, host: &'a str) -> Option<Parts<'a>>;
5 }
6
7 impl<T: List> TldExtract for T {
8 fn extract<'a>(&self, host: &'a str) -> Option<Parts<'a>> {
9 let host_len = host.len();
10 let suffix_len = self.suffix(host.as_bytes())?.as_bytes().len();
11 let suffix = {
12 let offset = host_len - suffix_len;
13 &host[offset..]
14 };
15 let suffix_plus_dot = suffix_len + 1;
16 let (subdomain, domain) = if host_len > suffix_plus_dot {
17 match host.get(..host_len - suffix_plus_dot) {
18 Some(prefix) => match prefix.rfind('.') {
19 Some(offset) => (prefix.get(..offset), prefix.get(offset + 1..)),
20 None => (None, Some(prefix)),
21 },
22 None => (None, None),
23 }
24 } else {
25 (None, None)
26 };
27 Some(Parts {
28 suffix,
29 domain,
30 subdomain,
31 })
32 }
33 }
34
35 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
36 pub struct Parts<'a> {
37 pub suffix: &'a str,
38 pub domain: Option<&'a str>,
39 pub subdomain: Option<&'a str>,
40 }
41
42 // This example is inspired by https://github.com/john-kurkowski/tldextract
43 // Unlike that project, we don't try to parse URLs though. That can easily
44 // be done by using the `url` crate and feeding the output of `Url::domain`
45 // to `TldExtract::extract`.
46 fn main() {
47 use psl::List;
48 use std::env;
49
50 let domain = match env::args().nth(1) {
51 Some(name) => name,
52 None => {
53 eprintln!("Usage: {} <domain name>", env::args().nth(0).unwrap());
54 std::process::exit(1);
55 }
56 };
57
58 match List.extract(&domain) {
59 Some(info) => println!(
60 "{} {} {}",
61 info.subdomain.unwrap_or("(None)"),
62 info.domain.unwrap_or("(None)"),
63 info.suffix
64 ),
65 None => eprintln!("`{}` is not domain name", domain),
66 }
67 }