1 // Copyright 2020 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 #ifndef UTIL_URL_H_
6 #define UTIL_URL_H_
7 
8 #include <cstdint>
9 #include <string>
10 
11 #include "util/osp_logging.h"
12 
13 namespace openscreen {
14 
15 // Parses a URL and stores its components separately.  If parsing is successful,
16 // is_valid() will return true, otherwise no other members should be accessed.
17 // This is a thin wrapper around //third_party/mozilla.  It does not handle
18 // file: or mailto: URLs.
19 class Url {
20  public:
21   explicit Url(const std::string& source);
22   Url(const Url&);
23   Url(Url&&) noexcept;
24   ~Url();
25 
26   Url& operator=(const Url&);
27   Url& operator=(Url&&);
28 
29   // No other members should be accessed if this is false.
is_valid()30   bool is_valid() const { return is_valid_; }
31 
32   // A successfully parsed URL will always have a scheme.  All the other
33   // components are optional and therefore have has_*() accessors for checking
34   // their presence.
scheme()35   const std::string& scheme() const {
36     OSP_DCHECK(is_valid_);
37     return scheme_;
38   }
has_host()39   bool has_host() const {
40     OSP_DCHECK(is_valid_);
41     return has_host_;
42   }
host()43   const std::string& host() const {
44     OSP_DCHECK(is_valid_);
45     return host_;
46   }
has_port()47   bool has_port() const {
48     OSP_DCHECK(is_valid_);
49     return has_port_;
50   }
port()51   int32_t port() const {
52     OSP_DCHECK(is_valid_);
53     return port_;
54   }
has_path()55   bool has_path() const {
56     OSP_DCHECK(is_valid_);
57     return has_path_;
58   }
path()59   const std::string& path() const {
60     OSP_DCHECK(is_valid_);
61     return path_;
62   }
has_query()63   bool has_query() const {
64     OSP_DCHECK(is_valid_);
65     return has_query_;
66   }
query()67   const std::string& query() const {
68     OSP_DCHECK(is_valid_);
69     return query_;
70   }
71 
72  private:
73   bool is_valid_ = false;
74   bool has_host_ = false;
75   bool has_port_ = false;
76   bool has_path_ = false;
77   bool has_query_ = false;
78 
79   std::string scheme_;
80   std::string host_;
81   int32_t port_ = 0;
82   std::string path_;
83   std::string query_;
84 };
85 
86 }  // namespace openscreen
87 
88 #endif  // UTIL_URL_H_
89