Adam Lesinski | 1e466385 | 2014-08-15 14:47:28 -0700 | [diff] [blame] | 1 | #ifndef __INDENT_PRINTER_H |
| 2 | #define __INDENT_PRINTER_H |
| 3 | |
| 4 | class IndentPrinter { |
| 5 | public: |
| 6 | IndentPrinter(FILE* stream, int indentSize=2) |
| 7 | : 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 | |
| 44 | private: |
| 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 | |