-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
72 lines (60 loc) · 2.67 KB
/
Copy pathmain.cpp
File metadata and controls
72 lines (60 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <filesystem>
#include <iostream>
#include <string>
#include "cpp_rs_serde.h"
#include "example.h"
int main(int, char **)
{
try
{
const std::filesystem::path source_root = std::filesystem::path(__FILE__).parent_path();
const std::string header_path = (source_root / "example.h").string();
const cpp_rs::Schema schema(header_path);
// Schema JSON is optional and only useful for inspection or debugging.
std::cout << "[1] Schema JSON:\n"
<< schema.schema_json() << "\n";
// Live C++ object.
Company company{
"TechCorp",
{{1, "Alice", true, Role::Admin},
{2, "Bob", false, Role::User},
{3, "Charlie", true, Role::Guest}}};
// Live object -> JSON string, driven entirely by the Rust schema.
const std::string serialized = schema.serialize(company, true);
std::cout << "[2] Serialized Company:\n"
<< serialized << "\n";
// Edit the JSON outside of C++ types to prove the round trip is data driven.
std::string modified_json = serialized;
const std::string bob_name = "\"Bob\"";
const std::string robert_name = "\"Robert\"";
const std::size_t bob_pos = modified_json.find(bob_name);
if (bob_pos != std::string::npos)
{
modified_json.replace(bob_pos, bob_name.length(), robert_name);
std::cout << "[3] Replaced Bob with Robert in the JSON string\n";
}
// JSON string -> new live object, no per-type C++ code involved.
const Company restored = schema.deserialize<Company>(modified_json);
std::cout << "[4] Restored Company: " << restored.name << " ("
<< restored.employees.size() << " employees)\n";
for (const Person &employee : restored.employees)
{
std::cout << " - " << employee.id << " " << employee.name
<< " active=" << (employee.active ? "true" : "false")
<< " role=" << static_cast<int>(employee.role) << "\n";
}
// The same generic path works for any other schema type.
const Person single = schema.deserialize<Person>(
R"({"id":42,"name":"Dana","active":true,"role":"Guest"})");
std::cout << "[5] Restored Person: " << single.name
<< " role=" << static_cast<int>(single.role) << "\n";
std::cout << "[6] Re-serialized restored Company:\n"
<< schema.serialize(restored, true) << "\n";
return 0;
}
catch (const std::exception &error)
{
std::cerr << error.what() << "\n";
return 1;
}
}