Inseob Kim | 5f8f32c | 2018-08-24 11:10:44 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 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 "CodeWriter.h" |
| 18 | |
| 19 | #ifdef LOG_TAG |
| 20 | #undef LOG_TAG |
| 21 | #endif |
| 22 | #define LOG_TAG "sysprop_gen" |
| 23 | |
| 24 | #include <cstdarg> |
| 25 | #include <cstdio> |
| 26 | #include <vector> |
| 27 | |
| 28 | #include <android-base/logging.h> |
| 29 | |
| 30 | CodeWriter::CodeWriter(std::string indent) : indent_(std::move(indent)) { |
| 31 | } |
| 32 | |
| 33 | void CodeWriter::Write(const char* format, ...) { |
| 34 | va_list ap, apc; |
| 35 | va_start(ap, format); |
| 36 | va_copy(apc, ap); |
| 37 | |
| 38 | int size = std::vsnprintf(nullptr, 0, format, ap); |
| 39 | va_end(ap); |
| 40 | |
| 41 | if (size < 0) { |
| 42 | va_end(apc); |
| 43 | PLOG(FATAL) << "vsnprintf failed"; |
| 44 | } |
| 45 | |
| 46 | std::vector<char> buf(size + 1); |
| 47 | if (std::vsnprintf(buf.data(), size + 1, format, apc) < 0) { |
| 48 | va_end(apc); |
| 49 | PLOG(FATAL) << "vsnprintf failed"; |
| 50 | } |
| 51 | va_end(apc); |
| 52 | |
| 53 | for (int i = 0; i < size; ++i) { |
| 54 | char ch = buf[i]; |
| 55 | if (ch == '\n') { |
| 56 | start_of_line_ = true; |
| 57 | } else { |
| 58 | if (start_of_line_) { |
| 59 | for (int j = 0; j < indent_level_; ++j) { |
| 60 | code_ += indent_; |
| 61 | } |
| 62 | start_of_line_ = false; |
| 63 | } |
| 64 | } |
| 65 | code_.push_back(ch); |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | void CodeWriter::Indent() { |
| 70 | ++indent_level_; |
| 71 | } |
| 72 | |
| 73 | void CodeWriter::Dedent() { |
| 74 | if (indent_level_ == 0) { |
| 75 | LOG(FATAL) << "Dedent failed: indent level is already 0"; |
| 76 | } |
| 77 | --indent_level_; |
| 78 | } |