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. Every element of the returned slice is
   455  // non-empty. Unlike [Split], leading and trailing runs of white space characters
   456  // are discarded.
   457  func Fields(s []byte) [][]byte {
   458  	// First count the fields.
   459  	// This is an exact count if s is ASCII, otherwise it is an approximation.
   460  	n := 0
   461  	wasSpace := 1
   462  	// setBits is used to track which bits are set in the bytes of s.
   463  	setBits := uint8(0)
   464  	for i := 0; i < len(s); i++ {
   465  		r := s[i]
   466  		setBits |= r
   467  		isSpace := int(asciiSpace[r])
   468  		n += wasSpace & ^isSpace
   469  		wasSpace = isSpace
   470  	}
   471  
   472  	if setBits >= utf8.RuneSelf {
   473  		// Some runes in the input slice are not ASCII.
   474  		return FieldsFunc(s, unicode.IsSpace)
   475  	}
   476  
   477  	// ASCII fast path
   478  	a := make([][]byte, n)
   479  	na := 0
   480  	fieldStart := 0
   481  	i := 0
   482  	// Skip spaces in the front of the input.
   483  	for i < len(s) && asciiSpace[s[i]] != 0 {
   484  		i++
   485  	}
   486  	fieldStart = i
   487  	for i < len(s) {
   488  		if asciiSpace[s[i]] == 0 {
   489  			i++
   490  			continue
   491  		}
   492  		a[na] = s[fieldStart:i:i]
   493  		na++
   494  		i++
   495  		// Skip spaces in between fields.
   496  		for i < len(s) && asciiSpace[s[i]] != 0 {
   497  			i++
   498  		}
   499  		fieldStart = i
   500  	}
   501  	if fieldStart < len(s) { // Last field might end at EOF.
   502  		a[na] = s[fieldStart:len(s):len(s)]
   503  	}
   504  	return a
   505  }
   506  
   507  // FieldsFunc interprets s as a sequence of UTF-8-encoded code points.
   508  // It splits the slice s at each run of code points c satisfying f(c) and
   509  // returns a slice of subslices of s. If all code points in s satisfy f(c), or
   510  // len(s) == 0, an empty slice is returned. Every element of the returned slice is
   511  // non-empty. Unlike [Split], leading and trailing runs of code points
   512  // satisfying f(c) are discarded.
   513  //
   514  // FieldsFunc makes no guarantees about the order in which it calls f(c)
   515  // and assumes that f always returns the same value for a given c.
   516  func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
   517  	// A span is used to record a slice of s of the form s[start:end].
   518  	// The start index is inclusive and the end index is exclusive.
   519  	type span struct {
   520  		start int
   521  		end   int
   522  	}
   523  	spans := make([]span, 0, 32)
   524  
   525  	// Find the field start and end indices.
   526  	// Doing this in a separate pass (rather than slicing the string s
   527  	// and collecting the result substrings right away) is significantly
   528  	// more efficient, possibly due to cache effects.
   529  	start := -1 // valid span start if >= 0
   530  	for i := 0; i < len(s); {
   531  		r, size := utf8.DecodeRune(s[i:])
   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  		r, wid := utf8.DecodeRune(s[i:])
   614  		r = mapping(r)
   615  		if r >= 0 {
   616  			b = utf8.AppendRune(b, r)
   617  		}
   618  		i += wid
   619  	}
   620  	return b
   621  }
   622  
   623  // Despite being an exported symbol,
   624  // Repeat is linknamed by widely used packages.
   625  // Notable members of the hall of shame include:
   626  //   - gitee.com/quant1x/num
   627  //
   628  // Do not remove or change the type signature.
   629  // See go.dev/issue/67401.
   630  //
   631  // Note that this comment is not part of the doc comment.
   632  //
   633  //go:linkname Repeat
   634  
   635  // Repeat returns a new byte slice consisting of count copies of b.
   636  //
   637  // It panics if count is negative or if the result of (len(b) * count)
   638  // overflows.
   639  func Repeat(b []byte, count int) []byte {
   640  	if count == 0 {
   641  		return []byte{}
   642  	}
   643  
   644  	// Since we cannot return an error on overflow,
   645  	// we should panic if the repeat will generate an overflow.
   646  	// See golang.org/issue/16237.
   647  	if count < 0 {
   648  		panic("bytes: negative Repeat count")
   649  	}
   650  	hi, lo := bits.Mul(uint(len(b)), uint(count))
   651  	if hi > 0 || lo > uint(maxInt) {
   652  		panic("bytes: Repeat output length overflow")
   653  	}
   654  	n := int(lo) // lo = len(b) * count
   655  
   656  	if len(b) == 0 {
   657  		return []byte{}
   658  	}
   659  
   660  	// Past a certain chunk size it is counterproductive to use
   661  	// larger chunks as the source of the write, as when the source
   662  	// is too large we are basically just thrashing the CPU D-cache.
   663  	// So if the result length is larger than an empirically-found
   664  	// limit (8KB), we stop growing the source string once the limit
   665  	// is reached and keep reusing the same source string - that
   666  	// should therefore be always resident in the L1 cache - until we
   667  	// have completed the construction of the result.
   668  	// This yields significant speedups (up to +100%) in cases where
   669  	// the result length is large (roughly, over L2 cache size).
   670  	const chunkLimit = 8 * 1024
   671  	chunkMax := n
   672  	if chunkMax > chunkLimit {
   673  		chunkMax = chunkLimit / len(b) * len(b)
   674  		if chunkMax == 0 {
   675  			chunkMax = len(b)
   676  		}
   677  	}
   678  	nb := bytealg.MakeNoZero(n)[:n:n]
   679  	bp := copy(nb, b)
   680  	for bp < n {
   681  		chunk := min(bp, chunkMax)
   682  		bp += copy(nb[bp:], nb[:chunk])
   683  	}
   684  	return nb
   685  }
   686  
   687  // ToUpper returns a copy of the byte slice s with all Unicode letters mapped to
   688  // their upper case.
   689  func ToUpper(s []byte) []byte {
   690  	isASCII, hasLower := true, false
   691  	for i := 0; i < len(s); i++ {
   692  		c := s[i]
   693  		if c >= utf8.RuneSelf {
   694  			isASCII = false
   695  			break
   696  		}
   697  		hasLower = hasLower || ('a' <= c && c <= 'z')
   698  	}
   699  
   700  	if isASCII { // optimize for ASCII-only byte slices.
   701  		if !hasLower {
   702  			// Just return a copy.
   703  			return append([]byte(""), s...)
   704  		}
   705  		b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
   706  		for i := 0; i < len(s); i++ {
   707  			c := s[i]
   708  			if 'a' <= c && c <= 'z' {
   709  				c -= 'a' - 'A'
   710  			}
   711  			b[i] = c
   712  		}
   713  		return b
   714  	}
   715  	return Map(unicode.ToUpper, s)
   716  }
   717  
   718  // ToLower returns a copy of the byte slice s with all Unicode letters mapped to
   719  // their lower case.
   720  func ToLower(s []byte) []byte {
   721  	isASCII, hasUpper := true, false
   722  	for i := 0; i < len(s); i++ {
   723  		c := s[i]
   724  		if c >= utf8.RuneSelf {
   725  			isASCII = false
   726  			break
   727  		}
   728  		hasUpper = hasUpper || ('A' <= c && c <= 'Z')
   729  	}
   730  
   731  	if isASCII { // optimize for ASCII-only byte slices.
   732  		if !hasUpper {
   733  			return append([]byte(""), s...)
   734  		}
   735  		b := bytealg.MakeNoZero(len(s))[:len(s):len(s)]
   736  		for i := 0; i < len(s); i++ {
   737  			c := s[i]
   738  			if 'A' <= c && c <= 'Z' {
   739  				c += 'a' - 'A'
   740  			}
   741  			b[i] = c
   742  		}
   743  		return b
   744  	}
   745  	return Map(unicode.ToLower, s)
   746  }
   747  
   748  // ToTitle treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their title case.
   749  func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
   750  
   751  // ToUpperSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   752  // upper case, giving priority to the special casing rules.
   753  func ToUpperSpecial(c unicode.SpecialCase, s []byte) []byte {
   754  	return Map(c.ToUpper, s)
   755  }
   756  
   757  // ToLowerSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   758  // lower case, giving priority to the special casing rules.
   759  func ToLowerSpecial(c unicode.SpecialCase, s []byte) []byte {
   760  	return Map(c.ToLower, s)
   761  }
   762  
   763  // ToTitleSpecial treats s as UTF-8-encoded bytes and returns a copy with all the Unicode letters mapped to their
   764  // title case, giving priority to the special casing rules.
   765  func ToTitleSpecial(c unicode.SpecialCase, s []byte) []byte {
   766  	return Map(c.ToTitle, s)
   767  }
   768  
   769  // ToValidUTF8 treats s as UTF-8-encoded bytes and returns a copy with each run of bytes
   770  // representing invalid UTF-8 replaced with the bytes in replacement, which may be empty.
   771  func ToValidUTF8(s, replacement []byte) []byte {
   772  	b := make([]byte, 0, len(s)+len(replacement))
   773  	invalid := false // previous byte was from an invalid UTF-8 sequence
   774  	for i := 0; i < len(s); {
   775  		c := s[i]
   776  		if c < utf8.RuneSelf {
   777  			i++
   778  			invalid = false
   779  			b = append(b, c)
   780  			continue
   781  		}
   782  		_, wid := utf8.DecodeRune(s[i:])
   783  		if wid == 1 {
   784  			i++
   785  			if !invalid {
   786  				invalid = true
   787  				b = append(b, replacement...)
   788  			}
   789  			continue
   790  		}
   791  		invalid = false
   792  		b = append(b, s[i:i+wid]...)
   793  		i += wid
   794  	}
   795  	return b
   796  }
   797  
   798  // isSeparator reports whether the rune could mark a word boundary.
   799  // TODO: update when package unicode captures more of the properties.
   800  func isSeparator(r rune) bool {
   801  	// ASCII alphanumerics and underscore are not separators
   802  	if r <= 0x7F {
   803  		switch {
   804  		case '0' <= r && r <= '9':
   805  			return false
   806  		case 'a' <= r && r <= 'z':
   807  			return false
   808  		case 'A' <= r && r <= 'Z':
   809  			return false
   810  		case r == '_':
   811  			return false
   812  		}
   813  		return true
   814  	}
   815  	// Letters and digits are not separators
   816  	if unicode.IsLetter(r) || unicode.IsDigit(r) {
   817  		return false
   818  	}
   819  	// Otherwise, all we can do for now is treat spaces as separators.
   820  	return unicode.IsSpace(r)
   821  }
   822  
   823  // Title treats s as UTF-8-encoded bytes and returns a copy with all Unicode letters that begin
   824  // words mapped to their title case.
   825  //
   826  // Deprecated: The rule Title uses for word boundaries does not handle Unicode
   827  // punctuation properly. Use golang.org/x/text/cases instead.
   828  func Title(s []byte) []byte {
   829  	// Use a closure here to remember state.
   830  	// Hackish but effective. Depends on Map scanning in order and calling
   831  	// the closure once per rune.
   832  	prev := ' '
   833  	return Map(
   834  		func(r rune) rune {
   835  			if isSeparator(prev) {
   836  				prev = r
   837  				return unicode.ToTitle(r)
   838  			}
   839  			prev = r
   840  			return r
   841  		},
   842  		s)
   843  }
   844  
   845  // TrimLeftFunc treats s as UTF-8-encoded bytes and returns a subslice of s by slicing off
   846  // all leading UTF-8-encoded code points c that satisfy f(c).
   847  func TrimLeftFunc(s []byte, f func(r rune) bool) []byte {
   848  	i := indexFunc(s, f, false)
   849  	if i == -1 {
   850  		return nil
   851  	}
   852  	return s[i:]
   853  }
   854  
   855  // TrimRightFunc returns a subslice of s by slicing off all trailing
   856  // UTF-8-encoded code points c that satisfy f(c).
   857  func TrimRightFunc(s []byte, f func(r rune) bool) []byte {
   858  	i := lastIndexFunc(s, f, false)
   859  	if i >= 0 && s[i] >= utf8.RuneSelf {
   860  		_, wid := utf8.DecodeRune(s[i:])
   861  		i += wid
   862  	} else {
   863  		i++
   864  	}
   865  	return s[0:i]
   866  }
   867  
   868  // TrimFunc returns a subslice of s by slicing off all leading and trailing
   869  // UTF-8-encoded code points c that satisfy f(c).
   870  func TrimFunc(s []byte, f func(r rune) bool) []byte {
   871  	return TrimRightFunc(TrimLeftFunc(s, f), f)
   872  }
   873  
   874  // TrimPrefix returns s without the provided leading prefix string.
   875  // If s doesn't start with prefix, s is returned unchanged.
   876  func TrimPrefix(s, prefix []byte) []byte {
   877  	if HasPrefix(s, prefix) {
   878  		return s[len(prefix):]
   879  	}
   880  	return s
   881  }
   882  
   883  // TrimSuffix returns s without the provided trailing suffix string.
   884  // If s doesn't end with suffix, s is returned unchanged.
   885  func TrimSuffix(s, suffix []byte) []byte {
   886  	if HasSuffix(s, suffix) {
   887  		return s[:len(s)-len(suffix)]
   888  	}
   889  	return s
   890  }
   891  
   892  // IndexFunc interprets s as a sequence of UTF-8-encoded code points.
   893  // It returns the byte index in s of the first Unicode
   894  // code point satisfying f(c), or -1 if none do.
   895  func IndexFunc(s []byte, f func(r rune) bool) int {
   896  	return indexFunc(s, f, true)
   897  }
   898  
   899  // LastIndexFunc interprets s as a sequence of UTF-8-encoded code points.
   900  // It returns the byte index in s of the last Unicode
   901  // code point satisfying f(c), or -1 if none do.
   902  func LastIndexFunc(s []byte, f func(r rune) bool) int {
   903  	return lastIndexFunc(s, f, true)
   904  }
   905  
   906  // indexFunc is the same as IndexFunc except that if
   907  // truth==false, the sense of the predicate function is
   908  // inverted.
   909  func indexFunc(s []byte, f func(r rune) bool, truth bool) int {
   910  	start := 0
   911  	for start < len(s) {
   912  		r, wid := utf8.DecodeRune(s[start:])
   913  		if f(r) == truth {
   914  			return start
   915  		}
   916  		start += wid
   917  	}
   918  	return -1
   919  }
   920  
   921  // lastIndexFunc is the same as LastIndexFunc except that if
   922  // truth==false, the sense of the predicate function is
   923  // inverted.
   924  func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int {
   925  	for i := len(s); i > 0; {
   926  		r, size := rune(s[i-1]), 1
   927  		if r >= utf8.RuneSelf {
   928  			r, size = utf8.DecodeLastRune(s[0:i])
   929  		}
   930  		i -= size
   931  		if f(r) == truth {
   932  			return i
   933  		}
   934  	}
   935  	return -1
   936  }
   937  
   938  // asciiSet is a 32-byte value, where each bit represents the presence of a
   939  // given ASCII character in the set. The 128-bits of the lower 16 bytes,
   940  // starting with the least-significant bit of the lowest word to the
   941  // most-significant bit of the highest word, map to the full range of all
   942  // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
   943  // ensuring that any non-ASCII character will be reported as not in the set.
   944  // This allocates a total of 32 bytes even though the upper half
   945  // is unused to avoid bounds checks in asciiSet.contains.
   946  type asciiSet [8]uint32
   947  
   948  // makeASCIISet creates a set of ASCII characters and reports whether all
   949  // characters in chars are ASCII.
   950  func makeASCIISet(chars string) (as asciiSet, ok bool) {
   951  	for i := 0; i < len(chars); i++ {
   952  		c := chars[i]
   953  		if c >= utf8.RuneSelf {
   954  			return as, false
   955  		}
   956  		as[c/32] |= 1 << (c % 32)
   957  	}
   958  	return as, true
   959  }
   960  
   961  // contains reports whether c is inside the set.
   962  func (as *asciiSet) contains(c byte) bool {
   963  	return (as[c/32] & (1 << (c % 32))) != 0
   964  }
   965  
   966  // containsRune is a simplified version of strings.ContainsRune
   967  // to avoid importing the strings package.
   968  // We avoid bytes.ContainsRune to avoid allocating a temporary copy of s.
   969  func containsRune(s string, r rune) bool {
   970  	for _, c := range s {
   971  		if c == r {
   972  			return true
   973  		}
   974  	}
   975  	return false
   976  }
   977  
   978  // Trim returns a subslice of s by slicing off all leading and
   979  // trailing UTF-8-encoded code points contained in cutset.
   980  func Trim(s []byte, cutset string) []byte {
   981  	if len(s) == 0 {
   982  		// This is what we've historically done.
   983  		return nil
   984  	}
   985  	if cutset == "" {
   986  		return s
   987  	}
   988  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
   989  		return trimLeftByte(trimRightByte(s, cutset[0]), cutset[0])
   990  	}
   991  	if as, ok := makeASCIISet(cutset); ok {
   992  		return trimLeftASCII(trimRightASCII(s, &as), &as)
   993  	}
   994  	return trimLeftUnicode(trimRightUnicode(s, cutset), cutset)
   995  }
   996  
   997  // TrimLeft returns a subslice of s by slicing off all leading
   998  // UTF-8-encoded code points contained in cutset.
   999  func TrimLeft(s []byte, cutset string) []byte {
  1000  	if len(s) == 0 {
  1001  		// This is what we've historically done.
  1002  		return nil
  1003  	}
  1004  	if cutset == "" {
  1005  		return s
  1006  	}
  1007  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
  1008  		return trimLeftByte(s, cutset[0])
  1009  	}
  1010  	if as, ok := makeASCIISet(cutset); ok {
  1011  		return trimLeftASCII(s, &as)
  1012  	}
  1013  	return trimLeftUnicode(s, cutset)
  1014  }
  1015  
  1016  func trimLeftByte(s []byte, c byte) []byte {
  1017  	for len(s) > 0 && s[0] == c {
  1018  		s = s[1:]
  1019  	}
  1020  	if len(s) == 0 {
  1021  		// This is what we've historically done.
  1022  		return nil
  1023  	}
  1024  	return s
  1025  }
  1026  
  1027  func trimLeftASCII(s []byte, as *asciiSet) []byte {
  1028  	for len(s) > 0 {
  1029  		if !as.contains(s[0]) {
  1030  			break
  1031  		}
  1032  		s = s[1:]
  1033  	}
  1034  	if len(s) == 0 {
  1035  		// This is what we've historically done.
  1036  		return nil
  1037  	}
  1038  	return s
  1039  }
  1040  
  1041  func trimLeftUnicode(s []byte, cutset string) []byte {
  1042  	for len(s) > 0 {
  1043  		r, n := utf8.DecodeRune(s)
  1044  		if !containsRune(cutset, r) {
  1045  			break
  1046  		}
  1047  		s = s[n:]
  1048  	}
  1049  	if len(s) == 0 {
  1050  		// This is what we've historically done.
  1051  		return nil
  1052  	}
  1053  	return s
  1054  }
  1055  
  1056  // TrimRight returns a subslice of s by slicing off all trailing
  1057  // UTF-8-encoded code points that are contained in cutset.
  1058  func TrimRight(s []byte, cutset string) []byte {
  1059  	if len(s) == 0 || cutset == "" {
  1060  		return s
  1061  	}
  1062  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
  1063  		return trimRightByte(s, cutset[0])
  1064  	}
  1065  	if as, ok := makeASCIISet(cutset); ok {
  1066  		return trimRightASCII(s, &as)
  1067  	}
  1068  	return trimRightUnicode(s, cutset)
  1069  }
  1070  
  1071  func trimRightByte(s []byte, c byte) []byte {
  1072  	for len(s) > 0 && s[len(s)-1] == c {
  1073  		s = s[:len(s)-1]
  1074  	}
  1075  	return s
  1076  }
  1077  
  1078  func trimRightASCII(s []byte, as *asciiSet) []byte {
  1079  	for len(s) > 0 {
  1080  		if !as.contains(s[len(s)-1]) {
  1081  			break
  1082  		}
  1083  		s = s[:len(s)-1]
  1084  	}
  1085  	return s
  1086  }
  1087  
  1088  func trimRightUnicode(s []byte, cutset string) []byte {
  1089  	for len(s) > 0 {
  1090  		r, n := rune(s[len(s)-1]), 1
  1091  		if r >= utf8.RuneSelf {
  1092  			r, n = utf8.DecodeLastRune(s)
  1093  		}
  1094  		if !containsRune(cutset, r) {
  1095  			break
  1096  		}
  1097  		s = s[:len(s)-n]
  1098  	}
  1099  	return s
  1100  }
  1101  
  1102  // TrimSpace returns a subslice of s by slicing off all leading and
  1103  // trailing white space, as defined by Unicode.
  1104  func TrimSpace(s []byte) []byte {
  1105  	// Fast path for ASCII: look for the first ASCII non-space byte.
  1106  	for lo, c := range s {
  1107  		if c >= utf8.RuneSelf {
  1108  			// If we run into a non-ASCII byte, fall back to the
  1109  			// slower unicode-aware method on the remaining bytes.
  1110  			return TrimFunc(s[lo:], unicode.IsSpace)
  1111  		}
  1112  		if asciiSpace[c] != 0 {
  1113  			continue
  1114  		}
  1115  		s = s[lo:]
  1116  		// Now look for the first ASCII non-space byte from the end.
  1117  		for hi := len(s) - 1; hi >= 0; hi-- {
  1118  			c := s[hi]
  1119  			if c >= utf8.RuneSelf {
  1120  				return TrimFunc(s[:hi+1], unicode.IsSpace)
  1121  			}
  1122  			if asciiSpace[c] == 0 {
  1123  				// At this point, s[:hi+1] starts and ends with ASCII
  1124  				// non-space bytes, so we're done. Non-ASCII cases have
  1125  				// already been handled above.
  1126  				return s[:hi+1]
  1127  			}
  1128  		}
  1129  	}
  1130  	// Special case to preserve previous TrimLeftFunc behavior,
  1131  	// returning nil instead of empty slice if all spaces.
  1132  	return nil
  1133  }
  1134  
  1135  // Runes interprets s as a sequence of UTF-8-encoded code points.
  1136  // It returns a slice of runes (Unicode code points) equivalent to s.
  1137  func Runes(s []byte) []rune {
  1138  	t := make([]rune, utf8.RuneCount(s))
  1139  	i := 0
  1140  	for len(s) > 0 {
  1141  		r, l := utf8.DecodeRune(s)
  1142  		t[i] = r
  1143  		i++
  1144  		s = s[l:]
  1145  	}
  1146  	return t
  1147  }
  1148  
  1149  // Replace returns a copy of the slice s with the first n
  1150  // non-overlapping instances of old replaced by new.
  1151  // If old is empty, it matches at the beginning of the slice
  1152  // and after each UTF-8 sequence, yielding up to k+1 replacements
  1153  // for a k-rune slice.
  1154  // If n < 0, there is no limit on the number of replacements.
  1155  func Replace(s, old, new []byte, n int) []byte {
  1156  	m := 0
  1157  	if n != 0 {
  1158  		// Compute number of replacements.
  1159  		m = Count(s, old)
  1160  	}
  1161  	if m == 0 {
  1162  		// Just return a copy.
  1163  		return append([]byte(nil), s...)
  1164  	}
  1165  	if n < 0 || m < n {
  1166  		n = m
  1167  	}
  1168  
  1169  	// Apply replacements to buffer.
  1170  	t := make([]byte, len(s)+n*(len(new)-len(old)))
  1171  	w := 0
  1172  	start := 0
  1173  	if len(old) > 0 {
  1174  		for range n {
  1175  			j := start + Index(s[start:], old)
  1176  			w += copy(t[w:], s[start:j])
  1177  			w += copy(t[w:], new)
  1178  			start = j + len(old)
  1179  		}
  1180  	} else { // len(old) == 0
  1181  		w += copy(t[w:], new)
  1182  		for range n - 1 {
  1183  			_, wid := utf8.DecodeRune(s[start:])
  1184  			j := start + wid
  1185  			w += copy(t[w:], s[start:j])
  1186  			w += copy(t[w:], new)
  1187  			start = j
  1188  		}
  1189  	}
  1190  	w += copy(t[w:], s[start:])
  1191  	return t[0:w]
  1192  }
  1193  
  1194  // ReplaceAll returns a copy of the slice s with all
  1195  // non-overlapping instances of old replaced by new.
  1196  // If old is empty, it matches at the beginning of the slice
  1197  // and after each UTF-8 sequence, yielding up to k+1 replacements
  1198  // for a k-rune slice.
  1199  func ReplaceAll(s, old, new []byte) []byte {
  1200  	return Replace(s, old, new, -1)
  1201  }
  1202  
  1203  // EqualFold reports whether s and t, interpreted as UTF-8 strings,
  1204  // are equal under simple Unicode case-folding, which is a more general
  1205  // form of case-insensitivity.
  1206  func EqualFold(s, t []byte) bool {
  1207  	// ASCII fast path
  1208  	i := 0
  1209  	for n := min(len(s), len(t)); i < n; i++ {
  1210  		sr := s[i]
  1211  		tr := t[i]
  1212  		if sr|tr >= utf8.RuneSelf {
  1213  			goto hasUnicode
  1214  		}
  1215  
  1216  		// Easy case.
  1217  		if tr == sr {
  1218  			continue
  1219  		}
  1220  
  1221  		// Make sr < tr to simplify what follows.
  1222  		if tr < sr {
  1223  			tr, sr = sr, tr
  1224  		}
  1225  		// ASCII only, sr/tr must be upper/lower case
  1226  		if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
  1227  			continue
  1228  		}
  1229  		return false
  1230  	}
  1231  	// Check if we've exhausted both strings.
  1232  	return len(s) == len(t)
  1233  
  1234  hasUnicode:
  1235  	s = s[i:]
  1236  	t = t[i:]
  1237  	for len(s) != 0 && len(t) != 0 {
  1238  		// Extract first rune from each.
  1239  		sr, size := utf8.DecodeRune(s)
  1240  		s = s[size:]
  1241  		tr, size := utf8.DecodeRune(t)
  1242  		t = t[size:]
  1243  
  1244  		// If they match, keep going; if not, return false.
  1245  
  1246  		// Easy case.
  1247  		if tr == sr {
  1248  			continue
  1249  		}
  1250  
  1251  		// Make sr < tr to simplify what follows.
  1252  		if tr < sr {
  1253  			tr, sr = sr, tr
  1254  		}
  1255  		// Fast check for ASCII.
  1256  		if tr < utf8.RuneSelf {
  1257  			// ASCII only, sr/tr must be upper/lower case
  1258  			if 'A' <= sr && sr <= 'Z' && tr == sr+'a'-'A' {
  1259  				continue
  1260  			}
  1261  			return false
  1262  		}
  1263  
  1264  		// General case. SimpleFold(x) returns the next equivalent rune > x
  1265  		// or wraps around to smaller values.
  1266  		r := unicode.SimpleFold(sr)
  1267  		for r != sr && r < tr {
  1268  			r = unicode.SimpleFold(r)
  1269  		}
  1270  		if r == tr {
  1271  			continue
  1272  		}
  1273  		return false
  1274  	}
  1275  
  1276  	// One string is empty. Are both?
  1277  	return len(s) == len(t)
  1278  }
  1279  
  1280  // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
  1281  func Index(s, sep []byte) int {
  1282  	n := len(sep)
  1283  	switch {
  1284  	case n == 0:
  1285  		return 0
  1286  	case n == 1:
  1287  		return IndexByte(s, sep[0])
  1288  	case n == len(s):
  1289  		if Equal(sep, s) {
  1290  			return 0
  1291  		}
  1292  		return -1
  1293  	case n > len(s):
  1294  		return -1
  1295  	case n <= bytealg.MaxLen:
  1296  		// Use brute force when s and sep both are small
  1297  		if len(s) <= bytealg.MaxBruteForce {
  1298  			return bytealg.Index(s, sep)
  1299  		}
  1300  		c0 := sep[0]
  1301  		c1 := sep[1]
  1302  		i := 0
  1303  		t := len(s) - n + 1
  1304  		fails := 0
  1305  		for i < t {
  1306  			if s[i] != c0 {
  1307  				// IndexByte is faster than bytealg.Index, so use it as long as
  1308  				// we're not getting lots of false positives.
  1309  				o := IndexByte(s[i+1:t], c0)
  1310  				if o < 0 {
  1311  					return -1
  1312  				}
  1313  				i += o + 1
  1314  			}
  1315  			if s[i+1] == c1 && Equal(s[i:i+n], sep) {
  1316  				return i
  1317  			}
  1318  			fails++
  1319  			i++
  1320  			// Switch to bytealg.Index when IndexByte produces too many false positives.
  1321  			if fails > bytealg.Cutover(i) {
  1322  				r := bytealg.Index(s[i:], sep)
  1323  				if r >= 0 {
  1324  					return r + i
  1325  				}
  1326  				return -1
  1327  			}
  1328  		}
  1329  		return -1
  1330  	}
  1331  	c0 := sep[0]
  1332  	c1 := sep[1]
  1333  	i := 0
  1334  	fails := 0
  1335  	t := len(s) - n + 1
  1336  	for i < t {
  1337  		if s[i] != c0 {
  1338  			o := IndexByte(s[i+1:t], c0)
  1339  			if o < 0 {
  1340  				break
  1341  			}
  1342  			i += o + 1
  1343  		}
  1344  		if s[i+1] == c1 && Equal(s[i:i+n], sep) {
  1345  			return i
  1346  		}
  1347  		i++
  1348  		fails++
  1349  		if fails >= 4+i>>4 && i < t {
  1350  			// Give up on IndexByte, it isn't skipping ahead
  1351  			// far enough to be better than Rabin-Karp.
  1352  			// Experiments (using IndexPeriodic) suggest
  1353  			// the cutover is about 16 byte skips.
  1354  			// TODO: if large prefixes of sep are matching
  1355  			// we should cutover at even larger average skips,
  1356  			// because Equal becomes that much more expensive.
  1357  			// This code does not take that effect into account.
  1358  			j := bytealg.IndexRabinKarp(s[i:], sep)
  1359  			if j < 0 {
  1360  				return -1
  1361  			}
  1362  			return i + j
  1363  		}
  1364  	}
  1365  	return -1
  1366  }
  1367  
  1368  // Cut slices s around the first instance of sep,
  1369  // returning the text before and after sep.
  1370  // The found result reports whether sep appears in s.
  1371  // If sep does not appear in s, cut returns s, nil, false.
  1372  //
  1373  // Cut returns slices of the original slice s, not copies.
  1374  func Cut(s, sep []byte) (before, after []byte, found bool) {
  1375  	if i := Index(s, sep); i >= 0 {
  1376  		return s[:i], s[i+len(sep):], true
  1377  	}
  1378  	return s, nil, false
  1379  }
  1380  
  1381  // Clone returns a copy of b[:len(b)].
  1382  // The result may have additional unused capacity.
  1383  // Clone(nil) returns nil.
  1384  func Clone(b []byte) []byte {
  1385  	if b == nil {
  1386  		return nil
  1387  	}
  1388  	return append([]byte{}, b...)
  1389  }
  1390  
  1391  // CutPrefix returns s without the provided leading prefix byte slice
  1392  // and reports whether it found the prefix.
  1393  // If s doesn't start with prefix, CutPrefix returns s, false.
  1394  // If prefix is the empty byte slice, CutPrefix returns s, true.
  1395  //
  1396  // CutPrefix returns slices of the original slice s, not copies.
  1397  func CutPrefix(s, prefix []byte) (after []byte, found bool) {
  1398  	if !HasPrefix(s, prefix) {
  1399  		return s, false
  1400  	}
  1401  	return s[len(prefix):], true
  1402  }
  1403  
  1404  // CutSuffix returns s without the provided ending suffix byte slice
  1405  // and reports whether it found the suffix.
  1406  // If s doesn't end with suffix, CutSuffix returns s, false.
  1407  // If suffix is the empty byte slice, CutSuffix returns s, true.
  1408  //
  1409  // CutSuffix returns slices of the original slice s, not copies.
  1410  func CutSuffix(s, suffix []byte) (before []byte, found bool) {
  1411  	if !HasSuffix(s, suffix) {
  1412  		return s, false
  1413  	}
  1414  	return s[:len(s)-len(suffix)], true
  1415  }
  1416  

View as plain text