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