| 202 | } |
| 203 | |
| 204 | std::string sprintf(const char* fmt, ...) { |
| 205 | int size = 1024; |
| 206 | std::vector<char> buffer(size); |
| 207 | |
| 208 | va_list args; |
| 209 | va_start(args, fmt); |
| 210 | int n = vsnprintf(buffer.data(), size, fmt, args); |
| 211 | va_end(args); |
| 212 | |
| 213 | if (n < 0) { |
| 214 | // vsnprintf failed |
| 215 | return ""; |
| 216 | } else if (n < size) { |
| 217 | // formatted string successfully placed in buffer |
| 218 | return std::string(buffer.data(), n); |
| 219 | } else { |
| 220 | // buffer is not enough, need to reallocate |
| 221 | size = n + 1; |
| 222 | buffer.resize(size); |
| 223 | |
| 224 | va_start(args, fmt); |
| 225 | n = vsnprintf(buffer.data(), size, fmt, args); |
| 226 | va_end(args); |
| 227 | |
| 228 | if (n < 0 || n >= size) { |
| 229 | return ""; |
| 230 | } |
| 231 | |
| 232 | return std::string(buffer.data(), n); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | NS_DORA_END |
no test coverage detected