-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchar_wrapper.go
64 lines (48 loc) · 1.21 KB
/
char_wrapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package wwrap
import (
"io"
"unicode/utf8"
"github.com/mattn/go-runewidth"
)
const (
ErrEndsWithInvalidUTF8 StringError = "byte slice ends with invalid UTF8"
)
type CharWrapper struct {
Width uint
buf []byte
currentColumn uint
}
func (cw *CharWrapper) Read(p []byte) (n int, err error) {
if len(cw.buf) == 0 {
return 0, io.EOF
}
if len(p) > len(cw.buf) {
p = p[:len(cw.buf)]
}
n = copy(p, cw.buf[:len(p)])
cw.buf = cw.buf[len(p):]
return n, nil
}
func (cw *CharWrapper) Write(p []byte) (n int, err error) {
str := string(p)
for i, r := range str {
if !utf8.ValidRune(r) {
p = p[:i]
err = ErrEndsWithInvalidUTF8
break
}
runeWidth := uint(runewidth.RuneWidth(r))
if cw.currentColumn + runeWidth > cw.Width {
if cw.currentColumn != 0 && r != '\n' {
cw.buf = append(cw.buf, '\n')
}
cw.currentColumn = runeWidth
} else if r == '\n'{
cw.currentColumn = 0
} else {
cw.currentColumn += runeWidth
}
cw.buf = append(cw.buf, p[i:i+utf8.RuneLen(r)]...)
}
return len(p), err
}