mirror of
https://github.com/nlohmann/json.git
synced 2026-10-03 05:00:30 +00:00
Support any-rank C arrays in from_json, not just rank 1-4
from_json() for C arrays had four hand-unrolled overloads (rank 1-4, added incrementally in #4262), each with its own nested loops. to_json() already handles any rank recursively, so a rank-5+ C array could be serialized but not read back with get_to()/get<>(). Replace the four overloads with one from_json() SFINAE-constrained on get<remove_all_extents<T>::type>() existing, forwarding to a pair of mutually recursive from_json_c_array_element() helpers: one assigns a non-array element via get<T>(), the other loops over a array element and recurses one dimension at a time. Each dimension still goes through at(), so type_error.304/out_of_range.401 stay unchanged; ranks 1-4 keep their existing behavior and semantics. Adds rank-5 round-trip and mismatched-shape tests to unit-conversions.cpp. Public API: additive only (rank 5+ C arrays become readable). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 1
This commit is contained in:
@@ -430,6 +430,37 @@ TEST_CASE("value conversion")
|
||||
CHECK(std::equal(std::begin(nbs[0][0][0]), std::end(nbs[1][1][1]), std::begin(nbs2[0][0][0])));
|
||||
}
|
||||
|
||||
SECTION("built-in arrays: 5D")
|
||||
{
|
||||
// NOLINTBEGIN(misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
const int nbs[1][1][1][2][2] = {{{{{0, 1}, {2, 3}}}}};
|
||||
int nbs2[1][1][1][2][2] = {{{{{0, 0}, {0, 0}}}}};
|
||||
// NOLINTEND(misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
|
||||
const json j2 = nbs;
|
||||
j2.get_to(nbs2);
|
||||
CHECK(std::equal(std::begin(nbs[0][0][0][0]), std::end(nbs[0][0][0][1]), std::begin(nbs2[0][0][0][0])));
|
||||
}
|
||||
|
||||
SECTION("built-in arrays: mismatched shape")
|
||||
{
|
||||
// NOLINTBEGIN(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
int nbs2[2][3] = {{0, 0, 0}, {0, 0, 0}};
|
||||
// NOLINTEND(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
||||
|
||||
SECTION("not an array")
|
||||
{
|
||||
const json j2 = 42;
|
||||
CHECK_THROWS_WITH_AS(j2.get_to(nbs2), "[json.exception.type_error.304] cannot use at() with number", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("too few elements")
|
||||
{
|
||||
const json j2 = {{0, 1, 2}};
|
||||
CHECK_THROWS_WITH_AS(j2.get_to(nbs2), "[json.exception.out_of_range.401] array index 1 is out of range", json::out_of_range&);
|
||||
}
|
||||
}
|
||||
|
||||
SECTION("std::deque<json>")
|
||||
{
|
||||
std::deque<json> a{"previous", "value"};
|
||||
|
||||
Reference in New Issue
Block a user