WarpX
Loading...
Searching...
No Matches
Serialization.H
Go to the documentation of this file.
1/* Copyright 2021 Luca Fedeli
2 *
3 * This file is part of WarpX.
4 *
5 * License: BSD-3-Clause-LBNL
6 */
7
8#ifndef ABLASTR_MSG_LOGGER_SERIALIZATION_H_
9#define ABLASTR_MSG_LOGGER_SERIALIZATION_H_
10
11#include <algorithm>
12#include <array>
13#include <cstring>
14#include <iterator>
15#include <string>
16#include <type_traits>
17#include <vector>
18
20{
30 template <typename T,
31 std::enable_if_t<std::is_trivially_copyable_v<T> || std::is_same_v<T, std::string>, bool> = true>
32 void put_in(const T &val, std::vector<char> &vec)
33 {
34 if constexpr (std::is_same<T, std::string>())
35 {
36 const char *c_str = val.c_str();
37 const auto length = static_cast<int>(val.size());
38
39 put_in(length, vec);
40 std::copy(c_str, c_str + length, std::back_inserter(vec));
41 }
42 else
43 {
44 const auto *ptr_val = reinterpret_cast<const char *>(&val);
45 std::copy(ptr_val, ptr_val + sizeof(T), std::back_inserter(vec));
46 }
47 }
48
59 template <typename T>
60 void put_in_vec(const std::vector<T> &val, std::vector<char> &vec)
61 {
62 put_in(static_cast<int>(val.size()), vec);
63 for (const auto &el : val) {
64 put_in(el, vec);
65 }
66 }
67
78 template <typename T,
79 std::enable_if_t<std::is_trivially_copyable_v<T> || std::is_same_v<T, std::string>, bool> = true>
80 T get_out(std::vector<char>::const_iterator &it)
81 {
82 if constexpr (std::is_same<T, std::string>())
83 {
84 const auto length = get_out<int>(it);
85 auto str = std::string{it, it + length};
86 it += length;
87
88 return str;
89 }
90 else
91 {
92 auto temp = std::array<char, sizeof(T)>{};
93 std::copy(it, it + sizeof(T), temp.begin());
94 it += sizeof(T);
95 T res;
96 std::memcpy(&res, temp.data(), sizeof(T));
97
98 return res;
99 }
100 }
101
112 template <typename T>
113 std::vector<T> get_out_vec(std::vector<char>::const_iterator &it)
114 {
115 const auto length = get_out<int>(it);
116
117 std::vector<T> res(length);
118 for (int i = 0; i < length; ++i) {
119 res[i] = get_out<T>(it);
120 }
121
122 return res;
123 }
124}
125
126#endif //ABLASTR_MSG_LOGGER_SERIALIZATION_H_
Definition Serialization.H:20
void put_in_vec(const std::vector< T > &val, std::vector< char > &vec)
Definition Serialization.H:60
T get_out(std::vector< char >::const_iterator &it)
Definition Serialization.H:80
void put_in(const T &val, std::vector< char > &vec)
Definition Serialization.H:32
std::vector< T > get_out_vec(std::vector< char >::const_iterator &it)
Definition Serialization.H:113