blob: bd0edcbed8ada73933fb55cdd1e40d54fdb08291 [file] [log] [blame]
Adam Lesinski1e4663852014-08-15 14:47:28 -07001#ifndef __INDENT_PRINTER_H
2#define __INDENT_PRINTER_H
3
4class IndentPrinter {
5public:
Chih-Hung Hsieh9b8528f2016-08-10 14:15:30 -07006 explicit IndentPrinter(FILE* stream, int indentSize=2)
Adam Lesinski1e4663852014-08-15 14:47:28 -07007 : mStream(stream)
8 , mIndentSize(indentSize)
9 , mIndent(0)
10 , mNeedsIndent(true) {
11 }
12
13 void indent(int amount = 1) {
14 mIndent += amount;
15 if (mIndent < 0) {
16 mIndent = 0;
17 }
18 }
19
20 void print(const char* fmt, ...) {
21 doIndent();
22 va_list args;
23 va_start(args, fmt);
24 vfprintf(mStream, fmt, args);
25 va_end(args);
26 }
27
28 void println(const char* fmt, ...) {
29 doIndent();
30 va_list args;
31 va_start(args, fmt);
32 vfprintf(mStream, fmt, args);
33 va_end(args);
34 fputs("\n", mStream);
35 mNeedsIndent = true;
36 }
37
38 void println() {
39 doIndent();
40 fputs("\n", mStream);
41 mNeedsIndent = true;
42 }
43
44private:
45 void doIndent() {
46 if (mNeedsIndent) {
47 int numSpaces = mIndent * mIndentSize;
48 while (numSpaces > 0) {
49 fputs(" ", mStream);
50 numSpaces--;
51 }
52 mNeedsIndent = false;
53 }
54 }
55
56 FILE* mStream;
57 const int mIndentSize;
58 int mIndent;
59 bool mNeedsIndent;
60};
61
62#endif // __INDENT_PRINTER_H
63