core: use std::string to format battery extra data

Create a format_string_std function that works like format_string,
but does return a std::string instead of a strdup()ed C string.

Make it a global function to be used in other parts of the code.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2024-03-01 23:27:55 +01:00 committed by Michael Keller
parent e6321a1305
commit affcbddbb0
2 changed files with 24 additions and 30 deletions

View file

@ -60,5 +60,21 @@ extern double strtod_flags(const char *str, const char **ptr, unsigned int flags
#ifdef __cplusplus
}
#include <string>
template <class... Args>
std::string format_string_std(const char *fmt, Args&&... args)
{
size_t stringsize = snprintf(NULL, 0, fmt, std::forward<Args>(args)...);
if (stringsize == 0)
return std::string();
std::string res;
res.resize(stringsize); // Pointless clearing, oh my.
// This overwrites the terminal null-byte of std::string.
// That's probably "undefined behavior". Oh my.
snprintf(res.data(), stringsize + 1, fmt, std::forward<Args>(args)...);
return res;
}
#endif
#endif // SUBSURFACE_STRING_H