-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFormatter.h
58 lines (46 loc) · 1.09 KB
/
Formatter.h
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* SPDX-License-Identifier: GPL-2.0
*
* Copyright (c) 2018 Intel Corporation
*
* Authors: Fengguang Wu <fengguang.wu@intel.com>
*/
#ifndef AEP_FORMATTER_H
#define AEP_FORMATTER_H
// source: https://stackoverflow.com/questions/12247646/c-delay-printf-until-needed
#include <cstdarg>
#include <cstdio>
#include <string>
class Formatter
{
private:
std::string buf;
public:
void clear() { buf.clear(); }
bool empty() { return buf.empty(); }
void reserve(size_t capacity) { buf.reserve(capacity); }
std::string const & str() const { return buf; }
void print(char const * fmt, ...)
{
int ret1;
int ret2;
std::size_t cur;
std::va_list ap, aq;
va_start(ap, fmt);
va_copy(aq, ap);
ret1 = std::vsnprintf(NULL, 0, fmt, ap);
if (ret1 < 0)
goto out;
cur = buf.size();
buf.resize(cur + ret1 + 1);
ret2 = std::vsnprintf(&buf[cur], ret1 + 1, fmt, aq);
if (ret2 < 0)
goto out;
buf.resize(cur + ret1);
out:
va_end(aq);
va_end(ap);
}
};
#endif
// vim:set ts=2 sw=2 et: