github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/strings/compare_test.go (about) 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. 4 5 package strings_test 6 7 // Derived from bytes/compare_test.go. 8 // Benchmarks omitted since the underlying implementation is identical. 9 10 import ( 11 . "strings" 12 "testing" 13 ) 14 15 var compareTests = []struct { 16 a, b string 17 i int 18 }{ 19 {"", "", 0}, 20 {"a", "", 1}, 21 {"", "a", -1}, 22 {"abc", "abc", 0}, 23 {"ab", "abc", -1}, 24 {"abc", "ab", 1}, 25 {"x", "ab", 1}, 26 {"ab", "x", -1}, 27 {"x", "a", 1}, 28 {"b", "x", -1}, 29 // test runtime·memeq's chunked implementation 30 {"abcdefgh", "abcdefgh", 0}, 31 {"abcdefghi", "abcdefghi", 0}, 32 {"abcdefghi", "abcdefghj", -1}, 33 } 34 35 func TestCompare(t *testing.T) { 36 for _, tt := range compareTests { 37 cmp := Compare(tt.a, tt.b) 38 if cmp != tt.i { 39 t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp) 40 } 41 } 42 } 43 44 func TestCompareIdenticalString(t *testing.T) { 45 var s = "Hello Gophers!" 46 if Compare(s, s) != 0 { 47 t.Error("s != s") 48 } 49 if Compare(s, s[:1]) != 1 { 50 t.Error("s > s[:1] failed") 51 } 52 } 53 54 func TestCompareStrings(t *testing.T) { 55 n := 128 56 a := make([]byte, n+1) 57 b := make([]byte, n+1) 58 for len := 0; len < 128; len++ { 59 // randomish but deterministic data. No 0 or 255. 60 for i := 0; i < len; i++ { 61 a[i] = byte(1 + 31*i%254) 62 b[i] = byte(1 + 31*i%254) 63 } 64 // data past the end is different 65 for i := len; i <= n; i++ { 66 a[i] = 8 67 b[i] = 9 68 } 69 70 cmp := Compare(string(a[:len]), string(b[:len])) 71 if cmp != 0 { 72 t.Errorf(`CompareIdentical(%d) = %d`, len, cmp) 73 } 74 if len > 0 { 75 cmp = Compare(string(a[:len-1]), string(b[:len])) 76 if cmp != -1 { 77 t.Errorf(`CompareAshorter(%d) = %d`, len, cmp) 78 } 79 cmp = Compare(string(a[:len]), string(b[:len-1])) 80 if cmp != 1 { 81 t.Errorf(`CompareBshorter(%d) = %d`, len, cmp) 82 } 83 } 84 for k := 0; k < len; k++ { 85 b[k] = a[k] - 1 86 cmp = Compare(string(a[:len]), string(b[:len])) 87 if cmp != 1 { 88 t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp) 89 } 90 b[k] = a[k] + 1 91 cmp = Compare(string(a[:len]), string(b[:len])) 92 if cmp != -1 { 93 t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp) 94 } 95 b[k] = a[k] 96 } 97 } 98 }