Replace std::snprintf() with wpi::format_to_n_c_str() (#5645)

fmtlib uses consteval format string processing, which makes it more
efficient than std::snprintf().

snprintf()s in libuv, mpack, processstarter, and wpigui were left alone.
processstarter uses stdlib only, and wpigui only depends on imgui.

fmt::format_to_n() is analogous to std::format_to_n()
(https://en.cppreference.com/w/cpp/utility/format/format_to_n)

wpi::format_to_n_c_str() is a wrapper which adds the trailing NUL.
This commit is contained in:
Tyler Veness
2023-09-17 20:00:16 -07:00
committed by GitHub
parent bb39900353
commit 17f1062885
25 changed files with 190 additions and 112 deletions

View File

@@ -17,6 +17,7 @@
#pragma once
#include <iterator>
#include <limits>
#include <optional>
#include <string>
@@ -24,6 +25,8 @@
#include <type_traits>
#include <utility>
#include <fmt/format.h>
namespace wpi {
template <typename T>
@@ -721,4 +724,23 @@ std::optional<long double> parse_float<long double>(
std::pair<std::string_view, std::string_view> UnescapeCString(
std::string_view str, SmallVectorImpl<char>& buf);
/**
* Like std::format_to_n() in that it writes at most n bytes to the output
* buffer, but also includes a terminating null byte in n.
*
* This is essentially a more performant replacement for std::snprintf().
*
* @param out The output buffer.
* @param n The size of the output buffer.
* @param fmt The format string.
* @param args The format string arguments.
*/
template <class OutputIt, class... Args>
inline void format_to_n_c_str(OutputIt out, std::iter_difference_t<OutputIt> n,
fmt::format_string<Args...> fmt, Args&&... args) {
const auto result =
fmt::format_to_n(out, n - 1, fmt, std::forward<Args>(args)...);
*result.out = '\0';
}
} // namespace wpi