upd: [imp] optimizes two formatting operations for short strings for fmt

This commit is contained in:
mutouyun 2022-12-03 16:53:02 +08:00
parent a2dfde6a63
commit f2e981c538
3 changed files with 7 additions and 5 deletions

View File

@ -67,8 +67,6 @@ LIBIMP_NODISCARD std::string fmt(A1 &&a1, A &&...args) {
/// @brief Return the string directly.
inline char const *to_string(char const *a) noexcept { return (a == nullptr) ? "" : a; }
template <std::size_t N>
inline char const *to_string(char const (&a)[N]) noexcept { return a; }
inline std::string to_string(std::string const &a) noexcept { return a; }
inline std::string to_string(std::string &&a) noexcept { return std::move(a); }
LIBIMP_EXPORT std::string to_string(char const *a, span<char const> fstr) noexcept;

View File

@ -74,8 +74,12 @@ std::string fmt_of_float(span<char const> fstr, span<char const> l) {
template <typename A /*a fundamental or pointer type*/>
std::string sprintf(std::string const &sfmt, A a) {
auto sz = std::snprintf(nullptr, 0, sfmt.c_str(), a);
char sbuf[2048];
auto sz = std::snprintf(sbuf, sizeof(sbuf), sfmt.c_str(), a);
if (sz <= 0) return {};
if (sz < sizeof(sbuf)) {
return sbuf;
}
std::string des;
des.resize(sz + 1);
if (std::snprintf(&des[0], des.size(), sfmt.c_str(), a) < 0) {

View File

@ -14,8 +14,8 @@ TEST(fmt, operator) {
TEST(fmt, to_string) {
/// @brief string
EXPECT_EQ(imp::to_string(""), "");
EXPECT_EQ(imp::to_string("%what%"), "%what%");
EXPECT_STREQ(imp::to_string(""), "");
EXPECT_STREQ(imp::to_string("%what%"), "%what%");
EXPECT_EQ(imp::to_string("%what%", "10") , " %what%");
EXPECT_EQ(imp::to_string("%what%", "-10"), "%what% ");