Skip to main content

internal/texttab/table.go

1// Note(alexwlchan, 2026-11-04): This file was retrieved from
2// https://cs.opensource.google/go/x/perf/+/be2c69fb:cmd/benchstat/internal/texttab/table.go
4// Copyright 2020 The Go Authors. All rights reserved.
5// Use of this source code is governed by a BSD-style
6// license that can be found in the LICENSE file.
8package texttab
10import (
11 "fmt"
12 "io"
13 "sort"
14 "strings"
15 "unicode/utf8"
18// Table does layout of text-based tables.
19//
20// Many of its methods return the textTable so callers can easily
21// chain them to build up many cells at once.
22type Table struct {
23 cells []textCell
24 cols int
26 shrink []bool
28 curRow, curCol int
31type textCell struct {
32 row, col, span int
33 value string
34 leftMargin string
35 alignment align
38type CellOption func(c *textCell)
40func LeftMargin(x string) CellOption {
41 return func(c *textCell) {
42 c.leftMargin = x
43 }
46var (
47 Left CellOption = func(c *textCell) { c.alignment = alignLeft }
48 Center = func(c *textCell) { c.alignment = alignCenter }
49 Right = func(c *textCell) { c.alignment = alignRight }
52type align int
54const (
55 alignLeft align = iota
56 alignCenter
57 alignRight
60func (a align) lpad(s string, w int) string {
61 switch a {
62 default:
63 return s
64 case alignCenter:
65 l := (w - utf8.RuneCountInString(s)) / 2
66 return fmt.Sprintf("%*s%s", l, "", s)
67 case alignRight:
68 return fmt.Sprintf("%*s", w, s)
69 }
72// Row starts a new row in table t.
73func (t *Table) Row() *Table {
74 if len(t.cells) > 0 {
75 t.curRow++
76 }
77 t.curCol = 0
78 return t
81// Col skips to column "col" in table t. Columns are numbered starting
82// at 0.
83func (t *Table) Col(col int) *Table {
84 if col < t.curCol {
85 panic(fmt.Sprintf("cannot move from column %d to earlier column %d", t.curCol, col))
86 }
87 t.curCol = col
88 return t
91// CurCol returns the current column index.
92func (t *Table) CurCol() int {
93 return t.curCol
96// Cell adds a single-column cell at the current row and column.
97func (t *Table) Cell(value string, opts ...CellOption) *Table {
98 return t.Span(1, value, opts...)
101// Span adds a multi-column cell at the current row and column.
102func (t *Table) Span(cols int, value string, opts ...CellOption) *Table {
103 lMargin := " "
104 if t.curCol == 0 || len(value) == 0 {
105 // For the left-most column or empty cells, we default
106 // to no left margin.
107 lMargin = ""
108 }
109 t.cells = append(t.cells, textCell{t.curRow, t.curCol, cols, value, lMargin, alignLeft})
110 for _, o := range opts {
111 o(&t.cells[len(t.cells)-1])
112 }
114 t.curCol += cols
115 if t.curCol > t.cols {
116 t.cols = t.curCol
117 }
119 return t
122// SetShrink marks a column as a "shrink" column, which will have
123// minimum width.
124func (t *Table) SetShrink(col int, shrink bool) {
125 for len(t.shrink) < col+1 {
126 t.shrink = append(t.shrink, false)
127 }
128 t.shrink[col] = shrink
131// Format lays out table t and writes it to w.
132func (t *Table) Format(w io.Writer) error {
133 shrink := func(col int) bool {
134 if col < len(t.shrink) {
135 return t.shrink[col]
136 }
137 return false
138 }
140 // Collect max length margin for each column.
141 lmargin := make([]int, t.cols)
142 for _, cell := range t.cells {
143 lmargin[cell.col] = max(utf8.RuneCountInString(cell.leftMargin), lmargin[cell.col])
144 }
146 // Compute column widths, including their left margins.
147 ws := make([]int, t.cols)
148 // Consider cells in increasing span width.
149 sort.Slice(t.cells, func(i, j int) bool {
150 return t.cells[i].span < t.cells[j].span
151 })
152 var spanCols []int
153 for _, cell := range t.cells {
154 w := utf8.RuneCountInString(cell.value) + lmargin[cell.col]
156 if cell.span == 1 {
157 // Easy case.
158 ws[cell.col] = max(ws[cell.col], w)
159 continue
160 }
162 // This cell spans multiple columns. Is the total
163 // width of those columns already sufficient?
164 tw := 0
165 for col := cell.col; col < cell.col+cell.span; col++ {
166 tw += ws[col]
167 }
168 if tw >= w {
169 continue
170 }
172 // We need to expand columns. The goal is to expand
173 // them all to the necessary average, but some may
174 // already be wider than this average. Hence, we
175 // process columns from widest to narrowest,
176 // subtracting out the columns that are already wider
177 // than the target average (which in turn changes the
178 // target), and then distributing the remaining space
179 // among the narrower ones.
180 spanCols = spanCols[:0]
181 for col := cell.col; col < cell.col+cell.span; col++ {
182 if shrink(col) {
183 // We can't grow a shrink column, so
184 // account for its space, but don't
185 // add it to the columns to adjust.
186 w -= ws[col]
187 } else {
188 spanCols = append(spanCols, col)
189 }
190 }
191 // Process the wider columns first.
192 sort.Slice(spanCols, func(i, j int) bool {
193 return ws[spanCols[i]] > ws[spanCols[j]]
194 })
195 span := len(spanCols)
196 for _, col := range spanCols {
197 // What's the target average width at this
198 // point? Round up with span.
199 avg := (w + span - 1) / span
200 // Expand column if it isn't wide enough.
201 ws[col] = max(ws[col], avg)
202 // Subtract this column from the space needed.
203 // If the column was already wide enough, this
204 // will redistribute its excess across the
205 // smaller columns. We also do this if we
206 // expanded the column as a convenient way to
207 // spread out the integer rounding of avg.
208 w -= ws[col]
209 span--
210 }
211 }
213 // Convert column widths into starting offsets. The offset of
214 // column i is where i's left margin begins. The slice
215 // includes a final offset for the width of the table.
216 offs := make([]int, t.cols+1)
217 off := 0
218 for i, w := range ws {
219 offs[i] = off
220 off += w
221 }
222 offs[len(ws)] = off
224 const debugPrintColumns = false
225 if debugPrintColumns {
226 fmt.Println(ws)
227 pos := 0
228 for col, off := range offs {
229 fmt.Fprintf(w, "%*s", off-pos, "")
230 pos = off
231 for i := 0; i < lmargin[col]; i++ {
232 fmt.Fprintf(w, "|")
233 pos++
234 }
235 }
236 fmt.Fprint(w, "\n")
237 }
239 // Format the table. Put the cells back into top-to-bottom
240 // left-to-right order.
241 sort.Slice(t.cells, func(i, j int) bool {
242 if t.cells[i].row != t.cells[j].row {
243 return t.cells[i].row < t.cells[j].row
244 }
245 return t.cells[i].col < t.cells[j].col
246 })
247 row, off := 0, 0
248 for _, cell := range t.cells {
249 if strings.TrimSpace(cell.value) == "" && strings.TrimSpace(cell.leftMargin) == "" {
250 // Skip empty cells. This avoids printing
251 // unnecessary trailing spaces if cells appear
252 // at the end of a row.
253 continue
254 }
256 // Get to cell's row.
257 for cell.row > row {
258 if _, err := fmt.Fprintf(w, "\n"); err != nil {
259 return err
260 }
261 row++
262 off = 0
263 }
265 // Space to the cell's starting offset and print its
266 // left margin.
267 spaces := offs[cell.col] - off
268 if _, err := fmt.Fprintf(w, "%*s%*s", spaces, "", lmargin[cell.col], cell.leftMargin); err != nil {
269 return err
270 }
271 off += spaces + lmargin[cell.col]
273 // Compute total cell width, excluding the margin we
274 // just printed.
275 tw := offs[cell.col+cell.span] - offs[cell.col] - lmargin[cell.col]
277 // Print cell contents.
278 s := cell.alignment.lpad(cell.value, tw)
279 if _, err := fmt.Fprintf(w, "%s", s); err != nil {
280 return err
281 }
282 off += utf8.RuneCountInString(s)
283 }
284 if len(t.cells) > 0 {
285 if _, err := fmt.Fprintf(w, "\n"); err != nil {
286 return err
287 }
288 }
290 return nil