Skip to content

Commit

Permalink
perf(ansi): width: loop through input to get the width
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Jul 9, 2024
1 parent 3099677 commit fe84162
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion ansi/width.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,31 @@ func StringWidth(s string) int {
if s == "" {
return 0
}
return uniseg.StringWidth(Strip(s))

var (
gstate = -1
pstate = parser.GroundState // initial state
cluster string
width int
)

for i := 0; i < len(s); i++ {
state, action := parser.Table.Transition(pstate, s[i])
switch action {
case parser.PrintAction:
if utf8ByteLen(s[i]) > 1 {
var w int
cluster, _, w, gstate = uniseg.FirstGraphemeClusterInString(s[i:], gstate)
width += w
i += len(cluster) - 1
pstate = parser.GroundState
continue
}
width++
}

pstate = state
}

return width
}

0 comments on commit fe84162

Please sign in to comment.