blob: 092ddbae2dc6fa262424d3a62d9d7577643f8ae8 [file] [log] [blame]
Ken Chend27d6c92021-10-21 22:18:59 +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 "netdutils/DumpWriter.h"
18
19#include <unistd.h>
20#include <limits>
21
22#include <android-base/stringprintf.h>
23#include <utils/String8.h>
24
25using android::base::StringAppendV;
26
27namespace android {
28namespace netdutils {
29
30namespace {
31
32const char kIndentString[] = " ";
33const size_t kIndentStringLen = strlen(kIndentString);
34
35} // namespace
36
37DumpWriter::DumpWriter(int fd) : mIndentLevel(0), mFd(fd) {}
38
39void DumpWriter::incIndent() {
40 if (mIndentLevel < std::numeric_limits<decltype(mIndentLevel)>::max()) {
41 mIndentLevel++;
42 }
43}
44
45void DumpWriter::decIndent() {
46 if (mIndentLevel > std::numeric_limits<decltype(mIndentLevel)>::min()) {
47 mIndentLevel--;
48 }
49}
50
51void DumpWriter::println(const std::string& line) {
52 if (!line.empty()) {
53 for (int i = 0; i < mIndentLevel; i++) {
54 ::write(mFd, kIndentString, kIndentStringLen);
55 }
56 ::write(mFd, line.c_str(), line.size());
57 }
58 ::write(mFd, "\n", 1);
59}
60
61// NOLINTNEXTLINE(cert-dcl50-cpp): Grandfathered C-style variadic function.
62void DumpWriter::println(const char* fmt, ...) {
63 std::string line;
64 va_list ap;
65 va_start(ap, fmt);
66 StringAppendV(&line, fmt, ap);
67 va_end(ap);
68 println(line);
69}
70
71} // namespace netdutils
72} // namespace android