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