Source file src/bytes/bytes.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package bytes implements functions for the manipulation of byte slices.
     6  // It is analogous to the facilities of the [strings] package.
     7  package bytes
     8  
     9  import (
    10  	"internal/bytealg"
    11  	"math/bits"
    12  	"unicode"
    13  	"unicode/utf8"
    14  	_ "unsafe" // for linkname
    15  )
    16  
    17  // Equal reports whether a and b
    18  // are the same length and contain the same bytes.
    19  // A nil argument is equivalent to an empty slice.
    20  func Equal(a, b []byte) bool {
    21  	// Neither cmd/compile nor gccgo allocates for these string conversions.
    22  	return string(a) == string(b)
    23  }
    24  
    25  // Compare returns an integer comparing two byte slices lexicographically.
    26  // The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
    27  // A nil argument is equivalent to an empty slice.
    28  func Compare(a, b []byte) int {
    29  	return bytealg.Compare(a, b)
    30  }
    31  
    32  // explode splits s into a slice of UTF-8 sequences, one per Unicode code point (still slices of bytes),
    33  // up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes.
    34  func explode(s []byte, n int) [][]byte {
    35  	if n <= 0 || n > len(s) {
    36  		n = len(s)
    37  	}
    38  	a := make([][]byte, n)
    39  	var size int
    40  	na := 0
    41  	for len(s) > 0 {
    42  		if na+1 >= n {
    43  			a[na] = s
    44  			na++
    45  			break
    46  		}
    47  		_, size = utf8.DecodeRune(s)
    48  		a[na] = s[0:size:size]
    49  		s = s[size:]
    50  		na++
    51  	}
    52  	return a[0:na]
    53  }
    54  
    55  // Count counts the number of non-overlapping instances of sep in s.
    56  // If sep is an empty slice, Count returns 1 + the number of UTF-8-encoded code points in s.
    57  func Count(s, sep []byte) int {
    58  	// special case
    59  	if len(sep) == 0 {
    60  		return utf8.RuneCount(s) + 1
    61  	}
    62  	if len(sep) == 1 {
    63  		return bytealg.Count(s, sep[0])
    64  	}
    65  	n := 0
    66  	for {
    67  		i := Index(s, sep)
    68  		if i == -1 {
    69  			return n
    70  		}
    71  		n++
    72  		s = s[i+len(sep):]
    73  	}
    74  }
    75  
    76  // Contains reports whether subslice is within b.
    77  func Contains(b, subslice []byte) bool {
    78  	return Index(b, subslice) != -1
    79  }
    80  
    81  // ContainsAny reports whether any of the UTF-8-encoded code points in chars are within b.
    82  func ContainsAny(b []byte, chars string) bool {
    83  	return IndexAny(b, chars) >= 0
    84  }
    85  
    86  // ContainsRune reports whether the rune is contained in the UTF-8-encoded byte slice b.
    87  func ContainsRune(b []byte, r rune) bool {
    88  	return IndexRune(b, r) >= 0
    89  }
    90  
    91  // ContainsFunc reports whether any of the UTF-8-encoded code points r within b satisfy f(r).
    92  func ContainsFunc(b []byte, f func(rune) bool) bool {
    93  	return IndexFunc(b, f) >= 0
    94  }
    95  
    96  // IndexByte returns the index of the first instance of c in b, or -1 if c is not present in b.
    97  func IndexByte(b []byte, c byte) int {
    98  	return bytealg.IndexByte(b, c)
    99  }
   100  
   101  func indexBytePortable(s []byte, c byte) int {
   102  	for i, b := range s {
   103  		if b == c {
   104  			return i
   105  		}
   106  	}
   107  	return -1
   108  }
   109  
   110  // LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
   111  func LastIndex(s, sep []byte) int {
   112  	n := len(sep)
   113  	switch {
   114  	case n == 0:
   115  		return len(s)
   116  	case n == 1:
   117  		return bytealg.LastIndexByte(s, sep[0])
   118  	case n == len(s):
   119  		if Equal(s, sep) {
   120  			return 0
   121  		}
   122  		return -1
   123  	case n > len(s):
   124  		return -1
   125  	}
   126  	return bytealg.LastIndexRabinKarp(s, sep)
   127  }
   128  
   129  // LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.
   130  func LastIndexByte(s []byte, c byte) int {
   131  	return bytealg.LastIndexByte(s, c)
   132  }
   133  
   134  // IndexRune interprets s as a sequence of UTF-8-encoded code points.
   135  // It returns the byte index of the first occurrence in s of the given rune.
   136  // It returns -1 if rune is not present in s.
   137  // If r is [utf8.RuneError], it returns the first instance of any
   138  // invalid UTF-8 byte sequence.
   139  func IndexRune(s []byte, r rune) int {
   140  	const haveFastIndex = bytealg.MaxBruteForce > 0
   141  	switch {
   142  	case 0 <= r && r < utf8.RuneSelf:
   143  		return IndexByte(s, byte(r))
   144  	case r == utf8.RuneError:
   145  		for i := 0; i < len(s); {
   146  			r1, n := utf8.DecodeRune(s[i:])
   147  			if r1 == utf8.RuneError {
   148  				return i
   149  			}
   150  			i += n
   151  		}
   152  		return -1
   153  	case !utf8.ValidRune(r):
   154  		return -1
   155  	default:
   156  		// Search for rune r using the last byte of its UTF-8 encoded form.
   157  		// The distribution of the last byte is more uniform compared to the
   158  		// first byte which has a 78% chance of being [240, 243, 244].
   159  		var b [utf8.UTFMax]byte
   160  		n := utf8.EncodeRune(b[:], r)
   161  		last := n - 1
   162  		i := last
   163  		fails := 0
   164  		for i < len(s) {
   165  			if s[i] != b[last] {
   166  				o := IndexByte(s[i+1:], b[last])
   167  				if o < 0 {
   168  					return -1
   169  				}
   170  				i += o + 1
   171  			}
   172  			// Step backwards comparing bytes.
   173  			for j := 1; j < n; j++ {
   174  				if s[i-j] != b[last-j] {
   175  					goto next
   176  				}
   177  			}
   178  			return i - last
   179  		next:
   180  			fails++
   181  			i++
   182  			if (haveFastIndex && fails > bytealg.Cutover(i)) && i < len(s) ||
   183  				(!haveFastIndex && fails >= 4+i>>4 && i < len(s)) {
   184  				goto fallback
   185  			}
   186  		}
   187  		return -1
   188  
   189  	fallback:
   190  		// Switch to bytealg.Index, if available, or a brute force search when
   191  		// IndexByte returns too many false positives.
   192  		if haveFastIndex {
   193  			if j := bytealg.Index(s[i-last:], b[:n]); j >= 0 {
   194  				return i + j - last
   195  			}
   196  		} else {
   197  			// If bytealg.Index is not available a brute force search is
   198  			// ~1.5-3x faster than Rabin-Karp since n is small.
   199  			c0 := b[last]
   200  			c1 := b[last-1] // There are at least 2 chars to match
   201  		loop:
   202  			for ; i < len(s); i++ {
   203  				if s[i] == c0 && s[i-1] == c1 {
   204  					for k := 2; k < n; k++ {
   205  						if s[i-k] != b[last-k] {
   206  							continue loop
   207  						}
   208  					}
   209  					return i - last
   210  				}
   211  			}
   212  		}
   213  		return -1
   214  	}
   215  }
   216  
   217  // IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points.
   218  // It returns the byte index of the first occurrence in s of any of the Unicode
   219  // code points in chars. It returns -1 if chars is empty or if there is no code
   220  // point in common.
   221  func IndexAny(s []byte, chars string) int {
   222  	if chars == "" {
   223  		// Avoid scanning all of s.
   224  		return -1
   225  	}
   226  	if len(s) == 1 {
   227  		r := rune(s[0])
   228  		if r >= utf8.RuneSelf {
   229  			// search utf8.RuneError.
   230  			for _, r = range chars {
   231  				if r == utf8.RuneError {
   232  					return 0
   233  				}
   234  			}
   235  			return -1
   236  		}
   237  		if bytealg.IndexByteString(chars, s[0]) >= 0 {
   238  			return 0
   239  		}
   240  		return -1
   241  	}
   242  	if len(chars) == 1 {
   243  		r := rune(chars[0])
   244  		if r >= utf8.RuneSelf {
   245  			r = utf8.RuneError
   246  		}
   247  		return IndexRune(s, r)
   248  	}
   249  	if len(s) > 8 {
   250  		if as, isASCII := makeASCIISet(chars); isASCII {
   251  			for i, c := range s {
   252  				if as.contains(c) {
   253  					return i
   254  				}
   255  			}
   256  			return -1
   257  		}
   258  	}
   259  	var width int
   260  	for i := 0; i < len(s); i += width {
   261  		r := rune(s[i])
   262  		if r < utf8.RuneSelf {
   263  			if bytealg.IndexByteString(chars, s[i]) >= 0 {
   264  				return i
   265  			}
   266  			width = 1
   267  			continue
   268  		}
   269  		r, width = utf8.DecodeRune(s[i:])
   270  		if r != utf8.RuneError {
   271  			// r is 2 to 4 bytes
   272  			if len(chars) == width {
   273  				if chars == string(r) {
   274  					return i
   275  				}
   276  				continue
   277  			}
   278  			// Use bytealg.IndexString for performance if available.
   279  			if bytealg.MaxLen >= width {
   280  				if bytealg.IndexString(chars, string(r)) >= 0 {
   281  					return i
   282  				}
   283  				continue
   284  			}
   285  		}
   286  		for _, ch := range chars {
   287  			if r == ch {
   288  				return i
   289  			}
   290  		}
   291  	}
   292  	return -1
   293  }
   294  
   295  // LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code
   296  // points. It returns the byte index of the last occurrence in s of any of
   297  // the Unicode code points in chars. It returns -1 if chars is empty or if
   298  // there is no code point in common.
   299  func LastIndexAny(s []byte, chars string) int {
   300  	if chars == "" {
   301  		// Avoid scanning all of s.
   302  		return -1
   303  	}
   304  	if len(s) > 8 {
   305  		if as, isASCII := makeASCIISet(chars); isASCII {
   306  			for i := len(s) - 1; i >= 0; i-- {
   307  				if as.contains(s[i]) {
   308  					return i
   309  				}
   310  			}
   311  			return -1
   312  		}
   313  	}
   314  	if len(s) == 1 {
   315  		r := rune(s[0])
   316  		if r >= utf8.RuneSelf {
   317  			for _, r = range chars {
   318  				if r == utf8.RuneError {
   319  					return 0
   320  				}
   321  			}
   322  			return -1
   323  		}
   324  		if bytealg.IndexByteString(chars, s[0]) >= 0 {
   325  			return 0
   326  		}
   327  		return -1
   328  	}
   329  	if len(chars) == 1 {
   330  		cr := rune(chars[0])
   331  		if cr >= utf8.RuneSelf {
   332  			cr = utf8.RuneError
   333  		}
   334  		for i := len(s); i > 0; {
   335  			r, size := utf8.DecodeLastRune(s[:i])
   336  			i -= size
   337  			if r == cr {
   338  				return i
   339  			}
   340  		}
   341  		return -1
   342  	}
   343  	for i := len(s); i > 0; {
   344  		r := rune(s[i-1])
   345  		if r < utf8.RuneSelf {
   346  			if bytealg.IndexByteString(chars, s[i-1]) >= 0 {
   347  				return i - 1
   348  			}
   349  			i--
   350  			continue
   351  		}
   352  		r, size := utf8.DecodeLastRune(s[:i])
   353  		i -= size
   354  		if r != utf8.RuneError {
   355  			// r is 2 to 4 bytes
   356  			if len(chars) == size {
   357  				if chars == string(r) {
   358  					return i
   359  				}
   360  				continue
   361  			}
   362  			// Use bytealg.IndexString for performance if available.
   363  			if bytealg.MaxLen >= size {
   364  				if bytealg.IndexString(chars, string(r)) >= 0 {
   365  					return i
   366  				}
   367  				continue
   368  			}
   369  		}
   370  		for _, ch := range chars {
   371  			if r == ch {
   372  				return i
   373  			}
   374  		}
   375  	}
   376  	return -1
   377  }
   378  
   379  // Generic split: splits after each instance of sep,
   380  // including sepSave bytes of sep in the subslices.
   381  func genSplit(s, sep []byte, sepSave, n int) [][]byte {
   382  	if n == 0 {
   383  		return nil
   384  	}
   385  	if len(sep) == 0 {
   386  		return explode(s, n)
   387  	}
   388  	if n < 0 {
   389  		n = Count(s, sep) + 1
   390  	}
   391  	if n > len(s)+1 {
   392  		n = len(s) + 1
   393  	}
   394  
   395  	a := make([][]byte, n)
   396  	n--
   397  	i := 0
   398  	for i < n {
   399  		m := Index(s, sep)
   400  		if m < 0 {
   401  			break
   402  		}
   403  		a[i] = s[: m+sepSave : m+sepSave]
   404  		s = s[m+len(sep):]
   405  		i++
   406  	}
   407  	a[i] = s
   408  	return a[:i+1]
   409  }
   410  
   411  // SplitN slices s into subslices separated by sep and returns a slice of
   412  // the subslices between those separators.
   413  // If sep is empty, SplitN splits after each UTF-8 sequence.
   414  // The count determines the number of subslices to return:
   415  //   - n > 0: at most n subslices; the last subslice will be the unsplit remainder;
   416  //   - n == 0: the result is nil (zero subslices);
   417  //   - n < 0: all subslices.
   418  //
   419  // To split around the first instance of a separator, see [Cut].
   420  func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
   421  
   422  // SplitAfterN slices s into subslices after each instance of sep and
   423  // returns a slice of those subslices.
   424  // If sep is empty, SplitAfterN splits after each UTF-8 sequence.
   425  // The count determines the number of subslices to return:
   426  //   - n > 0: at most n subslices; the last subslice will be the unsplit remainder;
   427  //   - n == 0: the result is nil (zero subslices);
   428  //   - n < 0: all subslices.
   429  func SplitAfterN(s, sep []byte, n int) [][]byte {
   430  	return genSplit(s, sep, len(sep), n)
   431  }
   432  
   433  // Split slices s into all subslices separated by sep and returns a slice of
   434  // the subslices between those separators.
   435  // If sep is empty, Split splits after each UTF-8 sequence.
   436  // It is equivalent to SplitN with a count of -1.
   437  //
   438  // To split around the first instance of a separator, see [Cut].
   439  func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) }
   440  
   441  // SplitAfter slices s into all subslices after each instance of sep and
   442  // returns a slice of those subslices.
   443  // If sep is empty, SplitAfter splits after each UTF-8 sequence.
   444  // It is equivalent to SplitAfterN with a count of -1.
   445  func SplitAfter(s, sep []byte) [][]byte {
   446  	return genSplit(s, sep, len(sep), -1)
   447  }
   448  
   449  var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
   450  
   451  // Fields interprets s as a sequence of UTF-8-encoded code points.
   452  // It splits the slice s around each instance of one or more consecutive white space
   453  // characters, as defined by [unicode.IsSpace], returning a slice of subslices of s or an
   454  // empty slice if s contains only white space.
   455  func Fields(s []byte) [][]byte {
   456  	// First count the fields.
   457  	// This is an exact count if s is ASCII, otherwise it is an approximation.
   458  	n := 0
   459  	wasSpace := 1
   460  	// setBits is used to track which bits are set in the bytes of s.
   461  	setBits := uint8(0)
   462  	for i := 0; i < len(s); i++ {
   463  		r := s[i]
   464  		setBits |= r
   465  		isSpace := int(asciiSpace[r])
   466  		n += wasSpace & ^isSpace
   467  		wasSpace = isSpace
   468  	}
   469  
   470  	if setBits >= utf8.RuneSelf {
   471  		// Some runes in the input slice are not ASCII.
   472  		return FieldsFunc(s, unicode.IsSpace)
   473  	}
   474  
   475  	// ASCII fast path
   476  	a := make([][]byte, n)
   477  	na := 0
   478  	fieldStart := 0
   479  	i := 0
   480  	// Skip spaces in the front of the input.
   481  	for i < len(s) && asciiSpace[s[i]] != 0 {
   482  		i++
   483  	}
   484  	fieldStart = i
   485  	for i < len(s) {
   486  		if asciiSpace[s[i]] == 0 {
   487  			i++
   488  			continue
   489  		}
   490  		a[na] = s[fieldStart:i:i]
   491  		na++
   492  		i++
   493  		// Skip spaces in between fields.
   494  		for i < len(s) && asciiSpace[s[i]] != 0 {
   495  			i++
   496  		}
   497  		fieldStart = i
   498  	}
   499  	if fieldStart < len(s) { // Last field might end at EOF.
   500  		a[na] = s[fieldStart:len(s):len(s)]
   501  	}
   502  	return a
   503  }
   504  
   505  // FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
   506  // It splits the slice s at each run of code points c satisfying f(c) and
   507  // returns a slice of subslices of s. If all code points in s satisfy f(c), or
   508  // len(s) == 0, an empty slice is returned.
   509  //
   510  // FieldsFunc makes no guarantees about the order in which it calls f(c)
   511  // and assumes that f always returns the same value for a given c.
   512  func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
   513  	// A span is used to record a slice of s of the form s[start:end].
   514  	// The start index is inclusive and the end index is exclusive.
   515  	type span struct {
   516  		start int
   517  		end   int
   518  	}
   519  	spans := make([]span, 0, 32)
   520  
   521  	// Find the field start and end indices.
   522  	// Doing this in a separate pass (rather than slicing the string s
   523  	// and collecting the result substrings right away) is significantly
   524  	// more efficient, possibly due to cache effects.
   525  	start := -1 // valid span start if >= 0
   526  	for i := 0; i < len(s); {
   527  		size := 1
   528  		r := rune(s[i])
   529  		if r >= utf8.RuneSelf {
   530  			r, size = utf8.DecodeRune(s[i:])
   531  		}
   532  		if f(r) {
   533  			if start >= 0 {
   534  				spans = append(spans, span{start, i})
   535  				start = -1
   536  			}
   537  		} else {
   538  			if start < 0 {
   539  				start = i
   540  			}
   541  		}
   542  		i += size
   543  	}
   544  
   545  	// Last field might end at EOF.
   546  	if start >= 0 {
   547  		spans = append(spans, span{start, len(s)})
   548  	}
   549  
   550  	// Create subslices from recorded field indices.
   551  	a := make([][]byte, len(spans))
   552  	for i, span := range spans {
   553  		a[i] = s[span.start:span.end:span.end]
   554  	}
   555  
   556  	return a
   557  }
   558  
   559  // Join concatenates the elements of s to create a new byte slice. The separator
   560  // sep is placed between elements in the resulting slice.
   561  func Join(s [][]byte, sep []byte) []byte {
   562  	if len(s) == 0 {
   563  		return []byte{}
   564  	}
   565  	if len(s) == 1 {
   566  		// Just return a copy.
   567  		return append([]byte(nil), s[0]...)
   568  	}
   569  
   570  	var n int
   571  	if len(sep) > 0 {
   572  		if len(sep) >= maxInt/(len(s)-1) {
   573  			panic("bytes: Join output length overflow")
   574  		}
   575  		n += len(sep) * (len(s) - 1)
   576  	}
   577  	for _, v := range s {
   578  		if len(v) > maxInt-n {
   579  			panic("bytes: Join output length overflow")
   580  		}
   581  		n += len(v)
   582  	}
   583  
   584  	b := bytealg.MakeNoZero(n)[:n:n]
   585  	bp := copy(b, s[0])
   586  	for _, v := range s[1:] {
   587  		bp += copy(b[bp:], sep)
   588  		bp += copy(b[bp:], v)
   589  	}
   590  	return b
   591  }
   592  
   593  // HasPrefix reports whether the byte slice s begins with prefix.
   594  func HasPrefix(s, prefix []byte) bool {
   595  	return len(s) >= len(prefix) && Equal(s[:len(prefix)], prefix)
   596  }
   597  
   598  // HasSuffix reports whether the byte slice s ends with suffix.
   599  func HasSuffix(s, suffix []byte) bool {
   600  	return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix)
   601  }
   602  
   603  // Map returns a copy of the byte slice s with all its characters modified
   604  // according to the mapping function. If mapping returns a negative value, the character is
   605  // dropped from the byte slice with no replacement. The characters in s and the
   606  // output are interpreted as UTF-8-encoded code points.
   607  func Map(mapping func(r rune) rune, s []byte) []byte {
   608  	// In the worst case, the slice can grow when mapped, making
   609  	// things unpleasant. But it's so rare we barge in assuming it's
   610  	// fine. It could also shrink but that falls out naturally.
   611  	b := make([]byte, 0, len(s))
   612  	for i := 0; i < len(s); {
   613  		wid := 1
   614  		r := rune(s[i])
   615  		if r >= utf8.RuneSelf {
   616  			r, wid = utf8.DecodeRune(s[i:])
   617  		}
   618  		r = mapping(r)
   619  		if r >= 0 {
   620  			b = utf8.AppendRune(b, r)
   621  		}
   622  		i += wid
   623  	}
   624  	return b
   625  }
   626  
   627  // Despite being an exported symbol,
   628  // Repeat is linknamed by widely used packages.
   629  // Notable members of the hall of shame include:
   630  //   - gitee.com/quant1x/num
   631  //
   632  // Do not remove or change the type signature.
   633  // See go.dev/issue/67401.
   634  //
   635  // Note that this comment is not part of the doc comment.
   636  //
   637  //go:linkname Repeat
   638  
   639  // Repeat returns a new byte slice consisting of count copies of b.
   640  //
   641  // It panics if count is negative or if the result of (len(b) * count)
   642  // overflows.
   643  func Repeat(b []byte, count int) []byte {
   644  	if count == 0 {
   645  		return []byte{}
   646  	}
   647  
   648  	// Since we cannot return an error on overflow,
   649  	// we should panic if the repeat will generate an overflow.
   650  	// See golang.org/issue/16237.
   651  	if count < 0 {
   652  		panic("bytes: negative Repeat count")
   653  	}
   654  	hi, lo := bits.Mul(uint(len(b)), uint(count))
   655  	if hi > 0 || lo > uint(maxInt) {
   656  		panic("bytes: Repeat output length overflow")
   657  	}
   658  	n := int(lo) // lo = len(b) * count
   659  
   660  	if len(b) == 0 {
   661  		return []byte{}
   662  	}
   663  
   664  	// Past a certain chunk size it is counterproductive to use
   665  	// larger chunks as the source of the write, as when the source
   666  	// is too large we are basically just thrashing the CPU D-cache.
   667  	// So if the result length is larger than an empirically-found
   668  	// limit (8KB), we stop growing the source string once the limit
   669  	// is reached and keep reusing the same source string - that
   670  	// should therefore be always resident in the L1 cache - until we
   671  	// have completed the construction of the result.
   672  	// This yields significant speedups (up to +100%) in cases where
   673  	// the result length is large (roughly, over L2 cache size).
   674  	const chunkLimit = 8 * 1024
   675  	chunkMax := n
   676  	if chunkMax > chunkLimit {
   677  		chunkMax = chunkLimit / len(b) * len(b)
   678  		if chunkMax == 0 {
   679  			chunkMax = len(b)
   680  		}
   681  	}
   682  	nb := bytealg.MakeNoZero(n)[:n:n]
   683  	bp := copy(nb, b)
   684  	for bp < n {
   685  		chunk := min(bp, chunkMax)
   686  		bp += copy(nb[bp:], nb[:chunk])
   687  	}
   688  	return nb
   689  }
   690  
   691  // ToUpper returns a copy of the byte slice s with all Unicode letters mapped to
   692  // their upper case.
   693  func ToUpper(s []byte) []byte {
   694  	isASCII, hasLower := true, false
   695  	for i := 0; i < len(s); i++ {
   696  		c := s[i]
   697  		if c >= utf8.RuneSelf {
   698  			isASCII = false
   699  			break
   700  		}
   701  		hasLower = hasLower || ('a' <= c && c <= 'z')
   702  	}
   703  
   704  	if isASCII { // optimize for ASCII-only byte slices.
   705  		if !hasLower {
   706  			// Just return a copy.
   707  			return append([]byte(""), s...)
   708  		}
   709  		b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
   710  		for i := 0; i < len(s); i++ {
   711  			c := s[i]
   712  			if 'a' <= c && c <= 'z' {
   713  				c -= 'a' - 'A'
   714  			}
   715  			b[i] = c
   716  		}
   717  		return b
   718  	}
   719  	return Map(unicode.ToUpper, s)
   720  }
   721  
   722  // ToLower returns a copy of the byte slice s with all Unicode letters mapped to
   723  // their lower case.
   724  func ToLower(s []byte) []byte {
   725  	isASCII, hasUpper := true, false
   726  	for i := 0; i < len(s); i++ {
   727  		c := s[i]
   728  		if c >= utf8.RuneSelf {
   729  			isASCII = false
   730  			break
   731  		}
   732  		hasUpper = hasUpper || ('A' <= c && c <= 'Z')
   733  	}
   734  
   735  	if isASCII { // optimize for ASCII-only byte slices.
   736  		if !hasUpper {
   737  			return append([]byte(""), s...)
   738  		}
   739  		b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
   740  		for i := 0; i < len(s); i++ {
   741  			c := s[i]
   742  			if 'A' <= c && c <= 'Z' {
   743  				c += 'a' - 'A'
   744  			}
   745  			b[i] = c
   746  		}
   747  		return b
   748  	}
   749  	return Map(unicode.ToLower, s)
   750  }
   751  
   752  // ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.
   753  func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
   754  
   755  // ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   756  // upper case, giving priority to the special casing rules.
   757  func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte {
   758  	return Map(c.ToUpper, s)
   759  }
   760  
   761  // ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   762  // lower case, giving priority to the special casing rules.
   763  func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte {
   764  	return Map(c.ToLower, s)
   765  }
   766  
   767  // ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   768  // title case, giving priority to the special casing rules.
   769  func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte {
   770  	return Map(c.ToTitle, s)
   771  }
   772  
   773  // ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes
   774  // representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.
   775  func ToValidUTF8(s, replacement []byte) []byte {
   776  	b := make([]byte, 0, len(s)+len(replacement))
   777  	invalid := false // previous byte was from an invalid UTF-8 sequence
   778  	for i := 0; i < len(s); {
   779  		c := s[i]
   780  		if c < utf8.RuneSelf {
   781  			i++
   782  			invalid = false
   783  			b = append(b, c)
   784  			continue
   785  		}
   786  		_, wid := utf8.DecodeRune(s[i:])
   787  		if wid == 1 {
   788  			i++
   789  			if !invalid {
   790  				invalid = true
   791  				b = append(b, replacement...)
   792  			}
   793  			continue
   794  		}
   795  		invalid = false
   796  		b = append(b, s[i:i+wid]...)
   797  		i += wid
   798  	}
   799  	return b
   800  }
   801  
   802  // isSeparator reports whether the rune could mark a word boundary.
   803  // TODO: update when package unicode captures more of the properties.
   804  func isSeparator(r rune) bool {
   805  	// ASCII alphanumerics and underscore are not separators
   806  	if r <= 0x7F {
   807  		switch {
   808  		case '0' <= r && r <= '9':
   809  			return false
   810  		case 'a' <= r && r <= 'z':
   811  			return false
   812  		case 'A' <= r && r <= 'Z':
   813  			return false
   814  		case r == '_':
   815  			return false
   816  		}
   817  		return true
   818  	}
   819  	// Letters and digits are not separators
   820  	if unicode.IsLetter(r) || unicode.IsDigit(r) {
   821  		return false
   822  	}
   823  	// Otherwise, all we can do for now is treat spaces as separators.
   824  	return unicode.IsSpace(r)
   825  }
   826  
   827  // Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin
   828  // words mapped to their title case.
   829  //
   830  // Deprecated: The rule Title uses for word boundaries does not handle Unicode
   831  // punctuation properly. Use golang.org/x/text/cases instead.
   832  func Title(s []byte) []byte {
   833  	// Use a closure here to remember state.
   834  	// Hackish but effective. Depends on Map scanning in order and calling
   835  	// the closure once per rune.
   836  	prev := ' '
   837  	return Map(
   838  		func(r rune) rune {
   839  			if isSeparator(prev) {
   840  				prev = r
   841  				return unicode.ToTitle(r)
   842  			}
   843  			prev = r
   844  			return r
   845  		},
   846  		s)
   847  }
   848  
   849  // TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off
   850  // all leading UTF-8-encoded code points c that satisfy f(c).
   851  func TrimLeftFunc(s []byte, f func(r rune) bool) []byte {
   852  	i := indexFunc(s, f, false)
   853  	if i == -1 {
   854  		return nil
   855  	}
   856  	return s[i:]
   857  }
   858  
   859  // TrimRightFunc returns a subslice of s by slicing off all trailing
   860  // UTF-8-encoded code points c that satisfy f(c).
   861  func TrimRightFunc(s []byte, f func(r rune) bool) []byte {
   862  	i := lastIndexFunc(s, f, false)
   863  	if i >= 0 && s[i] >= utf8.RuneSelf {
   864  		_, wid := utf8.DecodeRune(s[i:])
   865  		i += wid
   866  	} else {
   867  		i++
   868  	}
   869  	return s[0:i]
   870  }
   871  
   872  // TrimFunc returns a subslice of s by slicing off all leading and trailing
   873  // UTF-8-encoded code points c that satisfy f(c).
   874  func TrimFunc(s []byte, f func(r rune) bool) []byte {
   875  	return TrimRightFunc(TrimLeftFunc(s, f), f)
   876  }
   877  
   878  // TrimPrefix returns s without the provided leading prefix string.
   879  // If s doesn't start with prefix, s is returned unchanged.
   880  func TrimPrefix(s, prefix []byte) []byte {
   881  	if HasPrefix(s, prefix) {
   882  		return s[len(prefix):]
   883  	}
   884  	return s
   885  }
   886  
   887  // TrimSuffix returns s without the provided trailing suffix string.
   888  // If s doesn't end with suffix, s is returned unchanged.
   889  func TrimSuffix(s, suffix []byte) []byte {
   890  	if HasSuffix(s, suffix) {
   891  		return s[:len(s)-len(suffix)]
   892  	}
   893  	return s
   894  }
   895  
   896  // IndexFunc interprets s as a sequence of UTF-8-encoded code points.
   897  // It returns the byte index in s of the first Unicode
   898  // code point satisfying f(c), or -1 if none do.
   899  func IndexFunc(s []byte, f func(r rune) bool) int {
   900  	return indexFunc(s, f, true)
   901  }
   902  
   903  // LastIndexFunc interprets s as a sequence of UTF-8-encoded code points.
   904  // It returns the byte index in s of the last Unicode
   905  // code point satisfying f(c), or -1 if none do.
   906  func LastIndexFunc(s []byte, f func(r rune) bool) int {
   907  	return lastIndexFunc(s, f, true)
   908  }
   909  
   910  // indexFunc is the same as IndexFunc except that if
   911  // truth==false, the sense of the predicate function is
   912  // inverted.
   913  func indexFunc(s []byte, f func(r rune) bool, truth bool) int {
   914  	start := 0
   915  	for start < len(s) {
   916  		wid := 1
   917  		r := rune(s[start])
   918  		if r >= utf8.RuneSelf {
   919  			r, wid = utf8.DecodeRune(s[start:])
   920  		}
   921  		if f(r) == truth {
   922  			return start
   923  		}
   924  		start += wid
   925  	}
   926  	return -1
   927  }
   928  
   929  // lastIndexFunc is the same as LastIndexFunc except that if
   930  // truth==false, the sense of the predicate function is
   931  // inverted.
   932  func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int {
   933  	for i := len(s); i > 0; {
   934  		r, size := rune(s[i-1]), 1
   935  		if r >= utf8.RuneSelf {
   936  			r, size = utf8.DecodeLastRune(s[0:i])
   937  		}
   938  		i -= size
   939  		if f(r) == truth {
   940  			return i
   941  		}
   942  	}
   943  	return -1
   944  }
   945  
   946  // asciiSet is a 32-byte value, where each bit represents the presence of a
   947  // given ASCII character in the set. The 128-bits of the lower 16 bytes,
   948  // starting with the least-significant bit of the lowest word to the
   949  // most-significant bit of the highest word, map to the full range of all
   950  // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
   951  // ensuring that any non-ASCII character will be reported as not in the set.
   952  // This allocates a total of 32 bytes even though the upper half
   953  // is unused to avoid bounds checks in asciiSet.contains.
   954  type asciiSet [8]uint32
   955  
   956  // makeASCIISet creates a set of ASCII characters and reports whether all
   957  // characters in chars are ASCII.
   958  func makeASCIISet(chars string) (as asciiSet, ok bool) {
   959  	for i := 0; i < len(chars); i++ {
   960  		c := chars[i]
   961  		if c >= utf8.RuneSelf {
   962  			return as, false
   963  		}
   964  		as[c/32] |= 1 << (c % 32)
   965  	}
   966  	return as, true
   967  }
   968  
   969  // contains reports whether c is inside the set.
   970  func (as *asciiSet) contains(c byte) bool {
   971  	return (as[c/32] & (1 << (c % 32))) != 0
   972  }
   973  
   974  // containsRune is a simplified version of strings.ContainsRune
   975  // to avoid importing the strings package.
   976  // We avoid bytes.ContainsRune to avoid allocating a temporary copy of s.
   977  func containsRune(s string, r rune) bool {
   978  	for _, c := range s {
   979  		if c == r {
   980  			return true
   981  		}
   982  	}
   983  	return false
   984  }
   985  
   986  // Trim returns a subslice of s by slicing off all leading and
   987  // trailing UTF-8-encoded code points contained in cutset.
   988  func Trim(s []byte, cutset string) []byte {
   989  	if len(s) == 0 {
   990  		// This is what we've historically done.
   991  		return nil
   992  	}
   993  	if cutset == "" {
   994  		return s
   995  	}
   996  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
   997  		return trimLeftByte(trimRightByte(s, cutset[0]), cutset[0])
   998  	}
   999  	if as, ok := makeASCIISet(cutset); ok {
  1000  		return trimLeftASCII(trimRightASCII(s, &as), &as)
  1001  	}
  1002  	return trimLeftUnicode(trimRightUnicode(s, cutset), cutset)
  1003  }
  1004  
  1005  // TrimLeft returns a subslice of s by slicing off all leading
  1006  // UTF-8-encoded code points contained in cutset.
  1007  func TrimLeft(s []byte, cutset string) []byte {
  1008  	if len(s) == 0 {
  1009  		// This is what we've historically done.
  1010  		return nil
  1011  	}
  1012  	if cutset == "" {
  1013  		return s
  1014  	}
  1015  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
  1016  		return trimLeftByte(s, cutset[0])
  1017  	}
  1018  	if as, ok := makeASCIISet(cutset); ok {
  1019  		return trimLeftASCII(s, &as)
  1020  	}
  1021  	return trimLeftUnicode(s, cutset)
  1022  }
  1023  
  1024  func trimLeftByte(s []byte, c byte) []byte {
  1025  	for len(s) > 0 && s[0] == c {
  1026  		s = s[1:]
  1027  	}
  1028  	if len(s) == 0 {
  1029  		// This is what we've historically done.
  1030  		return nil
  1031  	}
  1032  	return s
  1033  }
  1034  
  1035  func trimLeftASCII(s []byte, as *asciiSet) []byte {
  1036  	for len(s) > 0 {
  1037  		if !as.contains(s[0]) {
  1038  			break
  1039  		}
  1040  		s = s[1:]
  1041  	}
  1042  	if len(s) == 0 {
  1043  		// This is what we've historically done.
  1044  		return nil
  1045  	}
  1046  	return s
  1047  }
  1048  
  1049  func trimLeftUnicode(s []byte, cutset string) []byte {
  1050  	for len(s) > 0 {
  1051  		r, n := rune(s[0]), 1
  1052  		if r >= utf8.RuneSelf {
  1053  			r, n = utf8.DecodeRune(s)
  1054  		}
  1055  		if !containsRune(cutset, r) {
  1056  			break
  1057  		}
  1058  		s = s[n:]
  1059  	}
  1060  	if len(s) == 0 {
  1061  		// This is what we've historically done.
  1062  		return nil
  1063  	}
  1064  	return s
  1065  }
  1066  
  1067  // TrimRight returns a subslice of s by slicing off all trailing
  1068  // UTF-8-encoded code points that are contained in cutset.
  1069  func TrimRight(s []byte, cutset string) []byte {
  1070  	if len(s) == 0 || cutset == "" {
  1071  		return s
  1072  	}
  1073  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
  1074  		return trimRightByte(s, cutset[0])
  1075  	}
  1076  	if as, ok := makeASCIISet(cutset); ok {
  1077  		return trimRightASCII(s, &as)
  1078  	}
  1079  	return trimRightUnicode(s, cutset)
  1080  }
  1081  
  1082  func trimRightByte(s []byte, c byte) []byte {
  1083  	for len(s) > 0 && s[len(s)-1] == c {
  1084  		s = s[:len(s)-1]
  1085  	}
  1086  	return s
  1087  }
  1088  
  1089  func trimRightASCII(s []byte, as *asciiSet) []byte {
  1090  	for len(s) > 0 {
  1091  		if !as.contains(s[len(s)-1]) {
  1092  			break
  1093  		}
  1094  		s = s[:len(s)-1]
  1095  	}
  1096  	return s
  1097  }
  1098  
  1099  func trimRightUnicode(s []byte, cutset string) []byte {
  1100  	for len(s) > 0 {
  1101  		r, n := rune(s[len(s)-1]), 1
  1102  		if r >= utf8.RuneSelf {
  1103  			r, n = utf8.DecodeLastRune(s)
  1104  		}
  1105  		if !containsRune(cutset, r) {
  1106  			break
  1107  		}
  1108  		s = s[:len(s)-n]
  1109  	}
  1110  	return s
  1111  }
  1112  
  1113  // TrimSpace returns a subslice of s by slicing off all leading and
  1114  // trailing white space, as defined by Unicode.
  1115  func TrimSpace(s []byte) []byte {
  1116  	// Fast path for ASCII: look for the first ASCII non-space byte
  1117  	start := 0
  1118  	for ; start < len(s); start++ {
  1119  		c := s[start]
  1120  		if c >= utf8.RuneSelf {
  1121  			// If we run into a non-ASCII byte, fall back to the
  1122  			// slower unicode-aware method on the remaining bytes
  1123  			return TrimFunc(s[start:], unicode.IsSpace)
  1124  		}
  1125  		if asciiSpace[c] == 0 {
  1126  			break
  1127  		}
  1128  	}
  1129  
  1130  	// Now look for the first ASCII non-space byte from the end
  1131  	stop := len(s)
  1132  	for ; stop > start; stop-- {
  1133  		c := s[stop-1]
  1134  		if c >= utf8.RuneSelf {
  1135  			return TrimFunc(s[start:stop], unicode.IsSpace)
  1136  		}
  1137  		if asciiSpace[c] == 0 {
  1138  			break
  1139  		}
  1140  	}
  1141  
  1142  	// At this point s[start:stop] starts and ends with an ASCII
  1143  	// non-space bytes, so we're done. Non-ASCII cases have already
  1144  	// been handled above.
  1145  	if start == stop {
  1146  		// Special case to preserve previous TrimLeftFunc behavior,
  1147  		// returning nil instead of empty slice if all spaces.
  1148  		return nil
  1149  	}
  1150  	return s[start:stop]
  1151  }
  1152  
  1153  // Runes interprets s as a sequence of UTF-8-encoded code points.
  1154  // It returns a slice of runes (Unicode code points) equivalent to s.
  1155  func Runes(s []byte) []rune {
  1156  	t := make([]rune, utf8.RuneCount(s))
  1157  	i := 0
  1158  	for len(s) > 0 {
  1159  		r, l := utf8.DecodeRune(s)
  1160  		t[i] = r
  1161  		i++
  1162  		s = s[l:]
  1163  	}
  1164  	return t
  1165  }
  1166  
  1167  // Replace returns a copy of the slice s with the first n
  1168  // non-overlapping instances of old replaced by new.
  1169  // If old is empty, it matches at the beginning of the slice
  1170  // and after each UTF-8 sequence, yielding up to k+1 replacements
  1171  // for a k-rune slice.
  1172  // If n < 0, there is no limit on the number of replacements.
  1173  func Replace(s, old, new []byte, n int) []byte {
  1174  	m := 0
  1175  	if n != 0 {
  1176  		// Compute number of replacements.
  1177  		m = Count(s, old)
  1178  	}
  1179  	if m == 0 {
  1180  		// Just return a copy.
  1181  		return append([]byte(nil), s...)
  1182  	}
  1183  	if n < 0 || m < n {
  1184  		n = m
  1185  	}
  1186  
  1187  	// Apply replacements to buffer.
  1188  	t := make([]byte, len(s)+n*(len(new)-len(old)))
  1189  	w := 0
  1190  	start := 0
  1191  	for i := 0; i < n; i++ {
  1192  		j := start
  1193  		if len(old) == 0 {
  1194  			if i > 0 {
  1195  				_, wid := utf8.DecodeRune(s[start:])
  1196  				j += wid
  1197  			}
  1198  		} else {
  1199  			j += Index(s[start:], old)
  1200  		}
  1201  		w += copy(t[w:], s[start:j])
  1202  		w += copy(t[w:], new)
  1203  		start = j + len(old)
  1204  	}
  1205  	w += copy(t[w:], s[start:])
  1206  	return t[0:w]
  1207  }
  1208  
  1209  // ReplaceAll returns a copy of the slice s with all
  1210  // non-overlapping instances of old replaced by new.
  1211  // If old is empty, it matches at the beginning of the slice
  1212  // and after each UTF-8 sequence, yielding up to k+1 replacements
  1213  // for a k-rune slice.
  1214  func ReplaceAll(s, old, new []byte) []byte {
  1215  	return Replace(s, old, new, -1)
  1216  }
  1217  
  1218  // EqualFold reports whether s and t, interpreted as UTF-8 strings,
  1219  // are equal under simple Unicode case-folding, which is a more general
  1220  // form of case-insensitivity.
  1221  func EqualFold(s, t []byte) bool {
  1222  	// ASCII fast path
  1223  	i := 0
  1224  	for ; i < len(s) && i < len(t); i++ {
  1225  		sr := s[i]
  1226  		tr := t[i]
  1227  		if sr|tr >= utf8.RuneSelf {
  1228  			goto hasUnicode
  1229  		}
  1230  
  1231  		// Easy case.
  1232  		if tr == sr {
  1233  			continue
  1234  		}
  1235  
  1236  		// Make sr < tr to simplify what follows.
  1237  		if tr < sr {
  1238  			tr, sr = sr, tr
  1239  		}
  1240  		// ASCII only, sr/tr must be upper/lower case
  1241  		if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
  1242  			continue
  1243  		}
  1244  		return false
  1245  	}
  1246  	// Check if we've exhausted both strings.
  1247  	return len(s) == len(t)
  1248  
  1249  hasUnicode:
  1250  	s = s[i:]
  1251  	t = t[i:]
  1252  	for len(s) != 0 && len(t) != 0 {
  1253  		// Extract first rune from each.
  1254  		var sr, tr rune
  1255  		if s[0] < utf8.RuneSelf {
  1256  			sr, s = rune(s[0]), s[1:]
  1257  		} else {
  1258  			r, size := utf8.DecodeRune(s)
  1259  			sr, s = r, s[size:]
  1260  		}
  1261  		if t[0] < utf8.RuneSelf {
  1262  			tr, t = rune(t[0]), t[1:]
  1263  		} else {
  1264  			r, size := utf8.DecodeRune(t)
  1265  			tr, t = r, t[size:]
  1266  		}
  1267  
  1268  		// If they match, keep going; if not, return false.
  1269  
  1270  		// Easy case.
  1271  		if tr == sr {
  1272  			continue
  1273  		}
  1274  
  1275  		// Make sr < tr to simplify what follows.
  1276  		if tr < sr {
  1277  			tr, sr = sr, tr
  1278  		}
  1279  		// Fast check for ASCII.
  1280  		if tr < utf8.RuneSelf {
  1281  			// ASCII only, sr/tr must be upper/lower case
  1282  			if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
  1283  				continue
  1284  			}
  1285  			return false
  1286  		}
  1287  
  1288  		// General case. SimpleFold(x) returns the next equivalent rune > x
  1289  		// or wraps around to smaller values.
  1290  		r := unicode.SimpleFold(sr)
  1291  		for r != sr && r < tr {
  1292  			r = unicode.SimpleFold(r)
  1293  		}
  1294  		if r == tr {
  1295  			continue
  1296  		}
  1297  		return false
  1298  	}
  1299  
  1300  	// One string is empty. Are both?
  1301  	return len(s) == len(t)
  1302  }
  1303  
  1304  // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
  1305  func Index(s, sep []byte) int {
  1306  	n := len(sep)
  1307  	switch {
  1308  	case n == 0:
  1309  		return 0
  1310  	case n == 1:
  1311  		return IndexByte(s, sep[0])
  1312  	case n == len(s):
  1313  		if Equal(sep, s) {
  1314  			return 0
  1315  		}
  1316  		return -1
  1317  	case n > len(s):
  1318  		return -1
  1319  	case n <= bytealg.MaxLen:
  1320  		// Use brute force when s and sep both are small
  1321  		if len(s) <= bytealg.MaxBruteForce {
  1322  			return bytealg.Index(s, sep)
  1323  		}
  1324  		c0 := sep[0]
  1325  		c1 := sep[1]
  1326  		i := 0
  1327  		t := len(s) - n + 1
  1328  		fails := 0
  1329  		for i < t {
  1330  			if s[i] != c0 {
  1331  				// IndexByte is faster than bytealg.Index, so use it as long as
  1332  				// we're not getting lots of false positives.
  1333  				o := IndexByte(s[i+1:t], c0)
  1334  				if o < 0 {
  1335  					return -1
  1336  				}
  1337  				i += o + 1
  1338  			}
  1339  			if s[i+1] == c1 && Equal(s[i:i+n], sep) {
  1340  				return i
  1341  			}
  1342  			fails++
  1343  			i++
  1344  			// Switch to bytealg.Index when IndexByte produces too many false positives.
  1345  			if fails > bytealg.Cutover(i) {
  1346  				r := bytealg.Index(s[i:], sep)
  1347  				if r >= 0 {
  1348  					return r + i
  1349  				}
  1350  				return -1
  1351  			}
  1352  		}
  1353  		return -1
  1354  	}
  1355  	c0 := sep[0]
  1356  	c1 := sep[1]
  1357  	i := 0
  1358  	fails := 0
  1359  	t := len(s) - n + 1
  1360  	for i < t {
  1361  		if s[i] != c0 {
  1362  			o := IndexByte(s[i+1:t], c0)
  1363  			if o < 0 {
  1364  				break
  1365  			}
  1366  			i += o + 1
  1367  		}
  1368  		if s[i+1] == c1 && Equal(s[i:i+n], sep) {
  1369  			return i
  1370  		}
  1371  		i++
  1372  		fails++
  1373  		if fails >= 4+i>>4 && i < t {
  1374  			// Give up on IndexByte, it isn't skipping ahead
  1375  			// far enough to be better than Rabin-Karp.
  1376  			// Experiments (using IndexPeriodic) suggest
  1377  			// the cutover is about 16 byte skips.
  1378  			// TODO: if large prefixes of sep are matching
  1379  			// we should cutover at even larger average skips,
  1380  			// because Equal becomes that much more expensive.
  1381  			// This code does not take that effect into account.
  1382  			j := bytealg.IndexRabinKarp(s[i:], sep)
  1383  			if j < 0 {
  1384  				return -1
  1385  			}
  1386  			return i + j
  1387  		}
  1388  	}
  1389  	return -1
  1390  }
  1391  
  1392  // Cut slices s around the first instance of sep,
  1393  // returning the text before and after sep.
  1394  // The found result reports whether sep appears in s.
  1395  // If sep does not appear in s, cut returns s, nil, false.
  1396  //
  1397  // Cut returns slices of the original slice s, not copies.
  1398  func Cut(s, sep []byte) (before, after []byte, found bool) {
  1399  	if i := Index(s, sep); i >= 0 {
  1400  		return s[:i], s[i+len(sep):], true
  1401  	}
  1402  	return s, nil, false
  1403  }
  1404  
  1405  // Clone returns a copy of b[:len(b)].
  1406  // The result may have additional unused capacity.
  1407  // Clone(nil) returns nil.
  1408  func Clone(b []byte) []byte {
  1409  	if b == nil {
  1410  		return nil
  1411  	}
  1412  	return append([]byte{}, b...)
  1413  }
  1414  
  1415  // CutPrefix returns s without the provided leading prefix byte slice
  1416  // and reports whether it found the prefix.
  1417  // If s doesn't start with prefix, CutPrefix returns s, false.
  1418  // If prefix is the empty byte slice, CutPrefix returns s, true.
  1419  //
  1420  // CutPrefix returns slices of the original slice s, not copies.
  1421  func CutPrefix(s, prefix []byte) (after []byte, found bool) {
  1422  	if !HasPrefix(s, prefix) {
  1423  		return s, false
  1424  	}
  1425  	return s[len(prefix):], true
  1426  }
  1427  
  1428  // CutSuffix returns s without the provided ending suffix byte slice
  1429  // and reports whether it found the suffix.
  1430  // If s doesn't end with suffix, CutSuffix returns s, false.
  1431  // If suffix is the empty byte slice, CutSuffix returns s, true.
  1432  //
  1433  // CutSuffix returns slices of the original slice s, not copies.
  1434  func CutSuffix(s, suffix []byte) (before []byte, found bool) {
  1435  	if !HasSuffix(s, suffix) {
  1436  		return s, false
  1437  	}
  1438  	return s[:len(s)-len(suffix)], true
  1439  }
  1440  

View as plain text