Source file src/strings/strings_test.go

     1  // Copyright 2009 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  import (
     8  	"bytes"
     9  	"fmt"
    10  	"io"
    11  	"math"
    12  	"math/rand"
    13  	"reflect"
    14  	"strconv"
    15  	. "strings"
    16  	"testing"
    17  	"unicode"
    18  	"unicode/utf8"
    19  	"unsafe"
    20  )
    21  
    22  func eq(a, b []string) bool {
    23  	if len(a) != len(b) {
    24  		return false
    25  	}
    26  	for i := 0; i < len(a); i++ {
    27  		if a[i] != b[i] {
    28  			return false
    29  		}
    30  	}
    31  	return true
    32  }
    33  
    34  var abcd = "abcd"
    35  var faces = "☺☻☹"
    36  var commas = "1,2,3,4"
    37  var dots = "1....2....3....4"
    38  
    39  type IndexTest struct {
    40  	s   string
    41  	sep string
    42  	out int
    43  }
    44  
    45  var indexTests = []IndexTest{
    46  	{"", "", 0},
    47  	{"", "a", -1},
    48  	{"", "foo", -1},
    49  	{"fo", "foo", -1},
    50  	{"foo", "foo", 0},
    51  	{"oofofoofooo", "f", 2},
    52  	{"oofofoofooo", "foo", 4},
    53  	{"barfoobarfoo", "foo", 3},
    54  	{"foo", "", 0},
    55  	{"foo", "o", 1},
    56  	{"abcABCabc", "A", 3},
    57  	{"jrzm6jjhorimglljrea4w3rlgosts0w2gia17hno2td4qd1jz", "jz", 47},
    58  	{"ekkuk5oft4eq0ocpacknhwouic1uua46unx12l37nioq9wbpnocqks6", "ks6", 52},
    59  	{"999f2xmimunbuyew5vrkla9cpwhmxan8o98ec", "98ec", 33},
    60  	{"9lpt9r98i04k8bz6c6dsrthb96bhi", "96bhi", 24},
    61  	{"55u558eqfaod2r2gu42xxsu631xf0zobs5840vl", "5840vl", 33},
    62  	// cases with one byte strings - test special case in Index()
    63  	{"", "a", -1},
    64  	{"x", "a", -1},
    65  	{"x", "x", 0},
    66  	{"abc", "a", 0},
    67  	{"abc", "b", 1},
    68  	{"abc", "c", 2},
    69  	{"abc", "x", -1},
    70  	// test special cases in Index() for short strings
    71  	{"", "ab", -1},
    72  	{"bc", "ab", -1},
    73  	{"ab", "ab", 0},
    74  	{"xab", "ab", 1},
    75  	{"xab"[:2], "ab", -1},
    76  	{"", "abc", -1},
    77  	{"xbc", "abc", -1},
    78  	{"abc", "abc", 0},
    79  	{"xabc", "abc", 1},
    80  	{"xabc"[:3], "abc", -1},
    81  	{"xabxc", "abc", -1},
    82  	{"", "abcd", -1},
    83  	{"xbcd", "abcd", -1},
    84  	{"abcd", "abcd", 0},
    85  	{"xabcd", "abcd", 1},
    86  	{"xyabcd"[:5], "abcd", -1},
    87  	{"xbcqq", "abcqq", -1},
    88  	{"abcqq", "abcqq", 0},
    89  	{"xabcqq", "abcqq", 1},
    90  	{"xyabcqq"[:6], "abcqq", -1},
    91  	{"xabxcqq", "abcqq", -1},
    92  	{"xabcqxq", "abcqq", -1},
    93  	{"", "01234567", -1},
    94  	{"32145678", "01234567", -1},
    95  	{"01234567", "01234567", 0},
    96  	{"x01234567", "01234567", 1},
    97  	{"x0123456x01234567", "01234567", 9},
    98  	{"xx01234567"[:9], "01234567", -1},
    99  	{"", "0123456789", -1},
   100  	{"3214567844", "0123456789", -1},
   101  	{"0123456789", "0123456789", 0},
   102  	{"x0123456789", "0123456789", 1},
   103  	{"x012345678x0123456789", "0123456789", 11},
   104  	{"xyz0123456789"[:12], "0123456789", -1},
   105  	{"x01234567x89", "0123456789", -1},
   106  	{"", "0123456789012345", -1},
   107  	{"3214567889012345", "0123456789012345", -1},
   108  	{"0123456789012345", "0123456789012345", 0},
   109  	{"x0123456789012345", "0123456789012345", 1},
   110  	{"x012345678901234x0123456789012345", "0123456789012345", 17},
   111  	{"", "01234567890123456789", -1},
   112  	{"32145678890123456789", "01234567890123456789", -1},
   113  	{"01234567890123456789", "01234567890123456789", 0},
   114  	{"x01234567890123456789", "01234567890123456789", 1},
   115  	{"x0123456789012345678x01234567890123456789", "01234567890123456789", 21},
   116  	{"xyz01234567890123456789"[:22], "01234567890123456789", -1},
   117  	{"", "0123456789012345678901234567890", -1},
   118  	{"321456788901234567890123456789012345678911", "0123456789012345678901234567890", -1},
   119  	{"0123456789012345678901234567890", "0123456789012345678901234567890", 0},
   120  	{"x0123456789012345678901234567890", "0123456789012345678901234567890", 1},
   121  	{"x012345678901234567890123456789x0123456789012345678901234567890", "0123456789012345678901234567890", 32},
   122  	{"xyz0123456789012345678901234567890"[:33], "0123456789012345678901234567890", -1},
   123  	{"", "01234567890123456789012345678901", -1},
   124  	{"32145678890123456789012345678901234567890211", "01234567890123456789012345678901", -1},
   125  	{"01234567890123456789012345678901", "01234567890123456789012345678901", 0},
   126  	{"x01234567890123456789012345678901", "01234567890123456789012345678901", 1},
   127  	{"x0123456789012345678901234567890x01234567890123456789012345678901", "01234567890123456789012345678901", 33},
   128  	{"xyz01234567890123456789012345678901"[:34], "01234567890123456789012345678901", -1},
   129  	{"xxxxxx012345678901234567890123456789012345678901234567890123456789012", "012345678901234567890123456789012345678901234567890123456789012", 6},
   130  	{"", "0123456789012345678901234567890123456789", -1},
   131  	{"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456789", 2},
   132  	{"xx012345678901234567890123456789012345678901234567890123456789012"[:41], "0123456789012345678901234567890123456789", -1},
   133  	{"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456xxx", -1},
   134  	{"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx", "0123456789012345678901234567890123456xxx", 65},
   135  	// test fallback to Rabin-Karp.
   136  	{"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
   137  	{"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
   138  }
   139  
   140  var lastIndexTests = []IndexTest{
   141  	{"", "", 0},
   142  	{"", "a", -1},
   143  	{"", "foo", -1},
   144  	{"fo", "foo", -1},
   145  	{"foo", "foo", 0},
   146  	{"foo", "f", 0},
   147  	{"oofofoofooo", "f", 7},
   148  	{"oofofoofooo", "foo", 7},
   149  	{"barfoobarfoo", "foo", 9},
   150  	{"foo", "", 3},
   151  	{"foo", "o", 2},
   152  	{"abcABCabc", "A", 3},
   153  	{"abcABCabc", "a", 6},
   154  }
   155  
   156  var indexAnyTests = []IndexTest{
   157  	{"", "", -1},
   158  	{"", "a", -1},
   159  	{"", "abc", -1},
   160  	{"a", "", -1},
   161  	{"a", "a", 0},
   162  	{"\x80", "\xffb", 0},
   163  	{"aaa", "a", 0},
   164  	{"abc", "xyz", -1},
   165  	{"abc", "xcz", 2},
   166  	{"ab☺c", "x☺yz", 2},
   167  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   168  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   169  	{"aRegExp*", ".(|)*+?^$[]", 7},
   170  	{dots + dots + dots, " ", -1},
   171  	{"012abcba210", "\xffb", 4},
   172  	{"012\x80bcb\x80210", "\xffb", 3},
   173  	{"0123456\xcf\x80abc", "\xcfb\x80", 10},
   174  }
   175  
   176  var lastIndexAnyTests = []IndexTest{
   177  	{"", "", -1},
   178  	{"", "a", -1},
   179  	{"", "abc", -1},
   180  	{"a", "", -1},
   181  	{"a", "a", 0},
   182  	{"\x80", "\xffb", 0},
   183  	{"aaa", "a", 2},
   184  	{"abc", "xyz", -1},
   185  	{"abc", "ab", 1},
   186  	{"ab☺c", "x☺yz", 2},
   187  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   188  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   189  	{"a.RegExp*", ".(|)*+?^$[]", 8},
   190  	{dots + dots + dots, " ", -1},
   191  	{"012abcba210", "\xffb", 6},
   192  	{"012\x80bcb\x80210", "\xffb", 7},
   193  	{"0123456\xcf\x80abc", "\xcfb\x80", 10},
   194  }
   195  
   196  // Execute f on each test case.  funcName should be the name of f; it's used
   197  // in failure reports.
   198  func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, testCases []IndexTest) {
   199  	for _, test := range testCases {
   200  		actual := f(test.s, test.sep)
   201  		if actual != test.out {
   202  			t.Errorf("%s(%q,%q) = %v; want %v", funcName, test.s, test.sep, actual, test.out)
   203  		}
   204  	}
   205  }
   206  
   207  func TestIndex(t *testing.T)     { runIndexTests(t, Index, "Index", indexTests) }
   208  func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
   209  func TestIndexAny(t *testing.T)  { runIndexTests(t, IndexAny, "IndexAny", indexAnyTests) }
   210  func TestLastIndexAny(t *testing.T) {
   211  	runIndexTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests)
   212  }
   213  
   214  func TestIndexByte(t *testing.T) {
   215  	for _, tt := range indexTests {
   216  		if len(tt.sep) != 1 {
   217  			continue
   218  		}
   219  		pos := IndexByte(tt.s, tt.sep[0])
   220  		if pos != tt.out {
   221  			t.Errorf(`IndexByte(%q, %q) = %v; want %v`, tt.s, tt.sep[0], pos, tt.out)
   222  		}
   223  	}
   224  }
   225  
   226  func TestLastIndexByte(t *testing.T) {
   227  	testCases := []IndexTest{
   228  		{"", "q", -1},
   229  		{"abcdef", "q", -1},
   230  		{"abcdefabcdef", "a", len("abcdef")},      // something in the middle
   231  		{"abcdefabcdef", "f", len("abcdefabcde")}, // last byte
   232  		{"zabcdefabcdef", "z", 0},                 // first byte
   233  		{"a☺b☻c☹d", "b", len("a☺")},               // non-ascii
   234  	}
   235  	for _, test := range testCases {
   236  		actual := LastIndexByte(test.s, test.sep[0])
   237  		if actual != test.out {
   238  			t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.s, test.sep[0], actual, test.out)
   239  		}
   240  	}
   241  }
   242  
   243  func simpleIndex(s, sep string) int {
   244  	n := len(sep)
   245  	for i := n; i <= len(s); i++ {
   246  		if s[i-n:i] == sep {
   247  			return i - n
   248  		}
   249  	}
   250  	return -1
   251  }
   252  
   253  func TestIndexRandom(t *testing.T) {
   254  	const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
   255  	for times := 0; times < 10; times++ {
   256  		for strLen := 5 + rand.Intn(5); strLen < 140; strLen += 10 { // Arbitrary
   257  			s1 := make([]byte, strLen)
   258  			for i := range s1 {
   259  				s1[i] = chars[rand.Intn(len(chars))]
   260  			}
   261  			s := string(s1)
   262  			for i := 0; i < 50; i++ {
   263  				begin := rand.Intn(len(s) + 1)
   264  				end := begin + rand.Intn(len(s)+1-begin)
   265  				sep := s[begin:end]
   266  				if i%4 == 0 {
   267  					pos := rand.Intn(len(sep) + 1)
   268  					sep = sep[:pos] + "A" + sep[pos:]
   269  				}
   270  				want := simpleIndex(s, sep)
   271  				res := Index(s, sep)
   272  				if res != want {
   273  					t.Errorf("Index(%s,%s) = %d; want %d", s, sep, res, want)
   274  				}
   275  			}
   276  		}
   277  	}
   278  }
   279  
   280  func TestIndexRune(t *testing.T) {
   281  	tests := []struct {
   282  		in   string
   283  		rune rune
   284  		want int
   285  	}{
   286  		{"", 'a', -1},
   287  		{"", '☺', -1},
   288  		{"foo", '☹', -1},
   289  		{"foo", 'o', 1},
   290  		{"foo☺bar", '☺', 3},
   291  		{"foo☺☻☹bar", '☹', 9},
   292  		{"a A x", 'A', 2},
   293  		{"some_text=some_value", '=', 9},
   294  		{"☺a", 'a', 3},
   295  		{"a☻☺b", '☺', 4},
   296  
   297  		// RuneError should match any invalid UTF-8 byte sequence.
   298  		{"�", '�', 0},
   299  		{"\xff", '�', 0},
   300  		{"☻x�", '�', len("☻x")},
   301  		{"☻x\xe2\x98", '�', len("☻x")},
   302  		{"☻x\xe2\x98�", '�', len("☻x")},
   303  		{"☻x\xe2\x98x", '�', len("☻x")},
   304  
   305  		// Invalid rune values should never match.
   306  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
   307  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair
   308  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
   309  	}
   310  	for _, tt := range tests {
   311  		if got := IndexRune(tt.in, tt.rune); got != tt.want {
   312  			t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
   313  		}
   314  	}
   315  
   316  	haystack := "test世界"
   317  	allocs := testing.AllocsPerRun(1000, func() {
   318  		if i := IndexRune(haystack, 's'); i != 2 {
   319  			t.Fatalf("'s' at %d; want 2", i)
   320  		}
   321  		if i := IndexRune(haystack, '世'); i != 4 {
   322  			t.Fatalf("'世' at %d; want 4", i)
   323  		}
   324  	})
   325  	if allocs != 0 && testing.CoverMode() == "" {
   326  		t.Errorf("expected no allocations, got %f", allocs)
   327  	}
   328  }
   329  
   330  const benchmarkString = "some_text=some☺value"
   331  
   332  func BenchmarkIndexRune(b *testing.B) {
   333  	if got := IndexRune(benchmarkString, '☺'); got != 14 {
   334  		b.Fatalf("wrong index: expected 14, got=%d", got)
   335  	}
   336  	for i := 0; i < b.N; i++ {
   337  		IndexRune(benchmarkString, '☺')
   338  	}
   339  }
   340  
   341  var benchmarkLongString = Repeat(" ", 100) + benchmarkString
   342  
   343  func BenchmarkIndexRuneLongString(b *testing.B) {
   344  	if got := IndexRune(benchmarkLongString, '☺'); got != 114 {
   345  		b.Fatalf("wrong index: expected 114, got=%d", got)
   346  	}
   347  	for i := 0; i < b.N; i++ {
   348  		IndexRune(benchmarkLongString, '☺')
   349  	}
   350  }
   351  
   352  func BenchmarkIndexRuneFastPath(b *testing.B) {
   353  	if got := IndexRune(benchmarkString, 'v'); got != 17 {
   354  		b.Fatalf("wrong index: expected 17, got=%d", got)
   355  	}
   356  	for i := 0; i < b.N; i++ {
   357  		IndexRune(benchmarkString, 'v')
   358  	}
   359  }
   360  
   361  func BenchmarkIndex(b *testing.B) {
   362  	if got := Index(benchmarkString, "v"); got != 17 {
   363  		b.Fatalf("wrong index: expected 17, got=%d", got)
   364  	}
   365  	for i := 0; i < b.N; i++ {
   366  		Index(benchmarkString, "v")
   367  	}
   368  }
   369  
   370  func BenchmarkLastIndex(b *testing.B) {
   371  	if got := Index(benchmarkString, "v"); got != 17 {
   372  		b.Fatalf("wrong index: expected 17, got=%d", got)
   373  	}
   374  	for i := 0; i < b.N; i++ {
   375  		LastIndex(benchmarkString, "v")
   376  	}
   377  }
   378  
   379  func BenchmarkIndexByte(b *testing.B) {
   380  	if got := IndexByte(benchmarkString, 'v'); got != 17 {
   381  		b.Fatalf("wrong index: expected 17, got=%d", got)
   382  	}
   383  	for i := 0; i < b.N; i++ {
   384  		IndexByte(benchmarkString, 'v')
   385  	}
   386  }
   387  
   388  type SplitTest struct {
   389  	s   string
   390  	sep string
   391  	n   int
   392  	a   []string
   393  }
   394  
   395  var splittests = []SplitTest{
   396  	{"", "", -1, []string{}},
   397  	{abcd, "", 2, []string{"a", "bcd"}},
   398  	{abcd, "", 4, []string{"a", "b", "c", "d"}},
   399  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   400  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   401  	{faces, "", 3, []string{"☺", "☻", "☹"}},
   402  	{faces, "", 17, []string{"☺", "☻", "☹"}},
   403  	{"☺�☹", "", -1, []string{"☺", "�", "☹"}},
   404  	{abcd, "a", 0, nil},
   405  	{abcd, "a", -1, []string{"", "bcd"}},
   406  	{abcd, "z", -1, []string{"abcd"}},
   407  	{commas, ",", -1, []string{"1", "2", "3", "4"}},
   408  	{dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
   409  	{faces, "☹", -1, []string{"☺☻", ""}},
   410  	{faces, "~", -1, []string{faces}},
   411  	{"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
   412  	{"1 2", " ", 3, []string{"1", "2"}},
   413  	{"", "T", math.MaxInt / 4, []string{""}},
   414  	{"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}},
   415  	{"\xff-\xff", "-", -1, []string{"\xff", "\xff"}},
   416  }
   417  
   418  func TestSplit(t *testing.T) {
   419  	for _, tt := range splittests {
   420  		a := SplitN(tt.s, tt.sep, tt.n)
   421  		if !eq(a, tt.a) {
   422  			t.Errorf("Split(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, a, tt.a)
   423  			continue
   424  		}
   425  		if tt.n == 0 {
   426  			continue
   427  		}
   428  		s := Join(a, tt.sep)
   429  		if s != tt.s {
   430  			t.Errorf("Join(Split(%q, %q, %d), %q) = %q", tt.s, tt.sep, tt.n, tt.sep, s)
   431  		}
   432  		if tt.n < 0 {
   433  			b := Split(tt.s, tt.sep)
   434  			if !reflect.DeepEqual(a, b) {
   435  				t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   436  			}
   437  		}
   438  	}
   439  }
   440  
   441  var splitaftertests = []SplitTest{
   442  	{abcd, "a", -1, []string{"a", "bcd"}},
   443  	{abcd, "z", -1, []string{"abcd"}},
   444  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   445  	{commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
   446  	{dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
   447  	{faces, "☹", -1, []string{"☺☻☹", ""}},
   448  	{faces, "~", -1, []string{faces}},
   449  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   450  	{"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
   451  	{"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
   452  	{"1 2", " ", 3, []string{"1 ", "2"}},
   453  	{"123", "", 2, []string{"1", "23"}},
   454  	{"123", "", 17, []string{"1", "2", "3"}},
   455  }
   456  
   457  func TestSplitAfter(t *testing.T) {
   458  	for _, tt := range splitaftertests {
   459  		a := SplitAfterN(tt.s, tt.sep, tt.n)
   460  		if !eq(a, tt.a) {
   461  			t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, a, tt.a)
   462  			continue
   463  		}
   464  		s := Join(a, "")
   465  		if s != tt.s {
   466  			t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
   467  		}
   468  		if tt.n < 0 {
   469  			b := SplitAfter(tt.s, tt.sep)
   470  			if !reflect.DeepEqual(a, b) {
   471  				t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   472  			}
   473  		}
   474  	}
   475  }
   476  
   477  type FieldsTest struct {
   478  	s string
   479  	a []string
   480  }
   481  
   482  var fieldstests = []FieldsTest{
   483  	{"", []string{}},
   484  	{" ", []string{}},
   485  	{" \t ", []string{}},
   486  	{"\u2000", []string{}},
   487  	{"  abc  ", []string{"abc"}},
   488  	{"1 2 3 4", []string{"1", "2", "3", "4"}},
   489  	{"1  2  3  4", []string{"1", "2", "3", "4"}},
   490  	{"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
   491  	{"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
   492  	{"\u2000\u2001\u2002", []string{}},
   493  	{"\n™\t™\n", []string{"™", "™"}},
   494  	{"\n\u20001™2\u2000 \u2001 ™", []string{"1™2", "™"}},
   495  	{"\n1\uFFFD \uFFFD2\u20003\uFFFD4", []string{"1\uFFFD", "\uFFFD2", "3\uFFFD4"}},
   496  	{"1\xFF\u2000\xFF2\xFF \xFF", []string{"1\xFF", "\xFF2\xFF", "\xFF"}},
   497  	{faces, []string{faces}},
   498  }
   499  
   500  func TestFields(t *testing.T) {
   501  	for _, tt := range fieldstests {
   502  		a := Fields(tt.s)
   503  		if !eq(a, tt.a) {
   504  			t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
   505  			continue
   506  		}
   507  	}
   508  }
   509  
   510  var FieldsFuncTests = []FieldsTest{
   511  	{"", []string{}},
   512  	{"XX", []string{}},
   513  	{"XXhiXXX", []string{"hi"}},
   514  	{"aXXbXXXcX", []string{"a", "b", "c"}},
   515  }
   516  
   517  func TestFieldsFunc(t *testing.T) {
   518  	for _, tt := range fieldstests {
   519  		a := FieldsFunc(tt.s, unicode.IsSpace)
   520  		if !eq(a, tt.a) {
   521  			t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
   522  			continue
   523  		}
   524  	}
   525  	pred := func(c rune) bool { return c == 'X' }
   526  	for _, tt := range FieldsFuncTests {
   527  		a := FieldsFunc(tt.s, pred)
   528  		if !eq(a, tt.a) {
   529  			t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
   530  		}
   531  	}
   532  }
   533  
   534  // Test case for any function which accepts and returns a single string.
   535  type StringTest struct {
   536  	in, out string
   537  }
   538  
   539  // Execute f on each test case.  funcName should be the name of f; it's used
   540  // in failure reports.
   541  func runStringTests(t *testing.T, f func(string) string, funcName string, testCases []StringTest) {
   542  	for _, tc := range testCases {
   543  		actual := f(tc.in)
   544  		if actual != tc.out {
   545  			t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
   546  		}
   547  	}
   548  }
   549  
   550  var upperTests = []StringTest{
   551  	{"", ""},
   552  	{"ONLYUPPER", "ONLYUPPER"},
   553  	{"abc", "ABC"},
   554  	{"AbC123", "ABC123"},
   555  	{"azAZ09_", "AZAZ09_"},
   556  	{"longStrinGwitHmixofsmaLLandcAps", "LONGSTRINGWITHMIXOFSMALLANDCAPS"},
   557  	{"RENAN BASTOS 93 AOSDAJDJAIDJAIDAJIaidsjjaidijadsjiadjiOOKKO", "RENAN BASTOS 93 AOSDAJDJAIDJAIDAJIAIDSJJAIDIJADSJIADJIOOKKO"},
   558  	{"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", "LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS"},
   559  	{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char
   560  	{"a\u0080\U0010FFFF", "A\u0080\U0010FFFF"},                           // test utf8.RuneSelf and utf8.MaxRune
   561  }
   562  
   563  var lowerTests = []StringTest{
   564  	{"", ""},
   565  	{"abc", "abc"},
   566  	{"AbC123", "abc123"},
   567  	{"azAZ09_", "azaz09_"},
   568  	{"longStrinGwitHmixofsmaLLandcAps", "longstringwithmixofsmallandcaps"},
   569  	{"renan bastos 93 AOSDAJDJAIDJAIDAJIaidsjjaidijadsjiadjiOOKKO", "renan bastos 93 aosdajdjaidjaidajiaidsjjaidijadsjiadjiookko"},
   570  	{"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", "long\u0250string\u0250with\u0250nonascii\u0250chars"},
   571  	{"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char
   572  	{"A\u0080\U0010FFFF", "a\u0080\U0010FFFF"},                           // test utf8.RuneSelf and utf8.MaxRune
   573  }
   574  
   575  const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
   576  
   577  var trimSpaceTests = []StringTest{
   578  	{"", ""},
   579  	{"abc", "abc"},
   580  	{space + "abc" + space, "abc"},
   581  	{" ", ""},
   582  	{" \t\r\n \t\t\r\r\n\n ", ""},
   583  	{" \t\r\n x\t\t\r\r\n\n ", "x"},
   584  	{" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"},
   585  	{"1 \t\r\n2", "1 \t\r\n2"},
   586  	{" x\x80", "x\x80"},
   587  	{" x\xc0", "x\xc0"},
   588  	{"x \xc0\xc0 ", "x \xc0\xc0"},
   589  	{"x \xc0", "x \xc0"},
   590  	{"x \xc0 ", "x \xc0"},
   591  	{"x \xc0\xc0 ", "x \xc0\xc0"},
   592  	{"x ☺\xc0\xc0 ", "x ☺\xc0\xc0"},
   593  	{"x ☺ ", "x ☺"},
   594  }
   595  
   596  func tenRunes(ch rune) string {
   597  	r := make([]rune, 10)
   598  	for i := range r {
   599  		r[i] = ch
   600  	}
   601  	return string(r)
   602  }
   603  
   604  // User-defined self-inverse mapping function
   605  func rot13(r rune) rune {
   606  	step := rune(13)
   607  	if r >= 'a' && r <= 'z' {
   608  		return ((r - 'a' + step) % 26) + 'a'
   609  	}
   610  	if r >= 'A' && r <= 'Z' {
   611  		return ((r - 'A' + step) % 26) + 'A'
   612  	}
   613  	return r
   614  }
   615  
   616  func TestMap(t *testing.T) {
   617  	// Run a couple of awful growth/shrinkage tests
   618  	a := tenRunes('a')
   619  	// 1.  Grow. This triggers two reallocations in Map.
   620  	maxRune := func(rune) rune { return unicode.MaxRune }
   621  	m := Map(maxRune, a)
   622  	expect := tenRunes(unicode.MaxRune)
   623  	if m != expect {
   624  		t.Errorf("growing: expected %q got %q", expect, m)
   625  	}
   626  
   627  	// 2. Shrink
   628  	minRune := func(rune) rune { return 'a' }
   629  	m = Map(minRune, tenRunes(unicode.MaxRune))
   630  	expect = a
   631  	if m != expect {
   632  		t.Errorf("shrinking: expected %q got %q", expect, m)
   633  	}
   634  
   635  	// 3. Rot13
   636  	m = Map(rot13, "a to zed")
   637  	expect = "n gb mrq"
   638  	if m != expect {
   639  		t.Errorf("rot13: expected %q got %q", expect, m)
   640  	}
   641  
   642  	// 4. Rot13^2
   643  	m = Map(rot13, Map(rot13, "a to zed"))
   644  	expect = "a to zed"
   645  	if m != expect {
   646  		t.Errorf("rot13: expected %q got %q", expect, m)
   647  	}
   648  
   649  	// 5. Drop
   650  	dropNotLatin := func(r rune) rune {
   651  		if unicode.Is(unicode.Latin, r) {
   652  			return r
   653  		}
   654  		return -1
   655  	}
   656  	m = Map(dropNotLatin, "Hello, 세계")
   657  	expect = "Hello"
   658  	if m != expect {
   659  		t.Errorf("drop: expected %q got %q", expect, m)
   660  	}
   661  
   662  	// 6. Identity
   663  	identity := func(r rune) rune {
   664  		return r
   665  	}
   666  	orig := "Input string that we expect not to be copied."
   667  	m = Map(identity, orig)
   668  	if unsafe.StringData(orig) != unsafe.StringData(m) {
   669  		t.Error("unexpected copy during identity map")
   670  	}
   671  
   672  	// 7. Handle invalid UTF-8 sequence
   673  	replaceNotLatin := func(r rune) rune {
   674  		if unicode.Is(unicode.Latin, r) {
   675  			return r
   676  		}
   677  		return utf8.RuneError
   678  	}
   679  	m = Map(replaceNotLatin, "Hello\255World")
   680  	expect = "Hello\uFFFDWorld"
   681  	if m != expect {
   682  		t.Errorf("replace invalid sequence: expected %q got %q", expect, m)
   683  	}
   684  
   685  	// 8. Check utf8.RuneSelf and utf8.MaxRune encoding
   686  	encode := func(r rune) rune {
   687  		switch r {
   688  		case utf8.RuneSelf:
   689  			return unicode.MaxRune
   690  		case unicode.MaxRune:
   691  			return utf8.RuneSelf
   692  		}
   693  		return r
   694  	}
   695  	s := string(rune(utf8.RuneSelf)) + string(utf8.MaxRune)
   696  	r := string(utf8.MaxRune) + string(rune(utf8.RuneSelf)) // reverse of s
   697  	m = Map(encode, s)
   698  	if m != r {
   699  		t.Errorf("encoding not handled correctly: expected %q got %q", r, m)
   700  	}
   701  	m = Map(encode, r)
   702  	if m != s {
   703  		t.Errorf("encoding not handled correctly: expected %q got %q", s, m)
   704  	}
   705  
   706  	// 9. Check mapping occurs in the front, middle and back
   707  	trimSpaces := func(r rune) rune {
   708  		if unicode.IsSpace(r) {
   709  			return -1
   710  		}
   711  		return r
   712  	}
   713  	m = Map(trimSpaces, "   abc    123   ")
   714  	expect = "abc123"
   715  	if m != expect {
   716  		t.Errorf("trimSpaces: expected %q got %q", expect, m)
   717  	}
   718  }
   719  
   720  func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
   721  
   722  func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
   723  
   724  var toValidUTF8Tests = []struct {
   725  	in   string
   726  	repl string
   727  	out  string
   728  }{
   729  	{"", "\uFFFD", ""},
   730  	{"abc", "\uFFFD", "abc"},
   731  	{"\uFDDD", "\uFFFD", "\uFDDD"},
   732  	{"a\xffb", "\uFFFD", "a\uFFFDb"},
   733  	{"a\xffb\uFFFD", "X", "aXb\uFFFD"},
   734  	{"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"},
   735  	{"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"},
   736  	{"\xC0\xAF", "\uFFFD", "\uFFFD"},
   737  	{"\xE0\x80\xAF", "\uFFFD", "\uFFFD"},
   738  	{"\xed\xa0\x80", "abc", "abc"},
   739  	{"\xed\xbf\xbf", "\uFFFD", "\uFFFD"},
   740  	{"\xF0\x80\x80\xaf", "☺", "☺"},
   741  	{"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
   742  	{"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
   743  }
   744  
   745  func TestToValidUTF8(t *testing.T) {
   746  	for _, tc := range toValidUTF8Tests {
   747  		got := ToValidUTF8(tc.in, tc.repl)
   748  		if got != tc.out {
   749  			t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out)
   750  		}
   751  	}
   752  }
   753  
   754  func BenchmarkToUpper(b *testing.B) {
   755  	for _, tc := range upperTests {
   756  		b.Run(tc.in, func(b *testing.B) {
   757  			for i := 0; i < b.N; i++ {
   758  				actual := ToUpper(tc.in)
   759  				if actual != tc.out {
   760  					b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out)
   761  				}
   762  			}
   763  		})
   764  	}
   765  }
   766  
   767  func BenchmarkToLower(b *testing.B) {
   768  	for _, tc := range lowerTests {
   769  		b.Run(tc.in, func(b *testing.B) {
   770  			for i := 0; i < b.N; i++ {
   771  				actual := ToLower(tc.in)
   772  				if actual != tc.out {
   773  					b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out)
   774  				}
   775  			}
   776  		})
   777  	}
   778  }
   779  
   780  func BenchmarkMapNoChanges(b *testing.B) {
   781  	identity := func(r rune) rune {
   782  		return r
   783  	}
   784  	for i := 0; i < b.N; i++ {
   785  		Map(identity, "Some string that won't be modified.")
   786  	}
   787  }
   788  
   789  func TestSpecialCase(t *testing.T) {
   790  	lower := "abcçdefgğhıijklmnoöprsştuüvyz"
   791  	upper := "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ"
   792  	u := ToUpperSpecial(unicode.TurkishCase, upper)
   793  	if u != upper {
   794  		t.Errorf("Upper(upper) is %s not %s", u, upper)
   795  	}
   796  	u = ToUpperSpecial(unicode.TurkishCase, lower)
   797  	if u != upper {
   798  		t.Errorf("Upper(lower) is %s not %s", u, upper)
   799  	}
   800  	l := ToLowerSpecial(unicode.TurkishCase, lower)
   801  	if l != lower {
   802  		t.Errorf("Lower(lower) is %s not %s", l, lower)
   803  	}
   804  	l = ToLowerSpecial(unicode.TurkishCase, upper)
   805  	if l != lower {
   806  		t.Errorf("Lower(upper) is %s not %s", l, lower)
   807  	}
   808  }
   809  
   810  func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
   811  
   812  var trimTests = []struct {
   813  	f            string
   814  	in, arg, out string
   815  }{
   816  	{"Trim", "abba", "a", "bb"},
   817  	{"Trim", "abba", "ab", ""},
   818  	{"TrimLeft", "abba", "ab", ""},
   819  	{"TrimRight", "abba", "ab", ""},
   820  	{"TrimLeft", "abba", "a", "bba"},
   821  	{"TrimLeft", "abba", "b", "abba"},
   822  	{"TrimRight", "abba", "a", "abb"},
   823  	{"TrimRight", "abba", "b", "abba"},
   824  	{"Trim", "<tag>", "<>", "tag"},
   825  	{"Trim", "* listitem", " *", "listitem"},
   826  	{"Trim", `"quote"`, `"`, "quote"},
   827  	{"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
   828  	{"Trim", "\x80test\xff", "\xff", "test"},
   829  	{"Trim", " Ġ ", " ", "Ġ"},
   830  	{"Trim", " Ġİ0", "0 ", "Ġİ"},
   831  	//empty string tests
   832  	{"Trim", "abba", "", "abba"},
   833  	{"Trim", "", "123", ""},
   834  	{"Trim", "", "", ""},
   835  	{"TrimLeft", "abba", "", "abba"},
   836  	{"TrimLeft", "", "123", ""},
   837  	{"TrimLeft", "", "", ""},
   838  	{"TrimRight", "abba", "", "abba"},
   839  	{"TrimRight", "", "123", ""},
   840  	{"TrimRight", "", "", ""},
   841  	{"TrimRight", "☺\xc0", "☺", "☺\xc0"},
   842  	{"TrimPrefix", "aabb", "a", "abb"},
   843  	{"TrimPrefix", "aabb", "b", "aabb"},
   844  	{"TrimSuffix", "aabb", "a", "aabb"},
   845  	{"TrimSuffix", "aabb", "b", "aab"},
   846  }
   847  
   848  func TestTrim(t *testing.T) {
   849  	for _, tc := range trimTests {
   850  		name := tc.f
   851  		var f func(string, string) string
   852  		switch name {
   853  		case "Trim":
   854  			f = Trim
   855  		case "TrimLeft":
   856  			f = TrimLeft
   857  		case "TrimRight":
   858  			f = TrimRight
   859  		case "TrimPrefix":
   860  			f = TrimPrefix
   861  		case "TrimSuffix":
   862  			f = TrimSuffix
   863  		default:
   864  			t.Errorf("Undefined trim function %s", name)
   865  		}
   866  		actual := f(tc.in, tc.arg)
   867  		if actual != tc.out {
   868  			t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
   869  		}
   870  	}
   871  }
   872  
   873  func BenchmarkTrim(b *testing.B) {
   874  	b.ReportAllocs()
   875  
   876  	for i := 0; i < b.N; i++ {
   877  		for _, tc := range trimTests {
   878  			name := tc.f
   879  			var f func(string, string) string
   880  			switch name {
   881  			case "Trim":
   882  				f = Trim
   883  			case "TrimLeft":
   884  				f = TrimLeft
   885  			case "TrimRight":
   886  				f = TrimRight
   887  			case "TrimPrefix":
   888  				f = TrimPrefix
   889  			case "TrimSuffix":
   890  				f = TrimSuffix
   891  			default:
   892  				b.Errorf("Undefined trim function %s", name)
   893  			}
   894  			actual := f(tc.in, tc.arg)
   895  			if actual != tc.out {
   896  				b.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
   897  			}
   898  		}
   899  	}
   900  }
   901  
   902  func BenchmarkToValidUTF8(b *testing.B) {
   903  	tests := []struct {
   904  		name  string
   905  		input string
   906  	}{
   907  		{"Valid", "typical"},
   908  		{"InvalidASCII", "foo\xffbar"},
   909  		{"InvalidNonASCII", "日本語\xff日本語"},
   910  	}
   911  	replacement := "\uFFFD"
   912  	b.ResetTimer()
   913  	for _, test := range tests {
   914  		b.Run(test.name, func(b *testing.B) {
   915  			for i := 0; i < b.N; i++ {
   916  				ToValidUTF8(test.input, replacement)
   917  			}
   918  		})
   919  	}
   920  }
   921  
   922  type predicate struct {
   923  	f    func(rune) bool
   924  	name string
   925  }
   926  
   927  var isSpace = predicate{unicode.IsSpace, "IsSpace"}
   928  var isDigit = predicate{unicode.IsDigit, "IsDigit"}
   929  var isUpper = predicate{unicode.IsUpper, "IsUpper"}
   930  var isValidRune = predicate{
   931  	func(r rune) bool {
   932  		return r != utf8.RuneError
   933  	},
   934  	"IsValidRune",
   935  }
   936  
   937  func not(p predicate) predicate {
   938  	return predicate{
   939  		func(r rune) bool {
   940  			return !p.f(r)
   941  		},
   942  		"not " + p.name,
   943  	}
   944  }
   945  
   946  var trimFuncTests = []struct {
   947  	f        predicate
   948  	in       string
   949  	trimOut  string
   950  	leftOut  string
   951  	rightOut string
   952  }{
   953  	{isSpace, space + " hello " + space,
   954  		"hello",
   955  		"hello " + space,
   956  		space + " hello"},
   957  	{isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51",
   958  		"hello",
   959  		"hello34\u0e50\u0e51",
   960  		"\u0e50\u0e5212hello"},
   961  	{isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
   962  		"hello",
   963  		"helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
   964  		"\u2C6F\u2C6F\u2C6F\u2C6FABCDhello"},
   965  	{not(isSpace), "hello" + space + "hello",
   966  		space,
   967  		space + "hello",
   968  		"hello" + space},
   969  	{not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo",
   970  		"\u0e50\u0e521234\u0e50\u0e51",
   971  		"\u0e50\u0e521234\u0e50\u0e51helo",
   972  		"hello\u0e50\u0e521234\u0e50\u0e51"},
   973  	{isValidRune, "ab\xc0a\xc0cd",
   974  		"\xc0a\xc0",
   975  		"\xc0a\xc0cd",
   976  		"ab\xc0a\xc0"},
   977  	{not(isValidRune), "\xc0a\xc0",
   978  		"a",
   979  		"a\xc0",
   980  		"\xc0a"},
   981  	{isSpace, "",
   982  		"",
   983  		"",
   984  		""},
   985  	{isSpace, " ",
   986  		"",
   987  		"",
   988  		""},
   989  }
   990  
   991  func TestTrimFunc(t *testing.T) {
   992  	for _, tc := range trimFuncTests {
   993  		trimmers := []struct {
   994  			name string
   995  			trim func(s string, f func(r rune) bool) string
   996  			out  string
   997  		}{
   998  			{"TrimFunc", TrimFunc, tc.trimOut},
   999  			{"TrimLeftFunc", TrimLeftFunc, tc.leftOut},
  1000  			{"TrimRightFunc", TrimRightFunc, tc.rightOut},
  1001  		}
  1002  		for _, trimmer := range trimmers {
  1003  			actual := trimmer.trim(tc.in, tc.f.f)
  1004  			if actual != trimmer.out {
  1005  				t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out)
  1006  			}
  1007  		}
  1008  	}
  1009  }
  1010  
  1011  var indexFuncTests = []struct {
  1012  	in          string
  1013  	f           predicate
  1014  	first, last int
  1015  }{
  1016  	{"", isValidRune, -1, -1},
  1017  	{"abc", isDigit, -1, -1},
  1018  	{"0123", isDigit, 0, 3},
  1019  	{"a1b", isDigit, 1, 1},
  1020  	{space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes
  1021  	{"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
  1022  	{"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
  1023  	{"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
  1024  
  1025  	// tests of invalid UTF-8
  1026  	{"\x801", isDigit, 1, 1},
  1027  	{"\x80abc", isDigit, -1, -1},
  1028  	{"\xc0a\xc0", isValidRune, 1, 1},
  1029  	{"\xc0a\xc0", not(isValidRune), 0, 2},
  1030  	{"\xc0☺\xc0", not(isValidRune), 0, 4},
  1031  	{"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
  1032  	{"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
  1033  	{"a\xe0\x80cd", not(isValidRune), 1, 2},
  1034  	{"\x80\x80\x80\x80", not(isValidRune), 0, 3},
  1035  }
  1036  
  1037  func TestIndexFunc(t *testing.T) {
  1038  	for _, tc := range indexFuncTests {
  1039  		first := IndexFunc(tc.in, tc.f.f)
  1040  		if first != tc.first {
  1041  			t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
  1042  		}
  1043  		last := LastIndexFunc(tc.in, tc.f.f)
  1044  		if last != tc.last {
  1045  			t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
  1046  		}
  1047  	}
  1048  }
  1049  
  1050  func equal(m string, s1, s2 string, t *testing.T) bool {
  1051  	if s1 == s2 {
  1052  		return true
  1053  	}
  1054  	e1 := Split(s1, "")
  1055  	e2 := Split(s2, "")
  1056  	for i, c1 := range e1 {
  1057  		if i >= len(e2) {
  1058  			break
  1059  		}
  1060  		r1, _ := utf8.DecodeRuneInString(c1)
  1061  		r2, _ := utf8.DecodeRuneInString(e2[i])
  1062  		if r1 != r2 {
  1063  			t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2)
  1064  		}
  1065  	}
  1066  	return false
  1067  }
  1068  
  1069  func TestCaseConsistency(t *testing.T) {
  1070  	// Make a string of all the runes.
  1071  	numRunes := int(unicode.MaxRune + 1)
  1072  	if testing.Short() {
  1073  		numRunes = 1000
  1074  	}
  1075  	a := make([]rune, numRunes)
  1076  	for i := range a {
  1077  		a[i] = rune(i)
  1078  	}
  1079  	s := string(a)
  1080  	// convert the cases.
  1081  	upper := ToUpper(s)
  1082  	lower := ToLower(s)
  1083  
  1084  	// Consistency checks
  1085  	if n := utf8.RuneCountInString(upper); n != numRunes {
  1086  		t.Error("rune count wrong in upper:", n)
  1087  	}
  1088  	if n := utf8.RuneCountInString(lower); n != numRunes {
  1089  		t.Error("rune count wrong in lower:", n)
  1090  	}
  1091  	if !equal("ToUpper(upper)", ToUpper(upper), upper, t) {
  1092  		t.Error("ToUpper(upper) consistency fail")
  1093  	}
  1094  	if !equal("ToLower(lower)", ToLower(lower), lower, t) {
  1095  		t.Error("ToLower(lower) consistency fail")
  1096  	}
  1097  	/*
  1098  		  These fail because of non-one-to-oneness of the data, such as multiple
  1099  		  upper case 'I' mapping to 'i'.  We comment them out but keep them for
  1100  		  interest.
  1101  		  For instance: CAPITAL LETTER I WITH DOT ABOVE:
  1102  			unicode.ToUpper(unicode.ToLower('\u0130')) != '\u0130'
  1103  
  1104  		if !equal("ToUpper(lower)", ToUpper(lower), upper, t) {
  1105  			t.Error("ToUpper(lower) consistency fail");
  1106  		}
  1107  		if !equal("ToLower(upper)", ToLower(upper), lower, t) {
  1108  			t.Error("ToLower(upper) consistency fail");
  1109  		}
  1110  	*/
  1111  }
  1112  
  1113  var longString = "a" + string(make([]byte, 1<<16)) + "z"
  1114  var longSpaces = func() string {
  1115  	b := make([]byte, 200)
  1116  	for i := range b {
  1117  		b[i] = ' '
  1118  	}
  1119  	return string(b)
  1120  }()
  1121  
  1122  var RepeatTests = []struct {
  1123  	in, out string
  1124  	count   int
  1125  }{
  1126  	{"", "", 0},
  1127  	{"", "", 1},
  1128  	{"", "", 2},
  1129  	{"-", "", 0},
  1130  	{"-", "-", 1},
  1131  	{"-", "----------", 10},
  1132  	{"abc ", "abc abc abc ", 3},
  1133  	{" ", " ", 1},
  1134  	{"--", "----", 2},
  1135  	{"===", "======", 2},
  1136  	{"000", "000000000", 3},
  1137  	{"\t\t\t\t", "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t", 4},
  1138  	{" ", longSpaces, len(longSpaces)},
  1139  	// Tests for results over the chunkLimit
  1140  	{string(rune(0)), string(make([]byte, 1<<16)), 1 << 16},
  1141  	{longString, longString + longString, 2},
  1142  }
  1143  
  1144  func TestRepeat(t *testing.T) {
  1145  	for _, tt := range RepeatTests {
  1146  		a := Repeat(tt.in, tt.count)
  1147  		if !equal("Repeat(s)", a, tt.out, t) {
  1148  			t.Errorf("Repeat(%v, %d) = %v; want %v", tt.in, tt.count, a, tt.out)
  1149  			continue
  1150  		}
  1151  	}
  1152  }
  1153  
  1154  func repeat(s string, count int) (err error) {
  1155  	defer func() {
  1156  		if r := recover(); r != nil {
  1157  			switch v := r.(type) {
  1158  			case error:
  1159  				err = v
  1160  			default:
  1161  				err = fmt.Errorf("%s", v)
  1162  			}
  1163  		}
  1164  	}()
  1165  
  1166  	Repeat(s, count)
  1167  
  1168  	return
  1169  }
  1170  
  1171  // See Issue golang.org/issue/16237
  1172  func TestRepeatCatchesOverflow(t *testing.T) {
  1173  	tests := [...]struct {
  1174  		s      string
  1175  		count  int
  1176  		errStr string
  1177  	}{
  1178  		0: {"--", -2147483647, "negative"},
  1179  		1: {"", int(^uint(0) >> 1), ""},
  1180  		2: {"-", 10, ""},
  1181  		3: {"gopher", 0, ""},
  1182  		4: {"-", -1, "negative"},
  1183  		5: {"--", -102, "negative"},
  1184  		6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
  1185  	}
  1186  
  1187  	for i, tt := range tests {
  1188  		err := repeat(tt.s, tt.count)
  1189  		if tt.errStr == "" {
  1190  			if err != nil {
  1191  				t.Errorf("#%d panicked %v", i, err)
  1192  			}
  1193  			continue
  1194  		}
  1195  
  1196  		if err == nil || !Contains(err.Error(), tt.errStr) {
  1197  			t.Errorf("#%d expected %q got %q", i, tt.errStr, err)
  1198  		}
  1199  	}
  1200  }
  1201  
  1202  func runesEqual(a, b []rune) bool {
  1203  	if len(a) != len(b) {
  1204  		return false
  1205  	}
  1206  	for i, r := range a {
  1207  		if r != b[i] {
  1208  			return false
  1209  		}
  1210  	}
  1211  	return true
  1212  }
  1213  
  1214  var RunesTests = []struct {
  1215  	in    string
  1216  	out   []rune
  1217  	lossy bool
  1218  }{
  1219  	{"", []rune{}, false},
  1220  	{" ", []rune{32}, false},
  1221  	{"ABC", []rune{65, 66, 67}, false},
  1222  	{"abc", []rune{97, 98, 99}, false},
  1223  	{"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
  1224  	{"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
  1225  	{"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
  1226  }
  1227  
  1228  func TestRunes(t *testing.T) {
  1229  	for _, tt := range RunesTests {
  1230  		a := []rune(tt.in)
  1231  		if !runesEqual(a, tt.out) {
  1232  			t.Errorf("[]rune(%q) = %v; want %v", tt.in, a, tt.out)
  1233  			continue
  1234  		}
  1235  		if !tt.lossy {
  1236  			// can only test reassembly if we didn't lose information
  1237  			s := string(a)
  1238  			if s != tt.in {
  1239  				t.Errorf("string([]rune(%q)) = %x; want %x", tt.in, s, tt.in)
  1240  			}
  1241  		}
  1242  	}
  1243  }
  1244  
  1245  func TestReadByte(t *testing.T) {
  1246  	testStrings := []string{"", abcd, faces, commas}
  1247  	for _, s := range testStrings {
  1248  		reader := NewReader(s)
  1249  		if e := reader.UnreadByte(); e == nil {
  1250  			t.Errorf("Unreading %q at beginning: expected error", s)
  1251  		}
  1252  		var res bytes.Buffer
  1253  		for {
  1254  			b, e := reader.ReadByte()
  1255  			if e == io.EOF {
  1256  				break
  1257  			}
  1258  			if e != nil {
  1259  				t.Errorf("Reading %q: %s", s, e)
  1260  				break
  1261  			}
  1262  			res.WriteByte(b)
  1263  			// unread and read again
  1264  			e = reader.UnreadByte()
  1265  			if e != nil {
  1266  				t.Errorf("Unreading %q: %s", s, e)
  1267  				break
  1268  			}
  1269  			b1, e := reader.ReadByte()
  1270  			if e != nil {
  1271  				t.Errorf("Reading %q after unreading: %s", s, e)
  1272  				break
  1273  			}
  1274  			if b1 != b {
  1275  				t.Errorf("Reading %q after unreading: want byte %q, got %q", s, b, b1)
  1276  				break
  1277  			}
  1278  		}
  1279  		if res.String() != s {
  1280  			t.Errorf("Reader(%q).ReadByte() produced %q", s, res.String())
  1281  		}
  1282  	}
  1283  }
  1284  
  1285  func TestReadRune(t *testing.T) {
  1286  	testStrings := []string{"", abcd, faces, commas}
  1287  	for _, s := range testStrings {
  1288  		reader := NewReader(s)
  1289  		if e := reader.UnreadRune(); e == nil {
  1290  			t.Errorf("Unreading %q at beginning: expected error", s)
  1291  		}
  1292  		res := ""
  1293  		for {
  1294  			r, z, e := reader.ReadRune()
  1295  			if e == io.EOF {
  1296  				break
  1297  			}
  1298  			if e != nil {
  1299  				t.Errorf("Reading %q: %s", s, e)
  1300  				break
  1301  			}
  1302  			res += string(r)
  1303  			// unread and read again
  1304  			e = reader.UnreadRune()
  1305  			if e != nil {
  1306  				t.Errorf("Unreading %q: %s", s, e)
  1307  				break
  1308  			}
  1309  			r1, z1, e := reader.ReadRune()
  1310  			if e != nil {
  1311  				t.Errorf("Reading %q after unreading: %s", s, e)
  1312  				break
  1313  			}
  1314  			if r1 != r {
  1315  				t.Errorf("Reading %q after unreading: want rune %q, got %q", s, r, r1)
  1316  				break
  1317  			}
  1318  			if z1 != z {
  1319  				t.Errorf("Reading %q after unreading: want size %d, got %d", s, z, z1)
  1320  				break
  1321  			}
  1322  		}
  1323  		if res != s {
  1324  			t.Errorf("Reader(%q).ReadRune() produced %q", s, res)
  1325  		}
  1326  	}
  1327  }
  1328  
  1329  var UnreadRuneErrorTests = []struct {
  1330  	name string
  1331  	f    func(*Reader)
  1332  }{
  1333  	{"Read", func(r *Reader) { r.Read([]byte{0}) }},
  1334  	{"ReadByte", func(r *Reader) { r.ReadByte() }},
  1335  	{"UnreadRune", func(r *Reader) { r.UnreadRune() }},
  1336  	{"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }},
  1337  	{"WriteTo", func(r *Reader) { r.WriteTo(&bytes.Buffer{}) }},
  1338  }
  1339  
  1340  func TestUnreadRuneError(t *testing.T) {
  1341  	for _, tt := range UnreadRuneErrorTests {
  1342  		reader := NewReader("0123456789")
  1343  		if _, _, err := reader.ReadRune(); err != nil {
  1344  			// should not happen
  1345  			t.Fatal(err)
  1346  		}
  1347  		tt.f(reader)
  1348  		err := reader.UnreadRune()
  1349  		if err == nil {
  1350  			t.Errorf("Unreading after %s: expected error", tt.name)
  1351  		}
  1352  	}
  1353  }
  1354  
  1355  var ReplaceTests = []struct {
  1356  	in       string
  1357  	old, new string
  1358  	n        int
  1359  	out      string
  1360  }{
  1361  	{"hello", "l", "L", 0, "hello"},
  1362  	{"hello", "l", "L", -1, "heLLo"},
  1363  	{"hello", "x", "X", -1, "hello"},
  1364  	{"", "x", "X", -1, ""},
  1365  	{"radar", "r", "<r>", -1, "<r>ada<r>"},
  1366  	{"", "", "<>", -1, "<>"},
  1367  	{"banana", "a", "<>", -1, "b<>n<>n<>"},
  1368  	{"banana", "a", "<>", 1, "b<>nana"},
  1369  	{"banana", "a", "<>", 1000, "b<>n<>n<>"},
  1370  	{"banana", "an", "<>", -1, "b<><>a"},
  1371  	{"banana", "ana", "<>", -1, "b<>na"},
  1372  	{"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
  1373  	{"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
  1374  	{"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
  1375  	{"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
  1376  	{"banana", "", "<>", 1, "<>banana"},
  1377  	{"banana", "a", "a", -1, "banana"},
  1378  	{"banana", "a", "a", 1, "banana"},
  1379  	{"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
  1380  }
  1381  
  1382  func TestReplace(t *testing.T) {
  1383  	for _, tt := range ReplaceTests {
  1384  		if s := Replace(tt.in, tt.old, tt.new, tt.n); s != tt.out {
  1385  			t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
  1386  		}
  1387  		if tt.n == -1 {
  1388  			s := ReplaceAll(tt.in, tt.old, tt.new)
  1389  			if s != tt.out {
  1390  				t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out)
  1391  			}
  1392  		}
  1393  	}
  1394  }
  1395  
  1396  var TitleTests = []struct {
  1397  	in, out string
  1398  }{
  1399  	{"", ""},
  1400  	{"a", "A"},
  1401  	{" aaa aaa aaa ", " Aaa Aaa Aaa "},
  1402  	{" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
  1403  	{"123a456", "123a456"},
  1404  	{"double-blind", "Double-Blind"},
  1405  	{"ÿøû", "Ÿøû"},
  1406  	{"with_underscore", "With_underscore"},
  1407  	{"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
  1408  }
  1409  
  1410  func TestTitle(t *testing.T) {
  1411  	for _, tt := range TitleTests {
  1412  		if s := Title(tt.in); s != tt.out {
  1413  			t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
  1414  		}
  1415  	}
  1416  }
  1417  
  1418  var ContainsTests = []struct {
  1419  	str, substr string
  1420  	expected    bool
  1421  }{
  1422  	{"abc", "bc", true},
  1423  	{"abc", "bcd", false},
  1424  	{"abc", "", true},
  1425  	{"", "a", false},
  1426  
  1427  	// cases to cover code in runtime/asm_amd64.s:indexShortStr
  1428  	// 2-byte needle
  1429  	{"xxxxxx", "01", false},
  1430  	{"01xxxx", "01", true},
  1431  	{"xx01xx", "01", true},
  1432  	{"xxxx01", "01", true},
  1433  	{"01xxxxx"[1:], "01", false},
  1434  	{"xxxxx01"[:6], "01", false},
  1435  	// 3-byte needle
  1436  	{"xxxxxxx", "012", false},
  1437  	{"012xxxx", "012", true},
  1438  	{"xx012xx", "012", true},
  1439  	{"xxxx012", "012", true},
  1440  	{"012xxxxx"[1:], "012", false},
  1441  	{"xxxxx012"[:7], "012", false},
  1442  	// 4-byte needle
  1443  	{"xxxxxxxx", "0123", false},
  1444  	{"0123xxxx", "0123", true},
  1445  	{"xx0123xx", "0123", true},
  1446  	{"xxxx0123", "0123", true},
  1447  	{"0123xxxxx"[1:], "0123", false},
  1448  	{"xxxxx0123"[:8], "0123", false},
  1449  	// 5-7-byte needle
  1450  	{"xxxxxxxxx", "01234", false},
  1451  	{"01234xxxx", "01234", true},
  1452  	{"xx01234xx", "01234", true},
  1453  	{"xxxx01234", "01234", true},
  1454  	{"01234xxxxx"[1:], "01234", false},
  1455  	{"xxxxx01234"[:9], "01234", false},
  1456  	// 8-byte needle
  1457  	{"xxxxxxxxxxxx", "01234567", false},
  1458  	{"01234567xxxx", "01234567", true},
  1459  	{"xx01234567xx", "01234567", true},
  1460  	{"xxxx01234567", "01234567", true},
  1461  	{"01234567xxxxx"[1:], "01234567", false},
  1462  	{"xxxxx01234567"[:12], "01234567", false},
  1463  	// 9-15-byte needle
  1464  	{"xxxxxxxxxxxxx", "012345678", false},
  1465  	{"012345678xxxx", "012345678", true},
  1466  	{"xx012345678xx", "012345678", true},
  1467  	{"xxxx012345678", "012345678", true},
  1468  	{"012345678xxxxx"[1:], "012345678", false},
  1469  	{"xxxxx012345678"[:13], "012345678", false},
  1470  	// 16-byte needle
  1471  	{"xxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEF", false},
  1472  	{"0123456789ABCDEFxxxx", "0123456789ABCDEF", true},
  1473  	{"xx0123456789ABCDEFxx", "0123456789ABCDEF", true},
  1474  	{"xxxx0123456789ABCDEF", "0123456789ABCDEF", true},
  1475  	{"0123456789ABCDEFxxxxx"[1:], "0123456789ABCDEF", false},
  1476  	{"xxxxx0123456789ABCDEF"[:20], "0123456789ABCDEF", false},
  1477  	// 17-31-byte needle
  1478  	{"xxxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEFG", false},
  1479  	{"0123456789ABCDEFGxxxx", "0123456789ABCDEFG", true},
  1480  	{"xx0123456789ABCDEFGxx", "0123456789ABCDEFG", true},
  1481  	{"xxxx0123456789ABCDEFG", "0123456789ABCDEFG", true},
  1482  	{"0123456789ABCDEFGxxxxx"[1:], "0123456789ABCDEFG", false},
  1483  	{"xxxxx0123456789ABCDEFG"[:21], "0123456789ABCDEFG", false},
  1484  
  1485  	// partial match cases
  1486  	{"xx01x", "012", false},                             // 3
  1487  	{"xx0123x", "01234", false},                         // 5-7
  1488  	{"xx01234567x", "012345678", false},                 // 9-15
  1489  	{"xx0123456789ABCDEFx", "0123456789ABCDEFG", false}, // 17-31, issue 15679
  1490  }
  1491  
  1492  func TestContains(t *testing.T) {
  1493  	for _, ct := range ContainsTests {
  1494  		if Contains(ct.str, ct.substr) != ct.expected {
  1495  			t.Errorf("Contains(%s, %s) = %v, want %v",
  1496  				ct.str, ct.substr, !ct.expected, ct.expected)
  1497  		}
  1498  	}
  1499  }
  1500  
  1501  var ContainsAnyTests = []struct {
  1502  	str, substr string
  1503  	expected    bool
  1504  }{
  1505  	{"", "", false},
  1506  	{"", "a", false},
  1507  	{"", "abc", false},
  1508  	{"a", "", false},
  1509  	{"a", "a", true},
  1510  	{"aaa", "a", true},
  1511  	{"abc", "xyz", false},
  1512  	{"abc", "xcz", true},
  1513  	{"a☺b☻c☹d", "uvw☻xyz", true},
  1514  	{"aRegExp*", ".(|)*+?^$[]", true},
  1515  	{dots + dots + dots, " ", false},
  1516  }
  1517  
  1518  func TestContainsAny(t *testing.T) {
  1519  	for _, ct := range ContainsAnyTests {
  1520  		if ContainsAny(ct.str, ct.substr) != ct.expected {
  1521  			t.Errorf("ContainsAny(%s, %s) = %v, want %v",
  1522  				ct.str, ct.substr, !ct.expected, ct.expected)
  1523  		}
  1524  	}
  1525  }
  1526  
  1527  var ContainsRuneTests = []struct {
  1528  	str      string
  1529  	r        rune
  1530  	expected bool
  1531  }{
  1532  	{"", 'a', false},
  1533  	{"a", 'a', true},
  1534  	{"aaa", 'a', true},
  1535  	{"abc", 'y', false},
  1536  	{"abc", 'c', true},
  1537  	{"a☺b☻c☹d", 'x', false},
  1538  	{"a☺b☻c☹d", '☻', true},
  1539  	{"aRegExp*", '*', true},
  1540  }
  1541  
  1542  func TestContainsRune(t *testing.T) {
  1543  	for _, ct := range ContainsRuneTests {
  1544  		if ContainsRune(ct.str, ct.r) != ct.expected {
  1545  			t.Errorf("ContainsRune(%q, %q) = %v, want %v",
  1546  				ct.str, ct.r, !ct.expected, ct.expected)
  1547  		}
  1548  	}
  1549  }
  1550  
  1551  func TestContainsFunc(t *testing.T) {
  1552  	for _, ct := range ContainsRuneTests {
  1553  		if ContainsFunc(ct.str, func(r rune) bool {
  1554  			return ct.r == r
  1555  		}) != ct.expected {
  1556  			t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v",
  1557  				ct.str, ct.r, !ct.expected, ct.expected)
  1558  		}
  1559  	}
  1560  }
  1561  
  1562  var EqualFoldTests = []struct {
  1563  	s, t string
  1564  	out  bool
  1565  }{
  1566  	{"abc", "abc", true},
  1567  	{"ABcd", "ABcd", true},
  1568  	{"123abc", "123ABC", true},
  1569  	{"αβδ", "ΑΒΔ", true},
  1570  	{"abc", "xyz", false},
  1571  	{"abc", "XYZ", false},
  1572  	{"abcdefghijk", "abcdefghijX", false},
  1573  	{"abcdefghijk", "abcdefghij\u212A", true},
  1574  	{"abcdefghijK", "abcdefghij\u212A", true},
  1575  	{"abcdefghijkz", "abcdefghij\u212Ay", false},
  1576  	{"abcdefghijKz", "abcdefghij\u212Ay", false},
  1577  	{"1", "2", false},
  1578  	{"utf-8", "US-ASCII", false},
  1579  }
  1580  
  1581  func TestEqualFold(t *testing.T) {
  1582  	for _, tt := range EqualFoldTests {
  1583  		if out := EqualFold(tt.s, tt.t); out != tt.out {
  1584  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
  1585  		}
  1586  		if out := EqualFold(tt.t, tt.s); out != tt.out {
  1587  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
  1588  		}
  1589  	}
  1590  }
  1591  
  1592  func BenchmarkEqualFold(b *testing.B) {
  1593  	b.Run("Tests", func(b *testing.B) {
  1594  		for i := 0; i < b.N; i++ {
  1595  			for _, tt := range EqualFoldTests {
  1596  				if out := EqualFold(tt.s, tt.t); out != tt.out {
  1597  					b.Fatal("wrong result")
  1598  				}
  1599  			}
  1600  		}
  1601  	})
  1602  
  1603  	const s1 = "abcdefghijKz"
  1604  	const s2 = "abcDefGhijKz"
  1605  
  1606  	b.Run("ASCII", func(b *testing.B) {
  1607  		for i := 0; i < b.N; i++ {
  1608  			EqualFold(s1, s2)
  1609  		}
  1610  	})
  1611  
  1612  	b.Run("UnicodePrefix", func(b *testing.B) {
  1613  		for i := 0; i < b.N; i++ {
  1614  			EqualFold("αβδ"+s1, "ΑΒΔ"+s2)
  1615  		}
  1616  	})
  1617  
  1618  	b.Run("UnicodeSuffix", func(b *testing.B) {
  1619  		for i := 0; i < b.N; i++ {
  1620  			EqualFold(s1+"αβδ", s2+"ΑΒΔ")
  1621  		}
  1622  	})
  1623  }
  1624  
  1625  var CountTests = []struct {
  1626  	s, sep string
  1627  	num    int
  1628  }{
  1629  	{"", "", 1},
  1630  	{"", "notempty", 0},
  1631  	{"notempty", "", 9},
  1632  	{"smaller", "not smaller", 0},
  1633  	{"12345678987654321", "6", 2},
  1634  	{"611161116", "6", 3},
  1635  	{"notequal", "NotEqual", 0},
  1636  	{"equal", "equal", 1},
  1637  	{"abc1231231123q", "123", 3},
  1638  	{"11111", "11", 2},
  1639  }
  1640  
  1641  func TestCount(t *testing.T) {
  1642  	for _, tt := range CountTests {
  1643  		if num := Count(tt.s, tt.sep); num != tt.num {
  1644  			t.Errorf("Count(%q, %q) = %d, want %d", tt.s, tt.sep, num, tt.num)
  1645  		}
  1646  	}
  1647  }
  1648  
  1649  var cutTests = []struct {
  1650  	s, sep        string
  1651  	before, after string
  1652  	found         bool
  1653  }{
  1654  	{"abc", "b", "a", "c", true},
  1655  	{"abc", "a", "", "bc", true},
  1656  	{"abc", "c", "ab", "", true},
  1657  	{"abc", "abc", "", "", true},
  1658  	{"abc", "", "", "abc", true},
  1659  	{"abc", "d", "abc", "", false},
  1660  	{"", "d", "", "", false},
  1661  	{"", "", "", "", true},
  1662  }
  1663  
  1664  func TestCut(t *testing.T) {
  1665  	for _, tt := range cutTests {
  1666  		if before, after, found := Cut(tt.s, tt.sep); before != tt.before || after != tt.after || found != tt.found {
  1667  			t.Errorf("Cut(%q, %q) = %q, %q, %v, want %q, %q, %v", tt.s, tt.sep, before, after, found, tt.before, tt.after, tt.found)
  1668  		}
  1669  	}
  1670  }
  1671  
  1672  var cutPrefixTests = []struct {
  1673  	s, sep string
  1674  	after  string
  1675  	found  bool
  1676  }{
  1677  	{"abc", "a", "bc", true},
  1678  	{"abc", "abc", "", true},
  1679  	{"abc", "", "abc", true},
  1680  	{"abc", "d", "abc", false},
  1681  	{"", "d", "", false},
  1682  	{"", "", "", true},
  1683  }
  1684  
  1685  func TestCutPrefix(t *testing.T) {
  1686  	for _, tt := range cutPrefixTests {
  1687  		if after, found := CutPrefix(tt.s, tt.sep); after != tt.after || found != tt.found {
  1688  			t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
  1689  		}
  1690  	}
  1691  }
  1692  
  1693  var cutSuffixTests = []struct {
  1694  	s, sep string
  1695  	before string
  1696  	found  bool
  1697  }{
  1698  	{"abc", "bc", "a", true},
  1699  	{"abc", "abc", "", true},
  1700  	{"abc", "", "abc", true},
  1701  	{"abc", "d", "abc", false},
  1702  	{"", "d", "", false},
  1703  	{"", "", "", true},
  1704  }
  1705  
  1706  func TestCutSuffix(t *testing.T) {
  1707  	for _, tt := range cutSuffixTests {
  1708  		if before, found := CutSuffix(tt.s, tt.sep); before != tt.before || found != tt.found {
  1709  			t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found)
  1710  		}
  1711  	}
  1712  }
  1713  
  1714  func makeBenchInputHard() string {
  1715  	tokens := [...]string{
  1716  		"<a>", "<p>", "<b>", "<strong>",
  1717  		"</a>", "</p>", "</b>", "</strong>",
  1718  		"hello", "world",
  1719  	}
  1720  	x := make([]byte, 0, 1<<20)
  1721  	for {
  1722  		i := rand.Intn(len(tokens))
  1723  		if len(x)+len(tokens[i]) >= 1<<20 {
  1724  			break
  1725  		}
  1726  		x = append(x, tokens[i]...)
  1727  	}
  1728  	return string(x)
  1729  }
  1730  
  1731  var benchInputHard = makeBenchInputHard()
  1732  
  1733  func benchmarkIndexHard(b *testing.B, sep string) {
  1734  	for i := 0; i < b.N; i++ {
  1735  		Index(benchInputHard, sep)
  1736  	}
  1737  }
  1738  
  1739  func benchmarkLastIndexHard(b *testing.B, sep string) {
  1740  	for i := 0; i < b.N; i++ {
  1741  		LastIndex(benchInputHard, sep)
  1742  	}
  1743  }
  1744  
  1745  func benchmarkCountHard(b *testing.B, sep string) {
  1746  	for i := 0; i < b.N; i++ {
  1747  		Count(benchInputHard, sep)
  1748  	}
  1749  }
  1750  
  1751  func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") }
  1752  func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") }
  1753  func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") }
  1754  func BenchmarkIndexHard4(b *testing.B) {
  1755  	benchmarkIndexHard(b, "<pre><b>hello</b><strong>world</strong></pre>")
  1756  }
  1757  
  1758  func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") }
  1759  func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") }
  1760  func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") }
  1761  
  1762  func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, "<>") }
  1763  func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, "</pre>") }
  1764  func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, "<b>hello world</b>") }
  1765  
  1766  var benchInputTorture = Repeat("ABC", 1<<10) + "123" + Repeat("ABC", 1<<10)
  1767  var benchNeedleTorture = Repeat("ABC", 1<<10+1)
  1768  
  1769  func BenchmarkIndexTorture(b *testing.B) {
  1770  	for i := 0; i < b.N; i++ {
  1771  		Index(benchInputTorture, benchNeedleTorture)
  1772  	}
  1773  }
  1774  
  1775  func BenchmarkCountTorture(b *testing.B) {
  1776  	for i := 0; i < b.N; i++ {
  1777  		Count(benchInputTorture, benchNeedleTorture)
  1778  	}
  1779  }
  1780  
  1781  func BenchmarkCountTortureOverlapping(b *testing.B) {
  1782  	A := Repeat("ABC", 1<<20)
  1783  	B := Repeat("ABC", 1<<10)
  1784  	for i := 0; i < b.N; i++ {
  1785  		Count(A, B)
  1786  	}
  1787  }
  1788  
  1789  func BenchmarkCountByte(b *testing.B) {
  1790  	indexSizes := []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
  1791  	benchStr := Repeat(benchmarkString,
  1792  		(indexSizes[len(indexSizes)-1]+len(benchmarkString)-1)/len(benchmarkString))
  1793  	benchFunc := func(b *testing.B, benchStr string) {
  1794  		b.SetBytes(int64(len(benchStr)))
  1795  		for i := 0; i < b.N; i++ {
  1796  			Count(benchStr, "=")
  1797  		}
  1798  	}
  1799  	for _, size := range indexSizes {
  1800  		b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
  1801  			benchFunc(b, benchStr[:size])
  1802  		})
  1803  	}
  1804  
  1805  }
  1806  
  1807  var makeFieldsInput = func() string {
  1808  	x := make([]byte, 1<<20)
  1809  	// Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.
  1810  	for i := range x {
  1811  		switch rand.Intn(10) {
  1812  		case 0:
  1813  			x[i] = ' '
  1814  		case 1:
  1815  			if i > 0 && x[i-1] == 'x' {
  1816  				copy(x[i-1:], "χ")
  1817  				break
  1818  			}
  1819  			fallthrough
  1820  		default:
  1821  			x[i] = 'x'
  1822  		}
  1823  	}
  1824  	return string(x)
  1825  }
  1826  
  1827  var makeFieldsInputASCII = func() string {
  1828  	x := make([]byte, 1<<20)
  1829  	// Input is ~10% space, rest ASCII non-space.
  1830  	for i := range x {
  1831  		if rand.Intn(10) == 0 {
  1832  			x[i] = ' '
  1833  		} else {
  1834  			x[i] = 'x'
  1835  		}
  1836  	}
  1837  	return string(x)
  1838  }
  1839  
  1840  var stringdata = []struct{ name, data string }{
  1841  	{"ASCII", makeFieldsInputASCII()},
  1842  	{"Mixed", makeFieldsInput()},
  1843  }
  1844  
  1845  func BenchmarkFields(b *testing.B) {
  1846  	for _, sd := range stringdata {
  1847  		b.Run(sd.name, func(b *testing.B) {
  1848  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1849  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1850  					b.ReportAllocs()
  1851  					b.SetBytes(int64(j))
  1852  					data := sd.data[:j]
  1853  					for i := 0; i < b.N; i++ {
  1854  						Fields(data)
  1855  					}
  1856  				})
  1857  			}
  1858  		})
  1859  	}
  1860  }
  1861  
  1862  func BenchmarkFieldsFunc(b *testing.B) {
  1863  	for _, sd := range stringdata {
  1864  		b.Run(sd.name, func(b *testing.B) {
  1865  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1866  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1867  					b.ReportAllocs()
  1868  					b.SetBytes(int64(j))
  1869  					data := sd.data[:j]
  1870  					for i := 0; i < b.N; i++ {
  1871  						FieldsFunc(data, unicode.IsSpace)
  1872  					}
  1873  				})
  1874  			}
  1875  		})
  1876  	}
  1877  }
  1878  
  1879  func BenchmarkSplitEmptySeparator(b *testing.B) {
  1880  	for i := 0; i < b.N; i++ {
  1881  		Split(benchInputHard, "")
  1882  	}
  1883  }
  1884  
  1885  func BenchmarkSplitSingleByteSeparator(b *testing.B) {
  1886  	for i := 0; i < b.N; i++ {
  1887  		Split(benchInputHard, "/")
  1888  	}
  1889  }
  1890  
  1891  func BenchmarkSplitMultiByteSeparator(b *testing.B) {
  1892  	for i := 0; i < b.N; i++ {
  1893  		Split(benchInputHard, "hello")
  1894  	}
  1895  }
  1896  
  1897  func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
  1898  	for i := 0; i < b.N; i++ {
  1899  		SplitN(benchInputHard, "/", 10)
  1900  	}
  1901  }
  1902  
  1903  func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
  1904  	for i := 0; i < b.N; i++ {
  1905  		SplitN(benchInputHard, "hello", 10)
  1906  	}
  1907  }
  1908  
  1909  func BenchmarkRepeat(b *testing.B) {
  1910  	s := "0123456789"
  1911  	for _, n := range []int{5, 10} {
  1912  		for _, c := range []int{0, 1, 2, 6} {
  1913  			b.Run(fmt.Sprintf("%dx%d", n, c), func(b *testing.B) {
  1914  				for i := 0; i < b.N; i++ {
  1915  					Repeat(s[:n], c)
  1916  				}
  1917  			})
  1918  		}
  1919  	}
  1920  }
  1921  
  1922  func BenchmarkRepeatLarge(b *testing.B) {
  1923  	s := Repeat("@", 8*1024)
  1924  	for j := 8; j <= 30; j++ {
  1925  		for _, k := range []int{1, 16, 4097} {
  1926  			s := s[:k]
  1927  			n := (1 << j) / k
  1928  			if n == 0 {
  1929  				continue
  1930  			}
  1931  			b.Run(fmt.Sprintf("%d/%d", 1<<j, k), func(b *testing.B) {
  1932  				for i := 0; i < b.N; i++ {
  1933  					Repeat(s, n)
  1934  				}
  1935  				b.SetBytes(int64(n * len(s)))
  1936  			})
  1937  		}
  1938  	}
  1939  }
  1940  
  1941  func BenchmarkRepeatSpaces(b *testing.B) {
  1942  	b.ReportAllocs()
  1943  	for i := 0; i < b.N; i++ {
  1944  		Repeat(" ", 2)
  1945  	}
  1946  }
  1947  
  1948  func BenchmarkIndexAnyASCII(b *testing.B) {
  1949  	x := Repeat("#", 2048) // Never matches set
  1950  	cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
  1951  	for k := 1; k <= 2048; k <<= 4 {
  1952  		for j := 1; j <= 64; j <<= 1 {
  1953  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1954  				for i := 0; i < b.N; i++ {
  1955  					IndexAny(x[:k], cs[:j])
  1956  				}
  1957  			})
  1958  		}
  1959  	}
  1960  }
  1961  
  1962  func BenchmarkIndexAnyUTF8(b *testing.B) {
  1963  	x := Repeat("#", 2048) // Never matches set
  1964  	cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
  1965  	for k := 1; k <= 2048; k <<= 4 {
  1966  		for j := 1; j <= 64; j <<= 1 {
  1967  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1968  				for i := 0; i < b.N; i++ {
  1969  					IndexAny(x[:k], cs[:j])
  1970  				}
  1971  			})
  1972  		}
  1973  	}
  1974  }
  1975  
  1976  func BenchmarkLastIndexAnyASCII(b *testing.B) {
  1977  	x := Repeat("#", 2048) // Never matches set
  1978  	cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
  1979  	for k := 1; k <= 2048; k <<= 4 {
  1980  		for j := 1; j <= 64; j <<= 1 {
  1981  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1982  				for i := 0; i < b.N; i++ {
  1983  					LastIndexAny(x[:k], cs[:j])
  1984  				}
  1985  			})
  1986  		}
  1987  	}
  1988  }
  1989  
  1990  func BenchmarkLastIndexAnyUTF8(b *testing.B) {
  1991  	x := Repeat("#", 2048) // Never matches set
  1992  	cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
  1993  	for k := 1; k <= 2048; k <<= 4 {
  1994  		for j := 1; j <= 64; j <<= 1 {
  1995  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1996  				for i := 0; i < b.N; i++ {
  1997  					LastIndexAny(x[:k], cs[:j])
  1998  				}
  1999  			})
  2000  		}
  2001  	}
  2002  }
  2003  
  2004  func BenchmarkTrimASCII(b *testing.B) {
  2005  	cs := "0123456789abcdef"
  2006  	for k := 1; k <= 4096; k <<= 4 {
  2007  		for j := 1; j <= 16; j <<= 1 {
  2008  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2009  				x := Repeat(cs[:j], k) // Always matches set
  2010  				for i := 0; i < b.N; i++ {
  2011  					Trim(x[:k], cs[:j])
  2012  				}
  2013  			})
  2014  		}
  2015  	}
  2016  }
  2017  
  2018  func BenchmarkTrimByte(b *testing.B) {
  2019  	x := "  the quick brown fox   "
  2020  	for i := 0; i < b.N; i++ {
  2021  		Trim(x, " ")
  2022  	}
  2023  }
  2024  
  2025  func BenchmarkIndexPeriodic(b *testing.B) {
  2026  	key := "aa"
  2027  	for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
  2028  		b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
  2029  			s := Repeat("a"+Repeat(" ", skip-1), 1<<16/skip)
  2030  			for i := 0; i < b.N; i++ {
  2031  				Index(s, key)
  2032  			}
  2033  		})
  2034  	}
  2035  }
  2036  
  2037  func BenchmarkJoin(b *testing.B) {
  2038  	vals := []string{"red", "yellow", "pink", "green", "purple", "orange", "blue"}
  2039  	for l := 0; l <= len(vals); l++ {
  2040  		b.Run(strconv.Itoa(l), func(b *testing.B) {
  2041  			b.ReportAllocs()
  2042  			vals := vals[:l]
  2043  			for i := 0; i < b.N; i++ {
  2044  				Join(vals, " and ")
  2045  			}
  2046  		})
  2047  	}
  2048  }
  2049  
  2050  func BenchmarkTrimSpace(b *testing.B) {
  2051  	tests := []struct{ name, input string }{
  2052  		{"NoTrim", "typical"},
  2053  		{"ASCII", "  foo bar  "},
  2054  		{"SomeNonASCII", "    \u2000\t\r\n x\t\t\r\r\ny\n \u3000    "},
  2055  		{"JustNonASCII", "\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000"},
  2056  	}
  2057  	for _, test := range tests {
  2058  		b.Run(test.name, func(b *testing.B) {
  2059  			for i := 0; i < b.N; i++ {
  2060  				TrimSpace(test.input)
  2061  			}
  2062  		})
  2063  	}
  2064  }
  2065  
  2066  var stringSink string
  2067  
  2068  func BenchmarkReplaceAll(b *testing.B) {
  2069  	b.ReportAllocs()
  2070  	for i := 0; i < b.N; i++ {
  2071  		stringSink = ReplaceAll("banana", "a", "<>")
  2072  	}
  2073  }
  2074  

View as plain text