Re-support indentation in fancy_serializer

This commit is contained in:
Evan Driscoll 2018-06-02 01:07:25 -05:00
parent 297ff8e53f
commit e38b4e8031
3 changed files with 75 additions and 393 deletions

View File

@ -278,11 +278,12 @@ class fancy_serializer
} }
template<typename BasicJsonType> template<typename BasicJsonType>
std::ostream& fancy_dump(std::ostream& o, const BasicJsonType& j) std::ostream& fancy_dump(std::ostream& o, const BasicJsonType& j,
unsigned int indent_step, char indent_char)
{ {
// do the actual serialization // do the actual serialization
detail::fancy_serializer<BasicJsonType> s(detail::output_adapter<char>(o), o.fill()); detail::fancy_serializer<BasicJsonType> s(detail::output_adapter<char>(o), indent_char);
s.dump(j, false, false, 0u); s.dump(j, indent_step > 0, false, indent_step);
return o; return o;
} }

View File

@ -10088,6 +10088,8 @@ class serializer
// #include <nlohmann/detail/value_t.hpp> // #include <nlohmann/detail/value_t.hpp>
// #include <nlohmann/detail/output/primitive_serializer.hpp>
namespace nlohmann namespace nlohmann
{ {
@ -10100,6 +10102,7 @@ namespace detail
template<typename BasicJsonType> template<typename BasicJsonType>
class fancy_serializer class fancy_serializer
{ {
using primitive_serializer_t = primitive_serializer<BasicJsonType>;
using string_t = typename BasicJsonType::string_t; using string_t = typename BasicJsonType::string_t;
using number_float_t = typename BasicJsonType::number_float_t; using number_float_t = typename BasicJsonType::number_float_t;
using number_integer_t = typename BasicJsonType::number_integer_t; using number_integer_t = typename BasicJsonType::number_integer_t;
@ -10113,10 +10116,7 @@ class fancy_serializer
@param[in] ichar indentation character to use @param[in] ichar indentation character to use
*/ */
fancy_serializer(output_adapter_t<char> s, const char ichar) fancy_serializer(output_adapter_t<char> s, const char ichar)
: o(std::move(s)), loc(std::localeconv()), : o(std::move(s)), indent_char(ichar), indent_string(512, indent_char)
thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
indent_char(ichar), indent_string(512, indent_char)
{} {}
// delete because of pointer members // delete because of pointer members
@ -10172,7 +10172,7 @@ class fancy_serializer
{ {
o->write_characters(indent_string.c_str(), new_indent); o->write_characters(indent_string.c_str(), new_indent);
o->write_character('\"'); o->write_character('\"');
dump_escaped(i->first, ensure_ascii); prim_serializer.dump_escaped(*o, i->first, ensure_ascii);
o->write_characters("\": ", 3); o->write_characters("\": ", 3);
dump(i->second, true, ensure_ascii, indent_step, new_indent); dump(i->second, true, ensure_ascii, indent_step, new_indent);
o->write_characters(",\n", 2); o->write_characters(",\n", 2);
@ -10183,7 +10183,7 @@ class fancy_serializer
assert(std::next(i) == val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend());
o->write_characters(indent_string.c_str(), new_indent); o->write_characters(indent_string.c_str(), new_indent);
o->write_character('\"'); o->write_character('\"');
dump_escaped(i->first, ensure_ascii); prim_serializer.dump_escaped(*o, i->first, ensure_ascii);
o->write_characters("\": ", 3); o->write_characters("\": ", 3);
dump(i->second, true, ensure_ascii, indent_step, new_indent); dump(i->second, true, ensure_ascii, indent_step, new_indent);
@ -10200,7 +10200,7 @@ class fancy_serializer
for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
{ {
o->write_character('\"'); o->write_character('\"');
dump_escaped(i->first, ensure_ascii); prim_serializer.dump_escaped(*o, i->first, ensure_ascii);
o->write_characters("\":", 2); o->write_characters("\":", 2);
dump(i->second, false, ensure_ascii, indent_step, current_indent); dump(i->second, false, ensure_ascii, indent_step, current_indent);
o->write_character(','); o->write_character(',');
@ -10210,7 +10210,7 @@ class fancy_serializer
assert(i != val.m_value.object->cend()); assert(i != val.m_value.object->cend());
assert(std::next(i) == val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend());
o->write_character('\"'); o->write_character('\"');
dump_escaped(i->first, ensure_ascii); prim_serializer.dump_escaped(*o, i->first, ensure_ascii);
o->write_characters("\":", 2); o->write_characters("\":", 2);
dump(i->second, false, ensure_ascii, indent_step, current_indent); dump(i->second, false, ensure_ascii, indent_step, current_indent);
@ -10282,7 +10282,7 @@ class fancy_serializer
case value_t::string: case value_t::string:
{ {
o->write_character('\"'); o->write_character('\"');
dump_escaped(*val.m_value.string, ensure_ascii); prim_serializer.dump_escaped(*o, *val.m_value.string, ensure_ascii);
o->write_character('\"'); o->write_character('\"');
return; return;
} }
@ -10302,19 +10302,19 @@ class fancy_serializer
case value_t::number_integer: case value_t::number_integer:
{ {
dump_integer(val.m_value.number_integer); prim_serializer.dump_integer(*o, val.m_value.number_integer);
return; return;
} }
case value_t::number_unsigned: case value_t::number_unsigned:
{ {
dump_integer(val.m_value.number_unsigned); prim_serializer.dump_integer(*o, val.m_value.number_unsigned);
return; return;
} }
case value_t::number_float: case value_t::number_float:
{ {
dump_float(val.m_value.number_float); prim_serializer.dump_float(*o, val.m_value.number_float);
return; return;
} }
@ -10332,378 +10332,28 @@ class fancy_serializer
} }
} }
private:
/*!
@brief dump escaped string
Escape a string by replacing certain special characters by a sequence of an
escape character (backslash) and another character and other control
characters by a sequence of "\u" followed by a four-digit hex
representation. The escaped string is written to output stream @a o.
@param[in] s the string to escape
@param[in] ensure_ascii whether to escape non-ASCII characters with
\uXXXX sequences
@complexity Linear in the length of string @a s.
*/
void dump_escaped(const string_t& s, const bool ensure_ascii)
{
uint32_t codepoint;
uint8_t state = UTF8_ACCEPT;
std::size_t bytes = 0; // number of bytes written to string_buffer
for (std::size_t i = 0; i < s.size(); ++i)
{
const auto byte = static_cast<uint8_t>(s[i]);
switch (decode(state, codepoint, byte))
{
case UTF8_ACCEPT: // decode found a new code point
{
switch (codepoint)
{
case 0x08: // backspace
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = 'b';
break;
}
case 0x09: // horizontal tab
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = 't';
break;
}
case 0x0A: // newline
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = 'n';
break;
}
case 0x0C: // formfeed
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = 'f';
break;
}
case 0x0D: // carriage return
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = 'r';
break;
}
case 0x22: // quotation mark
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = '\"';
break;
}
case 0x5C: // reverse solidus
{
string_buffer[bytes++] = '\\';
string_buffer[bytes++] = '\\';
break;
}
default:
{
// escape control characters (0x00..0x1F) or, if
// ensure_ascii parameter is used, non-ASCII characters
if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
{
if (codepoint <= 0xFFFF)
{
std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x",
static_cast<uint16_t>(codepoint));
bytes += 6;
}
else
{
std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
bytes += 12;
}
}
else
{
// copy byte to buffer (all previous bytes
// been copied have in default case above)
string_buffer[bytes++] = s[i];
}
break;
}
}
// write buffer and reset index; there must be 13 bytes
// left, as this is the maximal number of bytes to be
// written ("\uxxxx\uxxxx\0") for one code point
if (string_buffer.size() - bytes < 13)
{
o->write_characters(string_buffer.data(), bytes);
bytes = 0;
}
break;
}
case UTF8_REJECT: // decode found invalid UTF-8 byte
{
std::string sn(3, '\0');
snprintf(&sn[0], sn.size(), "%.2X", byte);
JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
}
default: // decode found yet incomplete multi-byte code point
{
if (not ensure_ascii)
{
// code point will not be escaped - copy byte to buffer
string_buffer[bytes++] = s[i];
}
break;
}
}
}
if (JSON_LIKELY(state == UTF8_ACCEPT))
{
// write buffer
if (bytes > 0)
{
o->write_characters(string_buffer.data(), bytes);
}
}
else
{
// we finish reading, but do not accept: string was incomplete
std::string sn(3, '\0');
snprintf(&sn[0], sn.size(), "%.2X", static_cast<uint8_t>(s.back()));
JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
}
}
/*!
@brief dump an integer
Dump a given integer to output stream @a o. Works internally with
@a number_buffer.
@param[in] x integer number (signed or unsigned) to dump
@tparam NumberType either @a number_integer_t or @a number_unsigned_t
*/
template<typename NumberType, detail::enable_if_t<
std::is_same<NumberType, number_unsigned_t>::value or
std::is_same<NumberType, number_integer_t>::value,
int> = 0>
void dump_integer(NumberType x)
{
// special case for "0"
if (x == 0)
{
o->write_character('0');
return;
}
const bool is_negative = (x <= 0) and (x != 0); // see issue #755
std::size_t i = 0;
while (x != 0)
{
// spare 1 byte for '\0'
assert(i < number_buffer.size() - 1);
const auto digit = std::labs(static_cast<long>(x % 10));
number_buffer[i++] = static_cast<char>('0' + digit);
x /= 10;
}
if (is_negative)
{
// make sure there is capacity for the '-'
assert(i < number_buffer.size() - 2);
number_buffer[i++] = '-';
}
std::reverse(number_buffer.begin(), number_buffer.begin() + i);
o->write_characters(number_buffer.data(), i);
}
/*!
@brief dump a floating-point number
Dump a given floating-point number to output stream @a o. Works internally
with @a number_buffer.
@param[in] x floating-point number to dump
*/
void dump_float(number_float_t x)
{
// NaN / inf
if (not std::isfinite(x))
{
o->write_characters("null", 4);
return;
}
// If number_float_t is an IEEE-754 single or double precision number,
// use the Grisu2 algorithm to produce short numbers which are
// guaranteed to round-trip, using strtof and strtod, resp.
//
// NB: The test below works if <long double> == <double>.
static constexpr bool is_ieee_single_or_double
= (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
(std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
}
void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
{
char* begin = number_buffer.data();
char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
o->write_characters(begin, static_cast<size_t>(end - begin));
}
void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
{
// get number of digits for a float -> text -> float round-trip
static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
// the actual conversion
std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
// negative value indicates an error
assert(len > 0);
// check if buffer was large enough
assert(static_cast<std::size_t>(len) < number_buffer.size());
// erase thousands separator
if (thousands_sep != '\0')
{
const auto end = std::remove(number_buffer.begin(),
number_buffer.begin() + len, thousands_sep);
std::fill(end, number_buffer.end(), '\0');
assert((end - number_buffer.begin()) <= len);
len = (end - number_buffer.begin());
}
// convert decimal point to '.'
if (decimal_point != '\0' and decimal_point != '.')
{
const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
if (dec_pos != number_buffer.end())
{
*dec_pos = '.';
}
}
o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
// determine if need to append ".0"
const bool value_is_int_like =
std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
[](char c)
{
return (c == '.' or c == 'e');
});
if (value_is_int_like)
{
o->write_characters(".0", 2);
}
}
/*!
@brief check whether a string is UTF-8 encoded
The function checks each byte of a string whether it is UTF-8 encoded. The
result of the check is stored in the @a state parameter. The function must
be called initially with state 0 (accept). State 1 means the string must
be rejected, because the current byte is not allowed. If the string is
completely processed, but the state is non-zero, the string ended
prematurely; that is, the last byte indicated more bytes should have
followed.
@param[in,out] state the state of the decoding
@param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
@param[in] byte next byte to decode
@return new state
@note The function has been edited: a std::array is used.
@copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
@sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
*/
static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept
{
static const std::array<uint8_t, 400> utf8d =
{
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, // s1..s2
1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
}
};
const uint8_t type = utf8d[byte];
codep = (state != UTF8_ACCEPT)
? (byte & 0x3fu) | (codep << 6)
: static_cast<uint32_t>(0xff >> type) & (byte);
state = utf8d[256u + state * 16u + type];
return state;
}
private: private:
/// the output of the fancy_serializer /// the output of the fancy_serializer
output_adapter_t<char> o = nullptr; output_adapter_t<char> o = nullptr;
/// a (hopefully) large enough character buffer
std::array<char, 64> number_buffer{{}};
/// the locale
const std::lconv* loc = nullptr;
/// the locale's thousand separator character
const char thousands_sep = '\0';
/// the locale's decimal point character
const char decimal_point = '\0';
/// string buffer
std::array<char, 512> string_buffer{{}};
/// the indentation character /// the indentation character
const char indent_char; const char indent_char;
/// the indentation string /// the indentation string
string_t indent_string; string_t indent_string;
/// Used for serializing "base" objects. Strings are sort of
/// counted in this, but not completely.
primitive_serializer_t prim_serializer;
}; };
} }
template<typename BasicJsonType> template<typename BasicJsonType>
std::ostream& fancy_dump(std::ostream& o, const BasicJsonType& j) std::ostream& fancy_dump(std::ostream& o, const BasicJsonType& j,
unsigned int indent_step, char indent_char)
{ {
// do the actual serialization // do the actual serialization
detail::fancy_serializer<BasicJsonType> s(detail::output_adapter<char>(o), o.fill()); detail::fancy_serializer<BasicJsonType> s(detail::output_adapter<char>(o), indent_char);
s.dump(j, false, false, 0u); s.dump(j, indent_step > 0, false, indent_step);
return o; return o;
} }

View File

@ -34,48 +34,79 @@ SOFTWARE.
using nlohmann::json; using nlohmann::json;
using nlohmann::fancy_dump; using nlohmann::fancy_dump;
std::string fancy_to_string(json j, unsigned int indent_step = 0, char indent_char = ' ')
{
std::stringstream ss;
fancy_dump(ss, j, indent_step, indent_char);
return ss.str();
}
TEST_CASE("serialization") TEST_CASE("serialization")
{ {
SECTION("primitives") SECTION("primitives")
{ {
SECTION("null") SECTION("null")
{ {
std::stringstream ss; auto str = fancy_to_string({});
json j; CHECK(str == "null");
fancy_dump(ss, j);
CHECK(ss.str() == "null");
} }
SECTION("true") SECTION("true")
{ {
std::stringstream ss; auto str = fancy_to_string(true);
json j = true; CHECK(str == "true");
fancy_dump(ss, j);
CHECK(ss.str() == "true");
} }
SECTION("false") SECTION("false")
{ {
std::stringstream ss; auto str = fancy_to_string(false);
json j = false; CHECK(str == "false");
fancy_dump(ss, j);
CHECK(ss.str() == "false");
} }
SECTION("integer") SECTION("integer")
{ {
std::stringstream ss; auto str = fancy_to_string(10);
json j = 10; CHECK(str == "10");
fancy_dump(ss, j);
CHECK(ss.str() == "10");
} }
SECTION("floating point") SECTION("floating point")
{ {
std::stringstream ss; auto str = fancy_to_string(7.5);
json j = 7.5; CHECK(str == "7.5");
fancy_dump(ss, j);
CHECK(ss.str() == "7.5");
} }
} }
SECTION("given width")
{
auto str = fancy_to_string({"foo", 1, 2, 3, false, {{"one", 1}}}, 4);
CHECK(str ==
"[\n"
" \"foo\",\n"
" 1,\n"
" 2,\n"
" 3,\n"
" false,\n"
" {\n"
" \"one\": 1\n"
" }\n"
"]"
);
}
SECTION("given fill")
{
auto str = fancy_to_string({"foo", 1, 2, 3, false, {{"one", 1}}}, 1, '\t');
CHECK(str ==
"[\n"
"\t\"foo\",\n"
"\t1,\n"
"\t2,\n"
"\t3,\n"
"\tfalse,\n"
"\t{\n"
"\t\t\"one\": 1\n"
"\t}\n"
"]"
);
}
} }