Fancy serializer can limit recursion depth

Elides objects with ... if that limit is exceeded
This commit is contained in:
Evan Driscoll 2018-06-02 22:22:24 -05:00
parent cd0c225a50
commit 28e7eecf33
3 changed files with 72 additions and 12 deletions

View File

@ -29,6 +29,8 @@ struct fancy_serializer_style
unsigned int indent_step = 0;
char indent_char = ' ';
unsigned int depth_limit = std::numeric_limits<unsigned>::max();
unsigned int strings_maximum_length = 0;
};
@ -156,6 +158,11 @@ class fancy_serializer
o->write_characters("{}", 2);
return;
}
else if (depth >= style.depth_limit)
{
o->write_characters("{...}", 5);
return;
}
// variable to hold indentation for recursive calls
const auto old_indent = depth * style.indent_step;
@ -201,6 +208,11 @@ class fancy_serializer
o->write_characters("[]", 2);
return;
}
else if (depth >= style.depth_limit)
{
o->write_characters("[...]", 5);
return;
}
// variable to hold indentation for recursive calls
const auto old_indent = depth * style.indent_step;

View File

@ -10099,6 +10099,8 @@ struct fancy_serializer_style
unsigned int indent_step = 0;
char indent_char = ' ';
unsigned int depth_limit = std::numeric_limits<unsigned>::max();
unsigned int strings_maximum_length = 0;
};
@ -10226,6 +10228,11 @@ class fancy_serializer
o->write_characters("{}", 2);
return;
}
else if (depth >= style.depth_limit)
{
o->write_characters("{...}", 5);
return;
}
// variable to hold indentation for recursive calls
const auto old_indent = depth * style.indent_step;
@ -10271,6 +10278,11 @@ class fancy_serializer
o->write_characters("[]", 2);
return;
}
else if (depth >= style.depth_limit)
{
o->write_characters("[...]", 5);
return;
}
// variable to hold indentation for recursive calls
const auto old_indent = depth * style.indent_step;

View File

@ -183,23 +183,59 @@ TEST_CASE("serialization")
// behavior to be, first. :-)
}
SECTION("maximum depth")
{
SECTION("recursing past the maximum depth with a list elides the subobjects")
{
fancy_serializer_style style;
style.depth_limit = 1;
auto str_flat = fancy_to_string({1, {1}}, style);
CHECK(str_flat == "[1,[...]]");
style.indent_step = 4;
auto str_lines = fancy_to_string({1, {1}}, style);
CHECK(str_lines == dedent(R"(
[
1,
[...]
])"));
}
SECTION("recursing past the maximum depth with an object elides the subobjects")
{
fancy_serializer_style style;
style.depth_limit = 1;
auto str_flat = fancy_to_string({1, {{"one", 1}}}, style);
CHECK(str_flat == "[1,{...}]");
style.indent_step = 4;
auto str_lines = fancy_to_string({1, {{"one", 1}}}, style);
CHECK(str_lines == dedent(R"(
[
1,
{...}
])"));
}
}
SECTION("given width")
{
fancy_serializer_style style;
style.indent_step = 4;
auto str = fancy_to_string({"foo", 1, 2, 3, false, {{"one", 1}}}, style);
CHECK(str ==
dedent(R"(
[
"foo",
1,
2,
3,
false,
{
"one": 1
}
])"));
CHECK(str == dedent(R"(
[
"foo",
1,
2,
3,
false,
{
"one": 1
}
])"));
}
SECTION("given fill")