• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
25 using android::base::StringAppendV;
26 
27 namespace android {
28 namespace netdutils {
29 
30 namespace {
31 
32 const char kIndentString[] = "  ";
33 const size_t kIndentStringLen = strlen(kIndentString);
34 
35 }  // namespace
36 
DumpWriter(int fd)37 DumpWriter::DumpWriter(int fd) : mIndentLevel(0), mFd(fd) {}
38 
incIndent()39 void DumpWriter::incIndent() {
40     if (mIndentLevel < std::numeric_limits<decltype(mIndentLevel)>::max()) {
41         mIndentLevel++;
42     }
43 }
44 
decIndent()45 void DumpWriter::decIndent() {
46     if (mIndentLevel > std::numeric_limits<decltype(mIndentLevel)>::min()) {
47         mIndentLevel--;
48     }
49 }
50 
println(const std::string & line)51 void 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.
println(const char * fmt,...)62 void 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
73