diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..f1aa4edc8 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,60 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Read and write flags + +`rfl::json` provides `inline constexpr` flag constants (combinable with `|`) so you do not need to reference underlying `YYJSON_*` constants directly. + +### Read flags (`rfl::json::read` and `rfl::json::load`) + +| Flag | Description | +| --- | --- | +| `rfl::json::allow_comments` | Allow C-style single-line (`//`) and multi-line (`/* */`) comments | +| `rfl::json::allow_trailing_commas` | Allow a single trailing comma at the end of an object or array | +| `rfl::json::jsonc` | Shorthand for `allow_comments \| allow_trailing_commas` (JSONC) | +| `rfl::json::allow_bom` | Allow and skip a leading UTF-8 BOM *(requires yyjson >= 0.11.0)* | +| `rfl::json::stop_when_done` | Stop after the first JSON value and ignore trailing content | +| `rfl::json::read_allow_inf_and_nan` | Allow `Inf`, `Infinity`, and `NaN` numbers and literals | +| `rfl::json::read_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences in string values | +| `rfl::json::allow_ext_number` | Allow hex numbers, leading/trailing decimal points, and leading `+` *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_escape` | Allow extended string escape sequences *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_ext_whitespace` | Allow extended whitespace characters *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_single_quoted_str` | Allow single-quoted strings *(requires yyjson >= 0.12.0)* | +| `rfl::json::allow_unquoted_key` | Allow unquoted object keys *(requires yyjson >= 0.12.0)* | +| `rfl::json::json5` | Allow JSON5 syntax *(requires yyjson >= 0.12.0)* | + +Example reading JSONC: + +```cpp +const auto result = rfl::json::read( + jsonc_string, rfl::json::allow_comments | rfl::json::allow_trailing_commas); + +// Or using the convenience alias: +const auto result2 = rfl::json::read(jsonc_string, rfl::json::jsonc); +``` + +### Write flags (`rfl::json::write`, `rfl::json::save`, and `rfl::json::to_schema`) + +| Flag | Description | +| --- | --- | +| `rfl::json::pretty` | Pretty-print with 4-space indentation | +| `rfl::json::pretty_two_spaces` | Pretty-print with 2-space indentation (overrides `pretty`) | +| `rfl::json::newline_at_end` | Append a trailing `\n` to the output *(requires yyjson >= 0.9.0)* | +| `rfl::json::escape_unicode` | Escape non-ASCII characters as `\uXXXX` for ASCII-only output | +| `rfl::json::escape_slashes` | Escape `/` as `\/` | +| `rfl::json::write_allow_inf_and_nan` | Write `Inf`/`NaN` as `Infinity`/`NaN` literals (non-standard) | +| `rfl::json::inf_and_nan_as_null` | Write `Inf`/`NaN` as `null` (overrides `write_allow_inf_and_nan`) | +| `rfl::json::write_allow_invalid_unicode` | Allow invalid UTF-8 byte sequences when encoding strings | + +Example combining write flags: + +```cpp +const std::string json_string = rfl::json::write( + person, rfl::json::pretty_two_spaces | rfl::json::newline_at_end); +``` + +> Note: `read_allow_inf_and_nan` / `write_allow_inf_and_nan` and `read_allow_invalid_unicode` / `write_allow_invalid_unicode` are prefixed with `read_` / `write_` because the underlying read and write flag bit values differ. Unsafe/incompatible read flags (`YYJSON_READ_INSITU`, `YYJSON_READ_NUMBER_AS_RAW`, `YYJSON_READ_BIGNUM_AS_RAW`) are intentionally not exposed (`YYJSON_READ_INSITU` is rejected at runtime). + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index ad3e47b1e..94d7ef06a 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -18,6 +18,61 @@ namespace rfl { namespace json { +/// Stop after parsing the first JSON value instead of issuing an error if +/// trailing content follows. +inline constexpr yyjson_read_flag stop_when_done = YYJSON_READ_STOP_WHEN_DONE; + +/// Allow a single trailing comma at the end of an object or array. +inline constexpr yyjson_read_flag allow_trailing_commas = + YYJSON_READ_ALLOW_TRAILING_COMMAS; + +/// Allow C-style single-line (//) and multi-line (/* */) comments. +inline constexpr yyjson_read_flag allow_comments = YYJSON_READ_ALLOW_COMMENTS; + +/// Allow Inf/NaN numbers and literals (e.g. 1e999, NaN, inf, -Infinity). +inline constexpr yyjson_read_flag read_allow_inf_and_nan = + YYJSON_READ_ALLOW_INF_AND_NAN; + +/// Allow invalid UTF-8 byte sequences when parsing string values. +inline constexpr yyjson_read_flag read_allow_invalid_unicode = + YYJSON_READ_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 +/// Allow and skip a leading UTF-8 BOM before parsing. +/// Requires yyjson >= 0.11.0. +inline constexpr yyjson_read_flag allow_bom = YYJSON_READ_ALLOW_BOM; +#endif + +/// Convenience flag for JSONC (comments and trailing commas). +inline constexpr yyjson_read_flag jsonc = + allow_comments | allow_trailing_commas; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 +/// Allow extended number formats (hexadecimal, leading/trailing decimal point, +/// leading plus sign). Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_number = + YYJSON_READ_ALLOW_EXT_NUMBER; + +/// Allow extended escape sequences in strings. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_escape = + YYJSON_READ_ALLOW_EXT_ESCAPE; + +/// Allow extended whitespace characters. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_ext_whitespace = + YYJSON_READ_ALLOW_EXT_WHITESPACE; + +/// Allow strings enclosed in single quotes. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_single_quoted_str = + YYJSON_READ_ALLOW_SINGLE_QUOTED_STR; + +/// Allow unquoted object keys. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag allow_unquoted_key = + YYJSON_READ_ALLOW_UNQUOTED_KEY; + +/// Convenience flag for JSON5. Requires yyjson >= 0.12.0. +inline constexpr yyjson_read_flag json5 = YYJSON_READ_JSON5; +#endif + using InputObjectType = typename Reader::InputObjectType; using InputVarType = typename Reader::InputVarType; diff --git a/include/rfl/json/write.hpp b/include/rfl/json/write.hpp index 88e762aff..4af90f877 100644 --- a/include/rfl/json/write.hpp +++ b/include/rfl/json/write.hpp @@ -1,7 +1,6 @@ #ifndef RFL_JSON_WRITE_HPP_ #define RFL_JSON_WRITE_HPP_ -#include #if __has_include() #include #else @@ -19,9 +18,39 @@ namespace rfl { namespace json { -/// Convenient alias for the YYJSON pretty flag +/// Write JSON pretty-printed with 4-space indentation. inline constexpr yyjson_write_flag pretty = YYJSON_WRITE_PRETTY; +/// Write JSON pretty-printed with 2-space indentation. +/// Overrides `pretty` if both are set. +inline constexpr yyjson_write_flag pretty_two_spaces = + YYJSON_WRITE_PRETTY_TWO_SPACES; + +/// Escape non-ASCII Unicode characters as `\uXXXX` for ASCII-only output. +inline constexpr yyjson_write_flag escape_unicode = YYJSON_WRITE_ESCAPE_UNICODE; + +/// Escape forward slashes `/` as `\/`. +inline constexpr yyjson_write_flag escape_slashes = YYJSON_WRITE_ESCAPE_SLASHES; + +/// Write Inf and NaN numbers as `Infinity` and `NaN` literals (non-standard). +inline constexpr yyjson_write_flag write_allow_inf_and_nan = + YYJSON_WRITE_ALLOW_INF_AND_NAN; + +/// Write Inf and NaN numbers as `null`. +/// Overrides `write_allow_inf_and_nan` if both are set. +inline constexpr yyjson_write_flag inf_and_nan_as_null = + YYJSON_WRITE_INF_AND_NAN_AS_NULL; + +/// Allow invalid UTF-8 byte sequences when encoding string values. +inline constexpr yyjson_write_flag write_allow_invalid_unicode = + YYJSON_WRITE_ALLOW_INVALID_UNICODE; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 +/// Append a trailing newline `\n` at the end of the JSON output. +/// Requires yyjson >= 0.9.0. +inline constexpr yyjson_write_flag newline_at_end = YYJSON_WRITE_NEWLINE_AT_END; +#endif + /// Returns a JSON string representation of the object. /// Uses compile-time reflection to serialize a C++ object to JSON format. /// @tparam Ps Processors to apply during serialization (transforms the data) diff --git a/tests/json/test_json_flags.cpp b/tests/json/test_json_flags.cpp new file mode 100644 index 000000000..4c3bc8e3a --- /dev/null +++ b/tests/json/test_json_flags.cpp @@ -0,0 +1,436 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_json_flags { + +struct Config { + std::string name; + int port; + std::vector hosts; +}; + +struct TextWrapper { + std::string text; +}; + +struct FloatingValues { + double pos_inf; + double neg_inf; + double nan_val; +}; + +struct OptionalFloatingValues { + std::optional pos_inf; + std::optional neg_inf; + std::optional nan_val; +}; + +TEST(json, test_json_flags_values_disambiguated) { + static_assert(rfl::json::pretty == YYJSON_WRITE_PRETTY); + static_assert(rfl::json::pretty_two_spaces == YYJSON_WRITE_PRETTY_TWO_SPACES); + static_assert(rfl::json::escape_unicode == YYJSON_WRITE_ESCAPE_UNICODE); + static_assert(rfl::json::escape_slashes == YYJSON_WRITE_ESCAPE_SLASHES); + static_assert(rfl::json::write_allow_inf_and_nan == + YYJSON_WRITE_ALLOW_INF_AND_NAN); + static_assert(rfl::json::inf_and_nan_as_null == + YYJSON_WRITE_INF_AND_NAN_AS_NULL); + static_assert(rfl::json::write_allow_invalid_unicode == + YYJSON_WRITE_ALLOW_INVALID_UNICODE); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 + static_assert(rfl::json::newline_at_end == YYJSON_WRITE_NEWLINE_AT_END); +#endif + + static_assert(rfl::json::stop_when_done == YYJSON_READ_STOP_WHEN_DONE); + static_assert(rfl::json::allow_trailing_commas == + YYJSON_READ_ALLOW_TRAILING_COMMAS); + static_assert(rfl::json::allow_comments == YYJSON_READ_ALLOW_COMMENTS); + static_assert(rfl::json::read_allow_inf_and_nan == + YYJSON_READ_ALLOW_INF_AND_NAN); + static_assert(rfl::json::read_allow_invalid_unicode == + YYJSON_READ_ALLOW_INVALID_UNICODE); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 + static_assert(rfl::json::allow_bom == YYJSON_READ_ALLOW_BOM); +#endif + static_assert(rfl::json::jsonc == + (YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS)); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 + static_assert(rfl::json::allow_ext_number == YYJSON_READ_ALLOW_EXT_NUMBER); + static_assert(rfl::json::allow_ext_escape == YYJSON_READ_ALLOW_EXT_ESCAPE); + static_assert(rfl::json::allow_ext_whitespace == + YYJSON_READ_ALLOW_EXT_WHITESPACE); + static_assert(rfl::json::allow_single_quoted_str == + YYJSON_READ_ALLOW_SINGLE_QUOTED_STR); + static_assert(rfl::json::allow_unquoted_key == + YYJSON_READ_ALLOW_UNQUOTED_KEY); + static_assert(rfl::json::json5 == YYJSON_READ_JSON5); +#endif + + // Confirm read/write flags with similar names have distinct bit values. + static_assert(rfl::json::read_allow_inf_and_nan != + rfl::json::write_allow_inf_and_nan); + static_assert(rfl::json::read_allow_invalid_unicode != + rfl::json::write_allow_invalid_unicode); + + SUCCEED(); +} + +TEST(json, test_pretty_two_spaces_vs_pretty) { + const auto cfg = + Config{.name = "app", .port = 8080, .hosts = {"localhost", "127.0.0.1"}}; + + const std::string expected_four_spaces = + "{\n" + " \"name\": \"app\",\n" + " \"port\": 8080,\n" + " \"hosts\": [\n" + " \"localhost\",\n" + " \"127.0.0.1\"\n" + " ]\n" + "}"; + + const std::string expected_two_spaces = + "{\n" + " \"name\": \"app\",\n" + " \"port\": 8080,\n" + " \"hosts\": [\n" + " \"localhost\",\n" + " \"127.0.0.1\"\n" + " ]\n" + "}"; + + EXPECT_EQ(rfl::json::write(cfg, rfl::json::pretty), expected_four_spaces); + EXPECT_EQ(rfl::json::write(cfg, rfl::json::pretty_two_spaces), + expected_two_spaces); + EXPECT_EQ( + rfl::json::write(cfg, rfl::json::pretty | rfl::json::pretty_two_spaces), + expected_two_spaces); + + // Also verify to_schema accepts pretty_two_spaces (and newline_at_end when + // supported by yyjson >= 0.9.0). +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 + const auto schema = rfl::json::to_schema( + rfl::json::pretty_two_spaces | rfl::json::newline_at_end); + EXPECT_NE(schema.find("\n \"$schema\""), std::string::npos); + EXPECT_EQ(schema.back(), '\n'); +#else + const auto schema = rfl::json::to_schema(rfl::json::pretty_two_spaces); + EXPECT_NE(schema.find("\n \"$schema\""), std::string::npos); +#endif +} + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 +TEST(json, test_newline_at_end) { + const auto wrapper = TextWrapper{.text = "hello"}; + + EXPECT_EQ(rfl::json::write(wrapper, rfl::json::newline_at_end), + "{\"text\":\"hello\"}\n"); + EXPECT_EQ(rfl::json::write( + wrapper, rfl::json::pretty_two_spaces | rfl::json::newline_at_end), + "{\n \"text\": \"hello\"\n}\n"); + + std::ostringstream oss; + rfl::json::write(wrapper, oss, + rfl::json::pretty_two_spaces | rfl::json::newline_at_end); + EXPECT_EQ(oss.str(), "{\n \"text\": \"hello\"\n}\n"); +} +#endif + +TEST(json, test_escape_slashes) { + const auto wrapper = TextWrapper{.text = "https://example.com/a/b"}; + + EXPECT_EQ(rfl::json::write(wrapper), + R"({"text":"https://example.com/a/b"})"); + EXPECT_EQ(rfl::json::write(wrapper, rfl::json::escape_slashes), + R"({"text":"https:\/\/example.com\/a\/b"})"); + + const auto roundtrip = rfl::json::read( + rfl::json::write(wrapper, rfl::json::escape_slashes)); + ASSERT_TRUE(roundtrip.has_value()); + EXPECT_EQ(roundtrip.value().text, wrapper.text); +} + +TEST(json, test_escape_unicode) { + // "cafe" with U+00E9 in UTF-8: c a f \xC3 \xA9 + const auto wrapper = TextWrapper{.text = "caf\xC3\xA9"}; + + const auto escaped = rfl::json::write(wrapper, rfl::json::escape_unicode); + EXPECT_EQ(escaped, R"({"text":"caf\u00E9"})"); + + const auto roundtrip = rfl::json::read(escaped); + ASSERT_TRUE(roundtrip.has_value()); + EXPECT_EQ(roundtrip.value().text, wrapper.text); +} + +TEST(json, test_allow_comments) { + const std::string json_with_comments = R"({ + // Single-line comment + "name": "svc", + /* Multi-line + block comment */ + "port": 443, + "hosts": ["example.com"] + })"; + + EXPECT_FALSE(rfl::json::read(json_with_comments).has_value()); + + const auto res = + rfl::json::read(json_with_comments, rfl::json::allow_comments); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res.value().name, "svc"); + EXPECT_EQ(res.value().port, 443); + EXPECT_EQ(res.value().hosts, std::vector{"example.com"}); +} + +TEST(json, test_allow_trailing_commas) { + const std::string json_with_trailing_commas = R"({ + "name": "svc", + "port": 443, + "hosts": ["a", "b",], + })"; + + EXPECT_FALSE(rfl::json::read(json_with_trailing_commas).has_value()); + + const auto res = rfl::json::read(json_with_trailing_commas, + rfl::json::allow_trailing_commas); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res.value().name, "svc"); + EXPECT_EQ(res.value().port, 443); + EXPECT_EQ(res.value().hosts, (std::vector{"a", "b"})); +} + +TEST(json, test_jsonc_combined_flags) { + const std::string jsonc_doc = R"({ + // Configuration for server + "name": "my-server", + /* Listen port */ + "port": 9000, + "hosts": [ + "127.0.0.1", // loopback + "::1", + ], + })"; + + EXPECT_FALSE(rfl::json::read(jsonc_doc).has_value()); + EXPECT_FALSE( + rfl::json::read(jsonc_doc, rfl::json::allow_comments).has_value()); + EXPECT_FALSE( + rfl::json::read(jsonc_doc, rfl::json::allow_trailing_commas) + .has_value()); + + const auto res_or = rfl::json::read( + jsonc_doc, rfl::json::allow_comments | rfl::json::allow_trailing_commas); + ASSERT_TRUE(res_or.has_value()); + EXPECT_EQ(res_or.value().name, "my-server"); + EXPECT_EQ(res_or.value().port, 9000); + EXPECT_EQ(res_or.value().hosts, (std::vector{"127.0.0.1", "::1"})); + + const auto res_jsonc = rfl::json::read(jsonc_doc, rfl::json::jsonc); + ASSERT_TRUE(res_jsonc.has_value()); + EXPECT_EQ(res_jsonc.value().name, "my-server"); + + // Also test istream overload with jsonc flag. + std::istringstream iss(jsonc_doc); + const auto res_stream = rfl::json::read(iss, rfl::json::jsonc); + ASSERT_TRUE(res_stream.has_value()); + EXPECT_EQ(res_stream.value().port, 9000); +} + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000B00 +TEST(json, test_allow_bom) { + const std::string json_with_bom = "\xEF\xBB\xBF{\"text\":\"bom\"}"; + + EXPECT_FALSE(rfl::json::read(json_with_bom).has_value()); + + const auto res = + rfl::json::read(json_with_bom, rfl::json::allow_bom); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res.value().text, "bom"); +} +#endif + +TEST(json, test_stop_when_done) { + const std::string ndjson = "{\"text\":\"first\"}\n{\"text\":\"second\"}\n"; + + EXPECT_FALSE(rfl::json::read(ndjson).has_value()); + + const auto res = + rfl::json::read(ndjson, rfl::json::stop_when_done); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res.value().text, "first"); +} + +TEST(json, test_inf_and_nan_flags) { + const auto vals = FloatingValues{ + .pos_inf = std::numeric_limits::infinity(), + .neg_inf = -std::numeric_limits::infinity(), + .nan_val = std::numeric_limits::quiet_NaN(), + }; + + // Default write rejects Inf/NaN. + EXPECT_THROW(rfl::json::write(vals), std::runtime_error); + + // write_allow_inf_and_nan emits Infinity/-Infinity/NaN literals. + const auto serialized = + rfl::json::write(vals, rfl::json::write_allow_inf_and_nan); + EXPECT_EQ(serialized, + R"({"pos_inf":Infinity,"neg_inf":-Infinity,"nan_val":NaN})"); + + // Default read rejects Inf/NaN. + EXPECT_FALSE(rfl::json::read(serialized).has_value()); + + // read_allow_inf_and_nan parses them back accurately. + const auto parsed = rfl::json::read( + serialized, rfl::json::read_allow_inf_and_nan); + ASSERT_TRUE(parsed.has_value()); + EXPECT_TRUE(std::isinf(parsed.value().pos_inf) && parsed.value().pos_inf > 0); + EXPECT_TRUE(std::isinf(parsed.value().neg_inf) && parsed.value().neg_inf < 0); + EXPECT_TRUE(std::isnan(parsed.value().nan_val)); + + // inf_and_nan_as_null serializes Inf/NaN as null. + const auto as_null = rfl::json::write(vals, rfl::json::inf_and_nan_as_null); + EXPECT_EQ(as_null, R"({"pos_inf":null,"neg_inf":null,"nan_val":null})"); + + const auto parsed_null = rfl::json::read(as_null); + ASSERT_TRUE(parsed_null.has_value()); + EXPECT_FALSE(parsed_null.value().pos_inf.has_value()); + EXPECT_FALSE(parsed_null.value().neg_inf.has_value()); + EXPECT_FALSE(parsed_null.value().nan_val.has_value()); +} + +TEST(json, test_invalid_unicode_flags) { + const std::string invalid_utf8_json = "{\"text\":\"bad\xFF\"}"; + + EXPECT_FALSE(rfl::json::read(invalid_utf8_json).has_value()); + + const auto parsed = rfl::json::read( + invalid_utf8_json, rfl::json::read_allow_invalid_unicode); + ASSERT_TRUE(parsed.has_value()); + EXPECT_EQ(parsed.value().text, std::string("bad\xFF")); + + EXPECT_THROW(rfl::json::write(parsed.value()), std::runtime_error); + const auto written = + rfl::json::write(parsed.value(), rfl::json::write_allow_invalid_unicode); + EXPECT_EQ(written, invalid_utf8_json); +} + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000C00 +TEST(json, test_json5_flags) { + const std::string json5_doc = + "{\v\n" + " // JSON5 document\n" + " name: 'json5-\\x41pp',\n" + " port: 0x1F90,\n" + " hosts: ['localhost',],\n" + "}"; + + EXPECT_FALSE(rfl::json::read(json5_doc).has_value()); + + const auto res = rfl::json::read(json5_doc, rfl::json::json5); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ(res.value().name, "json5-App"); + EXPECT_EQ(res.value().port, 0x1F90); + EXPECT_EQ(res.value().hosts, std::vector{"localhost"}); + + // Also test composing all individual JSON5 extension flags. + const auto res_composed = rfl::json::read( + json5_doc, rfl::json::allow_comments | rfl::json::allow_trailing_commas | + rfl::json::allow_unquoted_key | + rfl::json::allow_single_quoted_str | + rfl::json::allow_ext_number | + rfl::json::allow_ext_escape | + rfl::json::allow_ext_whitespace); + ASSERT_TRUE(res_composed.has_value()); + EXPECT_EQ(res_composed.value().name, "json5-App"); + EXPECT_EQ(res_composed.value().port, 0x1F90); +} +#endif + +TEST(json, test_save_and_load_with_flags) { + struct TempDirGuard { + std::filesystem::path dir; + TempDirGuard() { + const auto base = std::filesystem::temp_directory_path(); + const auto stamp = + std::chrono::steady_clock::now().time_since_epoch().count(); + for (int attempt = 0; attempt < 1000; ++attempt) { + auto candidate = base / ("rfl_json_flags_test_" + + std::to_string(stamp) + "_" + + std::to_string(attempt)); + std::error_code ec; + if (std::filesystem::create_directory(candidate, ec)) { + dir = std::move(candidate); + return; + } + } + throw std::runtime_error("Failed to create temporary directory"); + } + ~TempDirGuard() { + if (!dir.empty()) { + std::error_code ec; + std::filesystem::remove_all(dir, ec); + } + } + }; + + TempDirGuard tmp; + const auto saved_path = (tmp.dir / "saved.json").string(); + const auto cfg = + Config{.name = "saved", .port = 8081, .hosts = {"127.0.0.1"}}; + +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 + const auto write_flags = + rfl::json::pretty_two_spaces | rfl::json::newline_at_end; +#else + const auto write_flags = rfl::json::pretty_two_spaces; +#endif + const auto save_res = rfl::json::save(saved_path, cfg, write_flags); + ASSERT_TRUE(save_res.has_value()); + + // Verify the saved file actually honored the write flags. + { + std::ifstream ifs(saved_path, std::ios::binary); + ASSERT_TRUE(ifs.is_open()); + const std::string content((std::istreambuf_iterator(ifs)), + std::istreambuf_iterator()); + EXPECT_NE(content.find("\n \"name\": \"saved\""), std::string::npos); +#if defined(YYJSON_VERSION_HEX) && YYJSON_VERSION_HEX >= 0x000900 + ASSERT_FALSE(content.empty()); + EXPECT_EQ(content.back(), '\n'); +#endif + } + + // Write a JSONC file with comments + trailing comma and verify load flags. + const auto jsonc_path = (tmp.dir / "config.jsonc").string(); + { + std::ofstream ofs(jsonc_path, std::ios::binary); + ASSERT_TRUE(ofs.is_open()); + ofs << "{\n" + << " // comment\n" + << " \"name\": \"saved\",\n" + << " \"port\": 8081,\n" + << " \"hosts\": [\"127.0.0.1\",],\n" + << "}\n"; + } + + EXPECT_FALSE(rfl::json::load(jsonc_path).has_value()); + + const auto load_res = rfl::json::load(jsonc_path, rfl::json::jsonc); + ASSERT_TRUE(load_res.has_value()); + EXPECT_EQ(load_res.value().name, "saved"); + EXPECT_EQ(load_res.value().port, 8081); + EXPECT_EQ(load_res.value().hosts, std::vector{"127.0.0.1"}); +} + +} // namespace test_json_flags