Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / common / TextTable.cc
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4  * Ceph - scalable distributed file system
5  *
6  * Copyright (C) 2012 Inktank Storage, Inc.
7  *
8  * This is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License version 2.1, as published by the Free Software
11  * Foundation.  See file COPYING.
12  *
13  */
14 #include "TextTable.h"
15
16 using namespace std;
17
18 void TextTable::define_column(const string &heading,
19                               enum TextTable::Align hd_align,
20                               enum TextTable::Align col_align)
21 {
22   TextTableColumn def(heading, heading.length(), hd_align, col_align);
23   col.push_back(def);
24 }
25
26 void TextTable::clear() {
27   currow = curcol = 0;
28   indent = 0;
29   row.clear();
30   // reset widths to heading widths
31   for (unsigned int i = 0; i < col.size(); i++)
32     col[i].width = col[i].heading.size();
33 }
34
35 /**
36  * Pad s with space to appropriate alignment
37  *
38  * @param s string to pad
39  * @param width width of field to contain padded string
40  * @param align desired alignment (LEFT, CENTER, RIGHT)
41  *
42  * @return padded string
43  */
44 static string
45 pad(string s, int width, TextTable::Align align)
46 {
47   int lpad, rpad;
48   lpad = rpad = 0;
49   switch (align) {
50     case TextTable::LEFT:
51       rpad = width - s.length();
52       break;
53     case TextTable::CENTER:
54       lpad = width / 2 - s.length() / 2;
55       rpad = width - lpad - s.length();
56       break;
57     case TextTable::RIGHT:
58       lpad = width - s.length();
59       break;
60   }
61
62   return string(lpad, ' ') + s + string(rpad, ' ');
63 }
64
65 std::ostream &operator<<(std::ostream &out, const TextTable &t)
66 {
67   for (unsigned int i = 0; i < t.col.size(); i++) {
68     TextTable::TextTableColumn col = t.col[i];
69     out << string(t.indent, ' ')
70         << pad(col.heading, col.width, col.hd_align)
71         << ' ';
72   }
73   out << endl;
74
75   for (unsigned int i = 0; i < t.row.size(); i++) {
76     for (unsigned int j = 0; j < t.row[i].size(); j++) {
77       TextTable::TextTableColumn col = t.col[j];
78       out << string(t.indent, ' ')
79           << pad(t.row[i][j], col.width, col.col_align)
80           << ' ';
81     }
82     out << endl;
83   }
84   return out;
85 }