playground-sdk/core/save_snapshot.h

44 lines
1.5 KiB
C++

#pragma once
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
namespace playground {
struct SaveTable;
struct SaveValue {
using Table = std::shared_ptr<SaveTable>;
std::variant<bool, double, std::string, Table> data;
SaveValue() : data(false) {}
SaveValue(bool value) : data(value) {}
SaveValue(double value) : data(value) {}
SaveValue(std::string value) : data(std::move(value)) {}
SaveValue(const char* value) : data(std::string(value)) {}
SaveValue(Table value) : data(std::move(value)) {}
};
struct SaveEntry { SaveValue key; SaveValue value; };
struct SaveTable { std::vector<SaveEntry> entries; };
struct SaveLimits {
size_t maxBytes = 16 * 1024 * 1024;
size_t maxStringBytes = 1024 * 1024;
size_t maxEntries = 200000;
size_t maxDepth = 64;
};
// Versioned binary snapshot. Keys must be finite numbers or nonempty strings.
bool encodeSave(const SaveValue& root, std::string& bytes, std::string* error = nullptr,
const SaveLimits& limits = {});
bool decodeSave(std::string_view bytes, SaveValue& root, std::string* error = nullptr,
const SaveLimits& limits = {});
bool writeSaveAtomic(const std::filesystem::path& path, std::string_view bytes,
std::string* error = nullptr);
bool readSave(const std::filesystem::path& path, std::string& bytes,
std::string* error = nullptr, const SaveLimits& limits = {});
} // namespace playground