1 /*
2  * Copyright (C) 2012 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 #ifndef ART_RUNTIME_INDENTER_H_
18 #define ART_RUNTIME_INDENTER_H_
19 
20 #include "base/logging.h"
21 #include "base/macros.h"
22 #include <streambuf>
23 
24 const char kIndentChar =' ';
25 const size_t kIndentBy1Count = 2;
26 
27 class Indenter : public std::streambuf {
28  public:
Indenter(std::streambuf * out,char text,size_t count)29   Indenter(std::streambuf* out, char text, size_t count)
30       : indent_next_(true), out_sbuf_(out), text_(text), count_(count) {}
31 
32  private:
overflow(int_type c)33   int_type overflow(int_type c) {
34     if (UNLIKELY(c == std::char_traits<char>::eof())) {
35       out_sbuf_->pubsync();
36       return c;
37     }
38     if (indent_next_) {
39       for (size_t i = 0; i < count_; ++i) {
40         int_type r = out_sbuf_->sputc(text_);
41         if (UNLIKELY(r != text_)) {
42           out_sbuf_->pubsync();
43           r = out_sbuf_->sputc(text_);
44           CHECK_EQ(r, text_) << "Error writing to buffer. Disk full?";
45         }
46       }
47     }
48     indent_next_ = (c == '\n');
49     int_type r = out_sbuf_->sputc(c);
50     if (UNLIKELY(r != c)) {
51       out_sbuf_->pubsync();
52       r = out_sbuf_->sputc(c);
53       CHECK_EQ(r, c) << "Error writing to buffer. Disk full?";
54     }
55     return r;
56   }
57 
sync()58   int sync() {
59     return out_sbuf_->pubsync();
60   }
61 
62   bool indent_next_;
63 
64   // Buffer to write output to.
65   std::streambuf* const out_sbuf_;
66 
67   // Text output as indent.
68   const char text_;
69 
70   // Number of times text is output.
71   const size_t count_;
72 
73   DISALLOW_COPY_AND_ASSIGN(Indenter);
74 };
75 
76 #endif  // ART_RUNTIME_INDENTER_H_
77