From 8bb83867644fe17ef1a28d4a7eb32556d30bc371 Mon Sep 17 00:00:00 2001 From: Michael Hansen Date: Mon, 5 Jun 2023 13:49:04 -0700 Subject: [PATCH] Fix some issues with formatted_print: * Add a va_list version which can be correctly used by ivprintf (fixes pycdas output) * Use a `const char*` format parameter to avoid the need for clang warning workarounds * Make better use of return values. --- data.cpp | 35 +++++++++++++++++++++-------------- data.h | 3 ++- pyc_string.cpp | 1 - pycdas.cpp | 5 +++-- 4 files changed, 26 insertions(+), 18 deletions(-) diff --git a/data.cpp b/data.cpp index 011ef5d..2c0e2d3 100644 --- a/data.cpp +++ b/data.cpp @@ -1,6 +1,6 @@ #include "data.h" #include -#include +#include #include /* PycData */ @@ -83,20 +83,27 @@ int PycBuffer::getBuffer(int bytes, void* buffer) return bytes; } - - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wvarargs" -int formatted_print(std::ostream& stream, const std::string& format, ...) { +int formatted_print(std::ostream& stream, const char* format, ...) +{ va_list args; va_start(args, format); - size_t len = std::vsnprintf(NULL, 0, format.c_str(), args); + int result = formatted_printv(stream, format, args); va_end(args); - std::vector vec(len + 1); - va_start(args, format); - std::vsnprintf(&vec[0], len + 1, format.c_str(), args); - va_end(args); - stream << &vec[0]; - return 0; + return result; +} + +int formatted_printv(std::ostream& stream, const char* format, va_list args) +{ + va_list saved_args; + va_copy(saved_args, args); + int len = std::vsnprintf(nullptr, 0, format, args); + if (len < 0) + return len; + std::vector vec(static_cast(len) + 1); + int written = std::vsnprintf(&vec[0], vec.size(), format, saved_args); + va_end(saved_args); + + if (written >= 0) + stream << &vec[0]; + return written; } -#pragma clang diagnostic pop \ No newline at end of file diff --git a/data.h b/data.h index 3951c91..376d318 100644 --- a/data.h +++ b/data.h @@ -57,6 +57,7 @@ private: int m_size, m_pos; }; -int formatted_print(std::ostream& stream, const std::string& format, ...); +int formatted_print(std::ostream& stream, const char* format, ...); +int formatted_printv(std::ostream& stream, const char* format, va_list args); #endif diff --git a/pyc_string.cpp b/pyc_string.cpp index f22adf4..cf89856 100644 --- a/pyc_string.cpp +++ b/pyc_string.cpp @@ -2,7 +2,6 @@ #include "pyc_module.h" #include "data.h" #include -#include static bool check_ascii(const std::string& data) { diff --git a/pycdas.cpp b/pycdas.cpp index 1c2e0c5..cab16d7 100644 --- a/pycdas.cpp +++ b/pycdas.cpp @@ -58,11 +58,12 @@ static void iputs(std::ostream& pyc_output, int indent, const char* text) pyc_output << text; } -static void ivprintf(std::ostream& pyc_output, int indent, const char* fmt, va_list varargs) +static void ivprintf(std::ostream& pyc_output, int indent, const char* fmt, + va_list varargs) { for (int i=0; i