Created
November 13, 2024 15:39
-
-
Save t-mat/f63f6cdc34a774045f416c7df223a352 to your computer and use it in GitHub Desktop.
[C++]ylt/struct_pack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// struct_pack : https://alibaba.github.io/yalantinglibs/en/struct_pack/struct_pack_intro.html | |
#include <iostream> | |
#include <sstream> | |
#include <vector> | |
#include <map> | |
#include <ylt/struct_pack.hpp> | |
struct person | |
{ | |
int64_t id; | |
std::string name; | |
int age; | |
double salary; | |
std::vector<int> primes; | |
std::map<int, std::string> numberStrings; | |
void print(std::stringstream &out, const std::string &prefix) const { | |
out << prefix << ".id = " << id << "\n"; | |
out << prefix << ".name = " << name << "\n"; | |
out << prefix << ".age = " << age << "\n"; | |
out << prefix << ".salary = " << salary << "\n"; | |
out << prefix << ".primes.size = " << primes.size() << "\n"; | |
out << prefix << "primes"; | |
out << "[" << primes.size() << "] = {"; | |
for (const auto &i : primes) { | |
out << " " << i << ", "; | |
} | |
out << "}\n"; | |
out << prefix << "numberStrings"; | |
out << "[" << numberStrings.size() << "] = {\n"; | |
for (const auto &kv : numberStrings) { | |
out << prefix << " { " << kv.first << ", " << kv.second << " }\n"; | |
} | |
out << prefix << "}\n"; | |
} | |
}; | |
int main() { | |
// source | |
const person src_person{ | |
.id = 1, .name = "hello struct_pack", .age = 20, .salary = 1024.42, .primes = { 2, 3, 5, 7, 11, 13, 17, 19 }, | |
.numberStrings = { | |
{ 1, "one" }, | |
{ 2, "two" }, | |
{ 3, "three" }, | |
}, | |
}; | |
// prepare serialization | |
const auto sp_size = struct_pack::get_needed_size(src_person); | |
const std::unique_ptr memory = std::make_unique<char[]>(sp_size.size()); | |
const std::span<char> buf(memory.get(), sp_size.size()); | |
// serialize | |
struct_pack::serialize_to(buf.data(), sp_size, src_person); | |
// deserialize | |
person des_person; | |
const auto error_code = struct_pack::deserialize_to(des_person, buf.data(), buf.size()); | |
// check | |
bool ok = false; | |
if (error_code) { | |
std::cout << "error_code = " << error_code.val() << " (" << error_code.message() << ")\n"; | |
} else { | |
std::stringstream out1; | |
src_person.print(out1, " "); | |
std::stringstream out2; | |
des_person.print(out2, " "); | |
std::cout << "src_person\n" << out1.str() << "\n"; | |
std::cout << "des_person\n" << out2.str() << "\n"; | |
ok = (out1.str() == out2.str()); | |
} | |
if (ok) { | |
std::cout << "OK\n"; | |
} else { | |
std::cout << "*** !!! ERROR !!! ***\n"; | |
} | |
return ok ? EXIT_SUCCESS : EXIT_FAILURE; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment