Uri-inl.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright 2013-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef FOLLY_URI_H_
  17. #error This file may only be included from folly/Uri.h
  18. #endif
  19. #include <functional>
  20. #include <tuple>
  21. #include <folly/Conv.h>
  22. #include <folly/hash/Hash.h>
  23. namespace folly {
  24. namespace uri_detail {
  25. using UriTuple = std::tuple<
  26. const std::string&,
  27. const std::string&,
  28. const std::string&,
  29. const std::string&,
  30. uint16_t,
  31. const std::string&,
  32. const std::string&,
  33. const std::string&>;
  34. inline UriTuple as_tuple(const folly::Uri& k) {
  35. return UriTuple(
  36. k.scheme(),
  37. k.username(),
  38. k.password(),
  39. k.host(),
  40. k.port(),
  41. k.path(),
  42. k.query(),
  43. k.fragment());
  44. }
  45. } // namespace uri_detail
  46. template <class String>
  47. String Uri::toString() const {
  48. String str;
  49. if (hasAuthority_) {
  50. toAppend(scheme_, "://", &str);
  51. if (!password_.empty()) {
  52. toAppend(username_, ":", password_, "@", &str);
  53. } else if (!username_.empty()) {
  54. toAppend(username_, "@", &str);
  55. }
  56. toAppend(host_, &str);
  57. if (port_ != 0) {
  58. toAppend(":", port_, &str);
  59. }
  60. } else {
  61. toAppend(scheme_, ":", &str);
  62. }
  63. toAppend(path_, &str);
  64. if (!query_.empty()) {
  65. toAppend("?", query_, &str);
  66. }
  67. if (!fragment_.empty()) {
  68. toAppend("#", fragment_, &str);
  69. }
  70. return str;
  71. }
  72. } // namespace folly
  73. namespace std {
  74. template <>
  75. struct hash<folly::Uri> {
  76. std::size_t operator()(const folly::Uri& k) const {
  77. return std::hash<folly::uri_detail::UriTuple>{}(
  78. folly::uri_detail::as_tuple(k));
  79. }
  80. };
  81. template <>
  82. struct equal_to<folly::Uri> {
  83. bool operator()(const folly::Uri& a, const folly::Uri& b) const {
  84. return folly::uri_detail::as_tuple(a) == folly::uri_detail::as_tuple(b);
  85. }
  86. };
  87. } // namespace std