Line data Source code
1 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 <pup.h> 10 : #include <vector> 11 : 12 : #include "Utilities/Gsl.hpp" 13 : 14 : /*! 15 : * \ingroup ParallelGroup 16 : * \brief Serialize an object using PUP. 17 : * 18 : * The type to serialize as must be explicitly specified. We require 19 : * this because a mismatch between the serialize and deserialize calls 20 : * causes undefined behavior and we do not want this to depend on 21 : * inferred types for safety. 22 : * 23 : * \tparam T type to serialize 24 : */ 25 : template <typename T> 26 1 : std::vector<char> serialize(const T& obj) { 27 : const T& typed_obj = obj; 28 : // pup routine is non-const, but shouldn't modify anything in serialization 29 : // mode. 30 : // clang-tidy: do not use const_cast 31 : auto& mut_obj = const_cast<T&>(typed_obj); // NOLINT 32 : 33 : PUP::sizer sizer; 34 : sizer | mut_obj; 35 : std::vector<char> data(sizer.size()); 36 : PUP::toMem writer(data.data()); 37 : writer | mut_obj; 38 : 39 : return data; 40 : } 41 : 42 : /*! 43 : * \ingroup ParallelGroup 44 : * \brief Deserialize an object using PUP. 45 : * 46 : * \tparam T the type to deserialize to 47 : */ 48 : template <typename T> 49 1 : T deserialize(const void* const data) { // NOLINT 50 : // clang-tidy: no const in forward decl (this is a definition) 51 : PUP::fromMem reader(data); 52 : T result{}; 53 : reader | result; 54 : return result; 55 : } 56 : 57 : /*! 58 : * \ingroup ParallelGroup 59 : * \brief Deserialize an object using PUP. 60 : * 61 : * \tparam T the type to deserialize to. 62 : */ 63 : template <typename T> 64 1 : void deserialize(const gsl::not_null<T*> result, 65 : const void* const data) { // NOLINT 66 : // clang-tidy: no const in forward decl (this is a definition) 67 : PUP::fromMem reader(data); 68 : reader | *result; 69 : } 70 : 71 : /*! 72 : * \ingroup ParallelGroup 73 : * \brief Returns the size of an object in bytes 74 : */ 75 : template <typename T> 76 1 : size_t size_of_object_in_bytes(const T& obj) { 77 : PUP::sizer sizer; 78 : sizer | const_cast<T&>(obj); // NOLINT 79 : return sizer.size(); 80 : }