Source file
src/strings/compare_test.go
1
2
3
4
5 package strings_test
6
7
8
9
10 import (
11 "internal/testenv"
12 . "strings"
13 "testing"
14 "unsafe"
15 )
16
17 var compareTests = []struct {
18 a, b string
19 i int
20 }{
21 {"", "", 0},
22 {"a", "", 1},
23 {"", "a", -1},
24 {"abc", "abc", 0},
25 {"ab", "abc", -1},
26 {"abc", "ab", 1},
27 {"x", "ab", 1},
28 {"ab", "x", -1},
29 {"x", "a", 1},
30 {"b", "x", -1},
31
32 {"abcdefgh", "abcdefgh", 0},
33 {"abcdefghi", "abcdefghi", 0},
34 {"abcdefghi", "abcdefghj", -1},
35 }
36
37 func TestCompare(t *testing.T) {
38 for _, tt := range compareTests {
39 cmp := Compare(tt.a, tt.b)
40 if cmp != tt.i {
41 t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp)
42 }
43 }
44 }
45
46 func TestCompareIdenticalString(t *testing.T) {
47 var s = "Hello Gophers!"
48 if Compare(s, s) != 0 {
49 t.Error("s != s")
50 }
51 if Compare(s, s[:1]) != 1 {
52 t.Error("s > s[:1] failed")
53 }
54 }
55
56 func TestCompareStrings(t *testing.T) {
57
58
59 unsafeString := func(b []byte) string {
60 return *(*string)(unsafe.Pointer(&b))
61 }
62
63 lengths := make([]int, 0)
64 for i := 0; i <= 128; i++ {
65 lengths = append(lengths, i)
66 }
67 lengths = append(lengths, 256, 512, 1024, 1333, 4095, 4096, 4097)
68
69 if !testing.Short() || testenv.Builder() != "" {
70 lengths = append(lengths, 65535, 65536, 65537, 99999)
71 }
72
73 n := lengths[len(lengths)-1]
74 a := make([]byte, n+1)
75 b := make([]byte, n+1)
76 lastLen := 0
77 for _, len := range lengths {
78
79 for i := 0; i < len; i++ {
80 a[i] = byte(1 + 31*i%254)
81 b[i] = byte(1 + 31*i%254)
82 }
83
84 for i := len; i <= n; i++ {
85 a[i] = 8
86 b[i] = 9
87 }
88
89 sa, sb := unsafeString(a), unsafeString(b)
90 cmp := Compare(sa[:len], sb[:len])
91 if cmp != 0 {
92 t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
93 }
94 if len > 0 {
95 cmp = Compare(sa[:len-1], sb[:len])
96 if cmp != -1 {
97 t.Errorf(`CompareAshorter(%d) = %d`, len, cmp)
98 }
99 cmp = Compare(sa[:len], sb[:len-1])
100 if cmp != 1 {
101 t.Errorf(`CompareBshorter(%d) = %d`, len, cmp)
102 }
103 }
104 for k := lastLen; k < len; k++ {
105 b[k] = a[k] - 1
106 cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
107 if cmp != 1 {
108 t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
109 }
110 b[k] = a[k] + 1
111 cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
112 if cmp != -1 {
113 t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)
114 }
115 b[k] = a[k]
116 }
117 lastLen = len
118 }
119 }
120
View as plain text