1 /*
2 * Copyright (C) 2017 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 "text/Printer.h"
18
19 #include <algorithm>
20
21 #include "io/Util.h"
22
23 using ::android::OutputStream;
24 using ::android::StringPiece;
25
26 namespace aapt {
27 namespace text {
28
Println(StringPiece str)29 Printer& Printer::Println(StringPiece str) {
30 Print(str);
31 return Print("\n");
32 }
33
Println()34 Printer& Printer::Println() {
35 return Print("\n");
36 }
37
Print(StringPiece str)38 Printer& Printer::Print(StringPiece str) {
39 if (error_) {
40 return *this;
41 }
42
43 auto remaining_str_begin = str.begin();
44 const auto remaining_str_end = str.end();
45 while (remaining_str_end != remaining_str_begin) {
46 // Find the next new-line.
47 const auto new_line_iter = std::find(remaining_str_begin, remaining_str_end, '\n');
48
49 // We will copy the string up until the next new-line (or end of string).
50 const StringPiece str_to_copy(remaining_str_begin, new_line_iter - remaining_str_begin);
51 if (!str_to_copy.empty()) {
52 if (needs_indent_) {
53 for (int i = 0; i < indent_level_; i++) {
54 if (!io::Copy(out_, " ")) {
55 error_ = true;
56 return *this;
57 }
58 }
59 needs_indent_ = false;
60 }
61
62 if (!io::Copy(out_, str_to_copy)) {
63 error_ = true;
64 return *this;
65 }
66 }
67
68 // If we found a new-line.
69 if (new_line_iter != remaining_str_end) {
70 if (!io::Copy(out_, "\n")) {
71 error_ = true;
72 return *this;
73 }
74 needs_indent_ = true;
75 // Ok to increment iterator here because we know that the '\n' character is one byte.
76 remaining_str_begin = new_line_iter + 1;
77 } else {
78 remaining_str_begin = new_line_iter;
79 }
80 }
81 return *this;
82 }
83
Indent()84 void Printer::Indent() {
85 ++indent_level_;
86 }
87
Undent()88 void Printer::Undent() {
89 --indent_level_;
90 }
91
92 } // namespace text
93 } // namespace aapt
94