output_string.hpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //
  2. // Copyright (c) 2019-2024 Ruben Perez Hidalgo (rubenperez038 at gmail dot 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. #ifndef BOOST_MYSQL_DETAIL_OUTPUT_STRING_HPP
  8. #define BOOST_MYSQL_DETAIL_OUTPUT_STRING_HPP
  9. #include <boost/mysql/string_view.hpp>
  10. #include <boost/mysql/detail/config.hpp>
  11. #include <cstddef>
  12. #ifdef BOOST_MYSQL_HAS_CONCEPTS
  13. #include <concepts>
  14. #endif
  15. namespace boost {
  16. namespace mysql {
  17. namespace detail {
  18. #ifdef BOOST_MYSQL_HAS_CONCEPTS
  19. template <class T>
  20. concept output_string = std::movable<T> && requires(T& t, const char* data, std::size_t sz) {
  21. t.append(data, sz);
  22. t.clear();
  23. };
  24. #define BOOST_MYSQL_OUTPUT_STRING ::boost::mysql::detail::output_string
  25. #else
  26. #define BOOST_MYSQL_OUTPUT_STRING class
  27. #endif
  28. class output_string_ref
  29. {
  30. using append_fn_t = void (*)(void*, const char*, std::size_t);
  31. append_fn_t append_fn_;
  32. void* container_;
  33. template <class T>
  34. static void do_append(void* container, const char* data, std::size_t size)
  35. {
  36. static_cast<T*>(container)->append(data, size);
  37. }
  38. public:
  39. output_string_ref(append_fn_t append_fn, void* container) noexcept
  40. : append_fn_(append_fn), container_(container)
  41. {
  42. }
  43. template <class T>
  44. static output_string_ref create(T& obj) noexcept
  45. {
  46. return output_string_ref(&do_append<T>, &obj);
  47. }
  48. void append(string_view data)
  49. {
  50. if (data.size() > 0u)
  51. append_fn_(container_, data.data(), data.size());
  52. }
  53. };
  54. } // namespace detail
  55. } // namespace mysql
  56. } // namespace boost
  57. #endif