blob: 38b3585f81f55d17b1ba9fa28a6b82de2753bc31 [file] [log] [blame]
Adam Lesinski93190b72017-11-03 15:20:17 -07001/*
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
23using ::aapt::io::OutputStream;
24using ::android::StringPiece;
25
26namespace aapt {
27namespace text {
28
29void Printer::Println(const StringPiece& str) {
30 Print(str);
31 Print("\n");
32}
33
34void Printer::Println() {
35 Print("\n");
36}
37
38void Printer::Print(const StringPiece& str) {
39 if (error_) {
40 return;
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 = str.substr(remaining_str_begin, new_line_iter);
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;
57 }
58 }
59 needs_indent_ = false;
60 }
61
62 if (!io::Copy(out_, str_to_copy)) {
63 error_ = true;
64 return;
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;
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}
82
83void Printer::Indent() {
84 ++indent_level_;
85}
86
87void Printer::Undent() {
88 --indent_level_;
89}
90
91} // namespace text
92} // namespace aapt