github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/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/rand"
    12  	"reflect"
    13  	. "strings"
    14  	"testing"
    15  	"unicode"
    16  	"unicode/utf8"
    17  	"unsafe"
    18  )
    19  
    20  func eq(a, b []string) bool {
    21  	if len(a) != len(b) {
    22  		return false
    23  	}
    24  	for i := 0; i < len(a); i++ {
    25  		if a[i] != b[i] {
    26  			return false
    27  		}
    28  	}
    29  	return true
    30  }
    31  
    32  var abcd = "abcd"
    33  var faces = "☺☻☹"
    34  var commas = "1,2,3,4"
    35  var dots = "1....2....3....4"
    36  
    37  type IndexTest struct {
    38  	s   string
    39  	sep string
    40  	out int
    41  }
    42  
    43  var indexTests = []IndexTest{
    44  	{"", "", 0},
    45  	{"", "a", -1},
    46  	{"", "foo", -1},
    47  	{"fo", "foo", -1},
    48  	{"foo", "foo", 0},
    49  	{"oofofoofooo", "f", 2},
    50  	{"oofofoofooo", "foo", 4},
    51  	{"barfoobarfoo", "foo", 3},
    52  	{"foo", "", 0},
    53  	{"foo", "o", 1},
    54  	{"abcABCabc", "A", 3},
    55  	// cases with one byte strings - test special case in Index()
    56  	{"", "a", -1},
    57  	{"x", "a", -1},
    58  	{"x", "x", 0},
    59  	{"abc", "a", 0},
    60  	{"abc", "b", 1},
    61  	{"abc", "c", 2},
    62  	{"abc", "x", -1},
    63  	// test special cases in Index() for short strings
    64  	{"", "ab", -1},
    65  	{"bc", "ab", -1},
    66  	{"ab", "ab", 0},
    67  	{"xab", "ab", 1},
    68  	{"xab"[:2], "ab", -1},
    69  	{"", "abc", -1},
    70  	{"xbc", "abc", -1},
    71  	{"abc", "abc", 0},
    72  	{"xabc", "abc", 1},
    73  	{"xabc"[:3], "abc", -1},
    74  	{"xabxc", "abc", -1},
    75  	{"", "abcd", -1},
    76  	{"xbcd", "abcd", -1},
    77  	{"abcd", "abcd", 0},
    78  	{"xabcd", "abcd", 1},
    79  	{"xyabcd"[:5], "abcd", -1},
    80  	{"xbcqq", "abcqq", -1},
    81  	{"abcqq", "abcqq", 0},
    82  	{"xabcqq", "abcqq", 1},
    83  	{"xyabcqq"[:6], "abcqq", -1},
    84  	{"xabxcqq", "abcqq", -1},
    85  	{"xabcqxq", "abcqq", -1},
    86  	{"", "01234567", -1},
    87  	{"32145678", "01234567", -1},
    88  	{"01234567", "01234567", 0},
    89  	{"x01234567", "01234567", 1},
    90  	{"x0123456x01234567", "01234567", 9},
    91  	{"xx01234567"[:9], "01234567", -1},
    92  	{"", "0123456789", -1},
    93  	{"3214567844", "0123456789", -1},
    94  	{"0123456789", "0123456789", 0},
    95  	{"x0123456789", "0123456789", 1},
    96  	{"x012345678x0123456789", "0123456789", 11},
    97  	{"xyz0123456789"[:12], "0123456789", -1},
    98  	{"x01234567x89", "0123456789", -1},
    99  	{"", "0123456789012345", -1},
   100  	{"3214567889012345", "0123456789012345", -1},
   101  	{"0123456789012345", "0123456789012345", 0},
   102  	{"x0123456789012345", "0123456789012345", 1},
   103  	{"x012345678901234x0123456789012345", "0123456789012345", 17},
   104  	{"", "01234567890123456789", -1},
   105  	{"32145678890123456789", "01234567890123456789", -1},
   106  	{"01234567890123456789", "01234567890123456789", 0},
   107  	{"x01234567890123456789", "01234567890123456789", 1},
   108  	{"x0123456789012345678x01234567890123456789", "01234567890123456789", 21},
   109  	{"xyz01234567890123456789"[:22], "01234567890123456789", -1},
   110  	{"", "0123456789012345678901234567890", -1},
   111  	{"321456788901234567890123456789012345678911", "0123456789012345678901234567890", -1},
   112  	{"0123456789012345678901234567890", "0123456789012345678901234567890", 0},
   113  	{"x0123456789012345678901234567890", "0123456789012345678901234567890", 1},
   114  	{"x012345678901234567890123456789x0123456789012345678901234567890", "0123456789012345678901234567890", 32},
   115  	{"xyz0123456789012345678901234567890"[:33], "0123456789012345678901234567890", -1},
   116  	{"", "01234567890123456789012345678901", -1},
   117  	{"32145678890123456789012345678901234567890211", "01234567890123456789012345678901", -1},
   118  	{"01234567890123456789012345678901", "01234567890123456789012345678901", 0},
   119  	{"x01234567890123456789012345678901", "01234567890123456789012345678901", 1},
   120  	{"x0123456789012345678901234567890x01234567890123456789012345678901", "01234567890123456789012345678901", 33},
   121  	{"xyz01234567890123456789012345678901"[:34], "01234567890123456789012345678901", -1},
   122  	{"xxxxxx012345678901234567890123456789012345678901234567890123456789012", "012345678901234567890123456789012345678901234567890123456789012", 6},
   123  	{"", "0123456789012345678901234567890123456789", -1},
   124  	{"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456789", 2},
   125  	{"xx012345678901234567890123456789012345678901234567890123456789012"[:41], "0123456789012345678901234567890123456789", -1},
   126  	{"xx012345678901234567890123456789012345678901234567890123456789012", "0123456789012345678901234567890123456xxx", -1},
   127  	{"xx0123456789012345678901234567890123456789012345678901234567890120123456789012345678901234567890123456xxx", "0123456789012345678901234567890123456xxx", 65},
   128  }
   129  
   130  var lastIndexTests = []IndexTest{
   131  	{"", "", 0},
   132  	{"", "a", -1},
   133  	{"", "foo", -1},
   134  	{"fo", "foo", -1},
   135  	{"foo", "foo", 0},
   136  	{"foo", "f", 0},
   137  	{"oofofoofooo", "f", 7},
   138  	{"oofofoofooo", "foo", 7},
   139  	{"barfoobarfoo", "foo", 9},
   140  	{"foo", "", 3},
   141  	{"foo", "o", 2},
   142  	{"abcABCabc", "A", 3},
   143  	{"abcABCabc", "a", 6},
   144  }
   145  
   146  var indexAnyTests = []IndexTest{
   147  	{"", "", -1},
   148  	{"", "a", -1},
   149  	{"", "abc", -1},
   150  	{"a", "", -1},
   151  	{"a", "a", 0},
   152  	{"aaa", "a", 0},
   153  	{"abc", "xyz", -1},
   154  	{"abc", "xcz", 2},
   155  	{"ab☺c", "x☺yz", 2},
   156  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   157  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   158  	{"aRegExp*", ".(|)*+?^$[]", 7},
   159  	{dots + dots + dots, " ", -1},
   160  	{"012abcba210", "\xffb", 4},
   161  	{"012\x80bcb\x80210", "\xffb", 3},
   162  }
   163  
   164  var lastIndexAnyTests = []IndexTest{
   165  	{"", "", -1},
   166  	{"", "a", -1},
   167  	{"", "abc", -1},
   168  	{"a", "", -1},
   169  	{"a", "a", 0},
   170  	{"aaa", "a", 2},
   171  	{"abc", "xyz", -1},
   172  	{"abc", "ab", 1},
   173  	{"ab☺c", "x☺yz", 2},
   174  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   175  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   176  	{"a.RegExp*", ".(|)*+?^$[]", 8},
   177  	{dots + dots + dots, " ", -1},
   178  	{"012abcba210", "\xffb", 6},
   179  	{"012\x80bcb\x80210", "\xffb", 7},
   180  }
   181  
   182  // Execute f on each test case.  funcName should be the name of f; it's used
   183  // in failure reports.
   184  func runIndexTests(t *testing.T, f func(s, sep string) int, funcName string, testCases []IndexTest) {
   185  	for _, test := range testCases {
   186  		actual := f(test.s, test.sep)
   187  		if actual != test.out {
   188  			t.Errorf("%s(%q,%q) = %v; want %v", funcName, test.s, test.sep, actual, test.out)
   189  		}
   190  	}
   191  }
   192  
   193  func TestIndex(t *testing.T)        { runIndexTests(t, Index, "Index", indexTests) }
   194  func TestLastIndex(t *testing.T)    { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
   195  func TestIndexAny(t *testing.T)     { runIndexTests(t, IndexAny, "IndexAny", indexAnyTests) }
   196  func TestLastIndexAny(t *testing.T) { runIndexTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests) }
   197  
   198  func TestLastIndexByte(t *testing.T) {
   199  	testCases := []IndexTest{
   200  		{"", "q", -1},
   201  		{"abcdef", "q", -1},
   202  		{"abcdefabcdef", "a", len("abcdef")},      // something in the middle
   203  		{"abcdefabcdef", "f", len("abcdefabcde")}, // last byte
   204  		{"zabcdefabcdef", "z", 0},                 // first byte
   205  		{"a☺b☻c☹d", "b", len("a☺")},               // non-ascii
   206  	}
   207  	for _, test := range testCases {
   208  		actual := LastIndexByte(test.s, test.sep[0])
   209  		if actual != test.out {
   210  			t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.s, test.sep[0], actual, test.out)
   211  		}
   212  	}
   213  }
   214  
   215  func simpleIndex(s, sep string) int {
   216  	n := len(sep)
   217  	for i := n; i <= len(s); i++ {
   218  		if s[i-n:i] == sep {
   219  			return i - n
   220  		}
   221  	}
   222  	return -1
   223  }
   224  
   225  func TestIndexRandom(t *testing.T) {
   226  	const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
   227  	for times := 0; times < 10; times++ {
   228  		for strLen := 5 + rand.Intn(5); strLen < 140; strLen += 10 { // Arbitrary
   229  			s1 := make([]byte, strLen)
   230  			for i := range s1 {
   231  				s1[i] = chars[rand.Intn(len(chars))]
   232  			}
   233  			s := string(s1)
   234  			for i := 0; i < 50; i++ {
   235  				begin := rand.Intn(len(s) + 1)
   236  				end := begin + rand.Intn(len(s)+1-begin)
   237  				sep := s[begin:end]
   238  				if i%4 == 0 {
   239  					pos := rand.Intn(len(sep) + 1)
   240  					sep = sep[:pos] + "A" + sep[pos:]
   241  				}
   242  				want := simpleIndex(s, sep)
   243  				res := Index(s, sep)
   244  				if res != want {
   245  					t.Errorf("Index(%s,%s) = %d; want %d", s, sep, res, want)
   246  				}
   247  			}
   248  		}
   249  	}
   250  }
   251  
   252  func TestIndexRune(t *testing.T) {
   253  	tests := []struct {
   254  		in   string
   255  		rune rune
   256  		want int
   257  	}{
   258  		{"", 'a', -1},
   259  		{"", '☺', -1},
   260  		{"foo", '☹', -1},
   261  		{"foo", 'o', 1},
   262  		{"foo☺bar", '☺', 3},
   263  		{"foo☺☻☹bar", '☹', 9},
   264  		{"a A x", 'A', 2},
   265  		{"some_text=some_value", '=', 9},
   266  		{"☺a", 'a', 3},
   267  		{"a☻☺b", '☺', 4},
   268  
   269  		// RuneError should match any invalid UTF-8 byte sequence.
   270  		{"�", '�', 0},
   271  		{"\xff", '�', 0},
   272  		{"☻x�", '�', len("☻x")},
   273  		{"☻x\xe2\x98", '�', len("☻x")},
   274  		{"☻x\xe2\x98�", '�', len("☻x")},
   275  		{"☻x\xe2\x98x", '�', len("☻x")},
   276  
   277  		// Invalid rune values should never match.
   278  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
   279  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair
   280  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
   281  	}
   282  	for _, tt := range tests {
   283  		if got := IndexRune(tt.in, tt.rune); got != tt.want {
   284  			t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
   285  		}
   286  	}
   287  
   288  	haystack := "test世界"
   289  	allocs := testing.AllocsPerRun(1000, func() {
   290  		if i := IndexRune(haystack, 's'); i != 2 {
   291  			t.Fatalf("'s' at %d; want 2", i)
   292  		}
   293  		if i := IndexRune(haystack, '世'); i != 4 {
   294  			t.Fatalf("'世' at %d; want 4", i)
   295  		}
   296  	})
   297  	if allocs != 0 && testing.CoverMode() == "" {
   298  		t.Errorf("expected no allocations, got %f", allocs)
   299  	}
   300  }
   301  
   302  const benchmarkString = "some_text=some☺value"
   303  
   304  func BenchmarkIndexRune(b *testing.B) {
   305  	if got := IndexRune(benchmarkString, '☺'); got != 14 {
   306  		b.Fatalf("wrong index: expected 14, got=%d", got)
   307  	}
   308  	for i := 0; i < b.N; i++ {
   309  		IndexRune(benchmarkString, '☺')
   310  	}
   311  }
   312  
   313  var benchmarkLongString = Repeat(" ", 100) + benchmarkString
   314  
   315  func BenchmarkIndexRuneLongString(b *testing.B) {
   316  	if got := IndexRune(benchmarkLongString, '☺'); got != 114 {
   317  		b.Fatalf("wrong index: expected 114, got=%d", got)
   318  	}
   319  	for i := 0; i < b.N; i++ {
   320  		IndexRune(benchmarkLongString, '☺')
   321  	}
   322  }
   323  
   324  func BenchmarkIndexRuneFastPath(b *testing.B) {
   325  	if got := IndexRune(benchmarkString, 'v'); got != 17 {
   326  		b.Fatalf("wrong index: expected 17, got=%d", got)
   327  	}
   328  	for i := 0; i < b.N; i++ {
   329  		IndexRune(benchmarkString, 'v')
   330  	}
   331  }
   332  
   333  func BenchmarkIndex(b *testing.B) {
   334  	if got := Index(benchmarkString, "v"); got != 17 {
   335  		b.Fatalf("wrong index: expected 17, got=%d", got)
   336  	}
   337  	for i := 0; i < b.N; i++ {
   338  		Index(benchmarkString, "v")
   339  	}
   340  }
   341  
   342  func BenchmarkLastIndex(b *testing.B) {
   343  	if got := Index(benchmarkString, "v"); got != 17 {
   344  		b.Fatalf("wrong index: expected 17, got=%d", got)
   345  	}
   346  	for i := 0; i < b.N; i++ {
   347  		LastIndex(benchmarkString, "v")
   348  	}
   349  }
   350  
   351  func BenchmarkIndexByte(b *testing.B) {
   352  	if got := IndexByte(benchmarkString, 'v'); got != 17 {
   353  		b.Fatalf("wrong index: expected 17, got=%d", got)
   354  	}
   355  	for i := 0; i < b.N; i++ {
   356  		IndexByte(benchmarkString, 'v')
   357  	}
   358  }
   359  
   360  type SplitTest struct {
   361  	s   string
   362  	sep string
   363  	n   int
   364  	a   []string
   365  }
   366  
   367  var splittests = []SplitTest{
   368  	{"", "", -1, []string{}},
   369  	{abcd, "", 2, []string{"a", "bcd"}},
   370  	{abcd, "", 4, []string{"a", "b", "c", "d"}},
   371  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   372  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   373  	{faces, "", 3, []string{"☺", "☻", "☹"}},
   374  	{faces, "", 17, []string{"☺", "☻", "☹"}},
   375  	{"☺�☹", "", -1, []string{"☺", "�", "☹"}},
   376  	{abcd, "a", 0, nil},
   377  	{abcd, "a", -1, []string{"", "bcd"}},
   378  	{abcd, "z", -1, []string{"abcd"}},
   379  	{commas, ",", -1, []string{"1", "2", "3", "4"}},
   380  	{dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
   381  	{faces, "☹", -1, []string{"☺☻", ""}},
   382  	{faces, "~", -1, []string{faces}},
   383  	{"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
   384  	{"1 2", " ", 3, []string{"1", "2"}},
   385  }
   386  
   387  func TestSplit(t *testing.T) {
   388  	for _, tt := range splittests {
   389  		a := SplitN(tt.s, tt.sep, tt.n)
   390  		if !eq(a, tt.a) {
   391  			t.Errorf("Split(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, a, tt.a)
   392  			continue
   393  		}
   394  		if tt.n == 0 {
   395  			continue
   396  		}
   397  		s := Join(a, tt.sep)
   398  		if s != tt.s {
   399  			t.Errorf("Join(Split(%q, %q, %d), %q) = %q", tt.s, tt.sep, tt.n, tt.sep, s)
   400  		}
   401  		if tt.n < 0 {
   402  			b := Split(tt.s, tt.sep)
   403  			if !reflect.DeepEqual(a, b) {
   404  				t.Errorf("Split disagrees with SplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   405  			}
   406  		}
   407  	}
   408  }
   409  
   410  var splitaftertests = []SplitTest{
   411  	{abcd, "a", -1, []string{"a", "bcd"}},
   412  	{abcd, "z", -1, []string{"abcd"}},
   413  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   414  	{commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
   415  	{dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
   416  	{faces, "☹", -1, []string{"☺☻☹", ""}},
   417  	{faces, "~", -1, []string{faces}},
   418  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   419  	{"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
   420  	{"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
   421  	{"1 2", " ", 3, []string{"1 ", "2"}},
   422  	{"123", "", 2, []string{"1", "23"}},
   423  	{"123", "", 17, []string{"1", "2", "3"}},
   424  }
   425  
   426  func TestSplitAfter(t *testing.T) {
   427  	for _, tt := range splitaftertests {
   428  		a := SplitAfterN(tt.s, tt.sep, tt.n)
   429  		if !eq(a, tt.a) {
   430  			t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, a, tt.a)
   431  			continue
   432  		}
   433  		s := Join(a, "")
   434  		if s != tt.s {
   435  			t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
   436  		}
   437  		if tt.n < 0 {
   438  			b := SplitAfter(tt.s, tt.sep)
   439  			if !reflect.DeepEqual(a, b) {
   440  				t.Errorf("SplitAfter disagrees with SplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   441  			}
   442  		}
   443  	}
   444  }
   445  
   446  type FieldsTest struct {
   447  	s string
   448  	a []string
   449  }
   450  
   451  var fieldstests = []FieldsTest{
   452  	{"", []string{}},
   453  	{" ", []string{}},
   454  	{" \t ", []string{}},
   455  	{"\u2000", []string{}},
   456  	{"  abc  ", []string{"abc"}},
   457  	{"1 2 3 4", []string{"1", "2", "3", "4"}},
   458  	{"1  2  3  4", []string{"1", "2", "3", "4"}},
   459  	{"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
   460  	{"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
   461  	{"\u2000\u2001\u2002", []string{}},
   462  	{"\n™\t™\n", []string{"™", "™"}},
   463  	{"\n\u20001™2\u2000 \u2001 ™", []string{"1™2", "™"}},
   464  	{"\n1\uFFFD \uFFFD2\u20003\uFFFD4", []string{"1\uFFFD", "\uFFFD2", "3\uFFFD4"}},
   465  	{"1\xFF\u2000\xFF2\xFF \xFF", []string{"1\xFF", "\xFF2\xFF", "\xFF"}},
   466  	{faces, []string{faces}},
   467  }
   468  
   469  func TestFields(t *testing.T) {
   470  	for _, tt := range fieldstests {
   471  		a := Fields(tt.s)
   472  		if !eq(a, tt.a) {
   473  			t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
   474  			continue
   475  		}
   476  	}
   477  }
   478  
   479  var FieldsFuncTests = []FieldsTest{
   480  	{"", []string{}},
   481  	{"XX", []string{}},
   482  	{"XXhiXXX", []string{"hi"}},
   483  	{"aXXbXXXcX", []string{"a", "b", "c"}},
   484  }
   485  
   486  func TestFieldsFunc(t *testing.T) {
   487  	for _, tt := range fieldstests {
   488  		a := FieldsFunc(tt.s, unicode.IsSpace)
   489  		if !eq(a, tt.a) {
   490  			t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
   491  			continue
   492  		}
   493  	}
   494  	pred := func(c rune) bool { return c == 'X' }
   495  	for _, tt := range FieldsFuncTests {
   496  		a := FieldsFunc(tt.s, pred)
   497  		if !eq(a, tt.a) {
   498  			t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
   499  		}
   500  	}
   501  }
   502  
   503  // Test case for any function which accepts and returns a single string.
   504  type StringTest struct {
   505  	in, out string
   506  }
   507  
   508  // Execute f on each test case.  funcName should be the name of f; it's used
   509  // in failure reports.
   510  func runStringTests(t *testing.T, f func(string) string, funcName string, testCases []StringTest) {
   511  	for _, tc := range testCases {
   512  		actual := f(tc.in)
   513  		if actual != tc.out {
   514  			t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
   515  		}
   516  	}
   517  }
   518  
   519  var upperTests = []StringTest{
   520  	{"", ""},
   521  	{"abc", "ABC"},
   522  	{"AbC123", "ABC123"},
   523  	{"azAZ09_", "AZAZ09_"},
   524  	{"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char
   525  }
   526  
   527  var lowerTests = []StringTest{
   528  	{"", ""},
   529  	{"abc", "abc"},
   530  	{"AbC123", "abc123"},
   531  	{"azAZ09_", "azaz09_"},
   532  	{"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char
   533  }
   534  
   535  const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
   536  
   537  var trimSpaceTests = []StringTest{
   538  	{"", ""},
   539  	{"abc", "abc"},
   540  	{space + "abc" + space, "abc"},
   541  	{" ", ""},
   542  	{" \t\r\n \t\t\r\r\n\n ", ""},
   543  	{" \t\r\n x\t\t\r\r\n\n ", "x"},
   544  	{" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"},
   545  	{"1 \t\r\n2", "1 \t\r\n2"},
   546  	{" x\x80", "x\x80"},
   547  	{" x\xc0", "x\xc0"},
   548  	{"x \xc0\xc0 ", "x \xc0\xc0"},
   549  	{"x \xc0", "x \xc0"},
   550  	{"x \xc0 ", "x \xc0"},
   551  	{"x \xc0\xc0 ", "x \xc0\xc0"},
   552  	{"x ☺\xc0\xc0 ", "x ☺\xc0\xc0"},
   553  	{"x ☺ ", "x ☺"},
   554  }
   555  
   556  func tenRunes(ch rune) string {
   557  	r := make([]rune, 10)
   558  	for i := range r {
   559  		r[i] = ch
   560  	}
   561  	return string(r)
   562  }
   563  
   564  // User-defined self-inverse mapping function
   565  func rot13(r rune) rune {
   566  	step := rune(13)
   567  	if r >= 'a' && r <= 'z' {
   568  		return ((r - 'a' + step) % 26) + 'a'
   569  	}
   570  	if r >= 'A' && r <= 'Z' {
   571  		return ((r - 'A' + step) % 26) + 'A'
   572  	}
   573  	return r
   574  }
   575  
   576  func TestMap(t *testing.T) {
   577  	// Run a couple of awful growth/shrinkage tests
   578  	a := tenRunes('a')
   579  	// 1.  Grow. This triggers two reallocations in Map.
   580  	maxRune := func(rune) rune { return unicode.MaxRune }
   581  	m := Map(maxRune, a)
   582  	expect := tenRunes(unicode.MaxRune)
   583  	if m != expect {
   584  		t.Errorf("growing: expected %q got %q", expect, m)
   585  	}
   586  
   587  	// 2. Shrink
   588  	minRune := func(rune) rune { return 'a' }
   589  	m = Map(minRune, tenRunes(unicode.MaxRune))
   590  	expect = a
   591  	if m != expect {
   592  		t.Errorf("shrinking: expected %q got %q", expect, m)
   593  	}
   594  
   595  	// 3. Rot13
   596  	m = Map(rot13, "a to zed")
   597  	expect = "n gb mrq"
   598  	if m != expect {
   599  		t.Errorf("rot13: expected %q got %q", expect, m)
   600  	}
   601  
   602  	// 4. Rot13^2
   603  	m = Map(rot13, Map(rot13, "a to zed"))
   604  	expect = "a to zed"
   605  	if m != expect {
   606  		t.Errorf("rot13: expected %q got %q", expect, m)
   607  	}
   608  
   609  	// 5. Drop
   610  	dropNotLatin := func(r rune) rune {
   611  		if unicode.Is(unicode.Latin, r) {
   612  			return r
   613  		}
   614  		return -1
   615  	}
   616  	m = Map(dropNotLatin, "Hello, 세계")
   617  	expect = "Hello"
   618  	if m != expect {
   619  		t.Errorf("drop: expected %q got %q", expect, m)
   620  	}
   621  
   622  	// 6. Identity
   623  	identity := func(r rune) rune {
   624  		return r
   625  	}
   626  	orig := "Input string that we expect not to be copied."
   627  	m = Map(identity, orig)
   628  	if (*reflect.StringHeader)(unsafe.Pointer(&orig)).Data !=
   629  		(*reflect.StringHeader)(unsafe.Pointer(&m)).Data {
   630  		t.Error("unexpected copy during identity map")
   631  	}
   632  
   633  	// 7. Handle invalid UTF-8 sequence
   634  	replaceNotLatin := func(r rune) rune {
   635  		if unicode.Is(unicode.Latin, r) {
   636  			return r
   637  		}
   638  		return '?'
   639  	}
   640  	m = Map(replaceNotLatin, "Hello\255World")
   641  	expect = "Hello?World"
   642  	if m != expect {
   643  		t.Errorf("replace invalid sequence: expected %q got %q", expect, m)
   644  	}
   645  }
   646  
   647  func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
   648  
   649  func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
   650  
   651  func BenchmarkMapNoChanges(b *testing.B) {
   652  	identity := func(r rune) rune {
   653  		return r
   654  	}
   655  	for i := 0; i < b.N; i++ {
   656  		Map(identity, "Some string that won't be modified.")
   657  	}
   658  }
   659  
   660  func TestSpecialCase(t *testing.T) {
   661  	lower := "abcçdefgğhıijklmnoöprsştuüvyz"
   662  	upper := "ABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZ"
   663  	u := ToUpperSpecial(unicode.TurkishCase, upper)
   664  	if u != upper {
   665  		t.Errorf("Upper(upper) is %s not %s", u, upper)
   666  	}
   667  	u = ToUpperSpecial(unicode.TurkishCase, lower)
   668  	if u != upper {
   669  		t.Errorf("Upper(lower) is %s not %s", u, upper)
   670  	}
   671  	l := ToLowerSpecial(unicode.TurkishCase, lower)
   672  	if l != lower {
   673  		t.Errorf("Lower(lower) is %s not %s", l, lower)
   674  	}
   675  	l = ToLowerSpecial(unicode.TurkishCase, upper)
   676  	if l != lower {
   677  		t.Errorf("Lower(upper) is %s not %s", l, lower)
   678  	}
   679  }
   680  
   681  func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
   682  
   683  var trimTests = []struct {
   684  	f            string
   685  	in, arg, out string
   686  }{
   687  	{"Trim", "abba", "a", "bb"},
   688  	{"Trim", "abba", "ab", ""},
   689  	{"TrimLeft", "abba", "ab", ""},
   690  	{"TrimRight", "abba", "ab", ""},
   691  	{"TrimLeft", "abba", "a", "bba"},
   692  	{"TrimRight", "abba", "a", "abb"},
   693  	{"Trim", "<tag>", "<>", "tag"},
   694  	{"Trim", "* listitem", " *", "listitem"},
   695  	{"Trim", `"quote"`, `"`, "quote"},
   696  	{"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
   697  	{"Trim", "\x80test\xff", "\xff", "test"},
   698  	{"Trim", " Ġ ", " ", "Ġ"},
   699  	{"Trim", " Ġİ0", "0 ", "Ġİ"},
   700  	//empty string tests
   701  	{"Trim", "abba", "", "abba"},
   702  	{"Trim", "", "123", ""},
   703  	{"Trim", "", "", ""},
   704  	{"TrimLeft", "abba", "", "abba"},
   705  	{"TrimLeft", "", "123", ""},
   706  	{"TrimLeft", "", "", ""},
   707  	{"TrimRight", "abba", "", "abba"},
   708  	{"TrimRight", "", "123", ""},
   709  	{"TrimRight", "", "", ""},
   710  	{"TrimRight", "☺\xc0", "☺", "☺\xc0"},
   711  	{"TrimPrefix", "aabb", "a", "abb"},
   712  	{"TrimPrefix", "aabb", "b", "aabb"},
   713  	{"TrimSuffix", "aabb", "a", "aabb"},
   714  	{"TrimSuffix", "aabb", "b", "aab"},
   715  }
   716  
   717  func TestTrim(t *testing.T) {
   718  	for _, tc := range trimTests {
   719  		name := tc.f
   720  		var f func(string, string) string
   721  		switch name {
   722  		case "Trim":
   723  			f = Trim
   724  		case "TrimLeft":
   725  			f = TrimLeft
   726  		case "TrimRight":
   727  			f = TrimRight
   728  		case "TrimPrefix":
   729  			f = TrimPrefix
   730  		case "TrimSuffix":
   731  			f = TrimSuffix
   732  		default:
   733  			t.Errorf("Undefined trim function %s", name)
   734  		}
   735  		actual := f(tc.in, tc.arg)
   736  		if actual != tc.out {
   737  			t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
   738  		}
   739  	}
   740  }
   741  
   742  func BenchmarkTrim(b *testing.B) {
   743  	b.ReportAllocs()
   744  
   745  	for i := 0; i < b.N; i++ {
   746  		for _, tc := range trimTests {
   747  			name := tc.f
   748  			var f func(string, string) string
   749  			switch name {
   750  			case "Trim":
   751  				f = Trim
   752  			case "TrimLeft":
   753  				f = TrimLeft
   754  			case "TrimRight":
   755  				f = TrimRight
   756  			case "TrimPrefix":
   757  				f = TrimPrefix
   758  			case "TrimSuffix":
   759  				f = TrimSuffix
   760  			default:
   761  				b.Errorf("Undefined trim function %s", name)
   762  			}
   763  			actual := f(tc.in, tc.arg)
   764  			if actual != tc.out {
   765  				b.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
   766  			}
   767  		}
   768  	}
   769  }
   770  
   771  type predicate struct {
   772  	f    func(rune) bool
   773  	name string
   774  }
   775  
   776  var isSpace = predicate{unicode.IsSpace, "IsSpace"}
   777  var isDigit = predicate{unicode.IsDigit, "IsDigit"}
   778  var isUpper = predicate{unicode.IsUpper, "IsUpper"}
   779  var isValidRune = predicate{
   780  	func(r rune) bool {
   781  		return r != utf8.RuneError
   782  	},
   783  	"IsValidRune",
   784  }
   785  
   786  func not(p predicate) predicate {
   787  	return predicate{
   788  		func(r rune) bool {
   789  			return !p.f(r)
   790  		},
   791  		"not " + p.name,
   792  	}
   793  }
   794  
   795  var trimFuncTests = []struct {
   796  	f       predicate
   797  	in, out string
   798  }{
   799  	{isSpace, space + " hello " + space, "hello"},
   800  	{isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51", "hello"},
   801  	{isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", "hello"},
   802  	{not(isSpace), "hello" + space + "hello", space},
   803  	{not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo", "\u0e50\u0e521234\u0e50\u0e51"},
   804  	{isValidRune, "ab\xc0a\xc0cd", "\xc0a\xc0"},
   805  	{not(isValidRune), "\xc0a\xc0", "a"},
   806  }
   807  
   808  func TestTrimFunc(t *testing.T) {
   809  	for _, tc := range trimFuncTests {
   810  		actual := TrimFunc(tc.in, tc.f.f)
   811  		if actual != tc.out {
   812  			t.Errorf("TrimFunc(%q, %q) = %q; want %q", tc.in, tc.f.name, actual, tc.out)
   813  		}
   814  	}
   815  }
   816  
   817  var indexFuncTests = []struct {
   818  	in          string
   819  	f           predicate
   820  	first, last int
   821  }{
   822  	{"", isValidRune, -1, -1},
   823  	{"abc", isDigit, -1, -1},
   824  	{"0123", isDigit, 0, 3},
   825  	{"a1b", isDigit, 1, 1},
   826  	{space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes
   827  	{"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
   828  	{"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
   829  	{"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
   830  
   831  	// tests of invalid UTF-8
   832  	{"\x801", isDigit, 1, 1},
   833  	{"\x80abc", isDigit, -1, -1},
   834  	{"\xc0a\xc0", isValidRune, 1, 1},
   835  	{"\xc0a\xc0", not(isValidRune), 0, 2},
   836  	{"\xc0☺\xc0", not(isValidRune), 0, 4},
   837  	{"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
   838  	{"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
   839  	{"a\xe0\x80cd", not(isValidRune), 1, 2},
   840  	{"\x80\x80\x80\x80", not(isValidRune), 0, 3},
   841  }
   842  
   843  func TestIndexFunc(t *testing.T) {
   844  	for _, tc := range indexFuncTests {
   845  		first := IndexFunc(tc.in, tc.f.f)
   846  		if first != tc.first {
   847  			t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
   848  		}
   849  		last := LastIndexFunc(tc.in, tc.f.f)
   850  		if last != tc.last {
   851  			t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
   852  		}
   853  	}
   854  }
   855  
   856  func equal(m string, s1, s2 string, t *testing.T) bool {
   857  	if s1 == s2 {
   858  		return true
   859  	}
   860  	e1 := Split(s1, "")
   861  	e2 := Split(s2, "")
   862  	for i, c1 := range e1 {
   863  		if i >= len(e2) {
   864  			break
   865  		}
   866  		r1, _ := utf8.DecodeRuneInString(c1)
   867  		r2, _ := utf8.DecodeRuneInString(e2[i])
   868  		if r1 != r2 {
   869  			t.Errorf("%s diff at %d: U+%04X U+%04X", m, i, r1, r2)
   870  		}
   871  	}
   872  	return false
   873  }
   874  
   875  func TestCaseConsistency(t *testing.T) {
   876  	// Make a string of all the runes.
   877  	numRunes := int(unicode.MaxRune + 1)
   878  	if testing.Short() {
   879  		numRunes = 1000
   880  	}
   881  	a := make([]rune, numRunes)
   882  	for i := range a {
   883  		a[i] = rune(i)
   884  	}
   885  	s := string(a)
   886  	// convert the cases.
   887  	upper := ToUpper(s)
   888  	lower := ToLower(s)
   889  
   890  	// Consistency checks
   891  	if n := utf8.RuneCountInString(upper); n != numRunes {
   892  		t.Error("rune count wrong in upper:", n)
   893  	}
   894  	if n := utf8.RuneCountInString(lower); n != numRunes {
   895  		t.Error("rune count wrong in lower:", n)
   896  	}
   897  	if !equal("ToUpper(upper)", ToUpper(upper), upper, t) {
   898  		t.Error("ToUpper(upper) consistency fail")
   899  	}
   900  	if !equal("ToLower(lower)", ToLower(lower), lower, t) {
   901  		t.Error("ToLower(lower) consistency fail")
   902  	}
   903  	/*
   904  		  These fail because of non-one-to-oneness of the data, such as multiple
   905  		  upper case 'I' mapping to 'i'.  We comment them out but keep them for
   906  		  interest.
   907  		  For instance: CAPITAL LETTER I WITH DOT ABOVE:
   908  			unicode.ToUpper(unicode.ToLower('\u0130')) != '\u0130'
   909  
   910  		if !equal("ToUpper(lower)", ToUpper(lower), upper, t) {
   911  			t.Error("ToUpper(lower) consistency fail");
   912  		}
   913  		if !equal("ToLower(upper)", ToLower(upper), lower, t) {
   914  			t.Error("ToLower(upper) consistency fail");
   915  		}
   916  	*/
   917  }
   918  
   919  var RepeatTests = []struct {
   920  	in, out string
   921  	count   int
   922  }{
   923  	{"", "", 0},
   924  	{"", "", 1},
   925  	{"", "", 2},
   926  	{"-", "", 0},
   927  	{"-", "-", 1},
   928  	{"-", "----------", 10},
   929  	{"abc ", "abc abc abc ", 3},
   930  }
   931  
   932  func TestRepeat(t *testing.T) {
   933  	for _, tt := range RepeatTests {
   934  		a := Repeat(tt.in, tt.count)
   935  		if !equal("Repeat(s)", a, tt.out, t) {
   936  			t.Errorf("Repeat(%v, %d) = %v; want %v", tt.in, tt.count, a, tt.out)
   937  			continue
   938  		}
   939  	}
   940  }
   941  
   942  func repeat(s string, count int) (err error) {
   943  	defer func() {
   944  		if r := recover(); r != nil {
   945  			switch v := r.(type) {
   946  			case error:
   947  				err = v
   948  			default:
   949  				err = fmt.Errorf("%s", v)
   950  			}
   951  		}
   952  	}()
   953  
   954  	Repeat(s, count)
   955  
   956  	return
   957  }
   958  
   959  // See Issue golang.org/issue/16237
   960  func TestRepeatCatchesOverflow(t *testing.T) {
   961  	tests := [...]struct {
   962  		s      string
   963  		count  int
   964  		errStr string
   965  	}{
   966  		0: {"--", -2147483647, "negative"},
   967  		1: {"", int(^uint(0) >> 1), ""},
   968  		2: {"-", 10, ""},
   969  		3: {"gopher", 0, ""},
   970  		4: {"-", -1, "negative"},
   971  		5: {"--", -102, "negative"},
   972  		6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
   973  	}
   974  
   975  	for i, tt := range tests {
   976  		err := repeat(tt.s, tt.count)
   977  		if tt.errStr == "" {
   978  			if err != nil {
   979  				t.Errorf("#%d panicked %v", i, err)
   980  			}
   981  			continue
   982  		}
   983  
   984  		if err == nil || !Contains(err.Error(), tt.errStr) {
   985  			t.Errorf("#%d expected %q got %q", i, tt.errStr, err)
   986  		}
   987  	}
   988  }
   989  
   990  func runesEqual(a, b []rune) bool {
   991  	if len(a) != len(b) {
   992  		return false
   993  	}
   994  	for i, r := range a {
   995  		if r != b[i] {
   996  			return false
   997  		}
   998  	}
   999  	return true
  1000  }
  1001  
  1002  var RunesTests = []struct {
  1003  	in    string
  1004  	out   []rune
  1005  	lossy bool
  1006  }{
  1007  	{"", []rune{}, false},
  1008  	{" ", []rune{32}, false},
  1009  	{"ABC", []rune{65, 66, 67}, false},
  1010  	{"abc", []rune{97, 98, 99}, false},
  1011  	{"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
  1012  	{"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
  1013  	{"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
  1014  }
  1015  
  1016  func TestRunes(t *testing.T) {
  1017  	for _, tt := range RunesTests {
  1018  		a := []rune(tt.in)
  1019  		if !runesEqual(a, tt.out) {
  1020  			t.Errorf("[]rune(%q) = %v; want %v", tt.in, a, tt.out)
  1021  			continue
  1022  		}
  1023  		if !tt.lossy {
  1024  			// can only test reassembly if we didn't lose information
  1025  			s := string(a)
  1026  			if s != tt.in {
  1027  				t.Errorf("string([]rune(%q)) = %x; want %x", tt.in, s, tt.in)
  1028  			}
  1029  		}
  1030  	}
  1031  }
  1032  
  1033  func TestReadByte(t *testing.T) {
  1034  	testStrings := []string{"", abcd, faces, commas}
  1035  	for _, s := range testStrings {
  1036  		reader := NewReader(s)
  1037  		if e := reader.UnreadByte(); e == nil {
  1038  			t.Errorf("Unreading %q at beginning: expected error", s)
  1039  		}
  1040  		var res bytes.Buffer
  1041  		for {
  1042  			b, e := reader.ReadByte()
  1043  			if e == io.EOF {
  1044  				break
  1045  			}
  1046  			if e != nil {
  1047  				t.Errorf("Reading %q: %s", s, e)
  1048  				break
  1049  			}
  1050  			res.WriteByte(b)
  1051  			// unread and read again
  1052  			e = reader.UnreadByte()
  1053  			if e != nil {
  1054  				t.Errorf("Unreading %q: %s", s, e)
  1055  				break
  1056  			}
  1057  			b1, e := reader.ReadByte()
  1058  			if e != nil {
  1059  				t.Errorf("Reading %q after unreading: %s", s, e)
  1060  				break
  1061  			}
  1062  			if b1 != b {
  1063  				t.Errorf("Reading %q after unreading: want byte %q, got %q", s, b, b1)
  1064  				break
  1065  			}
  1066  		}
  1067  		if res.String() != s {
  1068  			t.Errorf("Reader(%q).ReadByte() produced %q", s, res.String())
  1069  		}
  1070  	}
  1071  }
  1072  
  1073  func TestReadRune(t *testing.T) {
  1074  	testStrings := []string{"", abcd, faces, commas}
  1075  	for _, s := range testStrings {
  1076  		reader := NewReader(s)
  1077  		if e := reader.UnreadRune(); e == nil {
  1078  			t.Errorf("Unreading %q at beginning: expected error", s)
  1079  		}
  1080  		res := ""
  1081  		for {
  1082  			r, z, e := reader.ReadRune()
  1083  			if e == io.EOF {
  1084  				break
  1085  			}
  1086  			if e != nil {
  1087  				t.Errorf("Reading %q: %s", s, e)
  1088  				break
  1089  			}
  1090  			res += string(r)
  1091  			// unread and read again
  1092  			e = reader.UnreadRune()
  1093  			if e != nil {
  1094  				t.Errorf("Unreading %q: %s", s, e)
  1095  				break
  1096  			}
  1097  			r1, z1, e := reader.ReadRune()
  1098  			if e != nil {
  1099  				t.Errorf("Reading %q after unreading: %s", s, e)
  1100  				break
  1101  			}
  1102  			if r1 != r {
  1103  				t.Errorf("Reading %q after unreading: want rune %q, got %q", s, r, r1)
  1104  				break
  1105  			}
  1106  			if z1 != z {
  1107  				t.Errorf("Reading %q after unreading: want size %d, got %d", s, z, z1)
  1108  				break
  1109  			}
  1110  		}
  1111  		if res != s {
  1112  			t.Errorf("Reader(%q).ReadRune() produced %q", s, res)
  1113  		}
  1114  	}
  1115  }
  1116  
  1117  var UnreadRuneErrorTests = []struct {
  1118  	name string
  1119  	f    func(*Reader)
  1120  }{
  1121  	{"Read", func(r *Reader) { r.Read([]byte{0}) }},
  1122  	{"ReadByte", func(r *Reader) { r.ReadByte() }},
  1123  	{"UnreadRune", func(r *Reader) { r.UnreadRune() }},
  1124  	{"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }},
  1125  	{"WriteTo", func(r *Reader) { r.WriteTo(&bytes.Buffer{}) }},
  1126  }
  1127  
  1128  func TestUnreadRuneError(t *testing.T) {
  1129  	for _, tt := range UnreadRuneErrorTests {
  1130  		reader := NewReader("0123456789")
  1131  		if _, _, err := reader.ReadRune(); err != nil {
  1132  			// should not happen
  1133  			t.Fatal(err)
  1134  		}
  1135  		tt.f(reader)
  1136  		err := reader.UnreadRune()
  1137  		if err == nil {
  1138  			t.Errorf("Unreading after %s: expected error", tt.name)
  1139  		}
  1140  	}
  1141  }
  1142  
  1143  var ReplaceTests = []struct {
  1144  	in       string
  1145  	old, new string
  1146  	n        int
  1147  	out      string
  1148  }{
  1149  	{"hello", "l", "L", 0, "hello"},
  1150  	{"hello", "l", "L", -1, "heLLo"},
  1151  	{"hello", "x", "X", -1, "hello"},
  1152  	{"", "x", "X", -1, ""},
  1153  	{"radar", "r", "<r>", -1, "<r>ada<r>"},
  1154  	{"", "", "<>", -1, "<>"},
  1155  	{"banana", "a", "<>", -1, "b<>n<>n<>"},
  1156  	{"banana", "a", "<>", 1, "b<>nana"},
  1157  	{"banana", "a", "<>", 1000, "b<>n<>n<>"},
  1158  	{"banana", "an", "<>", -1, "b<><>a"},
  1159  	{"banana", "ana", "<>", -1, "b<>na"},
  1160  	{"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
  1161  	{"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
  1162  	{"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
  1163  	{"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
  1164  	{"banana", "", "<>", 1, "<>banana"},
  1165  	{"banana", "a", "a", -1, "banana"},
  1166  	{"banana", "a", "a", 1, "banana"},
  1167  	{"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
  1168  }
  1169  
  1170  func TestReplace(t *testing.T) {
  1171  	for _, tt := range ReplaceTests {
  1172  		if s := Replace(tt.in, tt.old, tt.new, tt.n); s != tt.out {
  1173  			t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
  1174  		}
  1175  	}
  1176  }
  1177  
  1178  var TitleTests = []struct {
  1179  	in, out string
  1180  }{
  1181  	{"", ""},
  1182  	{"a", "A"},
  1183  	{" aaa aaa aaa ", " Aaa Aaa Aaa "},
  1184  	{" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
  1185  	{"123a456", "123a456"},
  1186  	{"double-blind", "Double-Blind"},
  1187  	{"ÿøû", "Ÿøû"},
  1188  	{"with_underscore", "With_underscore"},
  1189  	{"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
  1190  }
  1191  
  1192  func TestTitle(t *testing.T) {
  1193  	for _, tt := range TitleTests {
  1194  		if s := Title(tt.in); s != tt.out {
  1195  			t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
  1196  		}
  1197  	}
  1198  }
  1199  
  1200  var ContainsTests = []struct {
  1201  	str, substr string
  1202  	expected    bool
  1203  }{
  1204  	{"abc", "bc", true},
  1205  	{"abc", "bcd", false},
  1206  	{"abc", "", true},
  1207  	{"", "a", false},
  1208  
  1209  	// cases to cover code in runtime/asm_amd64.s:indexShortStr
  1210  	// 2-byte needle
  1211  	{"xxxxxx", "01", false},
  1212  	{"01xxxx", "01", true},
  1213  	{"xx01xx", "01", true},
  1214  	{"xxxx01", "01", true},
  1215  	{"01xxxxx"[1:], "01", false},
  1216  	{"xxxxx01"[:6], "01", false},
  1217  	// 3-byte needle
  1218  	{"xxxxxxx", "012", false},
  1219  	{"012xxxx", "012", true},
  1220  	{"xx012xx", "012", true},
  1221  	{"xxxx012", "012", true},
  1222  	{"012xxxxx"[1:], "012", false},
  1223  	{"xxxxx012"[:7], "012", false},
  1224  	// 4-byte needle
  1225  	{"xxxxxxxx", "0123", false},
  1226  	{"0123xxxx", "0123", true},
  1227  	{"xx0123xx", "0123", true},
  1228  	{"xxxx0123", "0123", true},
  1229  	{"0123xxxxx"[1:], "0123", false},
  1230  	{"xxxxx0123"[:8], "0123", false},
  1231  	// 5-7-byte needle
  1232  	{"xxxxxxxxx", "01234", false},
  1233  	{"01234xxxx", "01234", true},
  1234  	{"xx01234xx", "01234", true},
  1235  	{"xxxx01234", "01234", true},
  1236  	{"01234xxxxx"[1:], "01234", false},
  1237  	{"xxxxx01234"[:9], "01234", false},
  1238  	// 8-byte needle
  1239  	{"xxxxxxxxxxxx", "01234567", false},
  1240  	{"01234567xxxx", "01234567", true},
  1241  	{"xx01234567xx", "01234567", true},
  1242  	{"xxxx01234567", "01234567", true},
  1243  	{"01234567xxxxx"[1:], "01234567", false},
  1244  	{"xxxxx01234567"[:12], "01234567", false},
  1245  	// 9-15-byte needle
  1246  	{"xxxxxxxxxxxxx", "012345678", false},
  1247  	{"012345678xxxx", "012345678", true},
  1248  	{"xx012345678xx", "012345678", true},
  1249  	{"xxxx012345678", "012345678", true},
  1250  	{"012345678xxxxx"[1:], "012345678", false},
  1251  	{"xxxxx012345678"[:13], "012345678", false},
  1252  	// 16-byte needle
  1253  	{"xxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEF", false},
  1254  	{"0123456789ABCDEFxxxx", "0123456789ABCDEF", true},
  1255  	{"xx0123456789ABCDEFxx", "0123456789ABCDEF", true},
  1256  	{"xxxx0123456789ABCDEF", "0123456789ABCDEF", true},
  1257  	{"0123456789ABCDEFxxxxx"[1:], "0123456789ABCDEF", false},
  1258  	{"xxxxx0123456789ABCDEF"[:20], "0123456789ABCDEF", false},
  1259  	// 17-31-byte needle
  1260  	{"xxxxxxxxxxxxxxxxxxxxx", "0123456789ABCDEFG", false},
  1261  	{"0123456789ABCDEFGxxxx", "0123456789ABCDEFG", true},
  1262  	{"xx0123456789ABCDEFGxx", "0123456789ABCDEFG", true},
  1263  	{"xxxx0123456789ABCDEFG", "0123456789ABCDEFG", true},
  1264  	{"0123456789ABCDEFGxxxxx"[1:], "0123456789ABCDEFG", false},
  1265  	{"xxxxx0123456789ABCDEFG"[:21], "0123456789ABCDEFG", false},
  1266  
  1267  	// partial match cases
  1268  	{"xx01x", "012", false},                             // 3
  1269  	{"xx0123x", "01234", false},                         // 5-7
  1270  	{"xx01234567x", "012345678", false},                 // 9-15
  1271  	{"xx0123456789ABCDEFx", "0123456789ABCDEFG", false}, // 17-31, issue 15679
  1272  }
  1273  
  1274  func TestContains(t *testing.T) {
  1275  	for _, ct := range ContainsTests {
  1276  		if Contains(ct.str, ct.substr) != ct.expected {
  1277  			t.Errorf("Contains(%s, %s) = %v, want %v",
  1278  				ct.str, ct.substr, !ct.expected, ct.expected)
  1279  		}
  1280  	}
  1281  }
  1282  
  1283  var ContainsAnyTests = []struct {
  1284  	str, substr string
  1285  	expected    bool
  1286  }{
  1287  	{"", "", false},
  1288  	{"", "a", false},
  1289  	{"", "abc", false},
  1290  	{"a", "", false},
  1291  	{"a", "a", true},
  1292  	{"aaa", "a", true},
  1293  	{"abc", "xyz", false},
  1294  	{"abc", "xcz", true},
  1295  	{"a☺b☻c☹d", "uvw☻xyz", true},
  1296  	{"aRegExp*", ".(|)*+?^$[]", true},
  1297  	{dots + dots + dots, " ", false},
  1298  }
  1299  
  1300  func TestContainsAny(t *testing.T) {
  1301  	for _, ct := range ContainsAnyTests {
  1302  		if ContainsAny(ct.str, ct.substr) != ct.expected {
  1303  			t.Errorf("ContainsAny(%s, %s) = %v, want %v",
  1304  				ct.str, ct.substr, !ct.expected, ct.expected)
  1305  		}
  1306  	}
  1307  }
  1308  
  1309  var ContainsRuneTests = []struct {
  1310  	str      string
  1311  	r        rune
  1312  	expected bool
  1313  }{
  1314  	{"", 'a', false},
  1315  	{"a", 'a', true},
  1316  	{"aaa", 'a', true},
  1317  	{"abc", 'y', false},
  1318  	{"abc", 'c', true},
  1319  	{"a☺b☻c☹d", 'x', false},
  1320  	{"a☺b☻c☹d", '☻', true},
  1321  	{"aRegExp*", '*', true},
  1322  }
  1323  
  1324  func TestContainsRune(t *testing.T) {
  1325  	for _, ct := range ContainsRuneTests {
  1326  		if ContainsRune(ct.str, ct.r) != ct.expected {
  1327  			t.Errorf("ContainsRune(%q, %q) = %v, want %v",
  1328  				ct.str, ct.r, !ct.expected, ct.expected)
  1329  		}
  1330  	}
  1331  }
  1332  
  1333  var EqualFoldTests = []struct {
  1334  	s, t string
  1335  	out  bool
  1336  }{
  1337  	{"abc", "abc", true},
  1338  	{"ABcd", "ABcd", true},
  1339  	{"123abc", "123ABC", true},
  1340  	{"αβδ", "ΑΒΔ", true},
  1341  	{"abc", "xyz", false},
  1342  	{"abc", "XYZ", false},
  1343  	{"abcdefghijk", "abcdefghijX", false},
  1344  	{"abcdefghijk", "abcdefghij\u212A", true},
  1345  	{"abcdefghijK", "abcdefghij\u212A", true},
  1346  	{"abcdefghijkz", "abcdefghij\u212Ay", false},
  1347  	{"abcdefghijKz", "abcdefghij\u212Ay", false},
  1348  }
  1349  
  1350  func TestEqualFold(t *testing.T) {
  1351  	for _, tt := range EqualFoldTests {
  1352  		if out := EqualFold(tt.s, tt.t); out != tt.out {
  1353  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
  1354  		}
  1355  		if out := EqualFold(tt.t, tt.s); out != tt.out {
  1356  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
  1357  		}
  1358  	}
  1359  }
  1360  
  1361  var CountTests = []struct {
  1362  	s, sep string
  1363  	num    int
  1364  }{
  1365  	{"", "", 1},
  1366  	{"", "notempty", 0},
  1367  	{"notempty", "", 9},
  1368  	{"smaller", "not smaller", 0},
  1369  	{"12345678987654321", "6", 2},
  1370  	{"611161116", "6", 3},
  1371  	{"notequal", "NotEqual", 0},
  1372  	{"equal", "equal", 1},
  1373  	{"abc1231231123q", "123", 3},
  1374  	{"11111", "11", 2},
  1375  }
  1376  
  1377  func TestCount(t *testing.T) {
  1378  	for _, tt := range CountTests {
  1379  		if num := Count(tt.s, tt.sep); num != tt.num {
  1380  			t.Errorf("Count(\"%s\", \"%s\") = %d, want %d", tt.s, tt.sep, num, tt.num)
  1381  		}
  1382  	}
  1383  }
  1384  
  1385  func makeBenchInputHard() string {
  1386  	tokens := [...]string{
  1387  		"<a>", "<p>", "<b>", "<strong>",
  1388  		"</a>", "</p>", "</b>", "</strong>",
  1389  		"hello", "world",
  1390  	}
  1391  	x := make([]byte, 0, 1<<20)
  1392  	for {
  1393  		i := rand.Intn(len(tokens))
  1394  		if len(x)+len(tokens[i]) >= 1<<20 {
  1395  			break
  1396  		}
  1397  		x = append(x, tokens[i]...)
  1398  	}
  1399  	return string(x)
  1400  }
  1401  
  1402  var benchInputHard = makeBenchInputHard()
  1403  
  1404  func benchmarkIndexHard(b *testing.B, sep string) {
  1405  	for i := 0; i < b.N; i++ {
  1406  		Index(benchInputHard, sep)
  1407  	}
  1408  }
  1409  
  1410  func benchmarkLastIndexHard(b *testing.B, sep string) {
  1411  	for i := 0; i < b.N; i++ {
  1412  		LastIndex(benchInputHard, sep)
  1413  	}
  1414  }
  1415  
  1416  func benchmarkCountHard(b *testing.B, sep string) {
  1417  	for i := 0; i < b.N; i++ {
  1418  		Count(benchInputHard, sep)
  1419  	}
  1420  }
  1421  
  1422  func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") }
  1423  func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") }
  1424  func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") }
  1425  func BenchmarkIndexHard4(b *testing.B) {
  1426  	benchmarkIndexHard(b, "<pre><b>hello</b><strong>world</strong></pre>")
  1427  }
  1428  
  1429  func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") }
  1430  func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") }
  1431  func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") }
  1432  
  1433  func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, "<>") }
  1434  func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, "</pre>") }
  1435  func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, "<b>hello world</b>") }
  1436  
  1437  var benchInputTorture = Repeat("ABC", 1<<10) + "123" + Repeat("ABC", 1<<10)
  1438  var benchNeedleTorture = Repeat("ABC", 1<<10+1)
  1439  
  1440  func BenchmarkIndexTorture(b *testing.B) {
  1441  	for i := 0; i < b.N; i++ {
  1442  		Index(benchInputTorture, benchNeedleTorture)
  1443  	}
  1444  }
  1445  
  1446  func BenchmarkCountTorture(b *testing.B) {
  1447  	for i := 0; i < b.N; i++ {
  1448  		Count(benchInputTorture, benchNeedleTorture)
  1449  	}
  1450  }
  1451  
  1452  func BenchmarkCountTortureOverlapping(b *testing.B) {
  1453  	A := Repeat("ABC", 1<<20)
  1454  	B := Repeat("ABC", 1<<10)
  1455  	for i := 0; i < b.N; i++ {
  1456  		Count(A, B)
  1457  	}
  1458  }
  1459  
  1460  func BenchmarkCountByte(b *testing.B) {
  1461  	indexSizes := []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
  1462  	benchStr := Repeat(benchmarkString,
  1463  		(indexSizes[len(indexSizes)-1]+len(benchmarkString)-1)/len(benchmarkString))
  1464  	benchFunc := func(b *testing.B, benchStr string) {
  1465  		b.SetBytes(int64(len(benchStr)))
  1466  		for i := 0; i < b.N; i++ {
  1467  			Count(benchStr, "=")
  1468  		}
  1469  	}
  1470  	for _, size := range indexSizes {
  1471  		b.Run(fmt.Sprintf("%d", size), func(b *testing.B) {
  1472  			benchFunc(b, benchStr[:size])
  1473  		})
  1474  	}
  1475  
  1476  }
  1477  
  1478  var makeFieldsInput = func() string {
  1479  	x := make([]byte, 1<<20)
  1480  	// Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.
  1481  	for i := range x {
  1482  		switch rand.Intn(10) {
  1483  		case 0:
  1484  			x[i] = ' '
  1485  		case 1:
  1486  			if i > 0 && x[i-1] == 'x' {
  1487  				copy(x[i-1:], "χ")
  1488  				break
  1489  			}
  1490  			fallthrough
  1491  		default:
  1492  			x[i] = 'x'
  1493  		}
  1494  	}
  1495  	return string(x)
  1496  }
  1497  
  1498  var makeFieldsInputASCII = func() string {
  1499  	x := make([]byte, 1<<20)
  1500  	// Input is ~10% space, rest ASCII non-space.
  1501  	for i := range x {
  1502  		if rand.Intn(10) == 0 {
  1503  			x[i] = ' '
  1504  		} else {
  1505  			x[i] = 'x'
  1506  		}
  1507  	}
  1508  	return string(x)
  1509  }
  1510  
  1511  var stringdata = []struct{ name, data string }{
  1512  	{"ASCII", makeFieldsInputASCII()},
  1513  	{"Mixed", makeFieldsInput()},
  1514  }
  1515  
  1516  func BenchmarkFields(b *testing.B) {
  1517  	for _, sd := range stringdata {
  1518  		b.Run(sd.name, func(b *testing.B) {
  1519  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1520  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1521  					b.ReportAllocs()
  1522  					b.SetBytes(int64(j))
  1523  					data := sd.data[:j]
  1524  					for i := 0; i < b.N; i++ {
  1525  						Fields(data)
  1526  					}
  1527  				})
  1528  			}
  1529  		})
  1530  	}
  1531  }
  1532  
  1533  func BenchmarkFieldsFunc(b *testing.B) {
  1534  	for _, sd := range stringdata {
  1535  		b.Run(sd.name, func(b *testing.B) {
  1536  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1537  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1538  					b.ReportAllocs()
  1539  					b.SetBytes(int64(j))
  1540  					data := sd.data[:j]
  1541  					for i := 0; i < b.N; i++ {
  1542  						FieldsFunc(data, unicode.IsSpace)
  1543  					}
  1544  				})
  1545  			}
  1546  		})
  1547  	}
  1548  }
  1549  
  1550  func BenchmarkSplitEmptySeparator(b *testing.B) {
  1551  	for i := 0; i < b.N; i++ {
  1552  		Split(benchInputHard, "")
  1553  	}
  1554  }
  1555  
  1556  func BenchmarkSplitSingleByteSeparator(b *testing.B) {
  1557  	for i := 0; i < b.N; i++ {
  1558  		Split(benchInputHard, "/")
  1559  	}
  1560  }
  1561  
  1562  func BenchmarkSplitMultiByteSeparator(b *testing.B) {
  1563  	for i := 0; i < b.N; i++ {
  1564  		Split(benchInputHard, "hello")
  1565  	}
  1566  }
  1567  
  1568  func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
  1569  	for i := 0; i < b.N; i++ {
  1570  		SplitN(benchInputHard, "/", 10)
  1571  	}
  1572  }
  1573  
  1574  func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
  1575  	for i := 0; i < b.N; i++ {
  1576  		SplitN(benchInputHard, "hello", 10)
  1577  	}
  1578  }
  1579  
  1580  func BenchmarkRepeat(b *testing.B) {
  1581  	for i := 0; i < b.N; i++ {
  1582  		Repeat("-", 80)
  1583  	}
  1584  }
  1585  
  1586  func BenchmarkIndexAnyASCII(b *testing.B) {
  1587  	x := Repeat("#", 4096) // Never matches set
  1588  	cs := "0123456789abcdef"
  1589  	for k := 1; k <= 4096; k <<= 4 {
  1590  		for j := 1; j <= 16; j <<= 1 {
  1591  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1592  				for i := 0; i < b.N; i++ {
  1593  					IndexAny(x[:k], cs[:j])
  1594  				}
  1595  			})
  1596  		}
  1597  	}
  1598  }
  1599  
  1600  func BenchmarkTrimASCII(b *testing.B) {
  1601  	cs := "0123456789abcdef"
  1602  	for k := 1; k <= 4096; k <<= 4 {
  1603  		for j := 1; j <= 16; j <<= 1 {
  1604  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  1605  				x := Repeat(cs[:j], k) // Always matches set
  1606  				for i := 0; i < b.N; i++ {
  1607  					Trim(x[:k], cs[:j])
  1608  				}
  1609  			})
  1610  		}
  1611  	}
  1612  }