Add str_sprintf function that returns std::string (#2408)

This commit is contained in:
Oxan van Leeuwen 2021-09-27 23:24:55 +02:00 committed by GitHub
parent 6417d8132d
commit 5596751c2c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 0 deletions

View file

@ -351,6 +351,21 @@ bool str_startswith(const std::string &full, const std::string &start) { return
bool str_endswith(const std::string &full, const std::string &ending) {
return full.rfind(ending) == (full.size() - ending.size());
}
std::string str_sprintf(const char *fmt, ...) {
std::string str;
va_list args;
va_start(args, fmt);
size_t length = vsnprintf(nullptr, 0, fmt, args);
va_end(args);
str.resize(length);
va_start(args, fmt);
vsnprintf(&str[0], length + 1, fmt, args);
va_end(args);
return str;
}
uint16_t encode_uint16(uint8_t msb, uint8_t lsb) { return (uint16_t(msb) << 8) | uint16_t(lsb); }
std::array<uint8_t, 2> decode_uint16(uint16_t value) {

View file

@ -59,6 +59,9 @@ bool str_equals_case_insensitive(const std::string &a, const std::string &b);
bool str_startswith(const std::string &full, const std::string &start);
bool str_endswith(const std::string &full, const std::string &ending);
/// sprintf-like function returning std::string instead of writing to char array.
std::string __attribute__((format(printf, 1, 2))) str_sprintf(const char *fmt, ...);
class HighFrequencyLoopRequester {
public:
void start();