Skip to content

Commit

Permalink
perf(term): improve ansi.Strip by using a bytes.Buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Mar 13, 2024
1 parent 8565f07 commit 7fedce4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
10 changes: 1 addition & 9 deletions exp/term/ansi/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,15 +157,7 @@ func BenchmarkNext(bm *testing.B) {

bm.ResetTimer()

parser := Parser{
Print: func(r rune) {},
Execute: func(b byte) {},
CsiDispatch: func(marker byte, params [][]uint, inter byte, r byte, ignore bool) {},
OscDispatch: func(params [][]byte, bellTerminated bool) {},
EscDispatch: func(inter byte, r byte, ignore bool) {},
DcsDispatch: func(marker byte, params [][]uint, inter byte, r byte, data []byte, ignore bool) {},
SosPmApcDispatch: func(k byte, data []byte) {},
}
var parser Parser
parser.Parse(bts)
}

Expand Down
15 changes: 10 additions & 5 deletions exp/term/ansi/width.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package ansi

import (
"bytes"

. "github.com/charmbracelet/x/exp/term/ansi/parser"
"github.com/rivo/uniseg"
)

// Strip removes ANSI escape codes from a string.
func Strip(s string) string {
var (
b []byte // buffer for collecting printable characters
buf bytes.Buffer // buffer for collecting printable characters
ri int // rune index
rw int // rune width
pstate = GroundState // initial state
Expand All @@ -24,7 +26,7 @@ func Strip(s string) string {
// During this state, collect rw bytes to form a valid rune in the
// buffer. After getting all the rune bytes into the buffer,
// transition to GroundState and reset the counters.
b = append(b, s[i])
buf.WriteByte(s[i])
ri++
if ri < rw {
continue
Expand All @@ -36,12 +38,12 @@ func Strip(s string) string {
// This action happens when we transition to the Utf8State.
if w := utf8ByteLen(s[i]); w > 1 {
rw = w
b = append(b, s[i])
buf.WriteByte(s[i])
ri++
}
case action == PrintAction || action == ExecuteAction:
// collects printable ASCII and non-printable characters
b = append(b, s[i])
buf.WriteByte(s[i])
}

// Transition to the next state.
Expand All @@ -51,13 +53,16 @@ func Strip(s string) string {
}
}

return string(b)
return buf.String()
}

// StringWidth returns the width of a string in cells. This is the number of
// cells that the string will occupy when printed in a terminal. ANSI escape
// codes are ignored and wide characters (such as East Asians and emojis) are
// accounted for.
func StringWidth(s string) int {
if s == "" {
return 0
}
return uniseg.StringWidth(Strip(s))
}

0 comments on commit 7fedce4

Please sign in to comment.