/
output-correction.go
52 lines (44 loc) · 1.01 KB
/
output-correction.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
package naglib
import (
"fmt"
"strings"
)
const MAX_PLUGIN_OUTPUT_LENGTH = 4095
func DefaultOutputIfBlank(output string, status PluginStatus) string {
if len(output) > 4 || len(strings.TrimSpace(output)) > 0 {
return output
}
return fmt.Sprintf("%v\n", status)
}
func TruncateAndEnforceNewline(output string) string {
return TruncateUTF8StringAtByte(output, MAX_PLUGIN_OUTPUT_LENGTH) + "\n";
}
func TruncateUTF8StringAtByte(str string, at int) string {
if at >= len(str) {
return str
}
if at <= 0 {
return ""
}
maxidx := len(str) - 1
for idx := at - 1; idx >= 0; idx-- {
thisByte := str[idx]
if !inCodePoint(thisByte) {
return str[:idx+1] // up to thisByte inclusive
}
if idx < maxidx {
nextByte := str[idx+1]
if !inCodePoint(nextByte) || beginsCodePoint(nextByte) {
// thisByte is the last in a code point
return str[:idx+1]
}
}
}
return ""
}
func beginsCodePoint(c byte) bool {
return c&128 == 128 && c&64 == 64
}
func inCodePoint(c byte) bool {
return c&128 == 128
}