]> git.proxmox.com Git - ceph.git/blame - ceph/src/common/TextTable.cc
import ceph quincy 17.2.4
[ceph.git] / ceph / src / common / TextTable.cc
CommitLineData
7c673cae
FG
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
16using namespace std;
17
18void 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
26void TextTable::clear() {
11fdf7f2
TL
27 currow = 0;
28 curcol = 0;
7c673cae
FG
29 indent = 0;
30 row.clear();
31 // reset widths to heading widths
32 for (unsigned int i = 0; i < col.size(); i++)
33 col[i].width = col[i].heading.size();
34}
35
36/**
37 * Pad s with space to appropriate alignment
38 *
39 * @param s string to pad
40 * @param width width of field to contain padded string
41 * @param align desired alignment (LEFT, CENTER, RIGHT)
42 *
43 * @return padded string
44 */
45static string
46pad(string s, int width, TextTable::Align align)
47{
48 int lpad, rpad;
11fdf7f2
TL
49 lpad = 0;
50 rpad = 0;
7c673cae
FG
51 switch (align) {
52 case TextTable::LEFT:
53 rpad = width - s.length();
54 break;
55 case TextTable::CENTER:
56 lpad = width / 2 - s.length() / 2;
57 rpad = width - lpad - s.length();
58 break;
59 case TextTable::RIGHT:
60 lpad = width - s.length();
61 break;
62 }
63
64 return string(lpad, ' ') + s + string(rpad, ' ');
65}
66
67std::ostream &operator<<(std::ostream &out, const TextTable &t)
68{
69 for (unsigned int i = 0; i < t.col.size(); i++) {
70 TextTable::TextTableColumn col = t.col[i];
9f95a23c
TL
71 if (i) {
72 out << t.column_separation;
73 }
7c673cae 74 out << string(t.indent, ' ')
9f95a23c 75 << pad(col.heading, col.width, col.hd_align);
7c673cae
FG
76 }
77 out << endl;
78
79 for (unsigned int i = 0; i < t.row.size(); i++) {
80 for (unsigned int j = 0; j < t.row[i].size(); j++) {
81 TextTable::TextTableColumn col = t.col[j];
9f95a23c
TL
82 if (j) {
83 out << t.column_separation;
84 }
7c673cae 85 out << string(t.indent, ' ')
9f95a23c 86 << pad(t.row[i][j], col.width, col.col_align);
7c673cae
FG
87 }
88 out << endl;
89 }
90 return out;
91}