Debian Codegraph @

internal/encoder/string_scan_arm64_test.go

raw
1 package encoder
2
3 import (
4 "strconv"
5 "strings"
6 "testing"
7 "unsafe"
8 )
9
10 func TestScanStringNEON(t *testing.T) {
11 special := []byte{0x00, 0x1f, '"', '\\', '<', '>', '&', 0x7f, 0x80, 0xe3, 0xff, '\n', ' ', '!', '#', '=', '?', '[', ']'}
12 for index := range stringEscapes {
13 e := &stringEscapes[index]
14 expected := func(s string) int {
15 for i := 0; i < len(s); i++ {
16 if e.table[s[i]] {
17 return 1
18 }
19 }
20 return 0
21 }
22 for length := 16; length <= 100; length++ {
23 base := strings.Repeat("a", length)
24 check := func(s string) {
25 t.Helper()
26 got := scanStringNEON(unsafe.Pointer(unsafe.StringData(s)), len(s), &e.tables)
27 if expected := expected(s); got != expected {
28 t.Fatalf("escape %d, %q: expected %d but got %d", index, s, expected, got)
29 }
30 }
31 check(base)
32 for pos := 0; pos < length; pos++ {
33 for _, c := range special {
34 b := []byte(base)
35 b[pos] = c
36 check(string(b))
37 }
38 }
39 }
40 }
41 }
42
43 // The scan must not read out of the string.
44 func TestScanStringNEONAtEndOfMemory(t *testing.T) {
45 for length := 16; length <= 80; length++ {
46 mem := []byte(strings.Repeat("a", length))
47 for start := 0; start+16 <= length; start++ {
48 s := string(mem[start:])
49 if got := scanStringNEON(unsafe.Pointer(unsafe.StringData(s)), len(s), &stringEscapes[stringEscapeHTML|stringEscapeNormalize].tables); got != 0 {
50 t.Fatalf("%q: got %d", s, got)
51 }
52 }
53 }
54 }
55
56 // the scans alone: the one by words and the one by SIMD.
57 func BenchmarkScanString(b *testing.B) {
58 e := &stringEscapes[stringEscapeHTML|stringEscapeNormalize]
59 for _, n := range []int{16, 36, 100, 1000} {
60 s := strings.Repeat("a", n)
61 p := unsafe.Pointer(unsafe.StringData(s))
62 b.Run("Words/"+strconv.Itoa(n), func(b *testing.B) {
63 for i := 0; i < b.N; i++ {
64 if e.hasLooseEscape(p, n) {
65 b.Fatal("found")
66 }
67 }
68 })
69 b.Run("NEON/"+strconv.Itoa(n), func(b *testing.B) {
70 for i := 0; i < b.N; i++ {
71 if scanStringNEON(p, n, &e.tables) != 0 {
72 b.Fatal("found")
73 }
74 }
75 })
76 }
77 }