github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/strings/strings_test.go (about)

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