Skip to content

Commit 09439b7

Browse files
committed
Comment reading/write improvements
This patch fixes some aspects of reading and writing comments: - Multiple C++-style comments before a Json value had extra newlines appended to them. This patch removes the addition of those newlines. - Comments written before Json values in the StyledWriter were not indented to match the indentation level of the value. This patch adds indentation to comments. - Fixed inconsistency in newlines following C- and C++-style comments being saved as part of the comment. All newlines at the end of a comment are now removed. - Added an additional test of comments. https://sourceforge.net/p/jsoncpp/patches/25/
1 parent ea07973 commit 09439b7

File tree

4 files changed

+48
-1
lines changed

4 files changed

+48
-1
lines changed

src/lib_json/json_reader.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,17 @@ Reader::readValue()
191191

192192
if ( collectComments_ && !commentsBefore_.empty() )
193193
{
194+
// Remove newline characters at the end of the comments
195+
size_t lastNonNewline = commentsBefore_.find_last_not_of("\r\n");
196+
if (lastNonNewline != std::string::npos)
197+
{
198+
commentsBefore_.erase(lastNonNewline+1);
199+
}
200+
else
201+
{
202+
commentsBefore_.clear();
203+
}
204+
194205
currentValue().setComment( commentsBefore_, commentBefore );
195206
commentsBefore_ = "";
196207
}

src/lib_json/json_writer.cpp

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -483,7 +483,20 @@ StyledWriter::writeCommentBeforeValue( const Value &root )
483483
{
484484
if ( !root.hasComment( commentBefore ) )
485485
return;
486-
document_ += normalizeEOL( root.getComment( commentBefore ) );
486+
487+
document_ += "\n";
488+
writeIndent();
489+
std::string normalizedComment = normalizeEOL( root.getComment( commentBefore ) );
490+
std::string::const_iterator iter = normalizedComment.begin();
491+
while ( iter != normalizedComment.end() )
492+
{
493+
document_ += *iter;
494+
if ( *iter == '\n' && *(iter+1) == '/' )
495+
writeIndent();
496+
++iter;
497+
}
498+
499+
// Comments are stripped of newlines, so add one here
487500
document_ += "\n";
488501
}
489502

test/data/test_comment_02.expected

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
.={}
2+
.c-test={}
3+
.c-test.a=1
4+
.c-test.b=2
5+
.cpp-test={}
6+
.cpp-test.c=3
7+
.cpp-test.d=4

test/data/test_comment_02.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
/* C-style comment
3+
4+
C-style-2 comment */
5+
"c-test" : {
6+
"a" : 1,
7+
/* Internal comment c-style */
8+
"b" : 2
9+
},
10+
// C++-style comment
11+
"cpp-test" : {
12+
// Internal comment cpp-style
13+
"c" : 3,
14+
"d" : 4
15+
}
16+
}

0 commit comments

Comments
 (0)