Skip to content

Commit

Permalink
Fix overflow, and use writeRepeat
Browse files Browse the repository at this point in the history
  • Loading branch information
zix99 committed Aug 17, 2022
1 parent d2336a9 commit 5666195
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
22 changes: 15 additions & 7 deletions pkg/multiterm/termrenderers/heatmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,26 +102,28 @@ func (s *Heatmap) WriteHeader(colNames ...string) (colCount int) {
colCount = mini(len(colNames), s.colCount)

var sb strings.Builder
sb.WriteString(strings.Repeat(" ", s.maxRowKeyWidth+1))
const headerDelim = ".."
writeRepeat(&sb, ' ', s.maxRowKeyWidth+1)
const delim = '.'
const delimCount = 2

for i := 0; i < colCount; {
if i != 0 {
sb.WriteString(headerDelim)
i += len(headerDelim)
count := mini(colCount-i, delimCount)
writeRepeat(&sb, delim, count)
i += count
if i >= colCount {
break
}
}

name := colNames[i]

if i != 0 && i+len(name)+len(headerDelim) >= colCount {
if i != 0 && i+len(name)+delimCount >= colCount {
// Too long, jump to last displayable key
name = colNames[colCount-1]
indent := colCount - i - len(name)
if indent > 0 { // Align last name with last col
sb.WriteString(strings.Repeat(headerDelim[0:1], indent))
writeRepeat(&sb, delim, indent)
i += indent
}
sb.WriteString(underlineHeaderChar(name, colCount-i-1))
Expand All @@ -147,7 +149,7 @@ func (s *Heatmap) WriteRow(idx int, row *aggregation.TableRow, cols []string) {

var sb strings.Builder
sb.WriteString(color.Wrap(color.Yellow, row.Name()))
sb.WriteString(strings.Repeat(" ", s.maxRowKeyWidth-len(row.Name())+1))
writeRepeat(&sb, ' ', s.maxRowKeyWidth-len(row.Name())+1)

for i := 0; i < len(cols); i++ {
val := row.Value(cols[i])
Expand All @@ -164,6 +166,12 @@ func mini(i, j int) int {
return j
}

func writeRepeat(sb *strings.Builder, r rune, count int) {
for i := 0; i < count; i++ {
sb.WriteRune(r)
}
}

func underlineHeaderChar(word string, letter int) string {
if !color.Enabled {
return word
Expand Down
5 changes: 4 additions & 1 deletion pkg/multiterm/termrenderers/heatmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,11 @@ func TestHeatmapHeader(t *testing.T) {
assert.Equal(t, " a..d..g..j (2 more)", vt.Get(1))

// short, by slightly more
hm.WriteHeader("abc", "d", "e", "f")
hm.WriteHeader("abc", "d", "e", "f", "g")
assert.Equal(t, " abc..", vt.Get(1))

hm.WriteHeader("abc", "d", "e", "f")
assert.Equal(t, " abc.", vt.Get(1))
}

func TestUnderlineHeaderChar(t *testing.T) {
Expand Down

0 comments on commit 5666195

Please sign in to comment.