From 7a79e91ecd67a5e17fb2fc12a5d19ec70f457f63 Mon Sep 17 00:00:00 2001 From: Cory Omand Date: Tue, 8 Mar 2016 15:33:04 -0800 Subject: [PATCH] PrettyWriter formatting options. This change adds PrettyWriter::SetFormatOptions with a corresponding bitfield enum PrettyFormatOptions. This allows options affecting the format of the PrettyWriter to be set. The first option to be provided is kFormatSingleLineArray, which instructs the PrettyWriter to write arrays on a single line, rather than breaking them up onto a line per element. --- include/rapidjson/prettywriter.h | 30 +++++++++++++++++++++++++----- test/unittest/prettywritertest.cpp | 23 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/include/rapidjson/prettywriter.h b/include/rapidjson/prettywriter.h index 5ec4ccc3f..75dc474f4 100644 --- a/include/rapidjson/prettywriter.h +++ b/include/rapidjson/prettywriter.h @@ -24,6 +24,14 @@ RAPIDJSON_DIAG_OFF(effc++) RAPIDJSON_NAMESPACE_BEGIN +//! Combination of PrettyWriter format flags. +/*! \see PrettyWriter::SetFormatOptions + */ +enum PrettyFormatOptions { + kFormatDefault = 0, //!< Default pretty formatting. + kFormatSingleLineArray = 1 //!< Format arrays on a single line. +}; + //! Writer with indentation and spacing. /*! \tparam OutputStream Type of ouptut os. @@ -43,7 +51,7 @@ class PrettyWriter : public Writer()->inArray); bool empty = Base::level_stack_.template Pop(1)->valueCount == 0; - if (!empty) { + if (!empty && !(formatOptions_ & kFormatSingleLineArray)) { Base::os_->Put('\n'); WriteIndent(); } @@ -173,11 +189,14 @@ class PrettyWriter : public WriterinArray) { if (level->valueCount > 0) { Base::os_->Put(','); // add comma if it is not the first element in array - Base::os_->Put('\n'); + if (formatOptions_ & kFormatSingleLineArray) + Base::os_->Put(' '); } - else + + if (!(formatOptions_ & kFormatSingleLineArray)) { Base::os_->Put('\n'); - WriteIndent(); + WriteIndent(); + } } else { // in object if (level->valueCount > 0) { @@ -213,6 +232,7 @@ class PrettyWriter : public Writer writer(buffer); @@ -48,6 +61,16 @@ TEST(PrettyWriter, Basic) { EXPECT_STREQ(kPrettyJson, buffer.GetString()); } +TEST(PrettyWriter, FormatOptions) { + StringBuffer buffer; + PrettyWriter writer(buffer); + writer.SetFormatOptions(kFormatSingleLineArray); + Reader reader; + StringStream s(kJson); + reader.Parse(s, writer); + EXPECT_STREQ(kPrettyJson_FormatOptions_SLA, buffer.GetString()); +} + TEST(PrettyWriter, SetIndent) { StringBuffer buffer; PrettyWriter writer(buffer);