Wizard
Software Engineering Project - Wizard
Loading...
Searching...
No Matches
vector_utils.h
1//
2// Created by Manuel on 10.02.2021.
3//
4// Helper functions to serialize vectors containing objects that implement the 'serializable' class.
5
6#ifndef WIZARD_VECTOR_UTILS_H
7#define WIZARD_VECTOR_UTILS_H
8
9#include <vector>
10#include "serializable.h"
11#include "unique_serializable.h"
12#include "../../rapidjson/include/rapidjson/document.h"
13#include "../game_state/player/player.h"
14
15
16namespace vector_utils {
17
18 template<class T, class B> struct derived_from {
19 static void constraints(T* p) { B* pb = p; }
20 derived_from() { void(*p)(T*) = constraints; }
21 };
22
23 template<class T>
24 /* WARNING: can only be called with vectors containing elements of type T that derives from "serializable" */
25 static rapidjson::Value serialize_vector(const std::vector<T*>& serializables, rapidjson::Document::AllocatorType& allocator) {
26 derived_from<T,serializable>(); // ensure T derives from serializable
27 rapidjson::Value arr_val(rapidjson::kArrayType);
28 for (int i = 0; i < serializables.size(); i++) {
29 rapidjson::Value elem(rapidjson::kObjectType);
30 serializables[i]->write_into_json(elem, allocator);
31 arr_val.PushBack(elem, allocator);
32 }
33 return arr_val;
34 }
35
36 static rapidjson::Value serialize_cards_vector(
37 const std::vector<std::pair<card*, player*>>& cards,
38 rapidjson::Document::AllocatorType& allocator) {
39 rapidjson::Value arr_val(rapidjson::kArrayType);
40 for (const auto& pair : cards) {
41 rapidjson::Value obj(rapidjson::kObjectType);
42
43 // Serialize the pair componentsss
44 rapidjson::Value card_val(rapidjson::kObjectType);
45 pair.first->write_into_json(card_val, allocator);
46 obj.AddMember("card", card_val, allocator);
47
48 rapidjson::Value player_val(rapidjson::kObjectType);
49 pair.second->write_into_json(player_val, allocator);
50 obj.AddMember("player", player_val, allocator);
51
52 arr_val.PushBack(obj, allocator);
53 }
54 return arr_val;
55 }
56
57}
58
59#endif //WIZARD_VECTOR_UTILS_H
Definition vector_utils.h:18