Skip to content

Commit 1d28aa5

Browse files
committed
ignore bom at the beginning of the UTF-8 text
add a testcase about bom.
1 parent 3beb37e commit 1d28aa5

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/lib_json/json_reader.cpp

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include <memory>
1919
#include <set>
2020
#include <sstream>
21+
#include <string.h>
2122
#include <utility>
2223

2324
#include <cstdio>
@@ -939,6 +940,7 @@ class OurReader {
939940

940941
bool readToken(Token& token);
941942
void skipSpaces();
943+
void skipBom(Location& beginPtr);
942944
bool match(const Char* pattern, int patternLength);
943945
bool readComment();
944946
bool readCStyleComment(bool* containsNewLineResult);
@@ -1009,7 +1011,8 @@ bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root,
10091011
if (!features_.allowComments_) {
10101012
collectComments = false;
10111013
}
1012-
1014+
// skip byte order mark if it exists at the beginning of the UTF-8 text.
1015+
skipBom(beginDoc);
10131016
begin_ = beginDoc;
10141017
end_ = endDoc;
10151018
collectComments_ = collectComments;
@@ -1268,6 +1271,12 @@ void OurReader::skipSpaces() {
12681271
}
12691272
}
12701273

1274+
void OurReader::skipBom(Location& beginPtr) {
1275+
if (strncmp(beginPtr, "\xEF\xBB\xBF", 3) == 0) {
1276+
beginPtr += 3;
1277+
}
1278+
}
1279+
12711280
bool OurReader::match(const Char* pattern, int patternLength) {
12721281
if (end_ - current_ < patternLength)
12731282
return false;

src/test_lib_json/main.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3578,6 +3578,20 @@ JSONTEST_FIXTURE_LOCAL(BuilderTest, settings) {
35783578
}
35793579
}
35803580

3581+
struct BomTest : JsonTest::TestCase {};
3582+
3583+
JSONTEST_FIXTURE_LOCAL(BomTest, withBom) {
3584+
const std::string with_bom = u8"\xEF\xBB\xBF{}";
3585+
Json::Value root;
3586+
JSONCPP_STRING errs;
3587+
std::istringstream iss(with_bom);
3588+
bool ok = parseFromStream(Json::CharReaderBuilder(), iss, &root, &errs);
3589+
JSONTEST_ASSERT(ok);
3590+
if (!ok) {
3591+
std::cout << "errs: " << errs << std::endl;
3592+
}
3593+
}
3594+
35813595
struct IteratorTest : JsonTest::TestCase {};
35823596

35833597
JSONTEST_FIXTURE_LOCAL(IteratorTest, convert) {

0 commit comments

Comments
 (0)