TextTable.cpp revision 223388253658ff5b726690056d3f433db6a5f3e6
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
22namespace android {
23namespace lshal {
24
25void 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
34void 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} // namespace lshal
57} // namespace android
58