Skip to content

Commit

Permalink
Add operator== and std::hash specialization for upa::url
Browse files Browse the repository at this point in the history
  • Loading branch information
rmisev committed Oct 5, 2023
1 parent 9d9fdfd commit 3f3ece8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions include/upa/url.h
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,8 @@ class url {
std::size_t path_segment_count_ = 0;
detail::url_search_params_ptr search_params_ptr_;

friend bool operator==(const url& lhs, const url& rhs);
friend struct std::hash<url>;
friend detail::url_serializer;
friend detail::url_setter;
friend detail::url_parser;
Expand Down Expand Up @@ -2927,6 +2929,11 @@ inline bool is_unc_path(const CharT* first, const CharT* last)

// URL utilities (non-member functions)

/// @brief Lexicographically compares two URL's
inline bool operator==(const url& lhs, const url& rhs) {
return lhs.norm_url_ == rhs.norm_url_;
}

/// @brief Swaps the contents of two URLs
///
/// Swaps the contents of the @a lhs and @a rhs URLs
Expand Down Expand Up @@ -3002,6 +3009,15 @@ inline url url_from_file_path(StrT&& str) {

} // namespace upa


/// @brief std::hash specialization for upa::url class
template<>
struct std::hash<upa::url> {
std::size_t operator()(const upa::url& url) const noexcept {
return std::hash<std::string>{}(url.norm_url_);
}
};

// Includes that require the url class declaration
#include "url_search_params-inl.h"

Expand Down
18 changes: 18 additions & 0 deletions test/test-url.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "upa/url.h"
#include "doctest-main.h"
#include "test-utils.h"
#include <unordered_map>


std::string urls_to_str(const char* s1) {
Expand Down Expand Up @@ -566,3 +567,20 @@ TEST_CASE("url_from_file_path") {
CHECK_THROWS_AS(upa::url_from_file_path("\\\\.\\Volume{b75e2c83-0000-0000-0000-602f00000000}\\Test\\Foo.txt"), upa::url_error);
}
}

// Test operator== and std::hash specialization

TEST_CASE("operator== && std::hash<upa::url>") {
std::unordered_map<upa::url, int> map;

map.emplace(upa::url{ "about:blank" }, 1);
map.emplace(upa::url{ "file:///path" }, 2);
map.emplace(upa::url{ "https://example.org/" }, 3);

CHECK(map.at(upa::url{ "about:blank" }) == 1);
CHECK(map.at(upa::url{ "file:///path" }) == 2);
CHECK(map.at(upa::url{ "https://example.org/" }) == 3);

CHECK(upa::url{ "about:blank" } == upa::url{ "about:blank" });
CHECK_FALSE(upa::url{ "about:blank" } == upa::url{ "https://example.org/" });
}

0 comments on commit 3f3ece8

Please sign in to comment.