fixed offset calculation in WriteString

This commit is contained in:
milarin 2023-07-10 20:25:19 +02:00
parent 68591a3821
commit 5189fad815
3 changed files with 17 additions and 5 deletions

4
go.mod
View File

@ -1,3 +1,7 @@
module git.milar.in/milarin/buf2d module git.milar.in/milarin/buf2d
go 1.18 go 1.18
require github.com/mattn/go-runewidth v0.0.14
require github.com/rivo/uniseg v0.2.0 // indirect

4
go.sum
View File

@ -0,0 +1,4 @@
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=

View File

@ -2,19 +2,23 @@ package buf2d
import ( import (
"strings" "strings"
"github.com/mattn/go-runewidth"
) )
// WriteString writes a whole string to the buffer at position (x,y) // WriteString writes a whole string to the buffer at position (x,y).
// no word wrap is applied at all. If the string does not fit, it will be truncated // no word wrap is applied at all. If the string does not fit, it will be truncated.
func WriteString(b *Buffer[rune], str string, x, y int) { // It returns the amount of runes in str
func WriteString(b *Buffer[rune], str string, x, y int) (width int) {
dx := x dx := x
for _, r := range str { for _, r := range str {
if dx >= b.width { if dx >= b.Width() {
return return
} }
b.Set(dx, y, r) b.Set(dx, y, r)
dx++ dx += runewidth.RuneWidth(r)
} }
return dx - x
} }
// WriteMultiLineString writes a multi-line string to the buffer at position (x,y) // WriteMultiLineString writes a multi-line string to the buffer at position (x,y)