github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/bytes/bytes_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 bytes_test
     6  
     7  import (
     8  	. "bytes"
     9  	"fmt"
    10  	"internal/testenv"
    11  	"math"
    12  	"math/rand"
    13  	"reflect"
    14  	"strings"
    15  	"testing"
    16  	"unicode"
    17  	"unicode/utf8"
    18  	"unsafe"
    19  )
    20  
    21  func eq(a, b []string) bool {
    22  	if len(a) != len(b) {
    23  		return false
    24  	}
    25  	for i := 0; i < len(a); i++ {
    26  		if a[i] != b[i] {
    27  			return false
    28  		}
    29  	}
    30  	return true
    31  }
    32  
    33  func sliceOfString(s [][]byte) []string {
    34  	result := make([]string, len(s))
    35  	for i, v := range s {
    36  		result[i] = string(v)
    37  	}
    38  	return result
    39  }
    40  
    41  // For ease of reading, the test cases use strings that are converted to byte
    42  // slices before invoking the functions.
    43  
    44  var abcd = "abcd"
    45  var faces = "☺☻☹"
    46  var commas = "1,2,3,4"
    47  var dots = "1....2....3....4"
    48  
    49  type BinOpTest struct {
    50  	a string
    51  	b string
    52  	i int
    53  }
    54  
    55  func TestEqual(t *testing.T) {
    56  	// Run the tests and check for allocation at the same time.
    57  	allocs := testing.AllocsPerRun(10, func() {
    58  		for _, tt := range compareTests {
    59  			eql := Equal(tt.a, tt.b)
    60  			if eql != (tt.i == 0) {
    61  				t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql)
    62  			}
    63  		}
    64  	})
    65  	if allocs > 0 {
    66  		t.Errorf("Equal allocated %v times", allocs)
    67  	}
    68  }
    69  
    70  func TestEqualExhaustive(t *testing.T) {
    71  	var size = 128
    72  	if testing.Short() {
    73  		size = 32
    74  	}
    75  	a := make([]byte, size)
    76  	b := make([]byte, size)
    77  	b_init := make([]byte, size)
    78  	// randomish but deterministic data
    79  	for i := 0; i < size; i++ {
    80  		a[i] = byte(17 * i)
    81  		b_init[i] = byte(23*i + 100)
    82  	}
    83  
    84  	for len := 0; len <= size; len++ {
    85  		for x := 0; x <= size-len; x++ {
    86  			for y := 0; y <= size-len; y++ {
    87  				copy(b, b_init)
    88  				copy(b[y:y+len], a[x:x+len])
    89  				if !Equal(a[x:x+len], b[y:y+len]) || !Equal(b[y:y+len], a[x:x+len]) {
    90  					t.Errorf("Equal(%d, %d, %d) = false", len, x, y)
    91  				}
    92  			}
    93  		}
    94  	}
    95  }
    96  
    97  // make sure Equal returns false for minimally different strings. The data
    98  // is all zeros except for a single one in one location.
    99  func TestNotEqual(t *testing.T) {
   100  	var size = 128
   101  	if testing.Short() {
   102  		size = 32
   103  	}
   104  	a := make([]byte, size)
   105  	b := make([]byte, size)
   106  
   107  	for len := 0; len <= size; len++ {
   108  		for x := 0; x <= size-len; x++ {
   109  			for y := 0; y <= size-len; y++ {
   110  				for diffpos := x; diffpos < x+len; diffpos++ {
   111  					a[diffpos] = 1
   112  					if Equal(a[x:x+len], b[y:y+len]) || Equal(b[y:y+len], a[x:x+len]) {
   113  						t.Errorf("NotEqual(%d, %d, %d, %d) = true", len, x, y, diffpos)
   114  					}
   115  					a[diffpos] = 0
   116  				}
   117  			}
   118  		}
   119  	}
   120  }
   121  
   122  var indexTests = []BinOpTest{
   123  	{"", "", 0},
   124  	{"", "a", -1},
   125  	{"", "foo", -1},
   126  	{"fo", "foo", -1},
   127  	{"foo", "baz", -1},
   128  	{"foo", "foo", 0},
   129  	{"oofofoofooo", "f", 2},
   130  	{"oofofoofooo", "foo", 4},
   131  	{"barfoobarfoo", "foo", 3},
   132  	{"foo", "", 0},
   133  	{"foo", "o", 1},
   134  	{"abcABCabc", "A", 3},
   135  	// cases with one byte strings - test IndexByte and special case in Index()
   136  	{"", "a", -1},
   137  	{"x", "a", -1},
   138  	{"x", "x", 0},
   139  	{"abc", "a", 0},
   140  	{"abc", "b", 1},
   141  	{"abc", "c", 2},
   142  	{"abc", "x", -1},
   143  	{"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33},
   144  	{"fofofofooofoboo", "oo", 7},
   145  	{"fofofofofofoboo", "ob", 11},
   146  	{"fofofofofofoboo", "boo", 12},
   147  	{"fofofofofofoboo", "oboo", 11},
   148  	{"fofofofofoooboo", "fooo", 8},
   149  	{"fofofofofofoboo", "foboo", 10},
   150  	{"fofofofofofoboo", "fofob", 8},
   151  	{"fofofofofofofoffofoobarfoo", "foffof", 12},
   152  	{"fofofofofoofofoffofoobarfoo", "foffof", 13},
   153  	{"fofofofofofofoffofoobarfoo", "foffofo", 12},
   154  	{"fofofofofoofofoffofoobarfoo", "foffofo", 13},
   155  	{"fofofofofoofofoffofoobarfoo", "foffofoo", 13},
   156  	{"fofofofofofofoffofoobarfoo", "foffofoo", 12},
   157  	{"fofofofofoofofoffofoobarfoo", "foffofoob", 13},
   158  	{"fofofofofofofoffofoobarfoo", "foffofoob", 12},
   159  	{"fofofofofoofofoffofoobarfoo", "foffofooba", 13},
   160  	{"fofofofofofofoffofoobarfoo", "foffofooba", 12},
   161  	{"fofofofofoofofoffofoobarfoo", "foffofoobar", 13},
   162  	{"fofofofofofofoffofoobarfoo", "foffofoobar", 12},
   163  	{"fofofofofoofofoffofoobarfoo", "foffofoobarf", 13},
   164  	{"fofofofofofofoffofoobarfoo", "foffofoobarf", 12},
   165  	{"fofofofofoofofoffofoobarfoo", "foffofoobarfo", 13},
   166  	{"fofofofofofofoffofoobarfoo", "foffofoobarfo", 12},
   167  	{"fofofofofoofofoffofoobarfoo", "foffofoobarfoo", 13},
   168  	{"fofofofofofofoffofoobarfoo", "foffofoobarfoo", 12},
   169  	{"fofofofofoofofoffofoobarfoo", "ofoffofoobarfoo", 12},
   170  	{"fofofofofofofoffofoobarfoo", "ofoffofoobarfoo", 11},
   171  	{"fofofofofoofofoffofoobarfoo", "fofoffofoobarfoo", 11},
   172  	{"fofofofofofofoffofoobarfoo", "fofoffofoobarfoo", 10},
   173  	{"fofofofofoofofoffofoobarfoo", "foobars", -1},
   174  	{"foofyfoobarfoobar", "y", 4},
   175  	{"oooooooooooooooooooooo", "r", -1},
   176  	{"oxoxoxoxoxoxoxoxoxoxoxoy", "oy", 22},
   177  	{"oxoxoxoxoxoxoxoxoxoxoxox", "oy", -1},
   178  	// test fallback to Rabin-Karp.
   179  	{"000000000000000000000000000000000000000000000000000000000000000000000001", "0000000000000000000000000000000000000000000000000000000000000000001", 5},
   180  }
   181  
   182  var lastIndexTests = []BinOpTest{
   183  	{"", "", 0},
   184  	{"", "a", -1},
   185  	{"", "foo", -1},
   186  	{"fo", "foo", -1},
   187  	{"foo", "foo", 0},
   188  	{"foo", "f", 0},
   189  	{"oofofoofooo", "f", 7},
   190  	{"oofofoofooo", "foo", 7},
   191  	{"barfoobarfoo", "foo", 9},
   192  	{"foo", "", 3},
   193  	{"foo", "o", 2},
   194  	{"abcABCabc", "A", 3},
   195  	{"abcABCabc", "a", 6},
   196  }
   197  
   198  var indexAnyTests = []BinOpTest{
   199  	{"", "", -1},
   200  	{"", "a", -1},
   201  	{"", "abc", -1},
   202  	{"a", "", -1},
   203  	{"a", "a", 0},
   204  	{"\x80", "\xffb", 0},
   205  	{"aaa", "a", 0},
   206  	{"abc", "xyz", -1},
   207  	{"abc", "xcz", 2},
   208  	{"ab☺c", "x☺yz", 2},
   209  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   210  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   211  	{"aRegExp*", ".(|)*+?^$[]", 7},
   212  	{dots + dots + dots, " ", -1},
   213  	{"012abcba210", "\xffb", 4},
   214  	{"012\x80bcb\x80210", "\xffb", 3},
   215  	{"0123456\xcf\x80abc", "\xcfb\x80", 10},
   216  }
   217  
   218  var lastIndexAnyTests = []BinOpTest{
   219  	{"", "", -1},
   220  	{"", "a", -1},
   221  	{"", "abc", -1},
   222  	{"a", "", -1},
   223  	{"a", "a", 0},
   224  	{"\x80", "\xffb", 0},
   225  	{"aaa", "a", 2},
   226  	{"abc", "xyz", -1},
   227  	{"abc", "ab", 1},
   228  	{"ab☺c", "x☺yz", 2},
   229  	{"a☺b☻c☹d", "cx", len("a☺b☻")},
   230  	{"a☺b☻c☹d", "uvw☻xyz", len("a☺b")},
   231  	{"a.RegExp*", ".(|)*+?^$[]", 8},
   232  	{dots + dots + dots, " ", -1},
   233  	{"012abcba210", "\xffb", 6},
   234  	{"012\x80bcb\x80210", "\xffb", 7},
   235  	{"0123456\xcf\x80abc", "\xcfb\x80", 10},
   236  }
   237  
   238  // Execute f on each test case.  funcName should be the name of f; it's used
   239  // in failure reports.
   240  func runIndexTests(t *testing.T, f func(s, sep []byte) int, funcName string, testCases []BinOpTest) {
   241  	for _, test := range testCases {
   242  		a := []byte(test.a)
   243  		b := []byte(test.b)
   244  		actual := f(a, b)
   245  		if actual != test.i {
   246  			t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, b, actual, test.i)
   247  		}
   248  	}
   249  	var allocTests = []struct {
   250  		a []byte
   251  		b []byte
   252  		i int
   253  	}{
   254  		// case for function Index.
   255  		{[]byte("000000000000000000000000000000000000000000000000000000000000000000000001"), []byte("0000000000000000000000000000000000000000000000000000000000000000001"), 5},
   256  		// case for function LastIndex.
   257  		{[]byte("000000000000000000000000000000000000000000000000000000000000000010000"), []byte("00000000000000000000000000000000000000000000000000000000000001"), 3},
   258  	}
   259  	allocs := testing.AllocsPerRun(100, func() {
   260  		if i := Index(allocTests[1].a, allocTests[1].b); i != allocTests[1].i {
   261  			t.Errorf("Index([]byte(%q), []byte(%q)) = %v; want %v", allocTests[1].a, allocTests[1].b, i, allocTests[1].i)
   262  		}
   263  		if i := LastIndex(allocTests[0].a, allocTests[0].b); i != allocTests[0].i {
   264  			t.Errorf("LastIndex([]byte(%q), []byte(%q)) = %v; want %v", allocTests[0].a, allocTests[0].b, i, allocTests[0].i)
   265  		}
   266  	})
   267  	if allocs != 0 {
   268  		t.Errorf("expected no allocations, got %f", allocs)
   269  	}
   270  }
   271  
   272  func runIndexAnyTests(t *testing.T, f func(s []byte, chars string) int, funcName string, testCases []BinOpTest) {
   273  	for _, test := range testCases {
   274  		a := []byte(test.a)
   275  		actual := f(a, test.b)
   276  		if actual != test.i {
   277  			t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, test.b, actual, test.i)
   278  		}
   279  	}
   280  }
   281  
   282  func TestIndex(t *testing.T)     { runIndexTests(t, Index, "Index", indexTests) }
   283  func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) }
   284  func TestIndexAny(t *testing.T)  { runIndexAnyTests(t, IndexAny, "IndexAny", indexAnyTests) }
   285  func TestLastIndexAny(t *testing.T) {
   286  	runIndexAnyTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests)
   287  }
   288  
   289  func TestIndexByte(t *testing.T) {
   290  	for _, tt := range indexTests {
   291  		if len(tt.b) != 1 {
   292  			continue
   293  		}
   294  		a := []byte(tt.a)
   295  		b := tt.b[0]
   296  		pos := IndexByte(a, b)
   297  		if pos != tt.i {
   298  			t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos)
   299  		}
   300  		posp := IndexBytePortable(a, b)
   301  		if posp != tt.i {
   302  			t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp)
   303  		}
   304  	}
   305  }
   306  
   307  func TestLastIndexByte(t *testing.T) {
   308  	testCases := []BinOpTest{
   309  		{"", "q", -1},
   310  		{"abcdef", "q", -1},
   311  		{"abcdefabcdef", "a", len("abcdef")},      // something in the middle
   312  		{"abcdefabcdef", "f", len("abcdefabcde")}, // last byte
   313  		{"zabcdefabcdef", "z", 0},                 // first byte
   314  		{"a☺b☻c☹d", "b", len("a☺")},               // non-ascii
   315  	}
   316  	for _, test := range testCases {
   317  		actual := LastIndexByte([]byte(test.a), test.b[0])
   318  		if actual != test.i {
   319  			t.Errorf("LastIndexByte(%q,%c) = %v; want %v", test.a, test.b[0], actual, test.i)
   320  		}
   321  	}
   322  }
   323  
   324  // test a larger buffer with different sizes and alignments
   325  func TestIndexByteBig(t *testing.T) {
   326  	var n = 1024
   327  	if testing.Short() {
   328  		n = 128
   329  	}
   330  	b := make([]byte, n)
   331  	for i := 0; i < n; i++ {
   332  		// different start alignments
   333  		b1 := b[i:]
   334  		for j := 0; j < len(b1); j++ {
   335  			b1[j] = 'x'
   336  			pos := IndexByte(b1, 'x')
   337  			if pos != j {
   338  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   339  			}
   340  			b1[j] = 0
   341  			pos = IndexByte(b1, 'x')
   342  			if pos != -1 {
   343  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   344  			}
   345  		}
   346  		// different end alignments
   347  		b1 = b[:i]
   348  		for j := 0; j < len(b1); j++ {
   349  			b1[j] = 'x'
   350  			pos := IndexByte(b1, 'x')
   351  			if pos != j {
   352  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   353  			}
   354  			b1[j] = 0
   355  			pos = IndexByte(b1, 'x')
   356  			if pos != -1 {
   357  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   358  			}
   359  		}
   360  		// different start and end alignments
   361  		b1 = b[i/2 : n-(i+1)/2]
   362  		for j := 0; j < len(b1); j++ {
   363  			b1[j] = 'x'
   364  			pos := IndexByte(b1, 'x')
   365  			if pos != j {
   366  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   367  			}
   368  			b1[j] = 0
   369  			pos = IndexByte(b1, 'x')
   370  			if pos != -1 {
   371  				t.Errorf("IndexByte(%q, 'x') = %v", b1, pos)
   372  			}
   373  		}
   374  	}
   375  }
   376  
   377  // test a small index across all page offsets
   378  func TestIndexByteSmall(t *testing.T) {
   379  	b := make([]byte, 5015) // bigger than a page
   380  	// Make sure we find the correct byte even when straddling a page.
   381  	for i := 0; i <= len(b)-15; i++ {
   382  		for j := 0; j < 15; j++ {
   383  			b[i+j] = byte(100 + j)
   384  		}
   385  		for j := 0; j < 15; j++ {
   386  			p := IndexByte(b[i:i+15], byte(100+j))
   387  			if p != j {
   388  				t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 100+j, p)
   389  			}
   390  		}
   391  		for j := 0; j < 15; j++ {
   392  			b[i+j] = 0
   393  		}
   394  	}
   395  	// Make sure matches outside the slice never trigger.
   396  	for i := 0; i <= len(b)-15; i++ {
   397  		for j := 0; j < 15; j++ {
   398  			b[i+j] = 1
   399  		}
   400  		for j := 0; j < 15; j++ {
   401  			p := IndexByte(b[i:i+15], byte(0))
   402  			if p != -1 {
   403  				t.Errorf("IndexByte(%q, %d) = %d", b[i:i+15], 0, p)
   404  			}
   405  		}
   406  		for j := 0; j < 15; j++ {
   407  			b[i+j] = 0
   408  		}
   409  	}
   410  }
   411  
   412  func TestIndexRune(t *testing.T) {
   413  	tests := []struct {
   414  		in   string
   415  		rune rune
   416  		want int
   417  	}{
   418  		{"", 'a', -1},
   419  		{"", '☺', -1},
   420  		{"foo", '☹', -1},
   421  		{"foo", 'o', 1},
   422  		{"foo☺bar", '☺', 3},
   423  		{"foo☺☻☹bar", '☹', 9},
   424  		{"a A x", 'A', 2},
   425  		{"some_text=some_value", '=', 9},
   426  		{"☺a", 'a', 3},
   427  		{"a☻☺b", '☺', 4},
   428  
   429  		// RuneError should match any invalid UTF-8 byte sequence.
   430  		{"�", '�', 0},
   431  		{"\xff", '�', 0},
   432  		{"☻x�", '�', len("☻x")},
   433  		{"☻x\xe2\x98", '�', len("☻x")},
   434  		{"☻x\xe2\x98�", '�', len("☻x")},
   435  		{"☻x\xe2\x98x", '�', len("☻x")},
   436  
   437  		// Invalid rune values should never match.
   438  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", -1, -1},
   439  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", 0xD800, -1}, // Surrogate pair
   440  		{"a☺b☻c☹d\xe2\x98�\xff�\xed\xa0\x80", utf8.MaxRune + 1, -1},
   441  	}
   442  	for _, tt := range tests {
   443  		if got := IndexRune([]byte(tt.in), tt.rune); got != tt.want {
   444  			t.Errorf("IndexRune(%q, %d) = %v; want %v", tt.in, tt.rune, got, tt.want)
   445  		}
   446  	}
   447  
   448  	haystack := []byte("test世界")
   449  	allocs := testing.AllocsPerRun(1000, func() {
   450  		if i := IndexRune(haystack, 's'); i != 2 {
   451  			t.Fatalf("'s' at %d; want 2", i)
   452  		}
   453  		if i := IndexRune(haystack, '世'); i != 4 {
   454  			t.Fatalf("'世' at %d; want 4", i)
   455  		}
   456  	})
   457  	if allocs != 0 {
   458  		t.Errorf("expected no allocations, got %f", allocs)
   459  	}
   460  }
   461  
   462  // test count of a single byte across page offsets
   463  func TestCountByte(t *testing.T) {
   464  	b := make([]byte, 5015) // bigger than a page
   465  	windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
   466  	testCountWindow := func(i, window int) {
   467  		for j := 0; j < window; j++ {
   468  			b[i+j] = byte(100)
   469  			p := Count(b[i:i+window], []byte{100})
   470  			if p != j+1 {
   471  				t.Errorf("TestCountByte.Count(%q, 100) = %d", b[i:i+window], p)
   472  			}
   473  		}
   474  	}
   475  
   476  	maxWnd := windows[len(windows)-1]
   477  
   478  	for i := 0; i <= 2*maxWnd; i++ {
   479  		for _, window := range windows {
   480  			if window > len(b[i:]) {
   481  				window = len(b[i:])
   482  			}
   483  			testCountWindow(i, window)
   484  			for j := 0; j < window; j++ {
   485  				b[i+j] = byte(0)
   486  			}
   487  		}
   488  	}
   489  	for i := 4096 - (maxWnd + 1); i < len(b); i++ {
   490  		for _, window := range windows {
   491  			if window > len(b[i:]) {
   492  				window = len(b[i:])
   493  			}
   494  			testCountWindow(i, window)
   495  			for j := 0; j < window; j++ {
   496  				b[i+j] = byte(0)
   497  			}
   498  		}
   499  	}
   500  }
   501  
   502  // Make sure we don't count bytes outside our window
   503  func TestCountByteNoMatch(t *testing.T) {
   504  	b := make([]byte, 5015)
   505  	windows := []int{1, 2, 3, 4, 15, 16, 17, 31, 32, 33, 63, 64, 65, 128}
   506  	for i := 0; i <= len(b); i++ {
   507  		for _, window := range windows {
   508  			if window > len(b[i:]) {
   509  				window = len(b[i:])
   510  			}
   511  			// Fill the window with non-match
   512  			for j := 0; j < window; j++ {
   513  				b[i+j] = byte(100)
   514  			}
   515  			// Try to find something that doesn't exist
   516  			p := Count(b[i:i+window], []byte{0})
   517  			if p != 0 {
   518  				t.Errorf("TestCountByteNoMatch(%q, 0) = %d", b[i:i+window], p)
   519  			}
   520  			for j := 0; j < window; j++ {
   521  				b[i+j] = byte(0)
   522  			}
   523  		}
   524  	}
   525  }
   526  
   527  var bmbuf []byte
   528  
   529  func valName(x int) string {
   530  	if s := x >> 20; s<<20 == x {
   531  		return fmt.Sprintf("%dM", s)
   532  	}
   533  	if s := x >> 10; s<<10 == x {
   534  		return fmt.Sprintf("%dK", s)
   535  	}
   536  	return fmt.Sprint(x)
   537  }
   538  
   539  func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
   540  	for _, n := range sizes {
   541  		if isRaceBuilder && n > 4<<10 {
   542  			continue
   543  		}
   544  		b.Run(valName(n), func(b *testing.B) {
   545  			if len(bmbuf) < n {
   546  				bmbuf = make([]byte, n)
   547  			}
   548  			b.SetBytes(int64(n))
   549  			f(b, n)
   550  		})
   551  	}
   552  }
   553  
   554  var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
   555  
   556  var isRaceBuilder = strings.HasSuffix(testenv.Builder(), "-race")
   557  
   558  func BenchmarkIndexByte(b *testing.B) {
   559  	benchBytes(b, indexSizes, bmIndexByte(IndexByte))
   560  }
   561  
   562  func BenchmarkIndexBytePortable(b *testing.B) {
   563  	benchBytes(b, indexSizes, bmIndexByte(IndexBytePortable))
   564  }
   565  
   566  func bmIndexByte(index func([]byte, byte) int) func(b *testing.B, n int) {
   567  	return func(b *testing.B, n int) {
   568  		buf := bmbuf[0:n]
   569  		buf[n-1] = 'x'
   570  		for i := 0; i < b.N; i++ {
   571  			j := index(buf, 'x')
   572  			if j != n-1 {
   573  				b.Fatal("bad index", j)
   574  			}
   575  		}
   576  		buf[n-1] = '\x00'
   577  	}
   578  }
   579  
   580  func BenchmarkIndexRune(b *testing.B) {
   581  	benchBytes(b, indexSizes, bmIndexRune(IndexRune))
   582  }
   583  
   584  func BenchmarkIndexRuneASCII(b *testing.B) {
   585  	benchBytes(b, indexSizes, bmIndexRuneASCII(IndexRune))
   586  }
   587  
   588  func bmIndexRuneASCII(index func([]byte, rune) int) func(b *testing.B, n int) {
   589  	return func(b *testing.B, n int) {
   590  		buf := bmbuf[0:n]
   591  		buf[n-1] = 'x'
   592  		for i := 0; i < b.N; i++ {
   593  			j := index(buf, 'x')
   594  			if j != n-1 {
   595  				b.Fatal("bad index", j)
   596  			}
   597  		}
   598  		buf[n-1] = '\x00'
   599  	}
   600  }
   601  
   602  func bmIndexRune(index func([]byte, rune) int) func(b *testing.B, n int) {
   603  	return func(b *testing.B, n int) {
   604  		buf := bmbuf[0:n]
   605  		utf8.EncodeRune(buf[n-3:], '世')
   606  		for i := 0; i < b.N; i++ {
   607  			j := index(buf, '世')
   608  			if j != n-3 {
   609  				b.Fatal("bad index", j)
   610  			}
   611  		}
   612  		buf[n-3] = '\x00'
   613  		buf[n-2] = '\x00'
   614  		buf[n-1] = '\x00'
   615  	}
   616  }
   617  
   618  func BenchmarkEqual(b *testing.B) {
   619  	b.Run("0", func(b *testing.B) {
   620  		var buf [4]byte
   621  		buf1 := buf[0:0]
   622  		buf2 := buf[1:1]
   623  		for i := 0; i < b.N; i++ {
   624  			eq := Equal(buf1, buf2)
   625  			if !eq {
   626  				b.Fatal("bad equal")
   627  			}
   628  		}
   629  	})
   630  
   631  	sizes := []int{1, 6, 9, 15, 16, 20, 32, 4 << 10, 4 << 20, 64 << 20}
   632  	benchBytes(b, sizes, bmEqual(Equal))
   633  }
   634  
   635  func bmEqual(equal func([]byte, []byte) bool) func(b *testing.B, n int) {
   636  	return func(b *testing.B, n int) {
   637  		if len(bmbuf) < 2*n {
   638  			bmbuf = make([]byte, 2*n)
   639  		}
   640  		buf1 := bmbuf[0:n]
   641  		buf2 := bmbuf[n : 2*n]
   642  		buf1[n-1] = 'x'
   643  		buf2[n-1] = 'x'
   644  		for i := 0; i < b.N; i++ {
   645  			eq := equal(buf1, buf2)
   646  			if !eq {
   647  				b.Fatal("bad equal")
   648  			}
   649  		}
   650  		buf1[n-1] = '\x00'
   651  		buf2[n-1] = '\x00'
   652  	}
   653  }
   654  
   655  func BenchmarkIndex(b *testing.B) {
   656  	benchBytes(b, indexSizes, func(b *testing.B, n int) {
   657  		buf := bmbuf[0:n]
   658  		buf[n-1] = 'x'
   659  		for i := 0; i < b.N; i++ {
   660  			j := Index(buf, buf[n-7:])
   661  			if j != n-7 {
   662  				b.Fatal("bad index", j)
   663  			}
   664  		}
   665  		buf[n-1] = '\x00'
   666  	})
   667  }
   668  
   669  func BenchmarkIndexEasy(b *testing.B) {
   670  	benchBytes(b, indexSizes, func(b *testing.B, n int) {
   671  		buf := bmbuf[0:n]
   672  		buf[n-1] = 'x'
   673  		buf[n-7] = 'x'
   674  		for i := 0; i < b.N; i++ {
   675  			j := Index(buf, buf[n-7:])
   676  			if j != n-7 {
   677  				b.Fatal("bad index", j)
   678  			}
   679  		}
   680  		buf[n-1] = '\x00'
   681  		buf[n-7] = '\x00'
   682  	})
   683  }
   684  
   685  func BenchmarkCount(b *testing.B) {
   686  	benchBytes(b, indexSizes, func(b *testing.B, n int) {
   687  		buf := bmbuf[0:n]
   688  		buf[n-1] = 'x'
   689  		for i := 0; i < b.N; i++ {
   690  			j := Count(buf, buf[n-7:])
   691  			if j != 1 {
   692  				b.Fatal("bad count", j)
   693  			}
   694  		}
   695  		buf[n-1] = '\x00'
   696  	})
   697  }
   698  
   699  func BenchmarkCountEasy(b *testing.B) {
   700  	benchBytes(b, indexSizes, func(b *testing.B, n int) {
   701  		buf := bmbuf[0:n]
   702  		buf[n-1] = 'x'
   703  		buf[n-7] = 'x'
   704  		for i := 0; i < b.N; i++ {
   705  			j := Count(buf, buf[n-7:])
   706  			if j != 1 {
   707  				b.Fatal("bad count", j)
   708  			}
   709  		}
   710  		buf[n-1] = '\x00'
   711  		buf[n-7] = '\x00'
   712  	})
   713  }
   714  
   715  func BenchmarkCountSingle(b *testing.B) {
   716  	benchBytes(b, indexSizes, func(b *testing.B, n int) {
   717  		buf := bmbuf[0:n]
   718  		step := 8
   719  		for i := 0; i < len(buf); i += step {
   720  			buf[i] = 1
   721  		}
   722  		expect := (len(buf) + (step - 1)) / step
   723  		for i := 0; i < b.N; i++ {
   724  			j := Count(buf, []byte{1})
   725  			if j != expect {
   726  				b.Fatal("bad count", j, expect)
   727  			}
   728  		}
   729  		for i := 0; i < len(buf); i++ {
   730  			buf[i] = 0
   731  		}
   732  	})
   733  }
   734  
   735  type SplitTest struct {
   736  	s   string
   737  	sep string
   738  	n   int
   739  	a   []string
   740  }
   741  
   742  var splittests = []SplitTest{
   743  	{"", "", -1, []string{}},
   744  	{abcd, "a", 0, nil},
   745  	{abcd, "", 2, []string{"a", "bcd"}},
   746  	{abcd, "a", -1, []string{"", "bcd"}},
   747  	{abcd, "z", -1, []string{"abcd"}},
   748  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   749  	{commas, ",", -1, []string{"1", "2", "3", "4"}},
   750  	{dots, "...", -1, []string{"1", ".2", ".3", ".4"}},
   751  	{faces, "☹", -1, []string{"☺☻", ""}},
   752  	{faces, "~", -1, []string{faces}},
   753  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   754  	{"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}},
   755  	{"1 2", " ", 3, []string{"1", "2"}},
   756  	{"123", "", 2, []string{"1", "23"}},
   757  	{"123", "", 17, []string{"1", "2", "3"}},
   758  	{"bT", "T", math.MaxInt / 4, []string{"b", ""}},
   759  	{"\xff-\xff", "", -1, []string{"\xff", "-", "\xff"}},
   760  	{"\xff-\xff", "-", -1, []string{"\xff", "\xff"}},
   761  }
   762  
   763  func TestSplit(t *testing.T) {
   764  	for _, tt := range splittests {
   765  		a := SplitN([]byte(tt.s), []byte(tt.sep), tt.n)
   766  
   767  		// Appending to the results should not change future results.
   768  		var x []byte
   769  		for _, v := range a {
   770  			x = append(v, 'z')
   771  		}
   772  
   773  		result := sliceOfString(a)
   774  		if !eq(result, tt.a) {
   775  			t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
   776  			continue
   777  		}
   778  		if tt.n == 0 || len(a) == 0 {
   779  			continue
   780  		}
   781  
   782  		if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
   783  			t.Errorf("last appended result was %s; want %s", x, want)
   784  		}
   785  
   786  		s := Join(a, []byte(tt.sep))
   787  		if string(s) != tt.s {
   788  			t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
   789  		}
   790  		if tt.n < 0 {
   791  			b := Split([]byte(tt.s), []byte(tt.sep))
   792  			if !reflect.DeepEqual(a, b) {
   793  				t.Errorf("Split disagrees withSplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   794  			}
   795  		}
   796  		if len(a) > 0 {
   797  			in, out := a[0], s
   798  			if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
   799  				t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep)
   800  			}
   801  		}
   802  	}
   803  }
   804  
   805  var splitaftertests = []SplitTest{
   806  	{abcd, "a", -1, []string{"a", "bcd"}},
   807  	{abcd, "z", -1, []string{"abcd"}},
   808  	{abcd, "", -1, []string{"a", "b", "c", "d"}},
   809  	{commas, ",", -1, []string{"1,", "2,", "3,", "4"}},
   810  	{dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}},
   811  	{faces, "☹", -1, []string{"☺☻☹", ""}},
   812  	{faces, "~", -1, []string{faces}},
   813  	{faces, "", -1, []string{"☺", "☻", "☹"}},
   814  	{"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}},
   815  	{"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}},
   816  	{"1 2", " ", 3, []string{"1 ", "2"}},
   817  	{"123", "", 2, []string{"1", "23"}},
   818  	{"123", "", 17, []string{"1", "2", "3"}},
   819  }
   820  
   821  func TestSplitAfter(t *testing.T) {
   822  	for _, tt := range splitaftertests {
   823  		a := SplitAfterN([]byte(tt.s), []byte(tt.sep), tt.n)
   824  
   825  		// Appending to the results should not change future results.
   826  		var x []byte
   827  		for _, v := range a {
   828  			x = append(v, 'z')
   829  		}
   830  
   831  		result := sliceOfString(a)
   832  		if !eq(result, tt.a) {
   833  			t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a)
   834  			continue
   835  		}
   836  
   837  		if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
   838  			t.Errorf("last appended result was %s; want %s", x, want)
   839  		}
   840  
   841  		s := Join(a, nil)
   842  		if string(s) != tt.s {
   843  			t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s)
   844  		}
   845  		if tt.n < 0 {
   846  			b := SplitAfter([]byte(tt.s), []byte(tt.sep))
   847  			if !reflect.DeepEqual(a, b) {
   848  				t.Errorf("SplitAfter disagrees withSplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
   849  			}
   850  		}
   851  	}
   852  }
   853  
   854  type FieldsTest struct {
   855  	s string
   856  	a []string
   857  }
   858  
   859  var fieldstests = []FieldsTest{
   860  	{"", []string{}},
   861  	{" ", []string{}},
   862  	{" \t ", []string{}},
   863  	{"  abc  ", []string{"abc"}},
   864  	{"1 2 3 4", []string{"1", "2", "3", "4"}},
   865  	{"1  2  3  4", []string{"1", "2", "3", "4"}},
   866  	{"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}},
   867  	{"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}},
   868  	{"\u2000\u2001\u2002", []string{}},
   869  	{"\n™\t™\n", []string{"™", "™"}},
   870  	{faces, []string{faces}},
   871  }
   872  
   873  func TestFields(t *testing.T) {
   874  	for _, tt := range fieldstests {
   875  		b := []byte(tt.s)
   876  		a := Fields(b)
   877  
   878  		// Appending to the results should not change future results.
   879  		var x []byte
   880  		for _, v := range a {
   881  			x = append(v, 'z')
   882  		}
   883  
   884  		result := sliceOfString(a)
   885  		if !eq(result, tt.a) {
   886  			t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a)
   887  			continue
   888  		}
   889  
   890  		if string(b) != tt.s {
   891  			t.Errorf("slice changed to %s; want %s", string(b), tt.s)
   892  		}
   893  		if len(tt.a) > 0 {
   894  			if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
   895  				t.Errorf("last appended result was %s; want %s", x, want)
   896  			}
   897  		}
   898  	}
   899  }
   900  
   901  func TestFieldsFunc(t *testing.T) {
   902  	for _, tt := range fieldstests {
   903  		a := FieldsFunc([]byte(tt.s), unicode.IsSpace)
   904  		result := sliceOfString(a)
   905  		if !eq(result, tt.a) {
   906  			t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a)
   907  			continue
   908  		}
   909  	}
   910  	pred := func(c rune) bool { return c == 'X' }
   911  	var fieldsFuncTests = []FieldsTest{
   912  		{"", []string{}},
   913  		{"XX", []string{}},
   914  		{"XXhiXXX", []string{"hi"}},
   915  		{"aXXbXXXcX", []string{"a", "b", "c"}},
   916  	}
   917  	for _, tt := range fieldsFuncTests {
   918  		b := []byte(tt.s)
   919  		a := FieldsFunc(b, pred)
   920  
   921  		// Appending to the results should not change future results.
   922  		var x []byte
   923  		for _, v := range a {
   924  			x = append(v, 'z')
   925  		}
   926  
   927  		result := sliceOfString(a)
   928  		if !eq(result, tt.a) {
   929  			t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a)
   930  		}
   931  
   932  		if string(b) != tt.s {
   933  			t.Errorf("slice changed to %s; want %s", b, tt.s)
   934  		}
   935  		if len(tt.a) > 0 {
   936  			if want := tt.a[len(tt.a)-1] + "z"; string(x) != want {
   937  				t.Errorf("last appended result was %s; want %s", x, want)
   938  			}
   939  		}
   940  	}
   941  }
   942  
   943  // Test case for any function which accepts and returns a byte slice.
   944  // For ease of creation, we write the input byte slice as a string.
   945  type StringTest struct {
   946  	in  string
   947  	out []byte
   948  }
   949  
   950  var upperTests = []StringTest{
   951  	{"", []byte("")},
   952  	{"ONLYUPPER", []byte("ONLYUPPER")},
   953  	{"abc", []byte("ABC")},
   954  	{"AbC123", []byte("ABC123")},
   955  	{"azAZ09_", []byte("AZAZ09_")},
   956  	{"longStrinGwitHmixofsmaLLandcAps", []byte("LONGSTRINGWITHMIXOFSMALLANDCAPS")},
   957  	{"long\u0250string\u0250with\u0250nonascii\u2C6Fchars", []byte("LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS")},
   958  	{"\u0250\u0250\u0250\u0250\u0250", []byte("\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F")}, // grows one byte per char
   959  	{"a\u0080\U0010FFFF", []byte("A\u0080\U0010FFFF")},                           // test utf8.RuneSelf and utf8.MaxRune
   960  }
   961  
   962  var lowerTests = []StringTest{
   963  	{"", []byte("")},
   964  	{"abc", []byte("abc")},
   965  	{"AbC123", []byte("abc123")},
   966  	{"azAZ09_", []byte("azaz09_")},
   967  	{"longStrinGwitHmixofsmaLLandcAps", []byte("longstringwithmixofsmallandcaps")},
   968  	{"LONG\u2C6FSTRING\u2C6FWITH\u2C6FNONASCII\u2C6FCHARS", []byte("long\u0250string\u0250with\u0250nonascii\u0250chars")},
   969  	{"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", []byte("\u0251\u0251\u0251\u0251\u0251")}, // shrinks one byte per char
   970  	{"A\u0080\U0010FFFF", []byte("a\u0080\U0010FFFF")},                           // test utf8.RuneSelf and utf8.MaxRune
   971  }
   972  
   973  const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000"
   974  
   975  var trimSpaceTests = []StringTest{
   976  	{"", nil},
   977  	{"  a", []byte("a")},
   978  	{"b  ", []byte("b")},
   979  	{"abc", []byte("abc")},
   980  	{space + "abc" + space, []byte("abc")},
   981  	{" ", nil},
   982  	{"\u3000 ", nil},
   983  	{" \u3000", nil},
   984  	{" \t\r\n \t\t\r\r\n\n ", nil},
   985  	{" \t\r\n x\t\t\r\r\n\n ", []byte("x")},
   986  	{" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", []byte("x\t\t\r\r\ny")},
   987  	{"1 \t\r\n2", []byte("1 \t\r\n2")},
   988  	{" x\x80", []byte("x\x80")},
   989  	{" x\xc0", []byte("x\xc0")},
   990  	{"x \xc0\xc0 ", []byte("x \xc0\xc0")},
   991  	{"x \xc0", []byte("x \xc0")},
   992  	{"x \xc0 ", []byte("x \xc0")},
   993  	{"x \xc0\xc0 ", []byte("x \xc0\xc0")},
   994  	{"x ☺\xc0\xc0 ", []byte("x ☺\xc0\xc0")},
   995  	{"x ☺ ", []byte("x ☺")},
   996  }
   997  
   998  // Execute f on each test case.  funcName should be the name of f; it's used
   999  // in failure reports.
  1000  func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) {
  1001  	for _, tc := range testCases {
  1002  		actual := f([]byte(tc.in))
  1003  		if actual == nil && tc.out != nil {
  1004  			t.Errorf("%s(%q) = nil; want %q", funcName, tc.in, tc.out)
  1005  		}
  1006  		if actual != nil && tc.out == nil {
  1007  			t.Errorf("%s(%q) = %q; want nil", funcName, tc.in, actual)
  1008  		}
  1009  		if !Equal(actual, tc.out) {
  1010  			t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out)
  1011  		}
  1012  	}
  1013  }
  1014  
  1015  func tenRunes(r rune) string {
  1016  	runes := make([]rune, 10)
  1017  	for i := range runes {
  1018  		runes[i] = r
  1019  	}
  1020  	return string(runes)
  1021  }
  1022  
  1023  // User-defined self-inverse mapping function
  1024  func rot13(r rune) rune {
  1025  	const step = 13
  1026  	if r >= 'a' && r <= 'z' {
  1027  		return ((r - 'a' + step) % 26) + 'a'
  1028  	}
  1029  	if r >= 'A' && r <= 'Z' {
  1030  		return ((r - 'A' + step) % 26) + 'A'
  1031  	}
  1032  	return r
  1033  }
  1034  
  1035  func TestMap(t *testing.T) {
  1036  	// Run a couple of awful growth/shrinkage tests
  1037  	a := tenRunes('a')
  1038  
  1039  	// 1.  Grow. This triggers two reallocations in Map.
  1040  	maxRune := func(r rune) rune { return unicode.MaxRune }
  1041  	m := Map(maxRune, []byte(a))
  1042  	expect := tenRunes(unicode.MaxRune)
  1043  	if string(m) != expect {
  1044  		t.Errorf("growing: expected %q got %q", expect, m)
  1045  	}
  1046  
  1047  	// 2. Shrink
  1048  	minRune := func(r rune) rune { return 'a' }
  1049  	m = Map(minRune, []byte(tenRunes(unicode.MaxRune)))
  1050  	expect = a
  1051  	if string(m) != expect {
  1052  		t.Errorf("shrinking: expected %q got %q", expect, m)
  1053  	}
  1054  
  1055  	// 3. Rot13
  1056  	m = Map(rot13, []byte("a to zed"))
  1057  	expect = "n gb mrq"
  1058  	if string(m) != expect {
  1059  		t.Errorf("rot13: expected %q got %q", expect, m)
  1060  	}
  1061  
  1062  	// 4. Rot13^2
  1063  	m = Map(rot13, Map(rot13, []byte("a to zed")))
  1064  	expect = "a to zed"
  1065  	if string(m) != expect {
  1066  		t.Errorf("rot13: expected %q got %q", expect, m)
  1067  	}
  1068  
  1069  	// 5. Drop
  1070  	dropNotLatin := func(r rune) rune {
  1071  		if unicode.Is(unicode.Latin, r) {
  1072  			return r
  1073  		}
  1074  		return -1
  1075  	}
  1076  	m = Map(dropNotLatin, []byte("Hello, 세계"))
  1077  	expect = "Hello"
  1078  	if string(m) != expect {
  1079  		t.Errorf("drop: expected %q got %q", expect, m)
  1080  	}
  1081  
  1082  	// 6. Invalid rune
  1083  	invalidRune := func(r rune) rune {
  1084  		return utf8.MaxRune + 1
  1085  	}
  1086  	m = Map(invalidRune, []byte("x"))
  1087  	expect = "\uFFFD"
  1088  	if string(m) != expect {
  1089  		t.Errorf("invalidRune: expected %q got %q", expect, m)
  1090  	}
  1091  }
  1092  
  1093  func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) }
  1094  
  1095  func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) }
  1096  
  1097  func BenchmarkToUpper(b *testing.B) {
  1098  	for _, tc := range upperTests {
  1099  		tin := []byte(tc.in)
  1100  		b.Run(tc.in, func(b *testing.B) {
  1101  			for i := 0; i < b.N; i++ {
  1102  				actual := ToUpper(tin)
  1103  				if !Equal(actual, tc.out) {
  1104  					b.Errorf("ToUpper(%q) = %q; want %q", tc.in, actual, tc.out)
  1105  				}
  1106  			}
  1107  		})
  1108  	}
  1109  }
  1110  
  1111  func BenchmarkToLower(b *testing.B) {
  1112  	for _, tc := range lowerTests {
  1113  		tin := []byte(tc.in)
  1114  		b.Run(tc.in, func(b *testing.B) {
  1115  			for i := 0; i < b.N; i++ {
  1116  				actual := ToLower(tin)
  1117  				if !Equal(actual, tc.out) {
  1118  					b.Errorf("ToLower(%q) = %q; want %q", tc.in, actual, tc.out)
  1119  				}
  1120  			}
  1121  		})
  1122  	}
  1123  }
  1124  
  1125  var toValidUTF8Tests = []struct {
  1126  	in   string
  1127  	repl string
  1128  	out  string
  1129  }{
  1130  	{"", "\uFFFD", ""},
  1131  	{"abc", "\uFFFD", "abc"},
  1132  	{"\uFDDD", "\uFFFD", "\uFDDD"},
  1133  	{"a\xffb", "\uFFFD", "a\uFFFDb"},
  1134  	{"a\xffb\uFFFD", "X", "aXb\uFFFD"},
  1135  	{"a☺\xffb☺\xC0\xAFc☺\xff", "", "a☺b☺c☺"},
  1136  	{"a☺\xffb☺\xC0\xAFc☺\xff", "日本語", "a☺日本語b☺日本語c☺日本語"},
  1137  	{"\xC0\xAF", "\uFFFD", "\uFFFD"},
  1138  	{"\xE0\x80\xAF", "\uFFFD", "\uFFFD"},
  1139  	{"\xed\xa0\x80", "abc", "abc"},
  1140  	{"\xed\xbf\xbf", "\uFFFD", "\uFFFD"},
  1141  	{"\xF0\x80\x80\xaf", "☺", "☺"},
  1142  	{"\xF8\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
  1143  	{"\xFC\x80\x80\x80\x80\xAF", "\uFFFD", "\uFFFD"},
  1144  }
  1145  
  1146  func TestToValidUTF8(t *testing.T) {
  1147  	for _, tc := range toValidUTF8Tests {
  1148  		got := ToValidUTF8([]byte(tc.in), []byte(tc.repl))
  1149  		if !Equal(got, []byte(tc.out)) {
  1150  			t.Errorf("ToValidUTF8(%q, %q) = %q; want %q", tc.in, tc.repl, got, tc.out)
  1151  		}
  1152  	}
  1153  }
  1154  
  1155  func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) }
  1156  
  1157  type RepeatTest struct {
  1158  	in, out string
  1159  	count   int
  1160  }
  1161  
  1162  var longString = "a" + string(make([]byte, 1<<16)) + "z"
  1163  
  1164  var RepeatTests = []RepeatTest{
  1165  	{"", "", 0},
  1166  	{"", "", 1},
  1167  	{"", "", 2},
  1168  	{"-", "", 0},
  1169  	{"-", "-", 1},
  1170  	{"-", "----------", 10},
  1171  	{"abc ", "abc abc abc ", 3},
  1172  	// Tests for results over the chunkLimit
  1173  	{string(rune(0)), string(make([]byte, 1<<16)), 1 << 16},
  1174  	{longString, longString + longString, 2},
  1175  }
  1176  
  1177  func TestRepeat(t *testing.T) {
  1178  	for _, tt := range RepeatTests {
  1179  		tin := []byte(tt.in)
  1180  		tout := []byte(tt.out)
  1181  		a := Repeat(tin, tt.count)
  1182  		if !Equal(a, tout) {
  1183  			t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout)
  1184  			continue
  1185  		}
  1186  	}
  1187  }
  1188  
  1189  func repeat(b []byte, count int) (err error) {
  1190  	defer func() {
  1191  		if r := recover(); r != nil {
  1192  			switch v := r.(type) {
  1193  			case error:
  1194  				err = v
  1195  			default:
  1196  				err = fmt.Errorf("%s", v)
  1197  			}
  1198  		}
  1199  	}()
  1200  
  1201  	Repeat(b, count)
  1202  
  1203  	return
  1204  }
  1205  
  1206  // See Issue golang.org/issue/16237
  1207  func TestRepeatCatchesOverflow(t *testing.T) {
  1208  	tests := [...]struct {
  1209  		s      string
  1210  		count  int
  1211  		errStr string
  1212  	}{
  1213  		0: {"--", -2147483647, "negative"},
  1214  		1: {"", int(^uint(0) >> 1), ""},
  1215  		2: {"-", 10, ""},
  1216  		3: {"gopher", 0, ""},
  1217  		4: {"-", -1, "negative"},
  1218  		5: {"--", -102, "negative"},
  1219  		6: {string(make([]byte, 255)), int((^uint(0))/255 + 1), "overflow"},
  1220  	}
  1221  
  1222  	for i, tt := range tests {
  1223  		err := repeat([]byte(tt.s), tt.count)
  1224  		if tt.errStr == "" {
  1225  			if err != nil {
  1226  				t.Errorf("#%d panicked %v", i, err)
  1227  			}
  1228  			continue
  1229  		}
  1230  
  1231  		if err == nil || !strings.Contains(err.Error(), tt.errStr) {
  1232  			t.Errorf("#%d expected %q got %q", i, tt.errStr, err)
  1233  		}
  1234  	}
  1235  }
  1236  
  1237  func runesEqual(a, b []rune) bool {
  1238  	if len(a) != len(b) {
  1239  		return false
  1240  	}
  1241  	for i, r := range a {
  1242  		if r != b[i] {
  1243  			return false
  1244  		}
  1245  	}
  1246  	return true
  1247  }
  1248  
  1249  type RunesTest struct {
  1250  	in    string
  1251  	out   []rune
  1252  	lossy bool
  1253  }
  1254  
  1255  var RunesTests = []RunesTest{
  1256  	{"", []rune{}, false},
  1257  	{" ", []rune{32}, false},
  1258  	{"ABC", []rune{65, 66, 67}, false},
  1259  	{"abc", []rune{97, 98, 99}, false},
  1260  	{"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false},
  1261  	{"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true},
  1262  	{"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true},
  1263  }
  1264  
  1265  func TestRunes(t *testing.T) {
  1266  	for _, tt := range RunesTests {
  1267  		tin := []byte(tt.in)
  1268  		a := Runes(tin)
  1269  		if !runesEqual(a, tt.out) {
  1270  			t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out)
  1271  			continue
  1272  		}
  1273  		if !tt.lossy {
  1274  			// can only test reassembly if we didn't lose information
  1275  			s := string(a)
  1276  			if s != tt.in {
  1277  				t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin)
  1278  			}
  1279  		}
  1280  	}
  1281  }
  1282  
  1283  type TrimTest struct {
  1284  	f            string
  1285  	in, arg, out string
  1286  }
  1287  
  1288  var trimTests = []TrimTest{
  1289  	{"Trim", "abba", "a", "bb"},
  1290  	{"Trim", "abba", "ab", ""},
  1291  	{"TrimLeft", "abba", "ab", ""},
  1292  	{"TrimRight", "abba", "ab", ""},
  1293  	{"TrimLeft", "abba", "a", "bba"},
  1294  	{"TrimLeft", "abba", "b", "abba"},
  1295  	{"TrimRight", "abba", "a", "abb"},
  1296  	{"TrimRight", "abba", "b", "abba"},
  1297  	{"Trim", "<tag>", "<>", "tag"},
  1298  	{"Trim", "* listitem", " *", "listitem"},
  1299  	{"Trim", `"quote"`, `"`, "quote"},
  1300  	{"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"},
  1301  	{"Trim", "\x80test\xff", "\xff", "test"},
  1302  	{"Trim", " Ġ ", " ", "Ġ"},
  1303  	{"Trim", " Ġİ0", "0 ", "Ġİ"},
  1304  	//empty string tests
  1305  	{"Trim", "abba", "", "abba"},
  1306  	{"Trim", "", "123", ""},
  1307  	{"Trim", "", "", ""},
  1308  	{"TrimLeft", "abba", "", "abba"},
  1309  	{"TrimLeft", "", "123", ""},
  1310  	{"TrimLeft", "", "", ""},
  1311  	{"TrimRight", "abba", "", "abba"},
  1312  	{"TrimRight", "", "123", ""},
  1313  	{"TrimRight", "", "", ""},
  1314  	{"TrimRight", "☺\xc0", "☺", "☺\xc0"},
  1315  	{"TrimPrefix", "aabb", "a", "abb"},
  1316  	{"TrimPrefix", "aabb", "b", "aabb"},
  1317  	{"TrimSuffix", "aabb", "a", "aabb"},
  1318  	{"TrimSuffix", "aabb", "b", "aab"},
  1319  }
  1320  
  1321  type TrimNilTest struct {
  1322  	f   string
  1323  	in  []byte
  1324  	arg string
  1325  	out []byte
  1326  }
  1327  
  1328  var trimNilTests = []TrimNilTest{
  1329  	{"Trim", nil, "", nil},
  1330  	{"Trim", []byte{}, "", nil},
  1331  	{"Trim", []byte{'a'}, "a", nil},
  1332  	{"Trim", []byte{'a', 'a'}, "a", nil},
  1333  	{"Trim", []byte{'a'}, "ab", nil},
  1334  	{"Trim", []byte{'a', 'b'}, "ab", nil},
  1335  	{"Trim", []byte("☺"), "☺", nil},
  1336  	{"TrimLeft", nil, "", nil},
  1337  	{"TrimLeft", []byte{}, "", nil},
  1338  	{"TrimLeft", []byte{'a'}, "a", nil},
  1339  	{"TrimLeft", []byte{'a', 'a'}, "a", nil},
  1340  	{"TrimLeft", []byte{'a'}, "ab", nil},
  1341  	{"TrimLeft", []byte{'a', 'b'}, "ab", nil},
  1342  	{"TrimLeft", []byte("☺"), "☺", nil},
  1343  	{"TrimRight", nil, "", nil},
  1344  	{"TrimRight", []byte{}, "", []byte{}},
  1345  	{"TrimRight", []byte{'a'}, "a", []byte{}},
  1346  	{"TrimRight", []byte{'a', 'a'}, "a", []byte{}},
  1347  	{"TrimRight", []byte{'a'}, "ab", []byte{}},
  1348  	{"TrimRight", []byte{'a', 'b'}, "ab", []byte{}},
  1349  	{"TrimRight", []byte("☺"), "☺", []byte{}},
  1350  	{"TrimPrefix", nil, "", nil},
  1351  	{"TrimPrefix", []byte{}, "", []byte{}},
  1352  	{"TrimPrefix", []byte{'a'}, "a", []byte{}},
  1353  	{"TrimPrefix", []byte("☺"), "☺", []byte{}},
  1354  	{"TrimSuffix", nil, "", nil},
  1355  	{"TrimSuffix", []byte{}, "", []byte{}},
  1356  	{"TrimSuffix", []byte{'a'}, "a", []byte{}},
  1357  	{"TrimSuffix", []byte("☺"), "☺", []byte{}},
  1358  }
  1359  
  1360  func TestTrim(t *testing.T) {
  1361  	toFn := func(name string) (func([]byte, string) []byte, func([]byte, []byte) []byte) {
  1362  		switch name {
  1363  		case "Trim":
  1364  			return Trim, nil
  1365  		case "TrimLeft":
  1366  			return TrimLeft, nil
  1367  		case "TrimRight":
  1368  			return TrimRight, nil
  1369  		case "TrimPrefix":
  1370  			return nil, TrimPrefix
  1371  		case "TrimSuffix":
  1372  			return nil, TrimSuffix
  1373  		default:
  1374  			t.Errorf("Undefined trim function %s", name)
  1375  			return nil, nil
  1376  		}
  1377  	}
  1378  
  1379  	for _, tc := range trimTests {
  1380  		name := tc.f
  1381  		f, fb := toFn(name)
  1382  		if f == nil && fb == nil {
  1383  			continue
  1384  		}
  1385  		var actual string
  1386  		if f != nil {
  1387  			actual = string(f([]byte(tc.in), tc.arg))
  1388  		} else {
  1389  			actual = string(fb([]byte(tc.in), []byte(tc.arg)))
  1390  		}
  1391  		if actual != tc.out {
  1392  			t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
  1393  		}
  1394  	}
  1395  
  1396  	for _, tc := range trimNilTests {
  1397  		name := tc.f
  1398  		f, fb := toFn(name)
  1399  		if f == nil && fb == nil {
  1400  			continue
  1401  		}
  1402  		var actual []byte
  1403  		if f != nil {
  1404  			actual = f(tc.in, tc.arg)
  1405  		} else {
  1406  			actual = fb(tc.in, []byte(tc.arg))
  1407  		}
  1408  		report := func(s []byte) string {
  1409  			if s == nil {
  1410  				return "nil"
  1411  			} else {
  1412  				return fmt.Sprintf("%q", s)
  1413  			}
  1414  		}
  1415  		if len(actual) != 0 {
  1416  			t.Errorf("%s(%s, %q) returned non-empty value", name, report(tc.in), tc.arg)
  1417  		} else {
  1418  			actualNil := actual == nil
  1419  			outNil := tc.out == nil
  1420  			if actualNil != outNil {
  1421  				t.Errorf("%s(%s, %q) got nil %t; want nil %t", name, report(tc.in), tc.arg, actualNil, outNil)
  1422  			}
  1423  		}
  1424  	}
  1425  }
  1426  
  1427  type predicate struct {
  1428  	f    func(r rune) bool
  1429  	name string
  1430  }
  1431  
  1432  var isSpace = predicate{unicode.IsSpace, "IsSpace"}
  1433  var isDigit = predicate{unicode.IsDigit, "IsDigit"}
  1434  var isUpper = predicate{unicode.IsUpper, "IsUpper"}
  1435  var isValidRune = predicate{
  1436  	func(r rune) bool {
  1437  		return r != utf8.RuneError
  1438  	},
  1439  	"IsValidRune",
  1440  }
  1441  
  1442  type TrimFuncTest struct {
  1443  	f        predicate
  1444  	in       string
  1445  	trimOut  []byte
  1446  	leftOut  []byte
  1447  	rightOut []byte
  1448  }
  1449  
  1450  func not(p predicate) predicate {
  1451  	return predicate{
  1452  		func(r rune) bool {
  1453  			return !p.f(r)
  1454  		},
  1455  		"not " + p.name,
  1456  	}
  1457  }
  1458  
  1459  var trimFuncTests = []TrimFuncTest{
  1460  	{isSpace, space + " hello " + space,
  1461  		[]byte("hello"),
  1462  		[]byte("hello " + space),
  1463  		[]byte(space + " hello")},
  1464  	{isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51",
  1465  		[]byte("hello"),
  1466  		[]byte("hello34\u0e50\u0e51"),
  1467  		[]byte("\u0e50\u0e5212hello")},
  1468  	{isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F",
  1469  		[]byte("hello"),
  1470  		[]byte("helloEF\u2C6F\u2C6FGH\u2C6F\u2C6F"),
  1471  		[]byte("\u2C6F\u2C6F\u2C6F\u2C6FABCDhello")},
  1472  	{not(isSpace), "hello" + space + "hello",
  1473  		[]byte(space),
  1474  		[]byte(space + "hello"),
  1475  		[]byte("hello" + space)},
  1476  	{not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo",
  1477  		[]byte("\u0e50\u0e521234\u0e50\u0e51"),
  1478  		[]byte("\u0e50\u0e521234\u0e50\u0e51helo"),
  1479  		[]byte("hello\u0e50\u0e521234\u0e50\u0e51")},
  1480  	{isValidRune, "ab\xc0a\xc0cd",
  1481  		[]byte("\xc0a\xc0"),
  1482  		[]byte("\xc0a\xc0cd"),
  1483  		[]byte("ab\xc0a\xc0")},
  1484  	{not(isValidRune), "\xc0a\xc0",
  1485  		[]byte("a"),
  1486  		[]byte("a\xc0"),
  1487  		[]byte("\xc0a")},
  1488  	// The nils returned by TrimLeftFunc are odd behavior, but we need
  1489  	// to preserve backwards compatibility.
  1490  	{isSpace, "",
  1491  		nil,
  1492  		nil,
  1493  		[]byte("")},
  1494  	{isSpace, " ",
  1495  		nil,
  1496  		nil,
  1497  		[]byte("")},
  1498  }
  1499  
  1500  func TestTrimFunc(t *testing.T) {
  1501  	for _, tc := range trimFuncTests {
  1502  		trimmers := []struct {
  1503  			name string
  1504  			trim func(s []byte, f func(r rune) bool) []byte
  1505  			out  []byte
  1506  		}{
  1507  			{"TrimFunc", TrimFunc, tc.trimOut},
  1508  			{"TrimLeftFunc", TrimLeftFunc, tc.leftOut},
  1509  			{"TrimRightFunc", TrimRightFunc, tc.rightOut},
  1510  		}
  1511  		for _, trimmer := range trimmers {
  1512  			actual := trimmer.trim([]byte(tc.in), tc.f.f)
  1513  			if actual == nil && trimmer.out != nil {
  1514  				t.Errorf("%s(%q, %q) = nil; want %q", trimmer.name, tc.in, tc.f.name, trimmer.out)
  1515  			}
  1516  			if actual != nil && trimmer.out == nil {
  1517  				t.Errorf("%s(%q, %q) = %q; want nil", trimmer.name, tc.in, tc.f.name, actual)
  1518  			}
  1519  			if !Equal(actual, trimmer.out) {
  1520  				t.Errorf("%s(%q, %q) = %q; want %q", trimmer.name, tc.in, tc.f.name, actual, trimmer.out)
  1521  			}
  1522  		}
  1523  	}
  1524  }
  1525  
  1526  type IndexFuncTest struct {
  1527  	in          string
  1528  	f           predicate
  1529  	first, last int
  1530  }
  1531  
  1532  var indexFuncTests = []IndexFuncTest{
  1533  	{"", isValidRune, -1, -1},
  1534  	{"abc", isDigit, -1, -1},
  1535  	{"0123", isDigit, 0, 3},
  1536  	{"a1b", isDigit, 1, 1},
  1537  	{space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes
  1538  	{"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18},
  1539  	{"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34},
  1540  	{"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12},
  1541  
  1542  	// tests of invalid UTF-8
  1543  	{"\x801", isDigit, 1, 1},
  1544  	{"\x80abc", isDigit, -1, -1},
  1545  	{"\xc0a\xc0", isValidRune, 1, 1},
  1546  	{"\xc0a\xc0", not(isValidRune), 0, 2},
  1547  	{"\xc0☺\xc0", not(isValidRune), 0, 4},
  1548  	{"\xc0☺\xc0\xc0", not(isValidRune), 0, 5},
  1549  	{"ab\xc0a\xc0cd", not(isValidRune), 2, 4},
  1550  	{"a\xe0\x80cd", not(isValidRune), 1, 2},
  1551  }
  1552  
  1553  func TestIndexFunc(t *testing.T) {
  1554  	for _, tc := range indexFuncTests {
  1555  		first := IndexFunc([]byte(tc.in), tc.f.f)
  1556  		if first != tc.first {
  1557  			t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first)
  1558  		}
  1559  		last := LastIndexFunc([]byte(tc.in), tc.f.f)
  1560  		if last != tc.last {
  1561  			t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last)
  1562  		}
  1563  	}
  1564  }
  1565  
  1566  type ReplaceTest struct {
  1567  	in       string
  1568  	old, new string
  1569  	n        int
  1570  	out      string
  1571  }
  1572  
  1573  var ReplaceTests = []ReplaceTest{
  1574  	{"hello", "l", "L", 0, "hello"},
  1575  	{"hello", "l", "L", -1, "heLLo"},
  1576  	{"hello", "x", "X", -1, "hello"},
  1577  	{"", "x", "X", -1, ""},
  1578  	{"radar", "r", "<r>", -1, "<r>ada<r>"},
  1579  	{"", "", "<>", -1, "<>"},
  1580  	{"banana", "a", "<>", -1, "b<>n<>n<>"},
  1581  	{"banana", "a", "<>", 1, "b<>nana"},
  1582  	{"banana", "a", "<>", 1000, "b<>n<>n<>"},
  1583  	{"banana", "an", "<>", -1, "b<><>a"},
  1584  	{"banana", "ana", "<>", -1, "b<>na"},
  1585  	{"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"},
  1586  	{"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"},
  1587  	{"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"},
  1588  	{"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"},
  1589  	{"banana", "", "<>", 1, "<>banana"},
  1590  	{"banana", "a", "a", -1, "banana"},
  1591  	{"banana", "a", "a", 1, "banana"},
  1592  	{"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"},
  1593  }
  1594  
  1595  func TestReplace(t *testing.T) {
  1596  	for _, tt := range ReplaceTests {
  1597  		in := append([]byte(tt.in), "<spare>"...)
  1598  		in = in[:len(tt.in)]
  1599  		out := Replace(in, []byte(tt.old), []byte(tt.new), tt.n)
  1600  		if s := string(out); s != tt.out {
  1601  			t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out)
  1602  		}
  1603  		if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
  1604  			t.Errorf("Replace(%q, %q, %q, %d) didn't copy", tt.in, tt.old, tt.new, tt.n)
  1605  		}
  1606  		if tt.n == -1 {
  1607  			out := ReplaceAll(in, []byte(tt.old), []byte(tt.new))
  1608  			if s := string(out); s != tt.out {
  1609  				t.Errorf("ReplaceAll(%q, %q, %q) = %q, want %q", tt.in, tt.old, tt.new, s, tt.out)
  1610  			}
  1611  		}
  1612  	}
  1613  }
  1614  
  1615  type TitleTest struct {
  1616  	in, out string
  1617  }
  1618  
  1619  var TitleTests = []TitleTest{
  1620  	{"", ""},
  1621  	{"a", "A"},
  1622  	{" aaa aaa aaa ", " Aaa Aaa Aaa "},
  1623  	{" Aaa Aaa Aaa ", " Aaa Aaa Aaa "},
  1624  	{"123a456", "123a456"},
  1625  	{"double-blind", "Double-Blind"},
  1626  	{"ÿøû", "Ÿøû"},
  1627  	{"with_underscore", "With_underscore"},
  1628  	{"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"},
  1629  }
  1630  
  1631  func TestTitle(t *testing.T) {
  1632  	for _, tt := range TitleTests {
  1633  		if s := string(Title([]byte(tt.in))); s != tt.out {
  1634  			t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out)
  1635  		}
  1636  	}
  1637  }
  1638  
  1639  var ToTitleTests = []TitleTest{
  1640  	{"", ""},
  1641  	{"a", "A"},
  1642  	{" aaa aaa aaa ", " AAA AAA AAA "},
  1643  	{" Aaa Aaa Aaa ", " AAA AAA AAA "},
  1644  	{"123a456", "123A456"},
  1645  	{"double-blind", "DOUBLE-BLIND"},
  1646  	{"ÿøû", "ŸØÛ"},
  1647  }
  1648  
  1649  func TestToTitle(t *testing.T) {
  1650  	for _, tt := range ToTitleTests {
  1651  		if s := string(ToTitle([]byte(tt.in))); s != tt.out {
  1652  			t.Errorf("ToTitle(%q) = %q, want %q", tt.in, s, tt.out)
  1653  		}
  1654  	}
  1655  }
  1656  
  1657  var EqualFoldTests = []struct {
  1658  	s, t string
  1659  	out  bool
  1660  }{
  1661  	{"abc", "abc", true},
  1662  	{"ABcd", "ABcd", true},
  1663  	{"123abc", "123ABC", true},
  1664  	{"αβδ", "ΑΒΔ", true},
  1665  	{"abc", "xyz", false},
  1666  	{"abc", "XYZ", false},
  1667  	{"abcdefghijk", "abcdefghijX", false},
  1668  	{"abcdefghijk", "abcdefghij\u212A", true},
  1669  	{"abcdefghijK", "abcdefghij\u212A", true},
  1670  	{"abcdefghijkz", "abcdefghij\u212Ay", false},
  1671  	{"abcdefghijKz", "abcdefghij\u212Ay", false},
  1672  }
  1673  
  1674  func TestEqualFold(t *testing.T) {
  1675  	for _, tt := range EqualFoldTests {
  1676  		if out := EqualFold([]byte(tt.s), []byte(tt.t)); out != tt.out {
  1677  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out)
  1678  		}
  1679  		if out := EqualFold([]byte(tt.t), []byte(tt.s)); out != tt.out {
  1680  			t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out)
  1681  		}
  1682  	}
  1683  }
  1684  
  1685  var cutTests = []struct {
  1686  	s, sep        string
  1687  	before, after string
  1688  	found         bool
  1689  }{
  1690  	{"abc", "b", "a", "c", true},
  1691  	{"abc", "a", "", "bc", true},
  1692  	{"abc", "c", "ab", "", true},
  1693  	{"abc", "abc", "", "", true},
  1694  	{"abc", "", "", "abc", true},
  1695  	{"abc", "d", "abc", "", false},
  1696  	{"", "d", "", "", false},
  1697  	{"", "", "", "", true},
  1698  }
  1699  
  1700  func TestCut(t *testing.T) {
  1701  	for _, tt := range cutTests {
  1702  		if before, after, found := Cut([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || string(after) != tt.after || found != tt.found {
  1703  			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)
  1704  		}
  1705  	}
  1706  }
  1707  
  1708  var cutPrefixTests = []struct {
  1709  	s, sep string
  1710  	after  string
  1711  	found  bool
  1712  }{
  1713  	{"abc", "a", "bc", true},
  1714  	{"abc", "abc", "", true},
  1715  	{"abc", "", "abc", true},
  1716  	{"abc", "d", "abc", false},
  1717  	{"", "d", "", false},
  1718  	{"", "", "", true},
  1719  }
  1720  
  1721  func TestCutPrefix(t *testing.T) {
  1722  	for _, tt := range cutPrefixTests {
  1723  		if after, found := CutPrefix([]byte(tt.s), []byte(tt.sep)); string(after) != tt.after || found != tt.found {
  1724  			t.Errorf("CutPrefix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, after, found, tt.after, tt.found)
  1725  		}
  1726  	}
  1727  }
  1728  
  1729  var cutSuffixTests = []struct {
  1730  	s, sep string
  1731  	before string
  1732  	found  bool
  1733  }{
  1734  	{"abc", "bc", "a", true},
  1735  	{"abc", "abc", "", true},
  1736  	{"abc", "", "abc", true},
  1737  	{"abc", "d", "abc", false},
  1738  	{"", "d", "", false},
  1739  	{"", "", "", true},
  1740  }
  1741  
  1742  func TestCutSuffix(t *testing.T) {
  1743  	for _, tt := range cutSuffixTests {
  1744  		if before, found := CutSuffix([]byte(tt.s), []byte(tt.sep)); string(before) != tt.before || found != tt.found {
  1745  			t.Errorf("CutSuffix(%q, %q) = %q, %v, want %q, %v", tt.s, tt.sep, before, found, tt.before, tt.found)
  1746  		}
  1747  	}
  1748  }
  1749  
  1750  func TestBufferGrowNegative(t *testing.T) {
  1751  	defer func() {
  1752  		if err := recover(); err == nil {
  1753  			t.Fatal("Grow(-1) should have panicked")
  1754  		}
  1755  	}()
  1756  	var b Buffer
  1757  	b.Grow(-1)
  1758  }
  1759  
  1760  func TestBufferTruncateNegative(t *testing.T) {
  1761  	defer func() {
  1762  		if err := recover(); err == nil {
  1763  			t.Fatal("Truncate(-1) should have panicked")
  1764  		}
  1765  	}()
  1766  	var b Buffer
  1767  	b.Truncate(-1)
  1768  }
  1769  
  1770  func TestBufferTruncateOutOfRange(t *testing.T) {
  1771  	defer func() {
  1772  		if err := recover(); err == nil {
  1773  			t.Fatal("Truncate(20) should have panicked")
  1774  		}
  1775  	}()
  1776  	var b Buffer
  1777  	b.Write(make([]byte, 10))
  1778  	b.Truncate(20)
  1779  }
  1780  
  1781  var containsTests = []struct {
  1782  	b, subslice []byte
  1783  	want        bool
  1784  }{
  1785  	{[]byte("hello"), []byte("hel"), true},
  1786  	{[]byte("日本語"), []byte("日本"), true},
  1787  	{[]byte("hello"), []byte("Hello, world"), false},
  1788  	{[]byte("東京"), []byte("京東"), false},
  1789  }
  1790  
  1791  func TestContains(t *testing.T) {
  1792  	for _, tt := range containsTests {
  1793  		if got := Contains(tt.b, tt.subslice); got != tt.want {
  1794  			t.Errorf("Contains(%q, %q) = %v, want %v", tt.b, tt.subslice, got, tt.want)
  1795  		}
  1796  	}
  1797  }
  1798  
  1799  var ContainsAnyTests = []struct {
  1800  	b        []byte
  1801  	substr   string
  1802  	expected bool
  1803  }{
  1804  	{[]byte(""), "", false},
  1805  	{[]byte(""), "a", false},
  1806  	{[]byte(""), "abc", false},
  1807  	{[]byte("a"), "", false},
  1808  	{[]byte("a"), "a", true},
  1809  	{[]byte("aaa"), "a", true},
  1810  	{[]byte("abc"), "xyz", false},
  1811  	{[]byte("abc"), "xcz", true},
  1812  	{[]byte("a☺b☻c☹d"), "uvw☻xyz", true},
  1813  	{[]byte("aRegExp*"), ".(|)*+?^$[]", true},
  1814  	{[]byte(dots + dots + dots), " ", false},
  1815  }
  1816  
  1817  func TestContainsAny(t *testing.T) {
  1818  	for _, ct := range ContainsAnyTests {
  1819  		if ContainsAny(ct.b, ct.substr) != ct.expected {
  1820  			t.Errorf("ContainsAny(%s, %s) = %v, want %v",
  1821  				ct.b, ct.substr, !ct.expected, ct.expected)
  1822  		}
  1823  	}
  1824  }
  1825  
  1826  var ContainsRuneTests = []struct {
  1827  	b        []byte
  1828  	r        rune
  1829  	expected bool
  1830  }{
  1831  	{[]byte(""), 'a', false},
  1832  	{[]byte("a"), 'a', true},
  1833  	{[]byte("aaa"), 'a', true},
  1834  	{[]byte("abc"), 'y', false},
  1835  	{[]byte("abc"), 'c', true},
  1836  	{[]byte("a☺b☻c☹d"), 'x', false},
  1837  	{[]byte("a☺b☻c☹d"), '☻', true},
  1838  	{[]byte("aRegExp*"), '*', true},
  1839  }
  1840  
  1841  func TestContainsRune(t *testing.T) {
  1842  	for _, ct := range ContainsRuneTests {
  1843  		if ContainsRune(ct.b, ct.r) != ct.expected {
  1844  			t.Errorf("ContainsRune(%q, %q) = %v, want %v",
  1845  				ct.b, ct.r, !ct.expected, ct.expected)
  1846  		}
  1847  	}
  1848  }
  1849  
  1850  func TestContainsFunc(t *testing.T) {
  1851  	for _, ct := range ContainsRuneTests {
  1852  		if ContainsFunc(ct.b, func(r rune) bool {
  1853  			return ct.r == r
  1854  		}) != ct.expected {
  1855  			t.Errorf("ContainsFunc(%q, func(%q)) = %v, want %v",
  1856  				ct.b, ct.r, !ct.expected, ct.expected)
  1857  		}
  1858  	}
  1859  }
  1860  
  1861  var makeFieldsInput = func() []byte {
  1862  	x := make([]byte, 1<<20)
  1863  	// Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space.
  1864  	for i := range x {
  1865  		switch rand.Intn(10) {
  1866  		case 0:
  1867  			x[i] = ' '
  1868  		case 1:
  1869  			if i > 0 && x[i-1] == 'x' {
  1870  				copy(x[i-1:], "χ")
  1871  				break
  1872  			}
  1873  			fallthrough
  1874  		default:
  1875  			x[i] = 'x'
  1876  		}
  1877  	}
  1878  	return x
  1879  }
  1880  
  1881  var makeFieldsInputASCII = func() []byte {
  1882  	x := make([]byte, 1<<20)
  1883  	// Input is ~10% space, rest ASCII non-space.
  1884  	for i := range x {
  1885  		if rand.Intn(10) == 0 {
  1886  			x[i] = ' '
  1887  		} else {
  1888  			x[i] = 'x'
  1889  		}
  1890  	}
  1891  	return x
  1892  }
  1893  
  1894  var bytesdata = []struct {
  1895  	name string
  1896  	data []byte
  1897  }{
  1898  	{"ASCII", makeFieldsInputASCII()},
  1899  	{"Mixed", makeFieldsInput()},
  1900  }
  1901  
  1902  func BenchmarkFields(b *testing.B) {
  1903  	for _, sd := range bytesdata {
  1904  		b.Run(sd.name, func(b *testing.B) {
  1905  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1906  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1907  					b.ReportAllocs()
  1908  					b.SetBytes(int64(j))
  1909  					data := sd.data[:j]
  1910  					for i := 0; i < b.N; i++ {
  1911  						Fields(data)
  1912  					}
  1913  				})
  1914  			}
  1915  		})
  1916  	}
  1917  }
  1918  
  1919  func BenchmarkFieldsFunc(b *testing.B) {
  1920  	for _, sd := range bytesdata {
  1921  		b.Run(sd.name, func(b *testing.B) {
  1922  			for j := 1 << 4; j <= 1<<20; j <<= 4 {
  1923  				b.Run(fmt.Sprintf("%d", j), func(b *testing.B) {
  1924  					b.ReportAllocs()
  1925  					b.SetBytes(int64(j))
  1926  					data := sd.data[:j]
  1927  					for i := 0; i < b.N; i++ {
  1928  						FieldsFunc(data, unicode.IsSpace)
  1929  					}
  1930  				})
  1931  			}
  1932  		})
  1933  	}
  1934  }
  1935  
  1936  func BenchmarkTrimSpace(b *testing.B) {
  1937  	tests := []struct {
  1938  		name  string
  1939  		input []byte
  1940  	}{
  1941  		{"NoTrim", []byte("typical")},
  1942  		{"ASCII", []byte("  foo bar  ")},
  1943  		{"SomeNonASCII", []byte("    \u2000\t\r\n x\t\t\r\r\ny\n \u3000    ")},
  1944  		{"JustNonASCII", []byte("\u2000\u2000\u2000☺☺☺☺\u3000\u3000\u3000")},
  1945  	}
  1946  	for _, test := range tests {
  1947  		b.Run(test.name, func(b *testing.B) {
  1948  			for i := 0; i < b.N; i++ {
  1949  				TrimSpace(test.input)
  1950  			}
  1951  		})
  1952  	}
  1953  }
  1954  
  1955  func BenchmarkToValidUTF8(b *testing.B) {
  1956  	tests := []struct {
  1957  		name  string
  1958  		input []byte
  1959  	}{
  1960  		{"Valid", []byte("typical")},
  1961  		{"InvalidASCII", []byte("foo\xffbar")},
  1962  		{"InvalidNonASCII", []byte("日本語\xff日本語")},
  1963  	}
  1964  	replacement := []byte("\uFFFD")
  1965  	b.ResetTimer()
  1966  	for _, test := range tests {
  1967  		b.Run(test.name, func(b *testing.B) {
  1968  			for i := 0; i < b.N; i++ {
  1969  				ToValidUTF8(test.input, replacement)
  1970  			}
  1971  		})
  1972  	}
  1973  }
  1974  
  1975  func makeBenchInputHard() []byte {
  1976  	tokens := [...]string{
  1977  		"<a>", "<p>", "<b>", "<strong>",
  1978  		"</a>", "</p>", "</b>", "</strong>",
  1979  		"hello", "world",
  1980  	}
  1981  	x := make([]byte, 0, 1<<20)
  1982  	for {
  1983  		i := rand.Intn(len(tokens))
  1984  		if len(x)+len(tokens[i]) >= 1<<20 {
  1985  			break
  1986  		}
  1987  		x = append(x, tokens[i]...)
  1988  	}
  1989  	return x
  1990  }
  1991  
  1992  var benchInputHard = makeBenchInputHard()
  1993  
  1994  func benchmarkIndexHard(b *testing.B, sep []byte) {
  1995  	for i := 0; i < b.N; i++ {
  1996  		Index(benchInputHard, sep)
  1997  	}
  1998  }
  1999  
  2000  func benchmarkLastIndexHard(b *testing.B, sep []byte) {
  2001  	for i := 0; i < b.N; i++ {
  2002  		LastIndex(benchInputHard, sep)
  2003  	}
  2004  }
  2005  
  2006  func benchmarkCountHard(b *testing.B, sep []byte) {
  2007  	for i := 0; i < b.N; i++ {
  2008  		Count(benchInputHard, sep)
  2009  	}
  2010  }
  2011  
  2012  func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, []byte("<>")) }
  2013  func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, []byte("</pre>")) }
  2014  func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, []byte("<b>hello world</b>")) }
  2015  func BenchmarkIndexHard4(b *testing.B) {
  2016  	benchmarkIndexHard(b, []byte("<pre><b>hello</b><strong>world</strong></pre>"))
  2017  }
  2018  
  2019  func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, []byte("<>")) }
  2020  func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, []byte("</pre>")) }
  2021  func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, []byte("<b>hello world</b>")) }
  2022  
  2023  func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, []byte("<>")) }
  2024  func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, []byte("</pre>")) }
  2025  func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, []byte("<b>hello world</b>")) }
  2026  
  2027  func BenchmarkSplitEmptySeparator(b *testing.B) {
  2028  	for i := 0; i < b.N; i++ {
  2029  		Split(benchInputHard, nil)
  2030  	}
  2031  }
  2032  
  2033  func BenchmarkSplitSingleByteSeparator(b *testing.B) {
  2034  	sep := []byte("/")
  2035  	for i := 0; i < b.N; i++ {
  2036  		Split(benchInputHard, sep)
  2037  	}
  2038  }
  2039  
  2040  func BenchmarkSplitMultiByteSeparator(b *testing.B) {
  2041  	sep := []byte("hello")
  2042  	for i := 0; i < b.N; i++ {
  2043  		Split(benchInputHard, sep)
  2044  	}
  2045  }
  2046  
  2047  func BenchmarkSplitNSingleByteSeparator(b *testing.B) {
  2048  	sep := []byte("/")
  2049  	for i := 0; i < b.N; i++ {
  2050  		SplitN(benchInputHard, sep, 10)
  2051  	}
  2052  }
  2053  
  2054  func BenchmarkSplitNMultiByteSeparator(b *testing.B) {
  2055  	sep := []byte("hello")
  2056  	for i := 0; i < b.N; i++ {
  2057  		SplitN(benchInputHard, sep, 10)
  2058  	}
  2059  }
  2060  
  2061  func BenchmarkRepeat(b *testing.B) {
  2062  	for i := 0; i < b.N; i++ {
  2063  		Repeat([]byte("-"), 80)
  2064  	}
  2065  }
  2066  
  2067  func BenchmarkRepeatLarge(b *testing.B) {
  2068  	s := Repeat([]byte("@"), 8*1024)
  2069  	for j := 8; j <= 30; j++ {
  2070  		for _, k := range []int{1, 16, 4097} {
  2071  			s := s[:k]
  2072  			n := (1 << j) / k
  2073  			if n == 0 {
  2074  				continue
  2075  			}
  2076  			b.Run(fmt.Sprintf("%d/%d", 1<<j, k), func(b *testing.B) {
  2077  				for i := 0; i < b.N; i++ {
  2078  					Repeat(s, n)
  2079  				}
  2080  				b.SetBytes(int64(n * len(s)))
  2081  			})
  2082  		}
  2083  	}
  2084  }
  2085  
  2086  func BenchmarkBytesCompare(b *testing.B) {
  2087  	for n := 1; n <= 2048; n <<= 1 {
  2088  		b.Run(fmt.Sprint(n), func(b *testing.B) {
  2089  			var x = make([]byte, n)
  2090  			var y = make([]byte, n)
  2091  
  2092  			for i := 0; i < n; i++ {
  2093  				x[i] = 'a'
  2094  			}
  2095  
  2096  			for i := 0; i < n; i++ {
  2097  				y[i] = 'a'
  2098  			}
  2099  
  2100  			b.ResetTimer()
  2101  			for i := 0; i < b.N; i++ {
  2102  				Compare(x, y)
  2103  			}
  2104  		})
  2105  	}
  2106  }
  2107  
  2108  func BenchmarkIndexAnyASCII(b *testing.B) {
  2109  	x := Repeat([]byte{'#'}, 2048) // Never matches set
  2110  	cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
  2111  	for k := 1; k <= 2048; k <<= 4 {
  2112  		for j := 1; j <= 64; j <<= 1 {
  2113  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2114  				for i := 0; i < b.N; i++ {
  2115  					IndexAny(x[:k], cs[:j])
  2116  				}
  2117  			})
  2118  		}
  2119  	}
  2120  }
  2121  
  2122  func BenchmarkIndexAnyUTF8(b *testing.B) {
  2123  	x := Repeat([]byte{'#'}, 2048) // Never matches set
  2124  	cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
  2125  	for k := 1; k <= 2048; k <<= 4 {
  2126  		for j := 1; j <= 64; j <<= 1 {
  2127  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2128  				for i := 0; i < b.N; i++ {
  2129  					IndexAny(x[:k], cs[:j])
  2130  				}
  2131  			})
  2132  		}
  2133  	}
  2134  }
  2135  
  2136  func BenchmarkLastIndexAnyASCII(b *testing.B) {
  2137  	x := Repeat([]byte{'#'}, 2048) // Never matches set
  2138  	cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
  2139  	for k := 1; k <= 2048; k <<= 4 {
  2140  		for j := 1; j <= 64; j <<= 1 {
  2141  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2142  				for i := 0; i < b.N; i++ {
  2143  					LastIndexAny(x[:k], cs[:j])
  2144  				}
  2145  			})
  2146  		}
  2147  	}
  2148  }
  2149  
  2150  func BenchmarkLastIndexAnyUTF8(b *testing.B) {
  2151  	x := Repeat([]byte{'#'}, 2048) // Never matches set
  2152  	cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
  2153  	for k := 1; k <= 2048; k <<= 4 {
  2154  		for j := 1; j <= 64; j <<= 1 {
  2155  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2156  				for i := 0; i < b.N; i++ {
  2157  					LastIndexAny(x[:k], cs[:j])
  2158  				}
  2159  			})
  2160  		}
  2161  	}
  2162  }
  2163  
  2164  func BenchmarkTrimASCII(b *testing.B) {
  2165  	cs := "0123456789abcdef"
  2166  	for k := 1; k <= 4096; k <<= 4 {
  2167  		for j := 1; j <= 16; j <<= 1 {
  2168  			b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
  2169  				x := Repeat([]byte(cs[:j]), k) // Always matches set
  2170  				for i := 0; i < b.N; i++ {
  2171  					Trim(x[:k], cs[:j])
  2172  				}
  2173  			})
  2174  		}
  2175  	}
  2176  }
  2177  
  2178  func BenchmarkTrimByte(b *testing.B) {
  2179  	x := []byte("  the quick brown fox   ")
  2180  	for i := 0; i < b.N; i++ {
  2181  		Trim(x, " ")
  2182  	}
  2183  }
  2184  
  2185  func BenchmarkIndexPeriodic(b *testing.B) {
  2186  	key := []byte{1, 1}
  2187  	for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
  2188  		b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
  2189  			buf := make([]byte, 1<<16)
  2190  			for i := 0; i < len(buf); i += skip {
  2191  				buf[i] = 1
  2192  			}
  2193  			for i := 0; i < b.N; i++ {
  2194  				Index(buf, key)
  2195  			}
  2196  		})
  2197  	}
  2198  }
  2199  
  2200  func TestClone(t *testing.T) {
  2201  	var cloneTests = [][]byte{
  2202  		[]byte(nil),
  2203  		[]byte{},
  2204  		Clone([]byte{}),
  2205  		[]byte(strings.Repeat("a", 42))[:0],
  2206  		[]byte(strings.Repeat("a", 42))[:0:0],
  2207  		[]byte("short"),
  2208  		[]byte(strings.Repeat("a", 42)),
  2209  	}
  2210  	for _, input := range cloneTests {
  2211  		clone := Clone(input)
  2212  		if !Equal(clone, input) {
  2213  			t.Errorf("Clone(%q) = %q; want %q", input, clone, input)
  2214  		}
  2215  
  2216  		if input == nil && clone != nil {
  2217  			t.Errorf("Clone(%#v) return value should be equal to nil slice.", input)
  2218  		}
  2219  
  2220  		if input != nil && clone == nil {
  2221  			t.Errorf("Clone(%#v) return value should not be equal to nil slice.", input)
  2222  		}
  2223  
  2224  		if cap(input) != 0 && unsafe.SliceData(input) == unsafe.SliceData(clone) {
  2225  			t.Errorf("Clone(%q) return value should not reference inputs backing memory.", input)
  2226  		}
  2227  	}
  2228  }