Skip to content

Commit 0954807

Browse files
committed
TestSanitizeString
1 parent 9e905ea commit 0954807

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed

strings.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@ import (
55
"unicode"
66
)
77

8-
// SanitizeString returns valid UTF-8 without any control code characters.
8+
// SanitizeString returns valid UTF-8 only with printable characters.
99
func SanitizeString(s string) string {
10-
return strings.Map(removeControlCodes, strings.ToValidUTF8(s, ""))
11-
}
12-
13-
func removeControlCodes(r rune) rune {
14-
if unicode.IsControl(r) {
15-
return -1
16-
}
17-
return r
10+
return strings.Map(
11+
func(r rune) rune {
12+
if r == '�' || !unicode.IsPrint(r) {
13+
return -1
14+
}
15+
return r
16+
},
17+
s,
18+
)
1819
}

strings_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package sqldb
2+
3+
import "testing"
4+
5+
func TestSanitizeString(t *testing.T) {
6+
tests := map[string]string{
7+
"": "",
8+
"Hello World!": "Hello World!",
9+
"\u0000,\u0009,\u007f": ",,",
10+
"\a,\b,\v": ",,",
11+
"\xc3\x22": "\"",
12+
"\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98": "= ⌘",
13+
string([]byte{71, 101, 115, 99, 104, 195, 164, 102, 116, 115, 118, 111, 114, 102, 195}): "Geschäftsvorf",
14+
}
15+
for str, want := range tests {
16+
t.Run(str, func(t *testing.T) {
17+
if got := SanitizeString(str); got != want {
18+
t.Errorf("SanitizeString(%q) = %q, want %q", str, got, want)
19+
}
20+
})
21+
}
22+
}

0 commit comments

Comments
 (0)