Loading [MathJax]/extensions/TeX/AMSmath.js
ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages Concepts
pack.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2020-2022 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19#ifndef UTILS_SERIALIZATION_PACK_HPP
20#define UTILS_SERIALIZATION_PACK_HPP
21
22#include <boost/archive/binary_iarchive.hpp>
23#include <boost/archive/binary_oarchive.hpp>
24#include <boost/iostreams/device/array.hpp>
25#include <boost/iostreams/stream.hpp>
26
27#include <sstream>
28#include <string>
29
30namespace Utils {
31/**
32 * @brief Pack a serialize type into a string.
33 *
34 * @tparam T Serializable type
35 * @param v Value to serialize
36 * @return String representation
37 */
38template <class T> std::string pack(T const &v) {
39 std::stringstream ss;
40 boost::archive::binary_oarchive(ss) << v;
41
42 return ss.str();
43}
44
45/**
46 * @brief Unpack a serialize type into a string.
47 *
48 * @tparam T Serializable type
49 * @param state String to construct the value from, as returned by @ref
50 * Utils::pack.
51 * @return Unpacked value
52 */
53template <class T> T unpack(std::string const &state) {
54 namespace iostreams = boost::iostreams;
55
56 iostreams::array_source src(state.data(), state.size());
57 iostreams::stream<iostreams::array_source> ss(src);
58
59 T val;
60 boost::archive::binary_iarchive(ss) >> val;
61
62 return val;
63}
64} // namespace Utils
65
66#endif // UTILS_SERIALIZATION_PACK_HPP
T unpack(std::string const &state)
Unpack a serialize type into a string.
Definition pack.hpp:53
std::string pack(T const &v)
Pack a serialize type into a string.
Definition pack.hpp:38