-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp_rs_serde.h
More file actions
375 lines (340 loc) · 13.4 KB
/
Copy pathcpp_rs_serde.h
File metadata and controls
375 lines (340 loc) · 13.4 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#pragma once
#include <cctype>
#include <charconv>
#include <cstdint>
#include <cstdlib>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "cpp_rs_reflect.h"
extern "C" {
void *cpp_rs_init(const char *path);
char *cpp_rs_last_error();
char *cpp_rs_schema_json(void *schema);
char *cpp_rs_serialize(void *schema, const char *type_name, const char *json_value, bool indent);
char *cpp_rs_deserialize(void *schema, const char *type_name, const char *json_value, bool indent);
char *cpp_rs_normalize(void *schema, const char *type_name, const char *json_value, bool indent);
void cpp_rs_free_schema(void *schema);
void cpp_rs_free_string(char *ptr);
}
namespace cpp_rs {
struct RustStringDeleter {
void operator()(char *value) const noexcept { cpp_rs_free_string(value); }
};
using RustString = std::unique_ptr<char, RustStringDeleter>;
struct SchemaDeleter {
void operator()(void *value) const noexcept { cpp_rs_free_schema(value); }
};
using SchemaHandle = std::unique_ptr<void, SchemaDeleter>;
inline std::string last_error() {
RustString message(cpp_rs_last_error());
return message ? std::string(message.get()) : std::string();
}
inline std::string copy_rust_string(char *value, std::string_view operation) {
RustString owned(value);
if (!owned) {
const std::string reason = last_error();
throw std::runtime_error(std::string(operation) + " failed" +
(reason.empty() ? "" : ": " + reason));
}
return std::string(owned.get());
}
inline std::string quote_json(std::string_view value) {
std::string result;
result.reserve(value.size() + 2);
result.push_back('"');
for (const char character : value) {
switch (character) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\b': result += "\\b"; break;
case '\f': result += "\\f"; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default: result.push_back(character); break;
}
}
result.push_back('"');
return result;
}
namespace detail {
inline void skip_json_whitespace(std::string_view &value) {
while (!value.empty() && std::isspace(static_cast<unsigned char>(value.front()))) {
value.remove_prefix(1);
}
}
inline char consume_json_char(std::string_view &value, char expected) {
skip_json_whitespace(value);
if (value.empty() || value.front() != expected) {
throw std::runtime_error(std::string("Expected '") + expected + "' in JSON payload");
}
value.remove_prefix(1);
return expected;
}
inline std::string parse_json_string(std::string_view &value) {
skip_json_whitespace(value);
if (value.empty() || value.front() != '"') {
throw std::runtime_error("Expected string value in JSON payload");
}
value.remove_prefix(1);
std::string result;
while (!value.empty()) {
const char character = value.front();
value.remove_prefix(1);
if (character == '"') {
return result;
}
if (character == '\\') {
if (value.empty()) {
throw std::runtime_error("Invalid escape sequence in JSON string");
}
const char escaped = value.front();
value.remove_prefix(1);
switch (escaped) {
case '"': result.push_back('"'); break;
case '\\': result.push_back('\\'); break;
case '/': result.push_back('/'); break;
case 'b': result.push_back('\b'); break;
case 'f': result.push_back('\f'); break;
case 'n': result.push_back('\n'); break;
case 'r': result.push_back('\r'); break;
case 't': result.push_back('\t'); break;
case 'u': {
if (value.size() < 4) {
throw std::runtime_error("Invalid unicode escape in JSON string");
}
const std::string hex(value.substr(0, 4));
value.remove_prefix(4);
char *end = nullptr;
const unsigned long codepoint = std::strtoul(hex.c_str(), &end, 16);
if (end == hex.c_str() || codepoint > 0x10FFFF) {
throw std::runtime_error("Invalid unicode escape in JSON string");
}
if (codepoint <= 0x7F) {
result.push_back(static_cast<char>(codepoint));
} else if (codepoint <= 0x7FF) {
result.push_back(static_cast<char>(0xC0 | ((codepoint >> 6) & 0x1F)));
result.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
} else {
result.push_back(static_cast<char>(0xE0 | ((codepoint >> 12) & 0x0F)));
result.push_back(static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)));
result.push_back(static_cast<char>(0x80 | (codepoint & 0x3F)));
}
break;
}
default:
throw std::runtime_error("Unsupported JSON escape sequence");
}
continue;
}
if (static_cast<unsigned char>(character) < 0x20) {
throw std::runtime_error("Invalid control character in JSON string");
}
result.push_back(character);
}
throw std::runtime_error("Unterminated string in JSON payload");
}
inline std::string parse_json_number_text(std::string_view &value) {
skip_json_whitespace(value);
const std::size_t start = value.find_first_not_of("-0123456789.eE+");
if (start == std::string_view::npos) {
std::string number(value);
value = {};
return number;
}
const std::string number(value.substr(0, start));
value.remove_prefix(start);
return number;
}
} // namespace detail
template <typename T>
inline constexpr bool is_sequence_v = false;
template <typename T, typename Allocator>
inline constexpr bool is_sequence_v<std::vector<T, Allocator>> = true;
/// Writes any supported value as the positional wire form: aggregates become
/// declaration-ordered arrays and enums become their underlying integers. The
/// Rust schema turns that into named JSON, so no per-type code lives here.
template <typename T>
void write_value(const T &value, std::string &out) {
using Value = std::remove_cvref_t<T>;
if constexpr (std::is_same_v<Value, std::string>) {
out += quote_json(value);
} else if constexpr (std::is_same_v<Value, bool>) {
out += value ? "true" : "false";
} else if constexpr (std::is_enum_v<Value>) {
out += std::to_string(static_cast<std::int64_t>(value));
} else if constexpr (std::is_floating_point_v<Value>) {
char buffer[32];
const auto result = std::to_chars(buffer, buffer + sizeof(buffer), value);
out.append(buffer, result.ptr);
} else if constexpr (std::is_arithmetic_v<Value>) {
out += std::to_string(value);
} else if constexpr (is_sequence_v<Value>) {
out.push_back('[');
bool first = true;
for (const auto &item : value) {
if (!first) {
out.push_back(',');
}
first = false;
write_value(item, out);
}
out.push_back(']');
} else if constexpr (reflect::is_reflectable_aggregate_v<Value>) {
out.push_back('[');
reflect::visit_fields(value, [&out](const auto &...fields) {
bool first = true;
const auto emit = [&](const auto &field) {
if (!first) {
out.push_back(',');
}
first = false;
write_value(field, out);
};
(emit(fields), ...);
});
out.push_back(']');
} else {
static_assert(!sizeof(Value *), "Unsupported type for cpp_rs serialization");
}
}
/// Reads the positional wire form produced by the Rust layer back into a value.
template <typename T>
T read_value(std::string_view &json) {
using Value = std::remove_cvref_t<T>;
if constexpr (std::is_same_v<Value, std::string>) {
return detail::parse_json_string(json);
} else if constexpr (std::is_same_v<Value, bool>) {
detail::skip_json_whitespace(json);
if (json.compare(0, 4, "true") == 0) {
json.remove_prefix(4);
return true;
}
if (json.compare(0, 5, "false") == 0) {
json.remove_prefix(5);
return false;
}
throw std::runtime_error("Expected boolean value in JSON payload");
} else if constexpr (std::is_enum_v<Value>) {
return static_cast<Value>(read_value<std::int64_t>(json));
} else if constexpr (std::is_arithmetic_v<Value>) {
detail::skip_json_whitespace(json);
const std::string number_text = detail::parse_json_number_text(json);
if (number_text.empty()) {
throw std::runtime_error("Expected numeric value in JSON payload");
}
char *end = nullptr;
const double parsed = std::strtod(number_text.c_str(), &end);
if (end == number_text.c_str()) {
throw std::runtime_error("Malformed numeric value in JSON payload");
}
return static_cast<Value>(parsed);
} else if constexpr (is_sequence_v<Value>) {
detail::consume_json_char(json, '[');
Value values;
detail::skip_json_whitespace(json);
if (!json.empty() && json.front() == ']') {
json.remove_prefix(1);
return values;
}
while (true) {
values.push_back(read_value<typename Value::value_type>(json));
detail::skip_json_whitespace(json);
if (!json.empty() && json.front() == ',') {
json.remove_prefix(1);
continue;
}
detail::consume_json_char(json, ']');
break;
}
return values;
} else if constexpr (reflect::is_reflectable_aggregate_v<Value>) {
detail::consume_json_char(json, '[');
Value result{};
reflect::visit_fields(result, [&json](auto &...fields) {
bool first = true;
const auto load = [&](auto &field) {
if (!first) {
detail::consume_json_char(json, ',');
}
first = false;
field = read_value<std::remove_cvref_t<decltype(field)>>(json);
};
(load(fields), ...);
});
detail::consume_json_char(json, ']');
return result;
} else {
static_assert(!sizeof(Value *), "Unsupported type for cpp_rs deserialization");
}
}
template <typename T>
constexpr std::string_view schema_type_name() {
#if defined(__clang__) || defined(__GNUC__)
constexpr std::string_view signature = __PRETTY_FUNCTION__;
constexpr std::string_view marker = "T = ";
const std::size_t begin = signature.find(marker) + marker.size();
std::size_t end = signature.find(';', begin);
if (end == std::string_view::npos) {
end = signature.find(']', begin);
}
return signature.substr(begin, end - begin);
#else
static_assert(!sizeof(T), "schema_type_name requires a compiler-specific implementation");
#endif
}
class Schema {
public:
explicit Schema(const std::string &header_path)
: handle_(cpp_rs_init(header_path.c_str())) {
if (!handle_) {
const std::string reason = last_error();
throw std::runtime_error("Failed to initialize schema from " + header_path +
(reason.empty() ? "" : ": " + reason));
}
}
[[nodiscard]] std::string schema_json() const {
return copy_rust_string(cpp_rs_schema_json(handle_.get()), "Schema JSON retrieval");
}
/// Live C++ object -> named JSON string.
template <typename T>
[[nodiscard]] std::string serialize(const T &value, bool indent = false) const {
using Value = std::remove_cvref_t<T>;
const std::string type_name(schema_type_name<Value>());
std::string payload;
write_value(value, payload);
return copy_rust_string(
cpp_rs_serialize(handle_.get(), type_name.c_str(), payload.c_str(), indent),
"Serialization");
}
/// Named JSON string -> live C++ object of any reflectable type.
template <typename T>
[[nodiscard]] T deserialize(std::string_view json) const {
using Value = std::remove_cvref_t<T>;
const std::string type_name(schema_type_name<Value>());
const std::string input(json);
const std::string positional = copy_rust_string(
cpp_rs_deserialize(handle_.get(), type_name.c_str(), input.c_str(), false),
"Deserialization");
std::string_view view = positional;
return read_value<Value>(view);
}
/// Validates named JSON against the schema and returns its canonical form.
template <typename T>
[[nodiscard]] std::string normalize(std::string_view json, bool indent = false) const {
using Value = std::remove_cvref_t<T>;
const std::string type_name(schema_type_name<Value>());
const std::string input(json);
return copy_rust_string(
cpp_rs_normalize(handle_.get(), type_name.c_str(), input.c_str(), indent),
"Normalization");
}
[[nodiscard]] void *native_handle() const noexcept { return handle_.get(); }
private:
SchemaHandle handle_;
};
} // namespace cpp_rs