SC2API
An API for AI for StarCraft II
simple_serialization.h
1 // Simple functions for serializing structures.
2 
3 #pragma once
4 
5 #include <vector>
6 #include <string>
7 #include <fstream>
8 #include <iostream>
9 #include <set>
10 
11 
12 template<class Stream> bool IsReading(const Stream&) {
13  return typeid(Stream) == typeid(std::ifstream);
14 }
15 
16 // Strings.
17 static inline void SerializeT(std::ifstream& s, std::string& t) {
18  std::getline(s, t);
19 }
20 
21 static inline void SerializeT(std::ofstream& s, const std::string& t) {
22  s << t << std::endl;
23 }
24 
25 // Bools.
26 static inline void SerializeT(std::ifstream& s, bool& t) {
27  std::string linein;
28  if (!std::getline(s, linein))
29  return;
30 
31  uint32_t value = std::stoi(linein);
32  t = value == 1;
33 }
34 
35 void inline SerializeT(std::ofstream& s, bool t) {
36  if (t) {
37  s << "1" << std::endl;
38  }
39  else {
40  s << "0" << std::endl;
41  }
42 }
43 
44 // All other types, assumed to be 32-bit.
45 template<typename T> void SerializeT(std::ifstream& s, T& t) {
46  std::string linein;
47  if (!std::getline(s, linein))
48  return;
49 
50  uint32_t value = std::stoi(linein);
51  t = static_cast<T>(value);
52 }
53 
54 template<typename T> void SerializeT(std::ofstream& s, T t) {
55  s << std::to_string(static_cast<uint32_t>(t)) << std::endl;
56 }
57 
58 static inline void SerializeT(std::ofstream& data_file, const std::set<uint32_t>& s) {
59  data_file << std::to_string(s.size()) << std::endl;
60  for (std::set<uint32_t>::const_iterator it = s.begin(); it != s.end(); ++it) {
61  uint32_t value = *it;
62  data_file << std::to_string(value) << std::endl;
63  }
64 }
65 
66 static inline void SerializeT(std::ifstream& data_file, std::set<uint32_t>& s) {
67  uint32_t set_size = 0;
68  SerializeT<uint32_t>(data_file, set_size);
69  for (uint32_t i = 0; i < set_size; ++i) {
70  uint32_t value = 0;
71  SerializeT<uint32_t>(data_file, value);
72  s.insert(value);
73  }
74 }