Serialize.hpp
Go to the documentation of this file.
1 // Distributed under the MIT License.
2 // See LICENSE.txt for details.
3 
4 /// \file
5 /// Defines the serialize and deserialize functions.
6 
7 #pragma once
8 
9 #include <vector>
10 
11 #include <pup.h>
12 
13 /*!
14  * \ingroup ParallelGroup
15  * \brief Serialize an object using PUP.
16  *
17  * The type to serialize as must be explicitly specified. We require
18  * this because a mismatch between the serialize and deserialize calls
19  * causes undefined behavior and we do not want this to depend on
20  * inferred types for safety.
21  *
22  * \tparam T type to serialize
23  */
24 template <typename T, typename U>
26  static_assert(std::is_same<T, U>::value,
27  "Explicit type for serialization differs from deduced type");
28  const T& typed_obj = obj;
29  // pup routine is non-const, but shouldn't modify anything in serialization
30  // mode.
31  // clang-tidy: do not use const_cast
32  auto& mut_obj = const_cast<T&>(typed_obj); // NOLINT
33 
34  PUP::sizer sizer;
35  sizer | mut_obj;
36  std::vector<char> data(sizer.size());
37  PUP::toMem writer(data.data());
38  writer | mut_obj;
39 
40  return data;
41 }
42 
43 /*!
44  * \ingroup ParallelGroup
45  * \brief Deserialize an object using PUP.
46  *
47  * \tparam T the type to deserialize to
48  */
49 template <typename T>
50 T deserialize(const void* const data) {
51  PUP::fromMem reader(data);
52  T result{};
53  reader | result;
54  return result;
55 }
std::vector< char > serialize(const U &obj)
Serialize an object using PUP.
Definition: Serialize.hpp:25
T deserialize(const void *const data)
Deserialize an object using PUP.
Definition: Serialize.hpp:50