mirror of
https://github.com/nlohmann/json.git
synced 2026-08-22 00:53:18 +00:00
@@ -195,3 +195,4 @@ add_subdirectory(cmake_add_subdirectory)
|
||||
add_subdirectory(cmake_fetch_content)
|
||||
add_subdirectory(cmake_fetch_content2)
|
||||
add_subdirectory(cmake_target_include_directories)
|
||||
add_subdirectory(fmt_formatter)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
if (${CMAKE_VERSION} VERSION_GREATER "3.14.0")
|
||||
add_test(NAME fmt_formatter_configure
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-G "${CMAKE_GENERATOR}"
|
||||
-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
|
||||
-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/project
|
||||
)
|
||||
add_test(NAME fmt_formatter_build
|
||||
COMMAND ${CMAKE_COMMAND} --build .
|
||||
)
|
||||
set_tests_properties(fmt_formatter_configure PROPERTIES
|
||||
FIXTURES_SETUP fmt_formatter
|
||||
LABELS "git_required;not_reproducible"
|
||||
)
|
||||
set_tests_properties(fmt_formatter_build PROPERTIES
|
||||
FIXTURES_REQUIRED fmt_formatter
|
||||
LABELS "git_required;not_reproducible"
|
||||
)
|
||||
endif()
|
||||
@@ -0,0 +1,36 @@
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
|
||||
project(FmtFormatterTest CXX)
|
||||
|
||||
include(FetchContent)
|
||||
|
||||
get_filename_component(GIT_REPOSITORY_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../../.. ABSOLUTE)
|
||||
FetchContent_Declare(json GIT_REPOSITORY ${GIT_REPOSITORY_DIRECTORY} GIT_TAG HEAD)
|
||||
|
||||
set(FMT_TEST OFF CACHE BOOL "" FORCE)
|
||||
set(FMT_DOC OFF CACHE BOOL "" FORCE)
|
||||
set(FMT_INSTALL OFF CACHE BOOL "" FORCE)
|
||||
FetchContent_Declare(fmt
|
||||
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
|
||||
GIT_TAG 12.2.0
|
||||
GIT_SHALLOW TRUE
|
||||
)
|
||||
|
||||
FetchContent_MakeAvailable(json fmt)
|
||||
|
||||
if(MSVC)
|
||||
add_compile_options(/EHsc)
|
||||
endif()
|
||||
|
||||
add_executable(fmt_formatter_test main.cpp)
|
||||
target_link_libraries(fmt_formatter_test PRIVATE nlohmann_json::nlohmann_json fmt::fmt)
|
||||
target_compile_features(fmt_formatter_test PRIVATE cxx_std_17)
|
||||
|
||||
# Fail the build itself (and therefore the ctest "build" step that drives it) if the
|
||||
# recipe's runtime assertions don't hold -- there is no separate "run" step, since the
|
||||
# executable's location varies by platform/generator, but CMake resolves a target name
|
||||
# passed to a custom command's COMMAND for us.
|
||||
add_custom_command(TARGET fmt_formatter_test POST_BUILD
|
||||
COMMAND fmt_formatter_test
|
||||
COMMENT "Running fmt::formatter<nlohmann::json> recipe test"
|
||||
)
|
||||
@@ -0,0 +1,98 @@
|
||||
#include <cassert>
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
// A fmt::formatter<nlohmann::json> specialization mirroring std::formatter<basic_json>
|
||||
// (see docs/mkdocs/docs/api/basic_json/std_formatter.md), for use with fmt versions that
|
||||
// no longer pick up format_as() (fmt >= 11.1.0), or to get the same "{:#}"/width/
|
||||
// fill-and-align spec support with any fmt version.
|
||||
// --8<-- [start:formatter_recipe]
|
||||
template <>
|
||||
struct fmt::formatter<nlohmann::json>
|
||||
{
|
||||
// -1 means compact output (dump()); any value >= 0 means pretty-printed
|
||||
// output with that many spaces (or indent_char) per level.
|
||||
int indent = -1;
|
||||
char indent_char = ' ';
|
||||
|
||||
constexpr auto parse(format_parse_context& ctx) -> format_parse_context::iterator
|
||||
{
|
||||
auto it = ctx.begin();
|
||||
const auto end = ctx.end();
|
||||
constexpr auto is_align = [](char c)
|
||||
{
|
||||
return c == '<' || c == '>' || c == '^';
|
||||
};
|
||||
|
||||
// [[fill] align] - repurposed here to pick a custom indent character
|
||||
if (it != end && it + 1 != end && is_align(it[1]))
|
||||
{
|
||||
indent_char = *it;
|
||||
it += 2;
|
||||
}
|
||||
else if (it != end && is_align(*it))
|
||||
{
|
||||
++it;
|
||||
}
|
||||
|
||||
// ['#'] - "alternate form", used here to request pretty-printing
|
||||
bool pretty = false;
|
||||
if (it != end && *it == '#')
|
||||
{
|
||||
pretty = true;
|
||||
++it;
|
||||
}
|
||||
|
||||
// [width] - repurposed here to pick the indent size; a width without '#'
|
||||
// implies pretty-printing since an indent otherwise has no meaning
|
||||
if (it != end && *it >= '1' && *it <= '9')
|
||||
{
|
||||
indent = 0;
|
||||
while (it != end && *it >= '0' && *it <= '9')
|
||||
{
|
||||
indent = (indent * 10) + (*it - '0');
|
||||
++it;
|
||||
}
|
||||
}
|
||||
else if (pretty)
|
||||
{
|
||||
indent = 4;
|
||||
}
|
||||
|
||||
if (it != end && *it != '}')
|
||||
{
|
||||
throw fmt::format_error("invalid format args for nlohmann::json");
|
||||
}
|
||||
|
||||
return it;
|
||||
}
|
||||
|
||||
auto format(const nlohmann::json& j, format_context& ctx) const
|
||||
{
|
||||
const auto dumped = j.dump(indent, indent_char);
|
||||
return fmt::format_to(ctx.out(), "{}", dumped);
|
||||
}
|
||||
};
|
||||
// --8<-- [end:formatter_recipe]
|
||||
|
||||
int main()
|
||||
{
|
||||
const nlohmann::json j = {{"foo", 1}, {"bar", {1, 2, 3}}};
|
||||
|
||||
assert(fmt::format("{}", j) == j.dump());
|
||||
assert(fmt::format("{:#}", j) == j.dump(4));
|
||||
assert(fmt::format("{:2}", j) == j.dump(2));
|
||||
assert(fmt::format("{:#2}", j) == j.dump(2));
|
||||
assert(fmt::format("{:.>#}", j) == j.dump(4, '.'));
|
||||
|
||||
bool threw = false;
|
||||
try
|
||||
{
|
||||
(void)fmt::vformat("{:x}", fmt::make_format_args(j));
|
||||
}
|
||||
catch (const fmt::format_error&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
assert(threw);
|
||||
}
|
||||
@@ -46,7 +46,27 @@ TEST_CASE("std::formatter<nlohmann::json>")
|
||||
CHECK(std::format("{:#}", json::array()) == json::array().dump(4));
|
||||
}
|
||||
|
||||
SECTION("format args other than an empty spec or '#' are rejected")
|
||||
SECTION("a width sets the indent, like dump(width), with or without '#'")
|
||||
{
|
||||
const json j = {{"foo", 1}, {"bar", {1, 2, 3}}};
|
||||
CHECK(std::format("{:2}", j) == j.dump(2));
|
||||
CHECK(std::format("{:#2}", j) == j.dump(2));
|
||||
CHECK(std::format("{:8}", j) == j.dump(8));
|
||||
}
|
||||
|
||||
SECTION("fill-and-align sets the indent character, like dump(indent, indent_char)")
|
||||
{
|
||||
const json j = {{"foo", 1}, {"bar", {1, 2, 3}}};
|
||||
CHECK(std::format("{:.>#}", j) == j.dump(4, '.'));
|
||||
CHECK(std::format("{:.>#3}", j) == j.dump(3, '.'));
|
||||
CHECK(std::format("{:.>3}", j) == j.dump(3, '.'));
|
||||
// the alignment direction itself ('<', '>', '^') has no separate meaning for
|
||||
// JSON values -- only the fill character before it is used as the indent character
|
||||
CHECK(std::format("{:.<3}", j) == j.dump(3, '.'));
|
||||
CHECK(std::format("{:.^3}", j) == j.dump(3, '.'));
|
||||
}
|
||||
|
||||
SECTION("format args with no meaning for JSON values are rejected")
|
||||
{
|
||||
// std::vformat parses the format string at runtime (unlike std::format, whose
|
||||
// format_string type is checked at compile time), so it lets us verify that an
|
||||
@@ -54,7 +74,14 @@ TEST_CASE("std::formatter<nlohmann::json>")
|
||||
// format string.
|
||||
const json j = 42;
|
||||
CHECK_THROWS_AS(std::vformat("{:x}", std::make_format_args(j)), std::format_error);
|
||||
CHECK_THROWS_AS(std::vformat("{:10}", std::make_format_args(j)), std::format_error);
|
||||
CHECK_THROWS_AS(std::vformat("{:+}", std::make_format_args(j)), std::format_error); // sign
|
||||
CHECK_THROWS_AS(std::vformat("{:-}", std::make_format_args(j)), std::format_error); // sign
|
||||
CHECK_THROWS_AS(std::vformat("{: }", std::make_format_args(j)), std::format_error); // sign
|
||||
CHECK_THROWS_AS(std::vformat("{:04}", std::make_format_args(j)), std::format_error); // '0' flag
|
||||
CHECK_THROWS_AS(std::vformat("{:.2}", std::make_format_args(j)), std::format_error); // precision
|
||||
CHECK_THROWS_AS(std::vformat("{:L}", std::make_format_args(j)), std::format_error); // locale
|
||||
const int dynamic_width = 4;
|
||||
CHECK_THROWS_AS(std::vformat("{:{}}", std::make_format_args(j, dynamic_width)), std::format_error); // dynamic width
|
||||
}
|
||||
|
||||
SECTION("std::format_to writes through an arbitrary output iterator")
|
||||
|
||||
Reference in New Issue
Block a user