Conversion to JSON.

This commit is contained in:
Pcornat 2024-03-04 17:25:11 +01:00
parent a693da20bf
commit 2c3d736d5f
Signed by: Pcornat
GPG key ID: E0326CC678A00BDD
4 changed files with 179 additions and 12 deletions

View file

@ -2,9 +2,18 @@
// Created by postaron on 23/02/24.
//
#include "billy_objects.hpp"
#include <spdlog/spdlog.h>
#include "characteristic/characteristic.hpp"
#include "character_sheet.hpp"
std::uint32_t constexpr const_hash(const char *input) {
return *input ? static_cast<unsigned int>(*input) + 33 * const_hash(input + 1) : 5381;
}
constexpr std::uint32_t weaponsHash = const_hash("weapons");
constexpr std::uint32_t equipmentHash = const_hash("equipments");
constexpr std::uint32_t toolsHash = const_hash("tools");
namespace character {
using characteristic::Characteristic;
@ -205,4 +214,41 @@ namespace character {
}
}, object);
}
void BillyObjects::from_json(const json &j, BillyObjects::container &billy) {
for (const auto &element: j) {
const std::uint32_t key = element[0].get<std::uint32_t>();
const std::uint8_t value = element[1].get<std::uint8_t>();
switch (key) {
case weaponsHash:
billy.push_back(static_cast<weapons>(value));
break;
case equipmentHash:
billy.push_back(static_cast<equipments>(value));
break;
case toolsHash:
billy.push_back(static_cast<tools>(value));
break;
default:
SPDLOG_CRITICAL("Deserialize billy objects error, wrong hash.");
throw std::runtime_error("Deserialize billy objects error, wrong hash.");
}
}
}
void BillyObjects::to_json(json &j, const BillyObjects::container &billy) {
for (const auto &object: billy) {
std::visit(overloaded{
[&j](const weapons weapon) {
j.emplace_back(std::pair{ weaponsHash, static_cast<std::uint8_t>(weapon) });
},
[&j](const equipments equipment) {
j.emplace_back(std::pair{ equipmentHash, static_cast<std::uint8_t>(equipment) });
},
[&j](const tools tool) {
j.emplace_back(std::pair{ toolsHash, static_cast<std::uint8_t>(tool) });
}
}, object);
}
}
}