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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
|
// Glaze Library
// For the license information refer to glaze.hpp
#include <array>
#include <cstdint>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <variant>
#include <vector>
#include "glaze/containers/flat_map.hpp"
#include "glaze/json.hpp"
#include "json_test_shared_types.hpp"
#include "ut/ut.hpp"
using namespace ut;
struct put_action
{
std::map<std::string, int> data{};
[[nodiscard]] bool operator==(const put_action&) const = default;
};
template <>
struct glz::meta<put_action>
{
using T = put_action;
static constexpr std::string_view name = "put_action";
static constexpr auto value = object("data", &T::data);
};
struct delete_action
{
std::string data{};
[[nodiscard]] bool operator==(const delete_action&) const = default;
};
template <>
struct glz::meta<delete_action>
{
using T = delete_action;
static constexpr std::string_view name = "delete_action";
static constexpr auto value = object("data", &T::data);
};
using tagged_variant = std::variant<put_action, delete_action>;
template <>
struct glz::meta<tagged_variant>
{
static constexpr std::string_view tag = "action";
static constexpr auto ids = std::array{"PUT", "DELETE"}; // Defaults to glz::name_v of the type
};
// Test automatic ids
using tagged_variant2 = std::variant<put_action, delete_action, std::monostate>;
template <>
struct glz::meta<tagged_variant2>
{
static constexpr std::string_view tag = "type";
// ids defaults to glz::name_v of the type
};
// Test array based variant (experimental, not meant for external usage since api might change)
using num_variant = std::variant<double, int32_t, uint64_t, int8_t, float>;
struct holds_some_num
{
num_variant num{};
};
template <>
struct glz::meta<holds_some_num>
{
using T = holds_some_num;
static constexpr auto value = object("num", glz::array_variant{&T::num});
};
struct OptionA
{
std::string tag{};
int a{};
};
struct OptionB
{
std::string tag{};
int a{};
};
using TaggedObject = std::variant<OptionA, OptionB>;
template <>
struct glz::meta<TaggedObject>
{
static constexpr std::string_view tag = "tag";
static constexpr auto ids = std::array{"A", "B"};
};
suite tagged_variant_tests = [] {
"TaggedObject"_test = [] {
TaggedObject content;
std::string data = R"({ "tag": "A", "a": 2 })";
expect(!glz::read_json<TaggedObject>(content, data));
expect(std::get<OptionA>(content).a == 2);
};
"tagged_variant_read_tests"_test = [] {
tagged_variant var{};
expect(glz::read_json(var, R"({"action":"DELETE","data":"the_internet"})") == glz::error_code::none);
expect(std::holds_alternative<delete_action>(var));
expect(std::get<delete_action>(var).data == "the_internet");
// tag at end
expect(glz::read_json(var, R"({"data":"the_internet","action":"DELETE"})") == glz::error_code::none);
expect(std::holds_alternative<delete_action>(var));
expect(std::get<delete_action>(var).data == "the_internet");
tagged_variant2 var2{};
expect(glz::read_json(var2, R"({"type":"put_action","data":{"x":100,"y":200}})") == glz::error_code::none);
expect(std::holds_alternative<put_action>(var2));
expect(std::get<put_action>(var2).data["x"] == 100);
expect(std::get<put_action>(var2).data["y"] == 200);
// tag at end
expect(glz::read_json(var2, R"({"data":{"x":100,"y":200},"type":"put_action"})") == glz::error_code::none);
expect(std::holds_alternative<put_action>(var2));
expect(std::get<put_action>(var2).data["x"] == 100);
expect(std::get<put_action>(var2).data["y"] == 200);
//
const auto err = glz::read<glz::opts{.error_on_unknown_keys = false}>(
var2, R"({"type":"put_action","data":{"x":100,"y":200}})");
expect(err == glz::error_code::none);
expect(std::holds_alternative<put_action>(var2));
expect(std::get<put_action>(var2).data["x"] == 100);
expect(std::get<put_action>(var2).data["y"] == 200);
};
"tagged_variant_write_tests"_test = [] {
// custom tagged discriminator ids
tagged_variant var = delete_action{{"the_internet"}};
std::string s{};
expect(not glz::write_json(var, s));
expect(s == R"({"action":"DELETE","data":"the_internet"})");
s.clear();
// Automatic tagged discriminator ids
tagged_variant2 var2 = put_action{{{"x", 100}, {"y", 200}}};
expect(not glz::write_json(var2, s));
expect(s == R"({"type":"put_action","data":{"x":100,"y":200}})");
s.clear();
// prettifies valid JSON
expect(not glz::write<glz::opts{.prettify = true}>(var, s));
tagged_variant parsed_var;
expect(glz::read_json(parsed_var, s) == glz::error_code::none);
expect(parsed_var == var);
};
"tagged_variant_schema_tests"_test = [] {
auto s = glz::write_json_schema<tagged_variant>().value_or("error");
expect(
s ==
R"({"type":["object"],"$defs":{"int32_t":{"type":["integer"],"minimum":-2147483648,"maximum":2147483647},"std::map<std::string,int32_t>":{"type":["object"],"additionalProperties":{"$ref":"#/$defs/int32_t"}},"std::string":{"type":["string"]}},"oneOf":[{"type":["object"],"properties":{"action":{"const":"PUT"},"data":{"$ref":"#/$defs/std::map<std::string,int32_t>"}},"additionalProperties":false,"required":["action"],"title":"PUT"},{"type":["object"],"properties":{"action":{"const":"DELETE"},"data":{"$ref":"#/$defs/std::string"}},"additionalProperties":false,"required":["action"],"title":"DELETE"}],"title":"std::variant<put_action, delete_action>"})")
<< s;
};
"array_variant_tests"_test = [] {
// Test array based variant (experimental, not meant for external usage since api might change)
holds_some_num obj{};
auto ec = glz::read_json(obj, R"({"num":["float", 3.14]})");
std::string b = R"({"num":["float", 3.14]})";
expect(ec == glz::error_code::none) << glz::format_error(ec, b);
expect(std::get<float>(obj.num) == 3.14f);
expect(not glz::read_json(obj, R"({"num":["uint64_t", 5]})"));
expect(std::get<uint64_t>(obj.num) == 5);
expect(not glz::read_json(obj, R"({"num":["int8_t", -3]})"));
expect(std::get<int8_t>(obj.num) == -3);
expect(not glz::read_json(obj, R"({"num":["int32_t", -2]})"));
expect(std::get<int32_t>(obj.num) == -2);
obj.num = 5.0;
std::string s{};
expect(not glz::write_json(obj, s));
expect(s == R"({"num":["double",5]})");
obj.num = uint64_t{3};
expect(not glz::write_json(obj, s));
expect(s == R"({"num":["uint64_t",3]})");
obj.num = int8_t{-5};
expect(not glz::write_json(obj, s));
expect(s == R"({"num":["int8_t",-5]})");
};
"shared_ptr variant schema"_test = [] {
const auto schema = glz::write_json_schema<std::shared_ptr<tagged_variant2>>().value_or("error");
expect(
schema ==
R"({"type":["object","null"],"$defs":{"int32_t":{"type":["integer"],"minimum":-2147483648,"maximum":2147483647},"std::map<std::string,int32_t>":{"type":["object"],"additionalProperties":{"$ref":"#/$defs/int32_t"}},"std::string":{"type":["string"]}},"oneOf":[{"type":["object"],"properties":{"data":{"$ref":"#/$defs/std::map<std::string,int32_t>"},"type":{"const":"put_action"}},"additionalProperties":false,"required":["type"],"title":"put_action"},{"type":["object"],"properties":{"data":{"$ref":"#/$defs/std::string"},"type":{"const":"delete_action"}},"additionalProperties":false,"required":["type"],"title":"delete_action"},{"type":["null"],"title":"std::monostate","const":null}],"title":"std::shared_ptr<std::variant<put_action, delete_action, std::monostate>>"})")
<< schema;
};
};
struct variant_obj
{
std::variant<double, std::string> v{};
};
template <>
struct glz::meta<variant_obj>
{
static constexpr std::string_view name = "variant_obj";
using T = variant_obj;
static constexpr auto value = object("v", &T::v);
};
struct var_a1
{
int i{};
};
struct var_a2
{
double i{};
};
suite variant_tests = [] {
"variant_write_tests"_test = [] {
std::variant<double, std::string> d = "not_a_fish";
std::string s{};
expect(not glz::write_json(d, s));
expect(s == R"("not_a_fish")");
d = 5.7;
s.clear();
expect(not glz::write_json(d, s));
expect(s == "5.7");
std::variant<std::monostate, int, std::string> m{};
expect(not glz::write_json(m, s));
expect(s == "null") << s;
};
"variant_read_"_test = [] {
std::variant<int32_t, double> x = 44;
expect(glz::read_json(x, "33") == glz::error_code::none);
expect(std::get<int32_t>(x) == 33);
};
// TODO: Make reading into the active element work here
/*"variant read active"_test = [] {
std::variant<var_a1, var_a2> v = var_a2{};
std::string json = R"({"i":6})";
expect(not glz::read_json(v, json));
expect(v.index() == 1);
expect(std::get<var_a2>(v).i == 6);
};*/
"variant_read_auto"_test = [] {
// Auto deduce variant with no conflicting basic types
std::variant<std::monostate, int, std::string, bool, std::map<std::string, double>, std::vector<std::string>> m{};
expect(glz::read_json(m, R"("Hello World")") == glz::error_code::none);
expect[std::holds_alternative<std::string>(m)];
expect(std::get<std::string>(m) == "Hello World");
expect(glz::read_json(m, R"(872)") == glz::error_code::none);
expect[std::holds_alternative<int>(m)];
expect(std::get<int>(m) == 872);
expect(glz::read_json(m, R"({"pi":3.14})") == glz::error_code::none);
expect[std::holds_alternative<std::map<std::string, double>>(m)];
expect(std::get<std::map<std::string, double>>(m)["pi"] == 3.14);
expect(glz::read_json(m, R"(true)") == glz::error_code::none);
expect[std::holds_alternative<bool>(m)];
expect(std::get<bool>(m) == true);
expect(glz::read_json(m, R"(["a", "b", "c"])") == glz::error_code::none);
expect[std::holds_alternative<std::vector<std::string>>(m)];
expect(std::get<std::vector<std::string>>(m)[1] == "b");
expect(glz::read_json(m, "null") == glz::error_code::none);
expect[std::holds_alternative<std::monostate>(m)];
};
"variant_read_obj"_test = [] {
variant_obj obj{};
obj.v = double{};
expect(glz::read_json(obj, R"({"v": 5.5})") == glz::error_code::none);
expect(std::get<double>(obj.v) == 5.5);
};
"variant_request"_test = [] {
std::map<std::string, std::variant<std::string, int, bool>> request;
request["username"] = "paulo";
request["password"] = "123456";
request["remember"] = true;
auto str = glz::write_json(request).value_or("error");
expect(str == R"({"password":"123456","remember":true,"username":"paulo"})") << str;
};
"variant write/read enum"_test = [] {
std::variant<Color, std::uint16_t> var{Color::Red};
auto res{glz::write_json(var).value_or("error")};
expect(res == "\"Red\"") << res;
auto read{glz::read_json<std::variant<Color, std::uint16_t>>(res)};
expect(read.has_value());
expect(std::holds_alternative<Color>(read.value()));
expect(std::get<Color>(read.value()) == Color::Red);
};
"variant read tuple"_test = [] {
using int_int_tuple_t = std::tuple<int, int>;
std::variant<int, int_int_tuple_t, std::string> var;
expect(glz::read_json(var, R"(1)") == glz::error_code::none);
expect(std::get<int>(var) == 1);
expect(glz::read_json(var, R"("str")") == glz::error_code::none);
expect(std::get<std::string>(var) == "str");
expect(glz::read_json(var, R"([2, 3])") == glz::error_code::none);
expect(std::get<int_int_tuple_t>(var) == int_int_tuple_t{2, 3});
};
};
// Tests for std::vector<std::variant<...>> with purely reflected structs
struct reflected_person
{
std::string name{};
int age{};
double height{};
};
struct reflected_animal
{
std::string species{};
std::string name{};
int weight{};
};
struct reflected_vehicle
{
std::string make{};
std::string model{};
int year{};
double price{};
};
struct reflected_book
{
std::string title{};
std::string author{};
int pages{};
std::string isbn{};
};
static_assert(glz::reflectable<reflected_person>);
static_assert(glz::reflectable<reflected_animal>);
static_assert(glz::reflectable<reflected_vehicle>);
static_assert(glz::reflectable<reflected_book>);
suite vector_variant_reflection_tests = [] {
"vector of variant with two reflected structs"_test = [] {
using entity_variant = std::variant<reflected_person, reflected_animal>;
std::vector<entity_variant> entities;
entities.push_back(reflected_person{"Alice", 30, 165.5});
entities.push_back(reflected_animal{"Dog", "Buddy", 25});
entities.push_back(reflected_person{"Bob", 25, 180.0});
entities.push_back(reflected_animal{"Cat", "Whiskers", 4});
std::string json;
expect(!glz::write_json(entities, json));
std::vector<entity_variant> read_entities;
expect(glz::read_json(read_entities, json) == glz::error_code::none);
expect(read_entities.size() == 4);
expect(std::holds_alternative<reflected_person>(read_entities[0]));
auto& p1 = std::get<reflected_person>(read_entities[0]);
expect(p1.name == "Alice");
expect(p1.age == 30);
expect(p1.height == 165.5);
expect(std::holds_alternative<reflected_animal>(read_entities[1]));
auto& a1 = std::get<reflected_animal>(read_entities[1]);
expect(a1.species == "Dog");
expect(a1.name == "Buddy");
expect(a1.weight == 25);
expect(std::holds_alternative<reflected_person>(read_entities[2]));
auto& p2 = std::get<reflected_person>(read_entities[2]);
expect(p2.name == "Bob");
expect(p2.age == 25);
expect(p2.height == 180.0);
expect(std::holds_alternative<reflected_animal>(read_entities[3]));
auto& a2 = std::get<reflected_animal>(read_entities[3]);
expect(a2.species == "Cat");
expect(a2.name == "Whiskers");
expect(a2.weight == 4);
};
"vector of variant with three reflected structs"_test = [] {
using item_variant = std::variant<reflected_person, reflected_vehicle, reflected_book>;
std::vector<item_variant> items;
items.push_back(reflected_person{"Charlie", 35, 175.0});
items.push_back(reflected_vehicle{"Toyota", "Camry", 2022, 25000.0});
items.push_back(reflected_book{"The Great Gatsby", "F. Scott Fitzgerald", 180, "978-0-7432-7356-5"});
items.push_back(reflected_person{"Diana", 28, 160.0});
std::string json;
expect(!glz::write_json(items, json));
std::vector<item_variant> read_items;
expect(glz::read_json(read_items, json) == glz::error_code::none);
expect(read_items.size() == 4);
expect(std::holds_alternative<reflected_person>(read_items[0]));
expect(std::holds_alternative<reflected_vehicle>(read_items[1]));
expect(std::holds_alternative<reflected_book>(read_items[2]));
expect(std::holds_alternative<reflected_person>(read_items[3]));
auto& vehicle = std::get<reflected_vehicle>(read_items[1]);
expect(vehicle.make == "Toyota");
expect(vehicle.model == "Camry");
expect(vehicle.year == 2022);
expect(vehicle.price == 25000.0);
auto& book = std::get<reflected_book>(read_items[2]);
expect(book.title == "The Great Gatsby");
expect(book.author == "F. Scott Fitzgerald");
expect(book.pages == 180);
expect(book.isbn == "978-0-7432-7356-5");
};
"empty vector of variant"_test = [] {
using entity_variant = std::variant<reflected_person, reflected_animal>;
std::vector<entity_variant> entities;
std::string json;
expect(!glz::write_json(entities, json));
expect(json == "[]");
std::vector<entity_variant> read_entities;
expect(glz::read_json(read_entities, json) == glz::error_code::none);
expect(read_entities.empty());
};
"vector with single variant element"_test = [] {
using entity_variant = std::variant<reflected_person, reflected_animal>;
std::vector<entity_variant> entities;
entities.push_back(reflected_person{"Eve", 40, 170.0});
std::string json;
expect(!glz::write_json(entities, json));
std::vector<entity_variant> read_entities;
expect(glz::read_json(read_entities, json) == glz::error_code::none);
expect(read_entities.size() == 1);
expect(std::holds_alternative<reflected_person>(read_entities[0]));
auto& person = std::get<reflected_person>(read_entities[0]);
expect(person.name == "Eve");
expect(person.age == 40);
expect(person.height == 170.0);
};
"roundtrip with mixed types"_test = [] {
using mixed_variant = std::variant<reflected_person, reflected_animal, reflected_vehicle, reflected_book>;
std::vector<mixed_variant> original;
original.push_back(reflected_book{"1984", "George Orwell", 328, "978-0-452-28423-4"});
original.push_back(reflected_animal{"Horse", "Thunder", 500});
original.push_back(reflected_vehicle{"Honda", "Accord", 2023, 27000.0});
original.push_back(reflected_person{"Frank", 45, 185.0});
original.push_back(reflected_book{"To Kill a Mockingbird", "Harper Lee", 281, "978-0-06-112008-4"});
std::string json;
expect(!glz::write_json(original, json));
std::vector<mixed_variant> decoded;
expect(glz::read_json(decoded, json) == glz::error_code::none);
expect(decoded.size() == original.size());
for (size_t i = 0; i < original.size(); ++i) {
expect(original[i].index() == decoded[i].index());
}
};
"prettified json output"_test = [] {
using entity_variant = std::variant<reflected_person, reflected_animal>;
std::vector<entity_variant> entities;
entities.push_back(reflected_person{"Grace", 32, 168.0});
entities.push_back(reflected_animal{"Bird", "Tweety", 1});
std::string json;
expect(!glz::write<glz::opts{.prettify = true}>(entities, json));
expect(json.find("\n") != std::string::npos); // Should contain newlines
expect(json.find(" ") != std::string::npos); // Should contain indentation
std::vector<entity_variant> read_entities;
expect(glz::read_json(read_entities, json) == glz::error_code::none);
expect(read_entities.size() == 2);
};
"vector of variant with structs having overlapping field names"_test = [] {
// Both structs have a 'name' field, but different other fields
using ambiguous_variant = std::variant<reflected_person, reflected_animal>;
std::vector<ambiguous_variant> items;
// The variant should deduce the correct type based on all fields present
items.push_back(reflected_person{"Henry", 50, 175.5});
items.push_back(reflected_animal{"Lion", "Simba", 190});
std::string json;
expect(!glz::write_json(items, json));
std::vector<ambiguous_variant> read_items;
expect(glz::read_json(read_items, json) == glz::error_code::none);
expect(read_items.size() == 2);
expect(std::holds_alternative<reflected_person>(read_items[0]));
expect(std::holds_alternative<reflected_animal>(read_items[1]));
};
};
struct yz_t
{
int y{};
int z{};
};
template <>
struct glz::meta<yz_t>
{
using T = yz_t;
static constexpr auto value = object("y", &T::y, "z", &T::z);
};
struct xz_t
{
int x{};
int z{};
};
template <>
struct glz::meta<xz_t>
{
using T = xz_t;
static constexpr auto value = object("x", &T::x, "z", &T::z);
};
suite metaobject_variant_auto_deduction = [] {
"metaobject_variant_auto_deduction"_test = [] {
std::variant<xy_t, yz_t, xz_t> var{};
std::string b = R"({"y":1,"z":2})";
expect(glz::read_json(var, b) == glz::error_code::none);
expect(std::holds_alternative<yz_t>(var));
expect(std::get<yz_t>(var).y == 1);
expect(std::get<yz_t>(var).z == 2);
b = R"({"x":5,"y":7})";
expect(glz::read_json(var, b) == glz::error_code::none);
expect(std::holds_alternative<xy_t>(var));
expect(std::get<xy_t>(var).x == 5);
expect(std::get<xy_t>(var).y == 7);
b = R"({"z":3,"x":4})";
expect(glz::read_json(var, b) == glz::error_code::none);
expect(std::holds_alternative<xz_t>(var));
expect(std::get<xz_t>(var).z == 3);
expect(std::get<xz_t>(var).x == 4);
};
};
struct varx
{
struct glaze
{
static constexpr std::string_view name = "varx";
static constexpr auto value = glz::object();
};
};
static_assert(glz::name_v<varx> == "varx");
struct vary
{
struct glaze
{
static constexpr std::string_view name = "vary";
static constexpr auto value = glz::object();
};
};
using vari = std::variant<varx, vary>;
template <>
struct glz::meta<vari>
{
static constexpr std::string_view name = "vari";
static constexpr std::string_view tag = "type";
};
static_assert(glz::named<vari>);
static_assert(glz::name_v<vari> == "vari");
struct var_schema
{
std::string schema{};
vari variant{};
struct glaze
{
using T = var_schema;
static constexpr auto value = glz::object("$schema", &T::schema, &T::variant);
};
};
suite empty_variant_objects = [] {
"empty_variant_objects"_test = [] {
vari v = varx{};
std::string s;
expect(not glz::write_json(v, s));
expect(s == R"({"type":"varx"})");
v = vary{};
expect(!glz::read_json(v, s));
expect(std::holds_alternative<varx>(v));
};
"empty_variant_objects schema"_test = [] {
const auto s = glz::write_json_schema<var_schema>().value_or("error");
expect(
s ==
R"({"type":["object"],"properties":{"$schema":{"$ref":"#/$defs/std::string"},"variant":{"$ref":"#/$defs/vari"}},"additionalProperties":false,"$defs":{"std::string":{"type":["string"]},"vari":{"type":["object"],"oneOf":[{"type":["object"],"properties":{"type":{"const":"varx"}},"additionalProperties":false,"required":["type"],"title":"varx"},{"type":["object"],"properties":{"type":{"const":"vary"}},"additionalProperties":false,"required":["type"],"title":"vary"}]}},"title":"var_schema"})")
<< s;
};
};
struct Obj1
{
int value;
std::string text;
};
template <>
struct glz::meta<Obj1>
{
using T = Obj1;
static constexpr auto list_write = [](T& obj1) {
const auto& value = obj1.value;
return std::vector<int>{value, value + 1, value + 2};
};
static constexpr auto value = object(&T::value, &T::text, "list", glz::custom<skip{}, list_write>);
};
struct Obj2
{
int value;
std::string text;
Obj1 obj1;
};
suite custom_object_variant_test = [] {
"custom_object_variant"_test = [] {
using Serializable = std::variant<Obj1, Obj2>;
std::vector<Serializable> objects{
Obj1{1, "text 1"},
Obj1{2, "text 2"},
Obj2{3, "text 3", 10, "1000"},
Obj1{4, "text 4"},
};
constexpr auto prettify_json = glz::opts{.prettify = true};
std::string data = glz::write<prettify_json>(objects).value_or("error");
expect(data == R"([
{
"value": 1,
"text": "text 1",
"list": [
1,
2,
3
]
},
{
"value": 2,
"text": "text 2",
"list": [
2,
3,
4
]
},
{
"value": 3,
"text": "text 3",
"obj1": {
"value": 10,
"text": "1000",
"list": [
10,
11,
12
]
}
},
{
"value": 4,
"text": "text 4",
"list": [
4,
5,
6
]
}
])");
objects.clear();
expect(!glz::read_json(objects, data));
expect(data == glz::write<prettify_json>(objects));
};
};
struct var_a
{
int m1;
struct glaze
{
static constexpr auto value = glz::object("a", &var_a::m1);
};
};
struct var_b
{
std::vector<var_a> m1;
bool m2;
struct glaze
{
static constexpr auto value = glz::object("b", &var_b::m1, "c", &var_b::m2);
};
};
struct var_c
{
std::vector<var_a> m1;
struct glaze
{
static constexpr auto value = &var_c::m1;
};
};
struct var_abc_t
{
std::variant<var_a, var_b, var_c> m1;
struct glaze
{
static constexpr auto value = &var_abc_t::m1;
};
};
suite nested_variants = [] {
"nested_variants"_test = [] {
var_abc_t v{};
auto ec = glz::read_json(v, std::string{R"({"a":5})"});
expect(not ec) << glz::format_error(ec);
expect(std::get<var_a>(v.m1).m1 == 5);
};
};
struct hammerhead_t
{
double length{};
};
struct mako_t
{
double length{};
};
using shark_t = std::variant<hammerhead_t, mako_t>;
template <>
struct glz::meta<shark_t>
{
static constexpr std::string_view tag = "name";
static constexpr auto ids = std::array{"hammerhead", "mako"};
};
using shark_ptr_t = std::variant<std::shared_ptr<hammerhead_t>, std::shared_ptr<mako_t>>;
template <>
struct glz::meta<shark_ptr_t>
{
static constexpr std::string_view tag = "name";
static constexpr auto ids = std::array{"hammerhead", "mako"};
};
struct chair_t
{
float height{};
uint8_t number_of_legs{};
bool has_back{};
};
struct bed_t
{
float height{};
bool has_headboard{};
};
using furniture_ptr_t = std::variant<std::shared_ptr<chair_t>, std::shared_ptr<bed_t>>;
suite shark_variant = [] {
"shark_variant"_test = [] {
shark_t shark{};
auto ec = glz::read_json(shark, R"({"name":"mako","length":44.0})");
expect(!ec);
expect(std::holds_alternative<mako_t>(shark));
expect(std::get<mako_t>(shark).length == 44.0);
};
"shark_ptr variant"_test = [] {
shark_ptr_t shark{};
auto ec = glz::read_json(shark, R"({"name":"mako","length":44.0})");
expect(!ec);
expect(std::holds_alternative<std::shared_ptr<mako_t>>(shark));
expect(std::get<std::shared_ptr<mako_t>>(shark)->length == 44.0);
};
"furniture_ptr variant auto-deduction "_test = [] {
furniture_ptr_t furniture{};
auto ec = glz::read_json(furniture, R"({"height":44.0,"has_headboard":true})");
expect(!ec);
expect(std::holds_alternative<std::shared_ptr<bed_t>>(furniture));
expect(std::get<std::shared_ptr<bed_t>>(furniture)->height == 44.0f);
expect(std::get<std::shared_ptr<bed_t>>(furniture)->has_headboard);
};
};
struct A_empty
{};
struct B_empty
{};
using C_empty = std::variant<A_empty, B_empty>;
template <>
struct glz::meta<C_empty>
{
static constexpr std::string_view tag = "op";
};
suite empty_variant_testing = [] {
"empty_variant 1"_test = [] {
std::string_view text = R"({"xxx":"x","op":"B_empty"})";
C_empty c;
auto ec = glz::read<glz::opts{.error_on_unknown_keys = false, .error_on_missing_keys = true}>(c, text);
expect(not ec) << glz::format_error(ec, text);
expect(c.index() == 1);
};
"empty_variant 2"_test = [] {
std::string_view text = R"({"xx":"x","op":"B_empty"})";
C_empty c;
auto ec = glz::read<glz::opts{.error_on_unknown_keys = false, .error_on_missing_keys = true}>(c, text);
expect(not ec) << glz::format_error(ec, text);
expect(c.index() == 1);
};
};
struct A1
{
int p{};
};
struct B1
{
float p{};
};
using X1 = std::variant<A1>;
using Y1 = std::variant<A1, B1>;
template <>
struct glz::meta<A1>
{
static constexpr auto value = object("p", &A1::p);
};
template <>
struct glz::meta<B1>
{
static constexpr auto value = object("p", &B1::p);
};
template <>
struct glz::meta<X1>
{
static constexpr std::string_view tag = "tag";
};
template <>
struct glz::meta<Y1>
{
static constexpr std::string_view tag = "tag";
};
suite variant_tag_tests = [] {
"variant tag"_test = [] {
auto xString = glz::write_json(X1(A1()));
expect(xString.has_value());
auto x = glz::read_json<X1>(*xString);
expect(bool(x));
if (not x.has_value()) {
std::cerr << glz::format_error(x.error(), *xString);
}
};
};
struct Number
{
std::optional<double> minimum;
std::optional<double> maximum;
};
template <>
struct glz::meta<Number>
{
static constexpr auto value = glz::object(&Number::minimum, &Number::maximum);
};
struct Boolean
{};
template <>
struct glz::meta<Boolean>
{
static constexpr auto value = glz::object();
};
struct Integer
{
std::optional<int> minimum;
std::optional<int> maximum;
};
template <>
struct glz::meta<Integer>
{
static constexpr auto value = glz::object(&Integer::minimum, &Integer::maximum);
};
using Data = std::variant<Number, Integer>;
template <>
struct glz::meta<Data>
{
static constexpr std::string_view tag = "type";
static constexpr auto ids = std::array{"number", "integer"};
};
struct Array
{
Data items;
};
template <>
struct glz::meta<Array>
{
static constexpr auto value = glz::object(&Array::items);
};
using Data2 = std::variant<Number, Boolean>;
template <>
struct glz::meta<Data2>
{
static constexpr std::string_view tag = "type";
static constexpr auto ids = std::array{"number", "boolean"};
};
struct Array2
{
Data2 items;
};
template <>
struct glz::meta<Array2>
{
static constexpr auto value = glz::object(&Array2::items);
};
suite tagged_variant_null_members = [] {
"tagged_variant_null_members"_test = [] {
Array var = Array{Number{}};
std::string s{};
expect(not glz::write_json(var, s));
expect(s == R"({"items":{"type":"number"}})") << s;
};
"variant deduction"_test = [] {
Array2 var;
std::string str = R"({"items": { "type" : "boolean"}})";
auto pe = glz::read_json(var, str);
expect(not pe) << glz::format_error(pe, str);
};
};
struct Command401
{
int code{};
int indent{};
std::vector<std::string> parameters{};
};
struct Command250Params
{
std::string name{};
int volume{};
int pitch{};
int pan{};
};
struct Command250
{
int code{};
int indent{};
std::vector<Command250Params> parameters{};
};
using CommandVariant = std::variant<Command250, Command401>;
template <>
struct glz::meta<CommandVariant>
{
static constexpr std::string_view tag = "code";
static constexpr std::array ids = {250, 401};
};
suite integer_id_variant_tests = [] {
"command variant"_test = [] {
std::vector<CommandVariant> v{};
std::string buffer =
R"([{"code":401,"indent":0,"parameters":["You light the torch."]},{"code":250,"indent":0,"parameters":[{"name":"fnh_book1","volume":90,"pitch":100,"pan":0}]}])";
auto ec = glz::read_json(v, buffer);
expect(not ec) << glz::format_error(ec, buffer);
std::string out{};
expect(not glz::write_json(v, out));
expect(out == buffer) << out;
expect(not glz::write<glz::opts{.prettify = true}>(v, out));
expect(out == R"([
{
"code": 401,
"indent": 0,
"parameters": [
"You light the torch."
]
},
{
"code": 250,
"indent": 0,
"parameters": [
{
"name": "fnh_book1",
"volume": 90,
"pitch": 100,
"pan": 0
}
]
}
])") << out;
};
};
struct SiteDiagnostic
{
std::string message{};
int severity{};
};
template <>
struct glz::meta<SiteDiagnostic>
{
using T = SiteDiagnostic;
static constexpr std::string_view name = "SiteDiagnostic";
static constexpr auto value = object(&T::message, &T::severity);
};
struct DerivedSite0
{
std::string message{};
int severity{};
std::string additional_info{};
};
template <>
struct glz::meta<DerivedSite0>
{
using T = DerivedSite0;
static constexpr std::string_view name = "DerivedSite0";
static constexpr auto value = object(&T::message, &T::severity, &T::additional_info);
};
using SiteDiagnosticsVariant = std::variant<std::unique_ptr<SiteDiagnostic>, std::unique_ptr<DerivedSite0>>;
template <>
struct glz::meta<SiteDiagnosticsVariant>
{
static constexpr std::string_view tag = "type";
static constexpr auto ids = std::array{"SiteDiagnostic", "DerivedSite0"};
};
struct DiagnosticsConfig
{
glz::flat_map<std::string, SiteDiagnosticsVariant> diagnostics{};
};
template <>
struct glz::meta<DiagnosticsConfig>
{
using T = DiagnosticsConfig;
static constexpr auto value = object(&T::diagnostics);
};
suite unique_ptr_variant_tests = [] {
"flat_map with variant of unique_ptr"_test = [] {
DiagnosticsConfig config;
config.diagnostics["site1"] = std::make_unique<SiteDiagnostic>(SiteDiagnostic{"Basic diagnostic", 1});
config.diagnostics["site2"] =
std::make_unique<DerivedSite0>(DerivedSite0{"Advanced diagnostic", 2, "Extra details"});
std::string json;
auto write_result = glz::write_json(config, json);
expect(!write_result) << "Failed to write JSON";
expect(json.find(R"("message":"Basic diagnostic")") != std::string::npos);
expect(json.find(R"("message":"Advanced diagnostic")") != std::string::npos);
expect(json.find(R"("additional_info":"Extra details")") != std::string::npos);
DiagnosticsConfig parsed_config;
auto read_result = glz::read_json(parsed_config, json);
expect(!read_result) << glz::format_error(read_result, json);
expect(parsed_config.diagnostics.size() == 2);
expect(parsed_config.diagnostics.contains("site1"));
expect(parsed_config.diagnostics.contains("site2"));
auto& variant1 = parsed_config.diagnostics["site1"];
expect(std::holds_alternative<std::unique_ptr<SiteDiagnostic>>(variant1));
if (std::holds_alternative<std::unique_ptr<SiteDiagnostic>>(variant1)) {
auto& diag1 = std::get<std::unique_ptr<SiteDiagnostic>>(variant1);
expect(diag1 != nullptr);
expect(diag1->message == "Basic diagnostic");
expect(diag1->severity == 1);
}
auto& variant2 = parsed_config.diagnostics["site2"];
expect(std::holds_alternative<std::unique_ptr<DerivedSite0>>(variant2));
if (std::holds_alternative<std::unique_ptr<DerivedSite0>>(variant2)) {
auto& diag2 = std::get<std::unique_ptr<DerivedSite0>>(variant2);
expect(diag2 != nullptr);
expect(diag2->message == "Advanced diagnostic");
expect(diag2->severity == 2);
expect(diag2->additional_info == "Extra details");
}
};
"flat_map with variant unique_ptr - empty map"_test = [] {
DiagnosticsConfig config;
std::string json;
expect(!glz::write_json(config, json));
expect(json == R"({"diagnostics":{}})") << json;
DiagnosticsConfig parsed;
expect(!glz::read_json(parsed, json));
expect(parsed.diagnostics.empty());
};
"flat_map with variant unique_ptr - single entry"_test = [] {
DiagnosticsConfig config;
config.diagnostics["only_site"] = std::make_unique<DerivedSite0>(DerivedSite0{"Test", 3, "Info"});
std::string json;
expect(!glz::write_json(config, json));
DiagnosticsConfig parsed;
expect(!glz::read_json(parsed, json));
expect(parsed.diagnostics.size() == 1);
expect(parsed.diagnostics.contains("only_site"));
auto& variant = parsed.diagnostics["only_site"];
expect(std::holds_alternative<std::unique_ptr<DerivedSite0>>(variant));
};
"tagged variant with unique_ptr - tags are written"_test = [] {
SiteDiagnosticsVariant variant = std::make_unique<SiteDiagnostic>(SiteDiagnostic{"Test message", 5});
std::string json;
auto write_result = glz::write_json(variant, json);
expect(!write_result) << "Failed to write JSON";
expect(json.find(R"("type":"SiteDiagnostic")") != std::string::npos) << json;
expect(json.find(R"("message":"Test message")") != std::string::npos) << json;
expect(json.find(R"("severity":5)") != std::string::npos) << json;
};
"tagged variant with unique_ptr - roundtrip with tags"_test = [] {
SiteDiagnosticsVariant original = std::make_unique<DerivedSite0>(DerivedSite0{"Derived message", 7, "Extra"});
std::string json;
expect(!glz::write_json(original, json)) << "Write failed";
expect(json.find(R"("type":"DerivedSite0")") != std::string::npos) << json;
SiteDiagnosticsVariant parsed;
auto read_result = glz::read_json(parsed, json);
expect(!read_result) << glz::format_error(read_result, json);
expect(std::holds_alternative<std::unique_ptr<DerivedSite0>>(parsed));
if (std::holds_alternative<std::unique_ptr<DerivedSite0>>(parsed)) {
auto& diag = std::get<std::unique_ptr<DerivedSite0>>(parsed);
expect(diag != nullptr);
expect(diag->message == "Derived message");
expect(diag->severity == 7);
expect(diag->additional_info == "Extra");
}
};
"tagged variant with unique_ptr - flat_map preserves tags"_test = [] {
DiagnosticsConfig config;
config.diagnostics["a"] = std::make_unique<SiteDiagnostic>(SiteDiagnostic{"Msg A", 1});
config.diagnostics["b"] = std::make_unique<DerivedSite0>(DerivedSite0{"Msg B", 2, "Details"});
std::string json;
expect(!glz::write_json(config, json));
expect(json.find(R"("type":"SiteDiagnostic")") != std::string::npos) << json;
expect(json.find(R"("type":"DerivedSite0")") != std::string::npos) << json;
DiagnosticsConfig parsed;
expect(!glz::read_json(parsed, json)) << json;
expect(parsed.diagnostics.size() == 2);
expect(std::holds_alternative<std::unique_ptr<SiteDiagnostic>>(parsed.diagnostics["a"]));
expect(std::holds_alternative<std::unique_ptr<DerivedSite0>>(parsed.diagnostics["b"]));
};
};
struct Animal
{
std::string name{};
int age{};
};
template <>
struct glz::meta<Animal>
{
using T = Animal;
static constexpr std::string_view name = "Animal";
static constexpr auto value = object(&T::name, &T::age);
};
struct Dog
{
std::string name{};
int age{};
std::string breed{};
};
template <>
struct glz::meta<Dog>
{
using T = Dog;
static constexpr std::string_view name = "Dog";
static constexpr auto value = object(&T::name, &T::age, &T::breed);
};
using AnimalVariantShared = std::variant<std::shared_ptr<Animal>, std::shared_ptr<Dog>>;
template <>
struct glz::meta<AnimalVariantShared>
{
static constexpr std::string_view tag = "species";
static constexpr auto ids = std::array{"Animal", "Dog"};
};
suite shared_ptr_variant_tests = [] {
"tagged variant with shared_ptr - tags are written"_test = [] {
AnimalVariantShared variant = std::make_shared<Animal>(Animal{"Buddy", 3});
std::string json;
auto write_result = glz::write_json(variant, json);
expect(!write_result) << "Failed to write JSON";
expect(json.find(R"("species":"Animal")") != std::string::npos) << json;
expect(json.find(R"("name":"Buddy")") != std::string::npos) << json;
expect(json.find(R"("age":3)") != std::string::npos) << json;
};
"tagged variant with shared_ptr - roundtrip with tags"_test = [] {
AnimalVariantShared original = std::make_shared<Dog>(Dog{"Max", 5, "Golden Retriever"});
std::string json;
expect(!glz::write_json(original, json)) << "Write failed";
expect(json.find(R"("species":"Dog")") != std::string::npos) << json;
AnimalVariantShared parsed;
auto read_result = glz::read_json(parsed, json);
expect(!read_result) << glz::format_error(read_result, json);
expect(std::holds_alternative<std::shared_ptr<Dog>>(parsed));
if (std::holds_alternative<std::shared_ptr<Dog>>(parsed)) {
auto& dog = std::get<std::shared_ptr<Dog>>(parsed);
expect(dog != nullptr);
expect(dog->name == "Max");
expect(dog->age == 5);
expect(dog->breed == "Golden Retriever");
}
};
"tagged variant with shared_ptr - multiple instances"_test = [] {
std::vector<AnimalVariantShared> animals;
animals.push_back(std::make_shared<Animal>(Animal{"Cat", 2}));
animals.push_back(std::make_shared<Dog>(Dog{"Rover", 4, "Labrador"}));
animals.push_back(std::make_shared<Animal>(Animal{"Bird", 1}));
std::string json;
expect(!glz::write_json(animals, json));
std::vector<AnimalVariantShared> parsed;
expect(!glz::read_json(parsed, json)) << json;
expect(parsed.size() == 3);
expect(std::holds_alternative<std::shared_ptr<Animal>>(parsed[0]));
expect(std::holds_alternative<std::shared_ptr<Dog>>(parsed[1]));
expect(std::holds_alternative<std::shared_ptr<Animal>>(parsed[2]));
if (std::holds_alternative<std::shared_ptr<Dog>>(parsed[1])) {
auto& dog = std::get<std::shared_ptr<Dog>>(parsed[1]);
expect(dog->breed == "Labrador");
}
};
};
int main() { return 0; }
|