/
misc.cpp
39 lines (35 loc) · 967 Bytes
/
misc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <cstdarg>
#include <cstdio>
#include <string>
using namespace std;
#include "log.h"
#include "misc.h"
string str_vprintf(const char *format, va_list varg)
{
const int buf_len = 1024, max_buf_len = buf_len * 1024;
char buf[buf_len], *p = buf;
int iteration = 0, printed = false;
string formatted;
do {
int size = buf_len << iteration;
if (size > max_buf_len) {
log_error("Can't format string, the result is too long");
return format;
}
if (iteration > 0)
p = new char[size];
int res = vsnprintf(p, size, format, varg);
if (res < 0) {
log_error("Can't format string, vsnprintf() failed");
return format;
}
if (res < size) {
printed = true;
formatted = p;
}
if (iteration > 0)
delete[] p;
++iteration;
} while (not printed);
return formatted;
}