array_wrapper.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_HISTOGRAM_DETAIL_ARRAY_WRAPPER_HPP
  7. #define BOOST_HISTOGRAM_DETAIL_ARRAY_WRAPPER_HPP
  8. #include <boost/core/make_span.hpp>
  9. #include <boost/core/nvp.hpp>
  10. #include <boost/histogram/detail/static_if.hpp>
  11. #include <boost/mp11/function.hpp>
  12. #include <boost/mp11/utility.hpp>
  13. #include <type_traits>
  14. namespace boost {
  15. namespace histogram {
  16. namespace detail {
  17. template <class T, class = decltype(&T::template save_array<int>)>
  18. struct has_save_array_impl;
  19. template <class T, class = decltype(&T::template load_array<int>)>
  20. struct has_load_array_impl;
  21. template <class T>
  22. using has_array_optimization = mp11::mp_or<mp11::mp_valid<has_save_array_impl, T>,
  23. mp11::mp_valid<has_load_array_impl, T>>;
  24. template <class T>
  25. struct array_wrapper {
  26. using pointer = T*;
  27. pointer ptr;
  28. std::size_t size;
  29. template <class Archive>
  30. void serialize(Archive& ar, unsigned /* version */) {
  31. static_if_c<(has_array_optimization<Archive>::value &&
  32. std::is_trivially_copyable<T>::value)>(
  33. [this](auto& ar) {
  34. // cannot use and therefore bypass save_array / load_array interface, because
  35. // it requires exact type boost::serialization::array_wrapper<T>
  36. static_if_c<Archive::is_loading::value>(
  37. [this](auto& ar) { ar.load_binary(this->ptr, sizeof(T) * this->size); },
  38. [this](auto& ar) { ar.save_binary(this->ptr, sizeof(T) * this->size); },
  39. ar);
  40. },
  41. [this](auto& ar) {
  42. for (auto&& x : make_span(this->ptr, this->size)) ar& make_nvp("item", x);
  43. },
  44. ar);
  45. }
  46. };
  47. template <class T>
  48. auto make_array_wrapper(T* t, std::size_t s) {
  49. return array_wrapper<T>{t, s};
  50. }
  51. } // namespace detail
  52. } // namespace histogram
  53. } // namespace boost
  54. #endif