Skip to content

Commit 8824f8b

Browse files
committed
fixup! src: add C++-style sprintf utility
1 parent 3d90553 commit 8824f8b

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/debug_utils-inl.h

+6-2
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,18 @@ std::string ToString(const T& value) {
3232
}
3333

3434
inline std::string SPrintFImpl(const char* format) {
35-
return format;
35+
const char* p = strchr(format, '%');
36+
if (LIKELY(p == nullptr)) return format;
37+
CHECK(p[1] == '%'); // Only '%%' allowed when there are no arguments.
38+
39+
return std::string(format, p + 1) + SPrintFImpl(p + 2);
3640
}
3741

3842
template <typename Arg, typename... Args>
3943
std::string COLD_NOINLINE SPrintFImpl( // NOLINT(runtime/string)
4044
const char* format, Arg&& arg, Args&&... args) {
4145
const char* p = strchr(format, '%');
42-
if (p == nullptr) return format;
46+
CHECK_NOT_NULL(p);
4347
std::string ret(format, p);
4448
// Ignore long / size_t modifiers
4549
while (strchr("lz", *++p) != nullptr) {}

test/cctest/test_util.cc

+2
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,8 @@ TEST(UtilTest, SPrintF) {
282282
EXPECT_EQ(SPrintF("%s %s", foo, "bar"), "foo bar");
283283
EXPECT_EQ(SPrintF("%s %s", foo, bar), "foo bar");
284284

285+
EXPECT_EQ(SPrintF("[%% %s %%]", foo), "[% foo %]");
286+
285287
struct HasToString {
286288
std::string ToString() const {
287289
return "meow";

0 commit comments

Comments
 (0)