Turi Create  4.0
serialize_to_from_string.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef SERIALIZE_TO_FROM_STRING_HPP
7 #define SERIALIZE_TO_FROM_STRING_HPP
8 #include <sstream>
9 #include <boost/iostreams/stream.hpp>
10 
11 namespace turi {
12  /**
13  * \ingroup group_serialization
14  * \brief Serializes a object to a string
15  *
16  * Converts a \ref serializable object t to a string
17  * using the serializer.
18  *
19  * \tparam T the type of object to serialize. Typically
20  * will be inferred by the compiler.
21  *
22  * \param t The object to serializer
23  * \returns A string containing a serialized form of t
24  *
25  * \see deserialize_from_string()
26  */
27  template <typename T>
28  inline std::string serialize_to_string(const T &t) {
29  std::stringstream strm;
30  oarchive oarc(strm);
31  oarc << t;
32  strm.flush();
33  return strm.str();
34  }
35 
36 
37  /**
38  * \ingroup group_serialization
39  * \brief Deserializes a object from a string
40  *
41  * Deserializes a \ref serializable object t from a string
42  * using the deserializer.
43  *
44  * \tparam T the type of object to deserialize. Typically
45  * will be inferred by the compiler.
46  *
47  * \param s The string to deserialize
48  * \param t A reference to the object which will contain
49  * the deserialized object when the function returns
50  *
51  * \see serialize_from_string()
52  */
53  template <typename T>
54  inline void deserialize_from_string(const std::string &s, T &t) {
55  boost::iostreams::stream<boost::iostreams::array_source>
56  istrm(s.c_str(), s.length());
57  iarchive iarc(istrm);
58  iarc >> t;
59  }
60 }
61 
62 #endif
The serialization input archive object which, provided with a reference to an istream, will read from the istream, providing deserialization capabilities.
Definition: iarchive.hpp:60
std::string serialize_to_string(const T &t)
Serializes a object to a string.
void deserialize_from_string(const std::string &s, T &t)
Deserializes a object from a string.
The serialization output archive object which, provided with a reference to an ostream, will write to the ostream, providing serialization capabilities.
Definition: oarchive.hpp:80