Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/json_reporter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iomanip> // for setprecision
#include <iostream>
#include <limits>
Expand Down Expand Up @@ -60,9 +61,18 @@ std::string StrEscape(const std::string& s) {
case '"':
tmp += "\\\"";
break;
default:
tmp += c;
default: {
auto uc = static_cast<unsigned char>(c);
if (uc < 0x20) {
char buf[7];
std::snprintf(buf, sizeof(buf), "\\u%04x",
static_cast<unsigned int>(uc));
tmp += buf;
} else {
tmp += c;
}
break;
}
}
}
return tmp;
Expand Down
30 changes: 30 additions & 0 deletions test/reporter_list_gtest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,36 @@ TEST(ReporterListTest, CSVListsNameColumn) {
BENCHMARK_RESTORE_DEPRECATED_WARNING
}

const std::vector<BenchmarkInstance>& ListControlCharBenchmarks() {
static const std::vector<BenchmarkInstance>* const benchmarks = [] {
std::string name = "BM_ControlChar_";
name += '\x01';
name += "_";
name += '\x1f';
RegisterBenchmark(name, BM_ReporterListDummy);
auto* result = new std::vector<BenchmarkInstance>();
std::ostringstream err_stream;
FindBenchmarksInternal("^BM_ControlChar.*", result, &err_stream);
return result;
}();
return *benchmarks;
}

TEST(ReporterListTest, JSONEscapesC0ControlCharacters) {
JSONReporter reporter;
std::ostringstream out;
reporter.SetOutputStream(&out);
reporter.List(ListControlCharBenchmarks());
EXPECT_EQ(out.str(),
"{\n"
" \"benchmarks\": [\n"
" {\n"
" \"name\": \"BM_ControlChar_\\u0001_\\u001f\"\n"
" }\n"
" ]\n"
"}\n");
}

} // namespace
} // namespace internal
} // namespace benchmark
Loading