Skip to content

Commit

Permalink
Merge pull request open-source-parsers#137 from cdunn2001/avoid-extra…
Browse files Browse the repository at this point in the history
…-newline

Avoid extra newline
  • Loading branch information
cdunn2001 committed Jan 23, 2015
2 parents f8ca6cb + d383056 commit 9fbd12b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 15 deletions.
3 changes: 2 additions & 1 deletion include/json/writer.h
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,8 @@ class JSON_API StyledStreamWriter {
std::string indentString_;
int rightMargin_;
std::string indentation_;
bool addChildValues_;
bool addChildValues_ : 1;
bool indented_ : 1;
};

#if defined(JSON_HAS_INT64)
Expand Down
25 changes: 11 additions & 14 deletions src/lib_json/json_writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,7 @@ void StyledStreamWriter::write(std::ostream& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_ = "";
indented_ = false;
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
Expand Down Expand Up @@ -539,8 +540,10 @@ void StyledStreamWriter::writeArrayValue(const Value& value) {
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
writeIndent();
if (!indented_) writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
Expand Down Expand Up @@ -598,24 +601,17 @@ void StyledStreamWriter::pushValue(const std::string& value) {
}

void StyledStreamWriter::writeIndent() {
/*
Some comments in this method would have been nice. ;-)
if ( !document_.empty() )
{
char last = document_[document_.length()-1];
if ( last == ' ' ) // already indented
return;
if ( last != '\n' ) // Comments may add new-line
*document_ << '\n';
}
*/
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
*document_ << '\n' << indentString_;
}

void StyledStreamWriter::writeWithIndent(const std::string& value) {
writeIndent();
if (!indented_) writeIndent();
*document_ << value;
indented_ = false;
}

void StyledStreamWriter::indent() { indentString_ += indentation_; }
Expand Down Expand Up @@ -643,6 +639,7 @@ void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {

// Comments are stripped of trailing newlines, so add one here
*document_ << "\n";
indented_ = false;
}

void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
Expand Down

0 comments on commit 9fbd12b

Please sign in to comment.