-
Notifications
You must be signed in to change notification settings - Fork 26
/
wordwrap.go
126 lines (106 loc) · 2.42 KB
/
wordwrap.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package strutil
import (
"strings"
"unicode"
)
var newLine = rune('\n')
// WordWrap wraps the given string str based on colLen as max line width.
// if breakLongWords is true, it breaks the words which are longer than colLen.
//
// Notes:
// - WordWrap doesn't trim the lines, except it trims the left side of the new line
// created by breaking a long line.
// - Tabs should be converted to space before using WordWrap.
func WordWrap(str string, colLen int, breakLongWords bool) string {
if colLen == 0 || str == "" || Len(str) < colLen {
return str
}
var buff strings.Builder
buff.Grow(len(str) + int(len(str)/colLen) + 10)
var line strBuffer
var word strBuffer
var runeWritten bool
var r rune
for _, r = range str {
runeWritten = false
if r == newLine {
line.AppendStrBuffer(word).WriteRune(newLine)
buff.Write(line.buf)
line.Reset()
word.Reset()
continue
}
if unicode.IsSpace(r) {
line.AppendStrBuffer(word)
word.Reset()
}
if line.length+word.length+1 > colLen {
if line.length > 0 {
runeWritten = true
word.WriteRune(r)
line.WriteRune(newLine)
buff.Write(line.buf)
line.Reset()
word.LeftTrim()
} else if breakLongWords {
line.AppendStrBuffer(word).WriteRune(newLine)
buff.Write(line.buf)
line.Reset()
word.Reset()
}
}
if !runeWritten {
word.WriteRune(r)
}
}
line.AppendStrBuffer(word)
buff.Write(line.buf)
res := buff.String()
if r != newLine && len(res) > 0 && res[len(res)-1:] == "\n" {
res = res[:len(res)-1]
}
return res
}
// strBuffer is a special string builder, which can track rune count, written
// mainly for WordWrap
type strBuffer struct {
//internal array to store string
buf []byte
//count of runes.
length int
}
func (b *strBuffer) WriteString(str string, length int) *strBuffer {
b.buf = append(b.buf, str...)
b.length += length
return b
}
func (b *strBuffer) WriteRune(r rune) *strBuffer {
b.buf = append(b.buf, string(r)...)
b.length++
return b
}
func (b *strBuffer) AppendStrBuffer(n strBuffer) *strBuffer {
b.buf = append(b.buf, n.buf...)
b.length += n.length
return b
}
func (b *strBuffer) Reset() *strBuffer {
b.buf = b.buf[:0]
b.length = 0
return b
}
func (b *strBuffer) LeftTrim() *strBuffer {
for i, c := range b.buf {
if c != ' ' {
b.buf = b.buf[i:]
b.length -= i
return b
}
}
b.buf = b.buf[:0]
b.length = 0
return b
}
func (b *strBuffer) String() string {
return string(b.buf)
}