Skip to content

Commit 795ca77

Browse files
committed
Ignore bom at the beginning of the UTF-8 text
Add a testcase about bom.
1 parent 3beb37e commit 795ca77

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/lib_json/json_reader.cpp

Lines changed: 11 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();
942944
bool match(const Char* pattern, int patternLength);
943945
bool readComment();
944946
bool readCStyleComment(bool* containsNewLineResult);
@@ -1009,7 +1011,6 @@ bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root,
10091011
if (!features_.allowComments_) {
10101012
collectComments = false;
10111013
}
1012-
10131014
begin_ = beginDoc;
10141015
end_ = endDoc;
10151016
collectComments_ = collectComments;
@@ -1022,6 +1023,8 @@ bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root,
10221023
nodes_.pop();
10231024
nodes_.push(&root);
10241025

1026+
// skip byte order mark if it exists at the beginning of the UTF-8 text.
1027+
skipBom();
10251028
bool successful = readValue();
10261029
nodes_.pop();
10271030
Token token;
@@ -1268,6 +1271,13 @@ void OurReader::skipSpaces() {
12681271
}
12691272
}
12701273

1274+
void OurReader::skipBom() {
1275+
if (strncmp(begin_, "\xEF\xBB\xBF", 3) == 0) {
1276+
begin_ += 3;
1277+
current_ = begin_;
1278+
}
1279+
}
1280+
12711281
bool OurReader::match(const Char* pattern, int patternLength) {
12721282
if (end_ - current_ < patternLength)
12731283
return false;

src/test_lib_json/main.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3578,6 +3578,19 @@ 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{\"key\" : \"value\"}";
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+
JSONTEST_ASSERT(errs.empty());
3591+
JSONTEST_ASSERT_STRING_EQUAL(root["key"].asString(), "value");
3592+
}
3593+
35813594
struct IteratorTest : JsonTest::TestCase {};
35823595

35833596
JSONTEST_FIXTURE_LOCAL(IteratorTest, convert) {

0 commit comments

Comments
 (0)