TextTable.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. #ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_
  17. #define FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_
  18. #include <iostream>
  19. #include <string>
  20. #include <vector>
  21. namespace android {
  22. namespace lshal {
  23. // An element in TextTable. This is either an actual row (an array of cells
  24. // in this row), or a string of explanatory text.
  25. // To see if this is an actual row, test fields().empty().
  26. class TextTableRow {
  27. public:
  28. // An empty line.
  29. TextTableRow() {}
  30. // A row of cells.
  31. explicit TextTableRow(std::vector<std::string>&& v) : mFields(std::move(v)) {}
  32. // A single comment string.
  33. explicit TextTableRow(std::string&& s) : mLine(std::move(s)) {}
  34. explicit TextTableRow(const std::string& s) : mLine(s) {}
  35. // Whether this row is an actual row of cells.
  36. bool isRow() const { return !fields().empty(); }
  37. // Get all cells.
  38. const std::vector<std::string>& fields() const { return mFields; }
  39. // Get the single comment string.
  40. const std::string& line() const { return mLine; }
  41. private:
  42. std::vector<std::string> mFields;
  43. std::string mLine;
  44. };
  45. // A TextTable is a 2D array of strings.
  46. class TextTable {
  47. public:
  48. // Add a TextTableRow.
  49. void add() { mTable.emplace_back(); }
  50. void add(std::vector<std::string>&& v) {
  51. computeWidth(v);
  52. mTable.emplace_back(std::move(v));
  53. }
  54. void add(const std::string& s) { mTable.emplace_back(s); }
  55. void add(std::string&& s) { mTable.emplace_back(std::move(s)); }
  56. void addAll(TextTable&& other);
  57. // Prints the table to out, with column widths adjusted appropriately according
  58. // to the content.
  59. void dump(std::ostream& out) const;
  60. private:
  61. void computeWidth(const std::vector<std::string>& v);
  62. std::vector<size_t> mWidths;
  63. std::vector<TextTableRow> mTable;
  64. };
  65. } // namespace lshal
  66. } // namespace android
  67. #endif // FRAMEWORK_NATIVE_CMDS_LSHAL_TEXT_TABLE_H_