HALDLS
pickle.h
Go to the documentation of this file.
1 #pragma once
2 #include <iosfwd>
3 #include <vector>
4 #include <pybind11/pybind11.h>
5 
6 #include "hate/type_list.h"
7 
8 
9 namespace haldls::vx {
10 
15 template <typename TL>
16 struct AddPickle;
17 
18 template <typename... Ts>
19 struct AddPickle<hate::type_list<Ts...>>
20 {
28  static void apply(pybind11::module& parent, std::vector<std::string> const& container_names)
29  {
30  apply_impl(parent, container_names, std::make_index_sequence<sizeof...(Ts)>{});
31  }
32 
33 private:
34  template <size_t I, size_t... Is>
35  static void apply_impl(
36  pybind11::module& parent,
37  std::vector<std::string> const& container_names,
38  std::index_sequence<I, Is...>)
39  {
40  typedef typename hate::index_type_list_by_integer<I, hate::type_list<Ts...>>::type type;
41  apply_single<type>(parent, container_names.at(I));
42  if constexpr (sizeof...(Is)) {
43  apply_impl(parent, container_names, std::index_sequence<Is...>{});
44  }
45  }
46 
54  template <typename T>
55  static void apply_single(pybind11::module& parent, std::string const& name)
56  {
57  auto attr = parent.attr(name.c_str());
58  auto ism = pybind11::is_method(attr);
59  auto const getattr = [](pybind11::object const& self) {
60  auto& thing = self.cast<T const&>();
61  std::string serialized{haldls::vx::to_portablebinary(thing)};
62  if (pybind11::hasattr(self, "__dict__")) {
63  return pybind11::make_tuple(pybind11::bytes(serialized), self.attr("__dict__"));
64  } else {
65  return pybind11::make_tuple(pybind11::bytes(serialized));
66  }
67  };
68 
69  auto const setattr = [](pybind11::object& self, pybind11::tuple const& data) {
70  auto& thing = self.cast<T&>();
71  new (&thing) T();
72  haldls::vx::from_portablebinary(thing, data[0].cast<std::string>());
73  if (pybind11::hasattr(self, "__dict__")) {
74  self.attr("__dict__") = data[1];
75  }
76  };
77 
78  attr.attr("__getstate__") = pybind11::cpp_function(getattr, ism);
79  attr.attr("__setstate__") = pybind11::cpp_function(setattr, ism);
80  }
81 };
82 
83 } // namespace haldls::vx
cls def(pybind11::init<::haldls::vx::v2::CapMemCell::Value >(), pybind11::arg("value")=::haldls::vx::v2::CapMemCell::Value(0)) .def(pybind11 parent attr("CapMemCell").attr("value_type")
std::string to_portablebinary(T const &t)
void from_portablebinary(T &t, std::string const &s)
static void apply(pybind11::module &parent, std::vector< std::string > const &container_names)
Add pickle support to list of classes.
Definition: pickle.h:28
Add pickle support to list of classes.
Definition: pickle.h:16