DumpWriter.cpp 1.9 KB

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