Skip to content

Commit

Permalink
fixup! src: add C++-style sprintf utility
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax committed Jan 21, 2020
1 parent 3d90553 commit 8824f8b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/debug_utils-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,18 @@ std::string ToString(const T& value) {
}

inline std::string SPrintFImpl(const char* format) {
return format;
const char* p = strchr(format, '%');
if (LIKELY(p == nullptr)) return format;
CHECK(p[1] == '%'); // Only '%%' allowed when there are no arguments.

return std::string(format, p + 1) + SPrintFImpl(p + 2);
}

template <typename Arg, typename... Args>
std::string COLD_NOINLINE SPrintFImpl( // NOLINT(runtime/string)
const char* format, Arg&& arg, Args&&... args) {
const char* p = strchr(format, '%');
if (p == nullptr) return format;
CHECK_NOT_NULL(p);
std::string ret(format, p);
// Ignore long / size_t modifiers
while (strchr("lz", *++p) != nullptr) {}
Expand Down
2 changes: 2 additions & 0 deletions test/cctest/test_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,8 @@ TEST(UtilTest, SPrintF) {
EXPECT_EQ(SPrintF("%s %s", foo, "bar"), "foo bar");
EXPECT_EQ(SPrintF("%s %s", foo, bar), "foo bar");

EXPECT_EQ(SPrintF("[%% %s %%]", foo), "[% foo %]");

struct HasToString {
std::string ToString() const {
return "meow";
Expand Down

0 comments on commit 8824f8b

Please sign in to comment.