1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Derived from bytes/compare_test.go.
8 // Benchmarks omitted since the underlying implementation is identical.
17 var compareTests = []struct {
31 // test runtime·memeq's chunked implementation
32 {"abcdefgh", "abcdefgh", 0},
33 {"abcdefghi", "abcdefghi", 0},
34 {"abcdefghi", "abcdefghj", -1},
37 func TestCompare(t *testing.T) {
38 for _, tt := range compareTests {
39 cmp := Compare(tt.a, tt.b)
41 t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp)
46 func TestCompareIdenticalString(t *testing.T) {
47 var s = "Hello Gophers!"
48 if Compare(s, s) != 0 {
51 if Compare(s, s[:1]) != 1 {
52 t.Error("s > s[:1] failed")
56 func TestCompareStrings(t *testing.T) {
57 // unsafeString converts a []byte to a string with no allocation.
58 // The caller must not modify b while the result string is in use.
59 unsafeString := func(b []byte) string {
60 return *(*string)(unsafe.Pointer(&b))
63 lengths := make([]int, 0) // lengths to test in ascending order
64 for i := 0; i <= 128; i++ {
65 lengths = append(lengths, i)
67 lengths = append(lengths, 256, 512, 1024, 1333, 4095, 4096, 4097)
69 if !testing.Short() || testenv.Builder() != "" {
70 lengths = append(lengths, 65535, 65536, 65537, 99999)
73 n := lengths[len(lengths)-1]
74 a := make([]byte, n+1)
75 b := make([]byte, n+1)
77 for _, len := range lengths {
78 // randomish but deterministic data. No 0 or 255.
79 for i := 0; i < len; i++ {
80 a[i] = byte(1 + 31*i%254)
81 b[i] = byte(1 + 31*i%254)
83 // data past the end is different
84 for i := len; i <= n; i++ {
89 sa, sb := unsafeString(a), unsafeString(b)
90 cmp := Compare(sa[:len], sb[:len])
92 t.Errorf(`CompareIdentical(%d) = %d`, len, cmp)
95 cmp = Compare(sa[:len-1], sb[:len])
97 t.Errorf(`CompareAshorter(%d) = %d`, len, cmp)
99 cmp = Compare(sa[:len], sb[:len-1])
101 t.Errorf(`CompareBshorter(%d) = %d`, len, cmp)
104 for k := lastLen; k < len; k++ {
106 cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
108 t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp)
111 cmp = Compare(unsafeString(a[:len]), unsafeString(b[:len]))
113 t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp)