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 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
|
// 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");
}
};
};
// Test for GitHub issue #2172
// Empty struct in tagged variant roundtrip
namespace tagged_empty_variant
{
struct EmptyA
{
bool operator==(const EmptyA&) const = default;
};
using VariantWithEmpty = std::variant<EmptyA>;
struct Wrapper
{
VariantWithEmpty v;
bool operator==(const Wrapper&) const = default;
};
}
template <>
struct glz::meta<tagged_empty_variant::EmptyA>
{
static constexpr auto value = glz::object();
};
template <>
struct glz::meta<tagged_empty_variant::VariantWithEmpty>
{
static constexpr std::string_view tag = "tag";
static constexpr auto ids = std::array{"A"};
};
template <>
struct glz::meta<tagged_empty_variant::Wrapper>
{
static constexpr auto value = glz::object(&tagged_empty_variant::Wrapper::v);
};
suite empty_struct_variant_roundtrip = [] {
"empty struct variant roundtrip minified"_test = [] {
tagged_empty_variant::Wrapper x{tagged_empty_variant::EmptyA{}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"v":{"tag":"A"}})") << buffer;
tagged_empty_variant::Wrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(parsed == x);
};
"empty struct variant roundtrip prettified"_test = [] {
tagged_empty_variant::Wrapper x{tagged_empty_variant::EmptyA{}};
std::string buffer{};
expect(not glz::write<glz::opts{.prettify = true}>(x, buffer));
// Verify no extra blank lines in prettified output
expect(buffer == R"({
"v": {
"tag": "A"
}
})") << buffer;
tagged_empty_variant::Wrapper parsed{};
auto ec = glz::read<glz::opts{.prettify = true}>(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(parsed == x);
};
"empty struct variant full roundtrip"_test = [] {
// Test that write -> read roundtrip works for both minified and prettified
tagged_empty_variant::Wrapper original{tagged_empty_variant::EmptyA{}};
// Minified roundtrip
std::string minified{};
expect(not glz::write_json(original, minified));
tagged_empty_variant::Wrapper parsed_min{};
expect(not glz::read_json(parsed_min, minified)) << minified;
expect(parsed_min == original);
// Prettified roundtrip
std::string prettified{};
expect(not glz::write<glz::opts{.prettify = true}>(original, prettified));
tagged_empty_variant::Wrapper parsed_pretty{};
expect(not glz::read<glz::opts{.prettify = true}>(parsed_pretty, prettified)) << prettified;
expect(parsed_pretty == original);
};
"empty struct variant direct parsing"_test = [] {
// Test parsing the variant directly (not wrapped in another struct)
std::string json = R"({"tag":"A"})";
tagged_empty_variant::VariantWithEmpty v;
auto ec = glz::read_json(v, json);
expect(not ec) << glz::format_error(ec, json);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(v));
};
"empty struct variant with extra whitespace"_test = [] {
// Test parsing with various whitespace patterns
std::string json = R"({ "v" : { "tag" : "A" } })";
tagged_empty_variant::Wrapper parsed{};
auto ec = glz::read_json(parsed, json);
expect(not ec) << glz::format_error(ec, json);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.v));
};
};
// Additional test types for more comprehensive coverage
namespace tagged_variant_extended
{
// Multiple empty struct types in a variant
struct EmptyB
{
bool operator==(const EmptyB&) const = default;
};
struct EmptyC
{
bool operator==(const EmptyC&) const = default;
};
using MultiEmptyVariant = std::variant<tagged_empty_variant::EmptyA, EmptyB, EmptyC>;
struct MultiEmptyWrapper
{
MultiEmptyVariant v;
bool operator==(const MultiEmptyWrapper&) const = default;
};
// Mixed variant with empty and non-empty types
struct NonEmpty
{
int x{};
std::string y{};
bool operator==(const NonEmpty&) const = default;
};
using MixedVariant = std::variant<tagged_empty_variant::EmptyA, NonEmpty>;
struct MixedWrapper
{
MixedVariant v;
bool operator==(const MixedWrapper&) const = default;
};
// Wrapper with multiple fields including variant
struct MultiFieldWrapper
{
int before{};
tagged_empty_variant::VariantWithEmpty v;
std::string after{};
bool operator==(const MultiFieldWrapper&) const = default;
};
// Nested wrapper
struct OuterWrapper
{
tagged_empty_variant::Wrapper inner;
bool operator==(const OuterWrapper&) const = default;
};
}
template <>
struct glz::meta<tagged_variant_extended::EmptyB>
{
static constexpr auto value = glz::object();
};
template <>
struct glz::meta<tagged_variant_extended::EmptyC>
{
static constexpr auto value = glz::object();
};
template <>
struct glz::meta<tagged_variant_extended::MultiEmptyVariant>
{
static constexpr std::string_view tag = "type";
static constexpr auto ids = std::array{"A", "B", "C"};
};
template <>
struct glz::meta<tagged_variant_extended::MultiEmptyWrapper>
{
static constexpr auto value = glz::object(&tagged_variant_extended::MultiEmptyWrapper::v);
};
template <>
struct glz::meta<tagged_variant_extended::NonEmpty>
{
static constexpr auto value =
glz::object(&tagged_variant_extended::NonEmpty::x, &tagged_variant_extended::NonEmpty::y);
};
template <>
struct glz::meta<tagged_variant_extended::MixedVariant>
{
static constexpr std::string_view tag = "kind";
static constexpr auto ids = std::array{"empty", "non_empty"};
};
template <>
struct glz::meta<tagged_variant_extended::MixedWrapper>
{
static constexpr auto value = glz::object(&tagged_variant_extended::MixedWrapper::v);
};
template <>
struct glz::meta<tagged_variant_extended::MultiFieldWrapper>
{
static constexpr auto value =
glz::object(&tagged_variant_extended::MultiFieldWrapper::before, &tagged_variant_extended::MultiFieldWrapper::v,
&tagged_variant_extended::MultiFieldWrapper::after);
};
template <>
struct glz::meta<tagged_variant_extended::OuterWrapper>
{
static constexpr auto value = glz::object(&tagged_variant_extended::OuterWrapper::inner);
};
suite empty_struct_variant_extended = [] {
using namespace tagged_variant_extended;
"multiple empty types in variant - type A"_test = [] {
MultiEmptyWrapper x{tagged_empty_variant::EmptyA{}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"v":{"type":"A"}})") << buffer;
MultiEmptyWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.v));
};
"multiple empty types in variant - type B"_test = [] {
MultiEmptyWrapper x{EmptyB{}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"v":{"type":"B"}})") << buffer;
MultiEmptyWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<EmptyB>(parsed.v));
};
"multiple empty types in variant - type C"_test = [] {
MultiEmptyWrapper x{EmptyC{}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"v":{"type":"C"}})") << buffer;
MultiEmptyWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<EmptyC>(parsed.v));
};
"mixed variant with empty type"_test = [] {
MixedWrapper x{tagged_empty_variant::EmptyA{}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"v":{"kind":"empty"}})") << buffer;
MixedWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.v));
};
"mixed variant with non-empty type"_test = [] {
MixedWrapper x{NonEmpty{42, "hello"}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
MixedWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<NonEmpty>(parsed.v));
expect(std::get<NonEmpty>(parsed.v).x == 42);
expect(std::get<NonEmpty>(parsed.v).y == "hello");
};
"multi-field wrapper with empty variant"_test = [] {
MultiFieldWrapper x{10, tagged_empty_variant::EmptyA{}, "test"};
std::string buffer{};
expect(not glz::write_json(x, buffer));
MultiFieldWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(parsed.before == 10);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.v));
expect(parsed.after == "test");
};
"nested wrapper with empty variant"_test = [] {
OuterWrapper x{{tagged_empty_variant::EmptyA{}}};
std::string buffer{};
expect(not glz::write_json(x, buffer));
expect(buffer == R"({"inner":{"v":{"tag":"A"}}})") << buffer;
OuterWrapper parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.inner.v));
};
"nested wrapper prettified"_test = [] {
OuterWrapper x{{tagged_empty_variant::EmptyA{}}};
std::string buffer{};
expect(not glz::write<glz::opts{.prettify = true}>(x, buffer));
OuterWrapper parsed{};
auto ec = glz::read<glz::opts{.prettify = true}>(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.inner.v));
};
"multi-field wrapper field order variations"_test = [] {
// Test that field order in JSON doesn't matter
std::string json1 = R"({"before":5,"v":{"tag":"A"},"after":"x"})";
std::string json2 = R"({"v":{"tag":"A"},"before":5,"after":"x"})";
std::string json3 = R"({"after":"x","before":5,"v":{"tag":"A"}})";
for (const auto& json : {json1, json2, json3}) {
MultiFieldWrapper parsed{};
auto ec = glz::read_json(parsed, json);
expect(not ec) << glz::format_error(ec, json);
expect(parsed.before == 5);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed.v));
expect(parsed.after == "x");
}
};
"empty variant in array"_test = [] {
std::vector<tagged_empty_variant::Wrapper> vec{{tagged_empty_variant::EmptyA{}},
{tagged_empty_variant::EmptyA{}}};
std::string buffer{};
expect(not glz::write_json(vec, buffer));
expect(buffer == R"([{"v":{"tag":"A"}},{"v":{"tag":"A"}}])") << buffer;
std::vector<tagged_empty_variant::Wrapper> parsed{};
auto ec = glz::read_json(parsed, buffer);
expect(not ec) << glz::format_error(ec, buffer);
expect(parsed.size() == 2);
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed[0].v));
expect(std::holds_alternative<tagged_empty_variant::EmptyA>(parsed[1].v));
};
};
int main() { return 0; }
|