102 lines
2.6 KiB
C++
102 lines
2.6 KiB
C++
#include <CBOR/Core.hpp>
|
|
#include <CBOR/Decoder.hpp>
|
|
#include <CBOR/DecoderHooks.hpp> // IWYU pragma: keep
|
|
#include <CBOR/Encoder.hpp>
|
|
#include <CBOR/Printer.hpp>
|
|
|
|
#include <array>
|
|
#include <compare> // IWYU pragma: keep
|
|
#include <cstdint>
|
|
#include <iostream>
|
|
#include <print>
|
|
#include <stdexcept>
|
|
#include <vector>
|
|
|
|
struct SomeStruct
|
|
{
|
|
std::string name;
|
|
double speed;
|
|
float fov;
|
|
std::int8_t thing;
|
|
std::int64_t slots;
|
|
std::uint32_t times;
|
|
std::vector<std::string> tools;
|
|
|
|
constexpr auto operator<=>(const SomeStruct &) const = default;
|
|
};
|
|
|
|
void EncodeHook(CBOR::Encoder &enc, const SomeStruct &value)
|
|
{
|
|
enc.EncodeTaggedMap(
|
|
15'000,
|
|
"name", value.name,
|
|
"speed", value.speed,
|
|
"fov", value.fov,
|
|
"thing", value.thing,
|
|
"slots", value.slots,
|
|
"times", value.times,
|
|
"tools", value.tools
|
|
);
|
|
}
|
|
|
|
void DecodeHook(CBOR::Decoder &dec, SomeStruct &value)
|
|
{
|
|
CBOR::StructHelper helper {
|
|
CBOR::StructMember { "name", &SomeStruct::name },
|
|
CBOR::StructMember { "speed", &SomeStruct::speed },
|
|
CBOR::StructMember { "fov", &SomeStruct::fov },
|
|
CBOR::StructMember { "thing", &SomeStruct::thing },
|
|
CBOR::StructMember { "slots", &SomeStruct::slots },
|
|
CBOR::StructMember { "times", &SomeStruct::times },
|
|
CBOR::StructMember { "tools", &SomeStruct::tools },
|
|
};
|
|
CBOR::TaggedItem tagged = dec.TaggedItem();
|
|
if (tagged.Tag() != 15'000) {
|
|
throw std::runtime_error("Expected item with tag value 15000");
|
|
}
|
|
helper.Decode(tagged.Item(), value);
|
|
}
|
|
|
|
int main()
|
|
{
|
|
using namespace std::string_view_literals;
|
|
|
|
std::array<std::uint8_t, 1024> buffer {};
|
|
|
|
SomeStruct expected {
|
|
.name = "Player1",
|
|
.speed = 5.0,
|
|
.fov = 110.0f,
|
|
.thing = -15,
|
|
.slots = 40'000'000,
|
|
.times = 1234567,
|
|
.tools = {
|
|
"pickaxe",
|
|
"sword",
|
|
"axe",
|
|
"magical arrow",
|
|
"iron ore",
|
|
},
|
|
};
|
|
|
|
try {
|
|
CBOR::Encoder enc(buffer);
|
|
enc.Encode(expected);
|
|
|
|
CBOR::ConstBuffer encoded(buffer.data(), enc.Size());
|
|
|
|
CBOR::Decoder dec(encoded);
|
|
SomeStruct res = dec.Decode<SomeStruct>();
|
|
|
|
if (res != expected) {
|
|
throw std::runtime_error("test error: the encode/decode round trip should be lossless");
|
|
}
|
|
|
|
CBOR::Print(std::cout, encoded);
|
|
|
|
std::println("The test has been completed successfully.");
|
|
}
|
|
catch (const std::exception &e) {
|
|
std::println("Error: {}", e.what());
|
|
}
|
|
}
|