pos_map.hpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // Copyright (c) 2019-2023 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 BHO_MYSQL_DETAIL_TYPING_POS_MAP_HPP
  8. #define BHO_MYSQL_DETAIL_TYPING_POS_MAP_HPP
  9. #include <asio2/bho/mysql/field_view.hpp>
  10. #include <asio2/bho/mysql/metadata.hpp>
  11. #include <asio2/bho/mysql/metadata_collection_view.hpp>
  12. #include <asio2/bho/mysql/string_view.hpp>
  13. #include <asio2/bho/assert.hpp>
  14. #include <asio2/bho/core/span.hpp>
  15. #include <cstddef>
  16. namespace bho {
  17. namespace mysql {
  18. namespace detail {
  19. // These functions map C++ type positions to positions to positions in the DB query
  20. constexpr std::size_t pos_absent = static_cast<std::size_t>(-1);
  21. using name_table_t = bho::span<const string_view>;
  22. inline bool has_field_names(name_table_t name_table) noexcept { return !name_table.empty(); }
  23. inline void pos_map_reset(span<std::size_t> self) noexcept
  24. {
  25. for (std::size_t i = 0; i < self.size(); ++i)
  26. self.data()[i] = pos_absent;
  27. }
  28. inline void pos_map_add_field(
  29. span<std::size_t> self,
  30. name_table_t name_table,
  31. std::size_t db_index,
  32. string_view field_name
  33. ) noexcept
  34. {
  35. if (has_field_names(name_table))
  36. {
  37. BHO_ASSERT(self.size() == name_table.size());
  38. // We're mapping fields by name. Try to find where in our target struct
  39. // is the current field located
  40. auto it = std::find(name_table.begin(), name_table.end(), field_name);
  41. if (it != name_table.end())
  42. {
  43. std::size_t cpp_index = it - name_table.begin();
  44. self[cpp_index] = db_index;
  45. }
  46. }
  47. else
  48. {
  49. // We're mapping by position. Any extra trailing fields are discarded
  50. if (db_index < self.size())
  51. {
  52. self[db_index] = db_index;
  53. }
  54. }
  55. }
  56. inline field_view map_field_view(
  57. span<const std::size_t> self,
  58. std::size_t cpp_index,
  59. span<const field_view> array
  60. ) noexcept
  61. {
  62. BHO_ASSERT(cpp_index < self.size());
  63. return array[self[cpp_index]];
  64. }
  65. inline const metadata& map_metadata(
  66. span<const std::size_t> self,
  67. std::size_t cpp_index,
  68. metadata_collection_view meta
  69. ) noexcept
  70. {
  71. BHO_ASSERT(cpp_index < self.size());
  72. return meta[self[cpp_index]];
  73. }
  74. } // namespace detail
  75. } // namespace mysql
  76. } // namespace bho
  77. #endif