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