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 #ifndef NETDUTILS_DUMPWRITER_H_ 18 #define NETDUTILS_DUMPWRITER_H_ 19 20 #include <string> 21 22 namespace android { 23 namespace netdutils { 24 25 class DumpWriter { 26 public: 27 DumpWriter(int fd); 28 29 void incIndent(); 30 void decIndent(); 31 32 void println(const std::string& line); 33 template <size_t n> println(const char line[n])34 void println(const char line[n]) { 35 println(std::string(line)); 36 } 37 // Hint to the compiler that it should apply printf validation of 38 // arguments (beginning at position 3) of the format (specified in 39 // position 2). Note that position 1 is the implicit "this" argument. 40 void println(const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))); blankline()41 void blankline() { println(""); } 42 43 private: 44 uint8_t mIndentLevel; 45 int mFd; 46 }; 47 48 class ScopedIndent { 49 public: 50 ScopedIndent() = delete; 51 ScopedIndent(const ScopedIndent&) = delete; 52 ScopedIndent(ScopedIndent&&) = delete; ScopedIndent(DumpWriter & dw)53 explicit ScopedIndent(DumpWriter& dw) : mDw(dw) { mDw.incIndent(); } ~ScopedIndent()54 ~ScopedIndent() { mDw.decIndent(); } 55 ScopedIndent& operator=(const ScopedIndent&) = delete; 56 ScopedIndent& operator=(ScopedIndent&&) = delete; 57 58 // TODO: consider additional {inc,dec}Indent methods and a counter that 59 // can be used to unwind all pending increments on exit. 60 61 private: 62 DumpWriter& mDw; 63 }; 64 65 } // namespace netdutils 66 } // namespace android 67 68 #endif // NETDUTILS_DUMPWRITER_H_ 69