optional_string.hpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. //
  2. // Copyright (c) 2022 Alan de Freitas (alandefreitas@gmail.com)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // Official repository: https://github.com/boostorg/url
  8. //
  9. #ifndef BOOST_URL_DETAIL_OPTIONAL_STRING_HPP
  10. #define BOOST_URL_DETAIL_OPTIONAL_STRING_HPP
  11. #include <boost/url/detail/string_view.hpp>
  12. #include <boost/core/detail/string_view.hpp>
  13. namespace boost {
  14. namespace urls {
  15. #ifndef BOOST_URL_DOCS
  16. struct no_value_t;
  17. #endif
  18. namespace detail {
  19. struct optional_string
  20. {
  21. core::string_view s;
  22. bool b = false;
  23. };
  24. template <class String>
  25. typename std::enable_if<
  26. std::is_convertible<String, core::string_view>::value,
  27. optional_string>::type
  28. get_optional_string(
  29. String const& s)
  30. {
  31. optional_string r;
  32. r.s = s;
  33. r.b = true;
  34. return r;
  35. }
  36. template <class T, class = void>
  37. struct is_dereferenceable : std::false_type
  38. {};
  39. template <class T>
  40. struct is_dereferenceable<
  41. T,
  42. void_t<
  43. decltype(*std::declval<T>())
  44. >> : std::true_type
  45. {};
  46. template <class OptionalString>
  47. typename std::enable_if<
  48. !std::is_convertible<OptionalString, core::string_view>::value,
  49. optional_string>::type
  50. get_optional_string(
  51. OptionalString const& opt)
  52. {
  53. // If this goes off, it means the rule
  54. // passed in did not meet the requirements.
  55. // Please check the documentation of functions
  56. // that call get_optional_string.
  57. static_assert(
  58. is_dereferenceable<OptionalString>::value &&
  59. std::is_constructible<bool, OptionalString>::value &&
  60. !std::is_convertible<OptionalString, core::string_view>::value &&
  61. std::is_convertible<typename std::decay<decltype(*std::declval<OptionalString>())>::type, core::string_view>::value,
  62. "OptionalString requirements not met");
  63. optional_string r;
  64. r.s = opt ? detail::to_sv(*opt) : core::string_view{};
  65. r.b = static_cast<bool>(opt);
  66. return r;
  67. }
  68. inline
  69. optional_string
  70. get_optional_string(
  71. std::nullptr_t)
  72. {
  73. return {};
  74. }
  75. inline
  76. optional_string
  77. get_optional_string(
  78. no_value_t const&)
  79. {
  80. return {};
  81. }
  82. } // detail
  83. } // urls
  84. } // boost
  85. #endif