/
unexpectedunicodefinder.go
57 lines (50 loc) · 1.48 KB
/
unexpectedunicodefinder.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2022-present Datadog, Inc.
package setup
import (
"unicode"
"unicode/utf8"
)
// UnexpectedUnicodeCodepoint contains specifics about an occurrence of an unexpected unicode codepoint
type UnexpectedUnicodeCodepoint struct {
codepoint rune
reason string
position int
}
// FindUnexpectedUnicode reports any _unexpected_ unicode codepoints
// found in the given 'input' string
// Unexpected here generally means invisible whitespace and control chars
func FindUnexpectedUnicode(input string) []UnexpectedUnicodeCodepoint {
currentIndex := 0
str := input
results := make([]UnexpectedUnicodeCodepoint, 0)
for len(str) > 0 {
r, size := utf8.DecodeRuneInString(str)
reason := ""
switch {
case r == utf8.RuneError:
reason = "RuneError"
case r == ' ' || r == '\r' || r == '\n' || r == '\t':
// These are allowed whitespace
reason = ""
case unicode.IsSpace(r):
reason = "unsupported whitespace"
case unicode.Is(unicode.Bidi_Control, r):
reason = "Bidirectional control"
case unicode.Is(unicode.C, r):
reason = "Control/surrogate"
}
if reason != "" {
results = append(results, UnexpectedUnicodeCodepoint{
codepoint: r,
reason: reason,
position: currentIndex,
})
}
currentIndex += size
str = str[size:]
}
return results
}