TextTable.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (C) 2017 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 <algorithm>
  17. #include <iomanip>
  18. #include "TextTable.h"
  19. namespace android {
  20. namespace lshal {
  21. void TextTable::computeWidth(const std::vector<std::string>& v) {
  22. if (mWidths.size() < v.size()) {
  23. mWidths.resize(v.size());
  24. }
  25. for (size_t i = 0; i < v.size(); ++i) {
  26. mWidths[i] = std::max(mWidths[i], v[i].length());
  27. }
  28. }
  29. void TextTable::dump(std::ostream& out) const {
  30. out << std::left;
  31. for (const auto& row : mTable) {
  32. if (!row.isRow()) {
  33. out << row.line() << std::endl;
  34. continue;
  35. }
  36. for (size_t i = 0; i < row.fields().size(); ++i) {
  37. if (i != 0) {
  38. out << " ";
  39. }
  40. // last column does not std::setw to avoid printing unnecessary spaces.
  41. if (i < row.fields().size() - 1) {
  42. out << std::setw(mWidths[i]);
  43. }
  44. out << row.fields()[i];
  45. }
  46. out << std::endl;
  47. }
  48. }
  49. void TextTable::addAll(TextTable&& other) {
  50. for (auto&& row : other.mTable) {
  51. if (row.isRow()) {
  52. computeWidth(row.fields());
  53. }
  54. mTable.emplace_back(std::move(row));
  55. }
  56. }
  57. } // namespace lshal
  58. } // namespace android