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

View as plain text