Skip to content

Commit 96f8196

Browse files
committed
minor refactor: improve utils string_format function for readability and performance
1 parent d06db29 commit 96f8196

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

include/Utils.hpp

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -273,18 +273,16 @@ inline std::vector<T> get_triangle_strip_outline_indices(const std::size_t num_v
273273
return out_indices;
274274
}
275275

276-
template<typename... Args>
277-
std::string string_format(const std::string& format, Args... args)
276+
template<class... Args>
277+
std::string string_format(std::string_view fmt, const Args&... args)
278278
{
279-
int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
280-
if (size_s <= 0)
281-
{
282-
throw std::runtime_error("Error during formatting.");
283-
}
284-
auto size = static_cast<size_t>(size_s);
285-
auto buf = std::make_unique<char[]>(size);
286-
std::snprintf(buf.get(), size, format.c_str(), args...);
287-
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
279+
const int n = std::snprintf(nullptr, 0, fmt.data(), args...);
280+
if (n < 0)
281+
throw std::runtime_error("formatting failed");
282+
std::string out;
283+
out.resize(static_cast<size_t>(n));
284+
std::snprintf(out.data(), out.size() + 1, fmt.data(), args...);
285+
return out;
288286
}
289287

290288
template<class T, typename F>

0 commit comments

Comments
 (0)