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.
18// Table does layout of text-based tables.
20// Many of its methods return the textTable so callers can easily
21// chain them to build up many cells at once.
38type CellOption func(c *textCell)
40func LeftMargin(x string) CellOption {
41 return func(c *textCell) {
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 }
55 alignLeft align = iota
60func (a align) lpad(s string, w int) string {
65 l := (w - utf8.RuneCountInString(s)) / 2
66 return fmt.Sprintf("%*s%s", l, "", s)
68 return fmt.Sprintf("%*s", w, s)
72// Row starts a new row in table t.
73func (t *Table) Row() *Table {
81// Col skips to column "col" in table t. Columns are numbered starting
83func (t *Table) Col(col int) *Table {
85 panic(fmt.Sprintf("cannot move from column %d to earlier column %d", t.curCol, col))
91// CurCol returns the current column index.
92func (t *Table) CurCol() int {
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 {
104 if t.curCol == 0 || len(value) == 0 {
105 // For the left-most column or empty cells, we default
106 // to no left margin.
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])
115 if t.curCol > t.cols {
122// SetShrink marks a column as a "shrink" column, which will have
124func (t *Table) SetShrink(col int, shrink bool) {
125 for len(t.shrink) < col+1 {
126 t.shrink = append(t.shrink, false)
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) {
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])
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
153 for _, cell := range t.cells {
154 w := utf8.RuneCountInString(cell.value) + lmargin[cell.col]
158 ws[cell.col] = max(ws[cell.col], w)
162 // This cell spans multiple columns. Is the total
163 // width of those columns already sufficient?
165 for col := cell.col; col < cell.col+cell.span; col++ {
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++ {
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.
188 spanCols = append(spanCols, col)
191 // Process the wider columns first.
192 sort.Slice(spanCols, func(i, j int) bool {
193 return ws[spanCols[i]] > ws[spanCols[j]]
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.
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)
218 for i, w := range ws {
224 const debugPrintColumns = false
225 if debugPrintColumns {
228 for col, off := range offs {
229 fmt.Fprintf(w, "%*s", off-pos, "")
231 for i := 0; i < lmargin[col]; i++ {
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
245 return t.cells[i].col < t.cells[j].col
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.
256 // Get to cell's row.
258 if _, err := fmt.Fprintf(w, "\n"); err != nil {
265 // Space to the cell's starting offset and print its
267 spaces := offs[cell.col] - off
268 if _, err := fmt.Fprintf(w, "%*s%*s", spaces, "", lmargin[cell.col], cell.leftMargin); err != nil {
271 off += spaces + lmargin[cell.col]
273 // Compute total cell width, excluding the margin we
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 {
282 off += utf8.RuneCountInString(s)
284 if len(t.cells) > 0 {
285 if _, err := fmt.Fprintf(w, "\n"); err != nil {