-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrings.go
66 lines (52 loc) · 1.51 KB
/
strings.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
package main
import "strings"
// Split splits the passed text into chunks and concatenates them back to
// a list of strings where the length of each string in that list does
// not exceed maxNumChars
func Split(text, delimiter string, maxNumChars int) []string {
// no split needed
if len(text) <= maxNumChars {
return []string{text}
}
// max number of strings needed
result := make([]string, 0, (len(text)/maxNumChars)+1)
// reserve enough space
var sb strings.Builder
sb.Grow(int(float64(1.5) * float64(maxNumChars)))
// split text into e.g. lines
tokens := strings.Split(text, delimiter)
expectedGrowth := 0
tokenSuffix := ""
for idx, token := range tokens {
if idx < len(tokens)-1 {
// append delimiter
expectedGrowth = len(token) + len(delimiter)
tokenSuffix = delimiter
} else {
// no delimiter appended
expectedGrowth = len(token)
tokenSuffix = ""
}
// string can fit token and delimiter
if expectedGrowth > maxNumChars {
// edge case where the text between delimiters surpasses
// size requirements, force write
sb.WriteString(token)
sb.WriteString(tokenSuffix)
} else if sb.Len()+expectedGrowth <= maxNumChars {
sb.WriteString(token)
sb.WriteString(tokenSuffix)
} else {
// string length would exceed maxNumChars
result = append(result, sb.String())
sb.Reset()
// write the next token & delimiter pair
sb.WriteString(token)
sb.WriteString(tokenSuffix)
}
}
if sb.Len() > 0 {
result = append(result, sb.String())
}
return result
}