optional_string.hpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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/string_view.hpp>
  12. namespace boost {
  13. namespace urls {
  14. #ifndef BOOST_URL_DOCS
  15. struct no_value_t;
  16. #endif
  17. namespace detail {
  18. struct optional_string
  19. {
  20. string_view s;
  21. bool b = false;
  22. };
  23. template <class String>
  24. typename std::enable_if<
  25. std::is_convertible<String, string_view>::value,
  26. optional_string>::type
  27. get_optional_string(
  28. String const& s)
  29. {
  30. optional_string r;
  31. r.s = s;
  32. r.b = true;
  33. return r;
  34. }
  35. template <class T, class = void>
  36. struct is_dereferenceable : std::false_type
  37. {};
  38. template <class T>
  39. struct is_dereferenceable<
  40. T,
  41. void_t<
  42. decltype(*std::declval<T>())
  43. >> : std::true_type
  44. {};
  45. template <class OptionalString>
  46. typename std::enable_if<
  47. !std::is_convertible<OptionalString, string_view>::value,
  48. optional_string>::type
  49. get_optional_string(
  50. OptionalString const& opt)
  51. {
  52. // If this goes off, it means the rule
  53. // passed in did not meet the requirements.
  54. // Please check the documentation of functions
  55. // that call get_optional_string.
  56. static_assert(
  57. is_dereferenceable<OptionalString>::value &&
  58. std::is_constructible<bool, OptionalString>::value &&
  59. !std::is_convertible<OptionalString, string_view>::value &&
  60. std::is_convertible<typename std::decay<decltype(*std::declval<OptionalString>())>::type, string_view>::value,
  61. "OptionalString requirements not met");
  62. optional_string r;
  63. r.s = opt ? detail::to_sv(*opt) : string_view{};
  64. r.b = static_cast<bool>(opt);
  65. return r;
  66. }
  67. inline
  68. optional_string
  69. get_optional_string(
  70. std::nullptr_t)
  71. {
  72. return {};
  73. }
  74. inline
  75. optional_string
  76. get_optional_string(
  77. no_value_t const&)
  78. {
  79. return {};
  80. }
  81. } // detail
  82. } // urls
  83. } // boost
  84. #endif