Line data Source code
1 : /*
2 : * Protobuf serialization library - JSON serialize library.
3 : *
4 : * Copyright (c) 2024 Antonin Kriz <antonin.kriz@gmail.com>
5 : * Released under the MIT License. See LICENSE in the project root.
6 : */
7 :
8 : #pragma once
9 :
10 : #include "../concepts.h"
11 :
12 : #include "../to_from_chars.h"
13 : #include "base64.h"
14 : #include "field.hpp"
15 : #include "options.h"
16 : #include "spb/utf8.h"
17 : #include <algorithm>
18 : #include <array>
19 : #include <charconv>
20 : #include <cinttypes>
21 : #include <cmath>
22 : #include <cstddef>
23 : #include <cstdint>
24 : #include <cstring>
25 : #include <memory>
26 : #include <spb/io/io.hpp>
27 : #include <stdexcept>
28 : #include <string>
29 : #include <string_view>
30 : #include <sys/types.h>
31 : #include <type_traits>
32 :
33 : namespace spb::json::detail
34 : {
35 : struct ostream_size
36 : {
37 : static constexpr bool size_only = true;
38 :
39 : const serialize_options options = {};
40 : bool put_comma = false;
41 : size_t indent = 0;
42 : size_t size = 0;
43 :
44 4381853 : void write(uint8_t) noexcept
45 : {
46 4381853 : size += sizeof(uint8_t);
47 4381853 : }
48 :
49 3853 : void write(const void *, size_t data_size) noexcept
50 : {
51 3853 : size += data_size;
52 3853 : }
53 :
54 1320 : auto end() -> size_t
55 : {
56 1320 : if (options.pretty_print)
57 0 : write('\n');
58 :
59 1320 : return size;
60 : }
61 : };
62 :
63 : struct ostream_buffer
64 : {
65 : static constexpr bool size_only = false;
66 :
67 : const serialize_options options;
68 : uint8_t *p_buffer;
69 : bool put_comma = false;
70 : size_t indent = 0;
71 :
72 4379307 : void write(uint8_t byte) noexcept
73 : {
74 4379307 : *p_buffer++ = byte;
75 4379307 : }
76 :
77 2617 : void write(const void *data, size_t data_size) noexcept
78 : {
79 2617 : memcpy(p_buffer, data, data_size);
80 2617 : p_buffer += data_size;
81 2617 : }
82 :
83 898 : auto end(uint8_t *start) -> size_t
84 : {
85 898 : if (options.pretty_print)
86 0 : write('\n');
87 :
88 898 : return p_buffer - start;
89 : }
90 : };
91 :
92 : struct ostream_writer
93 : {
94 : static constexpr bool size_only = false;
95 :
96 : const serialize_options options;
97 : const spb::io::writer on_write;
98 : size_t size = 0;
99 : size_t indent = 0;
100 : bool put_comma = false;
101 :
102 2050 : void write(uint8_t byte)
103 : {
104 2050 : write(&byte, 1);
105 2050 : }
106 :
107 3170 : void write(const void *data, size_t data_size)
108 : {
109 3170 : on_write(data, data_size);
110 3170 : size += data_size;
111 3170 : }
112 :
113 388 : auto end() -> size_t
114 : {
115 388 : if (options.pretty_print)
116 0 : write('\n');
117 :
118 388 : return size;
119 : }
120 : };
121 :
122 : template <field_attributes = field_attributes{}>
123 : size_t serialize_size(const auto &value, const serialize_options &options);
124 :
125 : // Protocol Buffers - Google's data interchange format
126 : // Copyright 2008 Google Inc. All rights reserved.
127 : //
128 : // Use of this source code is governed by a BSD-style
129 : // license that can be found in the LICENSE file or at
130 : // https://developers.google.com/open-source/licenses/bsd
131 : //
132 : // Returns true if x round-trips through being cast to a double, i.e., if
133 : // x is represenable exactly as a double. This is a slightly weaker condition
134 : // than x < 2^52.
135 12 : template <typename Int> bool RoundTripsThroughDouble(Int x)
136 : {
137 12 : auto d = static_cast<double>(x);
138 : // d has guaranteed to be finite with no fractional part, because it came from
139 : // an integer, so we only need to check that it is not outside of the
140 : // representable range of `int`. The way to do this is somewhat not obvious:
141 : // UINT64_MAX isn't representable, and what it gets rounded to when we go
142 : // int->double is unspecified!
143 : //
144 : // Thus, we have to go through ldexp.
145 12 : double min = 0;
146 12 : double max_plus_one = std::ldexp(1.0, sizeof(Int) * 8);
147 : if (std::is_signed<Int>::value)
148 : {
149 0 : max_plus_one /= 2;
150 0 : min = -max_plus_one;
151 : }
152 :
153 12 : if (d < min || d >= max_plus_one)
154 : {
155 12 : return false;
156 : }
157 :
158 0 : return static_cast<Int>(d) == x;
159 : }
160 :
161 115 : void write_uft8(auto &stream, uint32_t codepoint)
162 : {
163 : char buffer[4];
164 :
165 115 : const auto size = spb::detail::utf8::encode_point(codepoint, buffer);
166 115 : stream.write(buffer, size);
167 115 : }
168 :
169 6 : void write_unicode(auto &stream, uint32_t codepoint)
170 : {
171 6 : if (codepoint <= 0xffff)
172 : {
173 6 : char buffer[8] = {};
174 6 : auto size = snprintf(buffer, sizeof(buffer), "\\u%04" PRIx32, codepoint);
175 6 : return stream.write(buffer, size);
176 : }
177 0 : if (codepoint <= 0x10FFFF)
178 : {
179 0 : codepoint -= 0x10000;
180 :
181 0 : auto high = static_cast<uint16_t>((codepoint >> 10) + 0xD800);
182 0 : auto low = static_cast<uint16_t>((codepoint & 0x3FF) + 0xDC00);
183 0 : char buffer[16] = {};
184 0 : auto size = snprintf(buffer, sizeof(buffer), "\\u%04" PRIx16 "\\u%04" PRIx16, high, low);
185 0 : return stream.write(buffer, size);
186 : }
187 0 : throw std::invalid_argument("invalid utf8");
188 : }
189 :
190 2591 : template <size_t N> void write_string(auto &stream, const char (&string)[N])
191 : {
192 2591 : stream.write(string, N - 1);
193 2591 : }
194 :
195 1666 : inline constexpr auto is_ascii_escape(uint8_t c) -> bool
196 : {
197 1666 : switch (c)
198 : {
199 26 : case '\\':
200 : case '\"':
201 : case '<':
202 : case '>':
203 26 : return true;
204 1640 : default:
205 1640 : return (c < ' ') || c >= 0x7f;
206 : }
207 : }
208 :
209 609 : inline constexpr auto is_printable_ascii(std::string_view str) -> bool
210 : {
211 609 : return std::none_of(str.begin(), str.end(), is_ascii_escape);
212 : }
213 :
214 243 : inline constexpr auto is_escape(uint32_t c) -> bool
215 : {
216 243 : constexpr std::array<std::pair<uint32_t, uint32_t>, 20> escapes = {
217 : {{0, 31}, {34, 34}, {60, 60}, {62, 62}, {92, 92},
218 : {127, 159}, {173, 173}, {1536, 1539}, {1757, 1757}, {1807, 1807},
219 : {6068, 6069}, {8203, 8207}, {8232, 8238}, {8288, 8292}, {8298, 8303},
220 : {65279, 65279}, {65529, 65531}, {119155, 119162}, {917505, 917505}, {917536, 917631}}};
221 :
222 243 : auto it = std::lower_bound(escapes.begin(), escapes.end(), c,
223 1112 : [](auto range, auto c) { return range.second < c; });
224 243 : return it != escapes.end() && it->first <= c;
225 : }
226 :
227 609 : void write_escaped(auto &stream, std::string_view str)
228 : {
229 609 : if (is_printable_ascii(str)) [[likely]]
230 : {
231 560 : stream.write(str.data(), str.size());
232 560 : return;
233 : }
234 :
235 49 : uint32_t codepoint = 0;
236 49 : uint32_t state = spb::detail::utf8::ok;
237 329 : for (uint8_t c : str)
238 : {
239 280 : if (spb::detail::utf8::decode_point(&state, &codepoint, c) != spb::detail::utf8::ok) [[unlikely]]
240 37 : continue;
241 :
242 243 : if (is_escape(codepoint)) [[unlikely]]
243 : {
244 128 : switch (codepoint)
245 : {
246 24 : case '"':
247 24 : write_string(stream, R"(\")");
248 24 : break;
249 16 : case '\\':
250 16 : write_string(stream, R"(\\)");
251 16 : break;
252 10 : case '\b':
253 10 : write_string(stream, R"(\b)");
254 10 : break;
255 10 : case '\f':
256 10 : write_string(stream, R"(\f)");
257 10 : break;
258 16 : case '\n':
259 16 : write_string(stream, R"(\n)");
260 16 : break;
261 16 : case '\r':
262 16 : write_string(stream, R"(\r)");
263 16 : break;
264 30 : case '\t':
265 30 : write_string(stream, R"(\t)");
266 30 : break;
267 6 : default:
268 6 : write_unicode(stream, codepoint);
269 : }
270 : }
271 : else
272 : {
273 115 : write_uft8(stream, codepoint);
274 : }
275 : }
276 :
277 49 : if (state != spb::detail::utf8::ok) [[unlikely]]
278 1 : throw std::runtime_error("invalid utf8");
279 : }
280 :
281 0 : void put_newline(auto &stream)
282 : {
283 0 : stream.write('\n');
284 0 : }
285 :
286 0 : void indent_increment(auto &stream)
287 : {
288 0 : ++stream.indent;
289 0 : }
290 :
291 0 : void indent_decrement(auto &stream)
292 : {
293 0 : assert(stream.indent > 0);
294 :
295 0 : --stream.indent;
296 0 : }
297 :
298 0 : void indent(auto &stream)
299 : {
300 0 : for (size_t i = 0; i < stream.indent; ++i)
301 : {
302 0 : stream.write(' ');
303 : }
304 0 : }
305 :
306 3904 : void indent_if_needed(auto &stream)
307 : {
308 3904 : if (!stream.options.pretty_print)
309 3904 : return;
310 :
311 0 : put_newline(stream);
312 0 : indent(stream);
313 : }
314 :
315 3904 : void put_comma_if_needed(auto &stream)
316 : {
317 3904 : if (stream.put_comma)
318 884 : stream.write(',');
319 :
320 3904 : stream.put_comma = true;
321 3904 : indent_if_needed(stream);
322 3904 : }
323 :
324 3485 : void container_begin(auto &stream, char c)
325 : {
326 3485 : stream.put_comma = false;
327 3485 : stream.write(c);
328 :
329 3485 : if (stream.options.pretty_print)
330 0 : indent_increment(stream);
331 3485 : }
332 :
333 3451 : void container_end(auto &stream, char c)
334 : {
335 3451 : if (!stream.options.pretty_print) [[likely]]
336 : {
337 3451 : stream.put_comma = true;
338 3451 : stream.write(c);
339 3451 : return;
340 : }
341 :
342 0 : indent_decrement(stream);
343 0 : if (stream.put_comma)
344 : {
345 0 : put_newline(stream);
346 0 : indent(stream);
347 : }
348 :
349 0 : stream.put_comma = true;
350 0 : stream.write(c);
351 : }
352 :
353 42 : void serialize_key_value(auto &stream, const spb::detail::proto_field_string auto &key)
354 : {
355 42 : stream.write(key.data(), key.size());
356 42 : }
357 :
358 2301 : void serialize_key_value(auto &stream, const std::string_view &key)
359 : {
360 2301 : stream.write(key.data(), key.size());
361 2301 : }
362 :
363 38 : void serialize_key_value(auto &stream, const auto &key)
364 : {
365 38 : serialize<field_attributes{}>(stream, key);
366 38 : }
367 :
368 2381 : void serialize_key(auto &stream, const auto &key)
369 : {
370 2381 : put_comma_if_needed(stream);
371 :
372 2381 : stream.write('"');
373 2381 : serialize_key_value(stream, key);
374 2381 : write_string(stream, R"(":)");
375 :
376 2381 : if (stream.options.pretty_print)
377 0 : stream.write(' ');
378 2381 : }
379 :
380 : template <field_attributes> void serialize(auto &stream, const bool &value);
381 : template <field_attributes> void serialize(auto &stream, const bool &value, std::string_view field);
382 :
383 : template <field_attributes>
384 : void serialize(auto &stream, const spb::detail::proto_field_int_or_float auto &value);
385 : template <field_attributes>
386 : void serialize(auto &stream, const spb::detail::proto_field_int_or_float auto &value, std::string_view field);
387 :
388 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_message auto &value);
389 : template <field_attributes>
390 : void serialize(auto &stream, const spb::detail::proto_message auto &value, std::string_view field);
391 :
392 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_enum auto &value);
393 : template <field_attributes>
394 : void serialize(auto &stream, const spb::detail::proto_enum auto &value, std::string_view field);
395 :
396 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_field_string auto &value);
397 : template <field_attributes>
398 : void serialize(auto &stream, const spb::detail::proto_field_string auto &value, std::string_view field);
399 :
400 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_field_bytes auto &value);
401 : template <field_attributes>
402 : void serialize(auto &stream, const spb::detail::proto_field_bytes auto &value, std::string_view field);
403 :
404 : template <field_attributes attributes>
405 : void serialize(auto &stream, const spb::detail::proto_label_optional auto &p_value);
406 : template <field_attributes attributes>
407 : void serialize(auto &stream, const spb::detail::proto_label_optional auto &p_value, std::string_view field);
408 :
409 : template <field_attributes attributes, typename T>
410 : void serialize(auto &stream, const std::unique_ptr<T> &p_value);
411 : template <field_attributes attributes, typename T>
412 : void serialize(auto &stream, const std::unique_ptr<T> &p_value, std::string_view field);
413 :
414 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_label_repeated auto &value);
415 : template <field_attributes>
416 : void serialize(auto &stream, const spb::detail::proto_label_repeated auto &value, std::string_view field);
417 :
418 : template <field_attributes>
419 : void serialize(auto &stream, const spb::detail::proto_label_repeated_fixed_size auto &value);
420 : template <field_attributes>
421 : void serialize(auto &stream, const spb::detail::proto_label_repeated_fixed_size auto &value,
422 : std::string_view field);
423 :
424 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_map auto &map);
425 : template <field_attributes>
426 : void serialize(auto &stream, const spb::detail::proto_map auto &map, std::string_view field);
427 :
428 88 : template <field_attributes> void serialize(auto &stream, const bool &value)
429 : {
430 88 : return value ? write_string(stream, "true") : write_string(stream, "false");
431 : }
432 :
433 124 : void serialize_enum(auto &stream, std::string_view value)
434 : {
435 124 : stream.write('"');
436 124 : stream.write(value.data(), value.size());
437 124 : stream.write('"');
438 124 : }
439 :
440 617 : template <field_attributes attributes> void serialize(auto &stream, const std::string_view &value)
441 : {
442 : using stream_type = std::remove_cvref_t<decltype(stream)>;
443 :
444 : if constexpr (!stream_type::size_only && attributes.max_size)
445 40 : check_size(value.size(), attributes.max_size);
446 :
447 609 : stream.write('"');
448 609 : write_escaped(stream, value);
449 608 : stream.write('"');
450 608 : }
451 :
452 : template <field_attributes attributes>
453 617 : void serialize(auto &stream, const spb::detail::proto_field_string auto &value)
454 : {
455 617 : serialize<attributes>(stream, std::string_view(value.data(), value.size()));
456 608 : }
457 :
458 : template <field_attributes>
459 1851 : void serialize(auto &stream, const spb::detail::proto_field_int_or_float auto &value)
460 : {
461 : using value_type = std::remove_cvref_t<decltype(value)>;
462 :
463 1851 : auto buffer = std::array<char, 32>();
464 5553 : auto result = spb_std_emu::to_chars(buffer.data(), buffer.data() + sizeof(buffer), value);
465 : if constexpr (std::is_same_v<value_type, int64_t> || std::is_same_v<value_type, uint64_t>)
466 : {
467 372 : if (!stream.options.quote_inexact_int64 || RoundTripsThroughDouble(value)) [[likely]]
468 : {
469 1080 : stream.write(buffer.data(), static_cast<size_t>(result.ptr - buffer.data()));
470 : }
471 : else
472 : {
473 12 : stream.write('"');
474 36 : stream.write(buffer.data(), static_cast<size_t>(result.ptr - buffer.data()));
475 12 : stream.write('"');
476 : }
477 : }
478 : else
479 : {
480 4437 : stream.write(buffer.data(), static_cast<size_t>(result.ptr - buffer.data()));
481 : }
482 1851 : }
483 :
484 36 : template <field_attributes attributes> void serialize(auto &stream, const bool &value, std::string_view field)
485 : {
486 36 : serialize_key(stream, field);
487 36 : serialize<attributes>(stream, value);
488 36 : }
489 :
490 : template <field_attributes attributes>
491 958 : void serialize(auto &stream, const spb::detail::proto_field_int_or_float auto &value, std::string_view field)
492 : {
493 958 : serialize_key(stream, field);
494 958 : serialize<attributes>(stream, value);
495 958 : }
496 :
497 : template <field_attributes attributes>
498 363 : void serialize(auto &stream, const spb::detail::proto_field_string auto &value, std::string_view field)
499 : {
500 363 : if (value.empty())
501 6 : return;
502 :
503 357 : serialize_key(stream, field);
504 357 : serialize<attributes>(stream, value);
505 : }
506 :
507 : template <field_attributes attributes>
508 388 : void serialize(auto &stream, const spb::detail::proto_field_bytes auto &value)
509 : {
510 : using stream_type = std::remove_cvref_t<decltype(stream)>;
511 :
512 : if constexpr (!stream_type::size_only && attributes.max_size)
513 40 : check_size(value.size(), attributes.max_size);
514 :
515 380 : stream.write('"');
516 380 : base64_encode(stream, value);
517 380 : stream.write('"');
518 380 : }
519 :
520 : template <field_attributes attributes>
521 152 : void serialize(auto &stream, const spb::detail::proto_field_bytes auto &value, std::string_view field)
522 : {
523 152 : if (value.empty())
524 6 : return;
525 :
526 146 : serialize_key(stream, field);
527 146 : serialize<attributes>(stream, value);
528 : }
529 :
530 : template <field_attributes attributes>
531 998 : void serialize(auto &stream, const spb::detail::proto_label_repeated auto &value, std::string_view field)
532 : {
533 998 : if (value.empty())
534 318 : return;
535 :
536 680 : serialize_key(stream, field);
537 680 : serialize<attributes>(stream, value);
538 : }
539 :
540 : template <field_attributes attributes>
541 706 : void serialize(auto &stream, const spb::detail::proto_label_repeated auto &value)
542 : {
543 : using stream_type = std::remove_cvref_t<decltype(stream)>;
544 :
545 : if constexpr (!stream_type::size_only && attributes.max_count)
546 85 : check_size(value.size(), attributes.max_count);
547 :
548 689 : container_begin(stream, '[');
549 2825 : for (const auto &v : value)
550 : {
551 1475 : put_comma_if_needed(stream);
552 :
553 : if constexpr (std::is_same_v<typename std::decay_t<decltype(value)>::value_type, bool>)
554 : {
555 40 : serialize<attributes>(stream, bool(v));
556 : }
557 : else
558 : {
559 1435 : serialize<attributes>(stream, v);
560 : }
561 : }
562 689 : container_end(stream, ']');
563 689 : }
564 :
565 : template <field_attributes attributes>
566 12 : void serialize(auto &stream, const spb::detail::proto_label_repeated_fixed_size auto &value)
567 : {
568 12 : container_begin(stream, '[');
569 120 : for (size_t i = 0; i < value.size(); i++)
570 : {
571 48 : put_comma_if_needed(stream);
572 :
573 : if constexpr (std::is_same_v<typename std::decay_t<decltype(value)>::value_type, bool>)
574 : {
575 : serialize<attributes>(stream, bool(value[i]));
576 : }
577 : else
578 : {
579 48 : serialize<attributes>(stream, value[i]);
580 : }
581 : }
582 12 : container_end(stream, ']');
583 12 : }
584 :
585 : template <field_attributes attributes>
586 12 : void serialize(auto &stream, const spb::detail::proto_label_repeated_fixed_size auto &value,
587 : std::string_view field)
588 : {
589 12 : serialize_key(stream, field);
590 12 : serialize<attributes>(stream, value);
591 12 : }
592 :
593 : template <field_attributes attributes>
594 54 : void serialize(auto &stream, const spb::detail::proto_map auto &map, std::string_view field)
595 : {
596 54 : if (map.empty())
597 0 : return;
598 :
599 54 : serialize_key(stream, field);
600 54 : serialize<attributes>(stream, map);
601 : }
602 :
603 74 : template <field_attributes attributes> void serialize(auto &stream, const spb::detail::proto_map auto &map)
604 : {
605 74 : container_begin(stream, '{');
606 154 : for (const auto &[map_key, map_value] : map)
607 : {
608 80 : serialize_key(stream, map_key);
609 80 : stream.put_comma = false;
610 80 : serialize<attributes>(stream, map_value);
611 80 : stream.put_comma = true;
612 : }
613 74 : container_end(stream, '}');
614 74 : }
615 :
616 : template <field_attributes attributes>
617 34 : void serialize(auto &stream, const spb::detail::proto_label_optional auto &p_value)
618 : {
619 34 : if (p_value.has_value())
620 22 : return serialize<attributes>(stream, *p_value);
621 : }
622 :
623 : template <field_attributes attributes>
624 730 : void serialize(auto &stream, const spb::detail::proto_label_optional auto &p_value, std::string_view field)
625 : {
626 730 : if (p_value.has_value())
627 618 : return serialize<attributes>(stream, *p_value, field);
628 : }
629 :
630 : template <field_attributes attributes, typename T>
631 : void serialize(auto &stream, const std::unique_ptr<T> &p_value)
632 : {
633 : if (p_value)
634 : return serialize<attributes>(stream, *p_value);
635 : }
636 :
637 : template <field_attributes attributes, typename T>
638 : void serialize(auto &stream, const std::unique_ptr<T> &p_value, std::string_view field)
639 : {
640 : if (p_value)
641 : return serialize<attributes>(stream, *p_value, field);
642 : }
643 :
644 2710 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_message auto &value)
645 : {
646 2710 : container_begin(stream, '{');
647 2710 : serialize_value(stream, value);
648 2676 : container_end(stream, '}');
649 2676 : }
650 :
651 : template <field_attributes attributes>
652 26 : void serialize(auto &stream, const spb::detail::proto_message auto &value, std::string_view field)
653 : {
654 26 : serialize_key(stream, field);
655 26 : serialize<attributes>(stream, value);
656 26 : }
657 :
658 92 : template <field_attributes> void serialize(auto &stream, const spb::detail::proto_enum auto &value)
659 : {
660 92 : serialize_value(stream, value);
661 92 : }
662 :
663 : template <field_attributes>
664 32 : void serialize(auto &stream, const spb::detail::proto_enum auto &value, std::string_view field)
665 : {
666 32 : serialize_key(stream, field);
667 32 : serialize_value(stream, value);
668 32 : }
669 :
670 : template <field_attributes attributes>
671 1321 : size_t serialize_size(const auto &value, const serialize_options &options)
672 : {
673 1321 : auto stream = ostream_size{options};
674 1321 : serialize<attributes>(stream, value);
675 2636 : return stream.end();
676 : }
677 :
678 : } // namespace spb::json::detail
|