diff options
Diffstat (limited to 'pkg/utils')
-rw-r--r-- | pkg/utils/formatting.go | 19 | ||||
-rw-r--r-- | pkg/utils/formatting_test.go | 25 |
2 files changed, 41 insertions, 3 deletions
diff --git a/pkg/utils/formatting.go b/pkg/utils/formatting.go index a6bbc5670..b7817346a 100644 --- a/pkg/utils/formatting.go +++ b/pkg/utils/formatting.go @@ -3,6 +3,7 @@ package utils import ( "fmt" "strings" + "unicode" "github.com/mattn/go-runewidth" "github.com/samber/lo" @@ -21,10 +22,22 @@ type ColumnConfig struct { Alignment Alignment } +func StringWidth(s string) int { + // We are intentionally not using a range loop here, because that would + // convert the characters to runes, which is unnecessary work in this case. + for i := 0; i < len(s); i++ { + if s[i] > unicode.MaxASCII { + return runewidth.StringWidth(s) + } + } + + return len(s) +} + // WithPadding pads a string as much as you want func WithPadding(str string, padding int, alignment Alignment) string { uncoloredStr := Decolorise(str) - width := runewidth.StringWidth(uncoloredStr) + width := StringWidth(uncoloredStr) if padding < width { return str } @@ -144,7 +157,7 @@ func getPadWidths(stringArrays [][]string) []int { return MaxFn(stringArrays, func(stringArray []string) int { uncoloredStr := Decolorise(stringArray[i]) - return runewidth.StringWidth(uncoloredStr) + return StringWidth(uncoloredStr) }) }) } @@ -161,7 +174,7 @@ func MaxFn[T any](items []T, fn func(T) int) int { // TruncateWithEllipsis returns a string, truncated to a certain length, with an ellipsis func TruncateWithEllipsis(str string, limit int) string { - if runewidth.StringWidth(str) > limit && limit <= 2 { + if StringWidth(str) > limit && limit <= 2 { return strings.Repeat(".", limit) } return runewidth.Truncate(str, limit, "…") diff --git a/pkg/utils/formatting_test.go b/pkg/utils/formatting_test.go index 5b56a9b33..ac2adee5f 100644 --- a/pkg/utils/formatting_test.go +++ b/pkg/utils/formatting_test.go @@ -4,6 +4,7 @@ import ( "strings" "testing" + "github.com/mattn/go-runewidth" "github.com/stretchr/testify/assert" ) @@ -250,3 +251,27 @@ func TestRenderDisplayStrings(t *testing.T) { assert.EqualValues(t, test.expectedColumnPositions, columnPositions) } } + +func BenchmarkStringWidthAsciiOriginal(b *testing.B) { + for i := 0; i < b.N; i++ { + runewidth.StringWidth("some ASCII string") + } +} + +func BenchmarkStringWidthAsciiOptimized(b *testing.B) { + for i := 0; i < b.N; i++ { + StringWidth("some ASCII string") + } +} + +func BenchmarkStringWidthNonAsciiOriginal(b *testing.B) { + for i := 0; i < b.N; i++ { + runewidth.StringWidth("some non-ASCII string 🍉") + } +} + +func BenchmarkStringWidthNonAsciiOptimized(b *testing.B) { + for i := 0; i < b.N; i++ { + StringWidth("some non-ASCII string 🍉") + } +} |