Skip to content

Commit

Permalink
Get rid of unsafe and error-prone printf_format
Browse files Browse the repository at this point in the history
  • Loading branch information
asl committed Jun 6, 2024
1 parent 3973b3c commit 25ec93a
Show file tree
Hide file tree
Showing 5 changed files with 0 additions and 105 deletions.
28 changes: 0 additions & 28 deletions lib/stringify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,32 +128,4 @@ cstring toString(cstring value) {

cstring toString(std::string_view value) { return cstring(value); }

cstring printf_format(const char *fmt_str, ...) {
if (fmt_str == nullptr) throw std::runtime_error("Null format string");
va_list ap;
va_start(ap, fmt_str);
cstring formatted = vprintf_format(fmt_str, ap);
va_end(ap);
return formatted;
}

// printf into a string
cstring vprintf_format(const char *fmt_str, va_list ap) {
static char buf[128];
va_list ap_copy;
va_copy(ap_copy, ap);
if (fmt_str == nullptr) throw std::runtime_error("Null format string");

int size = vsnprintf(buf, sizeof(buf), fmt_str, ap);
if (size < 0) throw std::runtime_error("Error in vsnprintf");
if (static_cast<size_t>(size) >= sizeof(buf)) {
char *formatted = new char[size + 1];
vsnprintf(formatted, size + 1, fmt_str, ap_copy);
va_end(ap_copy);
return cstring::own(formatted, size);
}
va_end(ap_copy);
return cstring(buf);
}

} // namespace Util
4 changes: 0 additions & 4 deletions lib/stringify.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,6 @@ cstring toString(std::string_view value);
cstring toString(const big_int &value, unsigned width, bool sign, unsigned int base = 10);
cstring toString(const void *value);

// printf into a string
cstring printf_format(const char *fmt_str, ...);
// vprintf into a string
cstring vprintf_format(const char *fmt_str, va_list ap);
char DigitToChar(int digit);
} // namespace Util

Expand Down
1 change: 0 additions & 1 deletion test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ set (GTEST_UNITTEST_SOURCES
gtest/source_file_test.cpp
gtest/strength_reduction.cpp
gtest/transforms.cpp
gtest/stringify.cpp
gtest/rtti_test.cpp
gtest/nethash.cpp
gtest/visitor.cpp
Expand Down
3 changes: 0 additions & 3 deletions test/gtest/format_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,6 @@ TEST(Util, Format) {

message = context.errorReporter().format_message("%1% %2%", x, 5);
EXPECT_EQ("x 5\n", message);

message = Util::printf_format("Number=%d, String=%s", 5, "short");
EXPECT_EQ("Number=5, String=short", message);
}

} // namespace Util
69 changes: 0 additions & 69 deletions test/gtest/stringify.cpp

This file was deleted.

0 comments on commit 25ec93a

Please sign in to comment.