blob: 8111b2786007ca8bf1a0f8ab9ce0b48a2e747586 [file] [log] [blame]
Joe Onorato1754d742016-11-21 17:51:35 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "printer.h"
18
19#include <unistd.h>
20#include <stdlib.h>
21#include <string.h>
Joe Onoratob69b95f2016-12-16 13:16:40 -080022#include <stdarg.h>
Joe Onorato1754d742016-11-21 17:51:35 -080023
24#define INITIAL_BUF_SIZE (16*1024)
25
26char const* SPACES = " ";
27const int SPACE_COUNT = strlen(SPACES);
28
29Out::Out(int fd)
30 :mOut(fd == STDOUT_FILENO ? stdout : fdopen(fd, "w")),
31 mBufSize(INITIAL_BUF_SIZE),
32 mBuf((char*)malloc(INITIAL_BUF_SIZE)),
33 mIndent(0),
34 mPendingIndent(false)
35{
36}
37
38Out::~Out()
39{
40 fclose(mOut);
41}
42
43int
44Out::reallocate(int size)
45{
46 if (size > mBufSize) {
47 char* p = (char*)malloc(size);
48 if (p != NULL) {
49 free(mBuf);
50 mBufSize = size;
51 mBuf = p;
52 return size;
53 }
54 }
55 return mBufSize;
56}
57
58void
59Out::printf(const char* format, ...)
60{
61 if (mPendingIndent) {
62 print_indent();
63 mPendingIndent = false;
64 }
65
66 int len;
67
68 va_list args;
69 va_start(args, format);
70
71 len = vsnprintf(mBuf, mBufSize, format, args);
72 bool truncated = (len >= mBufSize) && (reallocate(len) < len);
73
74 len = vsnprintf(mBuf, mBufSize, format, args);
75 va_end(args);
76
77 if (len > 0) {
78 if (mIndent == 0) {
79 fwrite(mBuf, len, 1, mOut);
80 } else {
81 char* last = mBuf;
82 char* p;
83 do {
84 p = strchr(last, '\n');
85 int size = p != NULL ? p - last + 1 : strlen(last);
86 fwrite(last, size, 1, mOut);
87 if (p != NULL) {
88 if (p[1] == '\0') {
89 mPendingIndent = true;
90 } else {
91 print_indent();
92 }
93 }
94 last = p+1;
95 } while (p != NULL);
96 }
97 }
98}
99
100void
101Out::indent()
102{
103 mPendingIndent = true;
104 mIndent += 2;
105}
106
107void
108Out::dedent()
109{
110 if (mIndent > 0) {
111 mIndent -= 2;
112 }
113}
114
115void
116Out::print_indent()
117{
118#if 0
119 fprintf(mOut, "[%d]", mIndent);
120#else
121 int indent = mIndent;
122 while (indent > SPACE_COUNT) {
123 fwrite(SPACES, SPACE_COUNT, 1, mOut);
124 indent -= SPACE_COUNT;
125 }
126 fwrite(SPACES + SPACE_COUNT - indent, indent, 1, mOut);
127#endif
128}