1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/page_load_metrics/common/page_load_metrics_util.h"
6
7 #include <algorithm>
8
9 #include "base/strings/string_util.h"
10 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
11
12 namespace page_load_metrics {
13
GetGoogleHostnamePrefix(const GURL & url)14 base::Optional<std::string> GetGoogleHostnamePrefix(const GURL& url) {
15 const size_t registry_length =
16 net::registry_controlled_domains::GetRegistryLength(
17 url,
18
19 // Do not include unknown registries (registries that don't have any
20 // matches in effective TLD names).
21 net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES,
22
23 // Do not include private registries, such as appspot.com. We don't
24 // want to match URLs like www.google.appspot.com.
25 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
26
27 const base::StringPiece hostname = url.host_piece();
28 if (registry_length == 0 || registry_length == std::string::npos ||
29 registry_length >= hostname.length()) {
30 return base::Optional<std::string>();
31 }
32
33 // Removes the tld and the preceding dot.
34 const base::StringPiece hostname_minus_registry =
35 hostname.substr(0, hostname.length() - (registry_length + 1));
36
37 if (hostname_minus_registry == "google")
38 return std::string("");
39
40 if (!base::EndsWith(hostname_minus_registry, ".google",
41 base::CompareCase::INSENSITIVE_ASCII)) {
42 return base::Optional<std::string>();
43 }
44
45 return std::string(hostname_minus_registry.substr(
46 0, hostname_minus_registry.length() - strlen(".google")));
47 }
48
IsGoogleHostname(const GURL & url)49 bool IsGoogleHostname(const GURL& url) {
50 return GetGoogleHostnamePrefix(url).has_value();
51 }
52
OptionalMin(const base::Optional<base::TimeDelta> & a,const base::Optional<base::TimeDelta> & b)53 base::Optional<base::TimeDelta> OptionalMin(
54 const base::Optional<base::TimeDelta>& a,
55 const base::Optional<base::TimeDelta>& b) {
56 if (a && !b)
57 return a;
58 if (b && !a)
59 return b;
60 if (!a && !b)
61 return a; // doesn't matter which
62 return base::Optional<base::TimeDelta>(std::min(a.value(), b.value()));
63 }
64
65 } // namespace page_load_metrics
66