Debian Codegraph @

bytes_unsafe_test.go

raw symbols SCIP
1 //go:build !appengine && !appenginevm
2 // +build !appengine,!appenginevm
3
4 package jsonparser
5
6 import (
7 "reflect"
8 "strings"
9 "testing"
10 "unsafe"
11 )
12
13 var (
14 // short string/[]byte sequences, as the difference between these
15 // three methods is a constant overhead
16 benchmarkString = "0123456789x"
17 benchmarkBytes = []byte("0123456789y")
18 )
19
20 // Test helper for SYS-REQ-001 and SYS-REQ-008.
21 func bytesEqualStrSafe(abytes []byte, bstr string) bool {
22 return bstr == string(abytes)
23 }
24
25 // Test helper for SYS-REQ-001 and SYS-REQ-008.
26 func bytesEqualStrUnsafeSlower(abytes *[]byte, bstr string) bool {
27 aslicehdr := (*reflect.SliceHeader)(unsafe.Pointer(abytes))
28 astrhdr := reflect.StringHeader{Data: aslicehdr.Data, Len: aslicehdr.Len}
29 return *(*string)(unsafe.Pointer(&astrhdr)) == bstr
30 }
31
32 // Verifies: SYS-REQ-001
33 // MCDC SYS-REQ-001: N/A
34 func TestEqual(t *testing.T) {
35 if !equalStr(&[]byte{}, "") {
36 t.Errorf(`equalStr("", ""): expected true, obtained false`)
37 return
38 }
39
40 longstr := strings.Repeat("a", 1000)
41 for i := 0; i < len(longstr); i++ {
42 s1, s2 := longstr[:i]+"1", longstr[:i]+"2"
43 b1 := []byte(s1)
44
45 if !equalStr(&b1, s1) {
46 t.Errorf(`equalStr("a"*%d + "1", "a"*%d + "1"): expected true, obtained false`, i, i)
47 break
48 }
49 if equalStr(&b1, s2) {
50 t.Errorf(`equalStr("a"*%d + "1", "a"*%d + "2"): expected false, obtained true`, i, i)
51 break
52 }
53 }
54 }
55
56 // Verifies: SYS-REQ-001
57 // MCDC SYS-REQ-001: N/A
58 func BenchmarkEqualStr(b *testing.B) {
59 for i := 0; i < b.N; i++ {
60 equalStr(&benchmarkBytes, benchmarkString)
61 }
62 }
63
64 // Alternative implementation without using unsafe
65 // Verifies: SYS-REQ-001
66 // MCDC SYS-REQ-001: N/A
67 func BenchmarkBytesEqualStrSafe(b *testing.B) {
68 for i := 0; i < b.N; i++ {
69 bytesEqualStrSafe(benchmarkBytes, benchmarkString)
70 }
71 }
72
73 // Alternative implementation using unsafe, but that is slower than the current implementation
74 // Verifies: SYS-REQ-001
75 // MCDC SYS-REQ-001: N/A
76 func BenchmarkBytesEqualStrUnsafeSlower(b *testing.B) {
77 for i := 0; i < b.N; i++ {
78 bytesEqualStrUnsafeSlower(&benchmarkBytes, benchmarkString)
79 }
80 }