github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/strings/strings.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package strings implements simple functions to manipulate UTF-8 encoded strings.
     6  //
     7  // For information about UTF-8 strings in Go, see https://blog.golang.org/strings.
     8  package strings
     9  
    10  import (
    11  	"unicode"
    12  	"unicode/utf8"
    13  )
    14  
    15  // explode splits s into a slice of UTF-8 strings,
    16  // one string per Unicode character up to a maximum of n (n < 0 means no limit).
    17  // Invalid UTF-8 sequences become correct encodings of U+FFFD.
    18  func explode(s string, n int) []string {
    19  	l := utf8.RuneCountInString(s)
    20  	if n < 0 || n > l {
    21  		n = l
    22  	}
    23  	a := make([]string, n)
    24  	for i := 0; i < n-1; i++ {
    25  		ch, size := utf8.DecodeRuneInString(s)
    26  		a[i] = s[:size]
    27  		s = s[size:]
    28  		if ch == utf8.RuneError {
    29  			a[i] = string(utf8.RuneError)
    30  		}
    31  	}
    32  	if n > 0 {
    33  		a[n-1] = s
    34  	}
    35  	return a
    36  }
    37  
    38  // primeRK is the prime base used in Rabin-Karp algorithm.
    39  const primeRK = 16777619
    40  
    41  // hashStr returns the hash and the appropriate multiplicative
    42  // factor for use in Rabin-Karp algorithm.
    43  func hashStr(sep string) (uint32, uint32) {
    44  	hash := uint32(0)
    45  	for i := 0; i < len(sep); i++ {
    46  		hash = hash*primeRK + uint32(sep[i])
    47  	}
    48  	var pow, sq uint32 = 1, primeRK
    49  	for i := len(sep); i > 0; i >>= 1 {
    50  		if i&1 != 0 {
    51  			pow *= sq
    52  		}
    53  		sq *= sq
    54  	}
    55  	return hash, pow
    56  }
    57  
    58  // hashStrRev returns the hash of the reverse of sep and the
    59  // appropriate multiplicative factor for use in Rabin-Karp algorithm.
    60  func hashStrRev(sep string) (uint32, uint32) {
    61  	hash := uint32(0)
    62  	for i := len(sep) - 1; i >= 0; i-- {
    63  		hash = hash*primeRK + uint32(sep[i])
    64  	}
    65  	var pow, sq uint32 = 1, primeRK
    66  	for i := len(sep); i > 0; i >>= 1 {
    67  		if i&1 != 0 {
    68  			pow *= sq
    69  		}
    70  		sq *= sq
    71  	}
    72  	return hash, pow
    73  }
    74  
    75  // countGeneric implements Count.
    76  func countGeneric(s, substr string) int {
    77  	// special case
    78  	if len(substr) == 0 {
    79  		return utf8.RuneCountInString(s) + 1
    80  	}
    81  	n := 0
    82  	for {
    83  		i := Index(s, substr)
    84  		if i == -1 {
    85  			return n
    86  		}
    87  		n++
    88  		s = s[i+len(substr):]
    89  	}
    90  }
    91  
    92  // Contains reports whether substr is within s.
    93  func Contains(s, substr string) bool {
    94  	return Index(s, substr) >= 0
    95  }
    96  
    97  // ContainsAny reports whether any Unicode code points in chars are within s.
    98  func ContainsAny(s, chars string) bool {
    99  	return IndexAny(s, chars) >= 0
   100  }
   101  
   102  // ContainsRune reports whether the Unicode code point r is within s.
   103  func ContainsRune(s string, r rune) bool {
   104  	return IndexRune(s, r) >= 0
   105  }
   106  
   107  // LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.
   108  func LastIndex(s, substr string) int {
   109  	n := len(substr)
   110  	switch {
   111  	case n == 0:
   112  		return len(s)
   113  	case n == 1:
   114  		return LastIndexByte(s, substr[0])
   115  	case n == len(s):
   116  		if substr == s {
   117  			return 0
   118  		}
   119  		return -1
   120  	case n > len(s):
   121  		return -1
   122  	}
   123  	// Rabin-Karp search from the end of the string
   124  	hashss, pow := hashStrRev(substr)
   125  	last := len(s) - n
   126  	var h uint32
   127  	for i := len(s) - 1; i >= last; i-- {
   128  		h = h*primeRK + uint32(s[i])
   129  	}
   130  	if h == hashss && s[last:] == substr {
   131  		return last
   132  	}
   133  	for i := last - 1; i >= 0; i-- {
   134  		h *= primeRK
   135  		h += uint32(s[i])
   136  		h -= pow * uint32(s[i+n])
   137  		if h == hashss && s[i:i+n] == substr {
   138  			return i
   139  		}
   140  	}
   141  	return -1
   142  }
   143  
   144  // IndexRune returns the index of the first instance of the Unicode code point
   145  // r, or -1 if rune is not present in s.
   146  // If r is utf8.RuneError, it returns the first instance of any
   147  // invalid UTF-8 byte sequence.
   148  func IndexRune(s string, r rune) int {
   149  	switch {
   150  	case 0 <= r && r < utf8.RuneSelf:
   151  		return IndexByte(s, byte(r))
   152  	case r == utf8.RuneError:
   153  		for i, r := range s {
   154  			if r == utf8.RuneError {
   155  				return i
   156  			}
   157  		}
   158  		return -1
   159  	case !utf8.ValidRune(r):
   160  		return -1
   161  	default:
   162  		return Index(s, string(r))
   163  	}
   164  }
   165  
   166  // IndexAny returns the index of the first instance of any Unicode code point
   167  // from chars in s, or -1 if no Unicode code point from chars is present in s.
   168  func IndexAny(s, chars string) int {
   169  	if len(chars) > 0 {
   170  		if len(s) > 8 {
   171  			if as, isASCII := makeASCIISet(chars); isASCII {
   172  				for i := 0; i < len(s); i++ {
   173  					if as.contains(s[i]) {
   174  						return i
   175  					}
   176  				}
   177  				return -1
   178  			}
   179  		}
   180  		for i, c := range s {
   181  			for _, m := range chars {
   182  				if c == m {
   183  					return i
   184  				}
   185  			}
   186  		}
   187  	}
   188  	return -1
   189  }
   190  
   191  // LastIndexAny returns the index of the last instance of any Unicode code
   192  // point from chars in s, or -1 if no Unicode code point from chars is
   193  // present in s.
   194  func LastIndexAny(s, chars string) int {
   195  	if len(chars) > 0 {
   196  		if len(s) > 8 {
   197  			if as, isASCII := makeASCIISet(chars); isASCII {
   198  				for i := len(s) - 1; i >= 0; i-- {
   199  					if as.contains(s[i]) {
   200  						return i
   201  					}
   202  				}
   203  				return -1
   204  			}
   205  		}
   206  		for i := len(s); i > 0; {
   207  			r, size := utf8.DecodeLastRuneInString(s[:i])
   208  			i -= size
   209  			for _, c := range chars {
   210  				if r == c {
   211  					return i
   212  				}
   213  			}
   214  		}
   215  	}
   216  	return -1
   217  }
   218  
   219  // LastIndexByte returns the index of the last instance of c in s, or -1 if c is not present in s.
   220  func LastIndexByte(s string, c byte) int {
   221  	for i := len(s) - 1; i >= 0; i-- {
   222  		if s[i] == c {
   223  			return i
   224  		}
   225  	}
   226  	return -1
   227  }
   228  
   229  // Generic split: splits after each instance of sep,
   230  // including sepSave bytes of sep in the subarrays.
   231  func genSplit(s, sep string, sepSave, n int) []string {
   232  	if n == 0 {
   233  		return nil
   234  	}
   235  	if sep == "" {
   236  		return explode(s, n)
   237  	}
   238  	if n < 0 {
   239  		n = Count(s, sep) + 1
   240  	}
   241  
   242  	a := make([]string, n)
   243  	n--
   244  	i := 0
   245  	for i < n {
   246  		m := Index(s, sep)
   247  		if m < 0 {
   248  			break
   249  		}
   250  		a[i] = s[:m+sepSave]
   251  		s = s[m+len(sep):]
   252  		i++
   253  	}
   254  	a[i] = s
   255  	return a[:i+1]
   256  }
   257  
   258  // SplitN slices s into substrings separated by sep and returns a slice of
   259  // the substrings between those separators.
   260  // If sep is empty, SplitN splits after each UTF-8 sequence.
   261  // The count determines the number of substrings to return:
   262  //   n > 0: at most n substrings; the last substring will be the unsplit remainder.
   263  //   n == 0: the result is nil (zero substrings)
   264  //   n < 0: all substrings
   265  func SplitN(s, sep string, n int) []string { return genSplit(s, sep, 0, n) }
   266  
   267  // SplitAfterN slices s into substrings after each instance of sep and
   268  // returns a slice of those substrings.
   269  // If sep is empty, SplitAfterN splits after each UTF-8 sequence.
   270  // The count determines the number of substrings to return:
   271  //   n > 0: at most n substrings; the last substring will be the unsplit remainder.
   272  //   n == 0: the result is nil (zero substrings)
   273  //   n < 0: all substrings
   274  func SplitAfterN(s, sep string, n int) []string {
   275  	return genSplit(s, sep, len(sep), n)
   276  }
   277  
   278  // Split slices s into all substrings separated by sep and returns a slice of
   279  // the substrings between those separators.
   280  // If sep is empty, Split splits after each UTF-8 sequence.
   281  // It is equivalent to SplitN with a count of -1.
   282  func Split(s, sep string) []string { return genSplit(s, sep, 0, -1) }
   283  
   284  // SplitAfter slices s into all substrings after each instance of sep and
   285  // returns a slice of those substrings.
   286  // If sep is empty, SplitAfter splits after each UTF-8 sequence.
   287  // It is equivalent to SplitAfterN with a count of -1.
   288  func SplitAfter(s, sep string) []string {
   289  	return genSplit(s, sep, len(sep), -1)
   290  }
   291  
   292  var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
   293  
   294  // Fields splits the string s around each instance of one or more consecutive white space
   295  // characters, as defined by unicode.IsSpace, returning an array of substrings of s or an
   296  // empty list if s contains only white space.
   297  func Fields(s string) []string {
   298  	// First count the fields.
   299  	// This is an exact count if s is ASCII, otherwise it is an approximation.
   300  	n := 0
   301  	wasSpace := 1
   302  	// setBits is used to track which bits are set in the bytes of s.
   303  	setBits := uint8(0)
   304  	for i := 0; i < len(s); i++ {
   305  		r := s[i]
   306  		setBits |= r
   307  		isSpace := int(asciiSpace[r])
   308  		n += wasSpace & ^isSpace
   309  		wasSpace = isSpace
   310  	}
   311  
   312  	if setBits < utf8.RuneSelf { // ASCII fast path
   313  		a := make([]string, n)
   314  		na := 0
   315  		fieldStart := 0
   316  		i := 0
   317  		// Skip spaces in the front of the input.
   318  		for i < len(s) && asciiSpace[s[i]] != 0 {
   319  			i++
   320  		}
   321  		fieldStart = i
   322  		for i < len(s) {
   323  			if asciiSpace[s[i]] == 0 {
   324  				i++
   325  				continue
   326  			}
   327  			a[na] = s[fieldStart:i]
   328  			na++
   329  			i++
   330  			// Skip spaces in between fields.
   331  			for i < len(s) && asciiSpace[s[i]] != 0 {
   332  				i++
   333  			}
   334  			fieldStart = i
   335  		}
   336  		if fieldStart < len(s) { // Last field might end at EOF.
   337  			a[na] = s[fieldStart:]
   338  		}
   339  		return a
   340  	}
   341  
   342  	// Some runes in the input string are not ASCII.
   343  	// Same general approach as in the ASCII path but
   344  	// uses DecodeRuneInString and unicode.IsSpace if
   345  	// a non-ASCII rune needs to be decoded and checked
   346  	// if it corresponds to a space.
   347  	a := make([]string, 0, n)
   348  	fieldStart := 0
   349  	i := 0
   350  	// Skip spaces in the front of the input.
   351  	for i < len(s) {
   352  		if c := s[i]; c < utf8.RuneSelf {
   353  			if asciiSpace[c] == 0 {
   354  				break
   355  			}
   356  			i++
   357  		} else {
   358  			r, w := utf8.DecodeRuneInString(s[i:])
   359  			if !unicode.IsSpace(r) {
   360  				break
   361  			}
   362  			i += w
   363  		}
   364  	}
   365  	fieldStart = i
   366  	for i < len(s) {
   367  		if c := s[i]; c < utf8.RuneSelf {
   368  			if asciiSpace[c] == 0 {
   369  				i++
   370  				continue
   371  			}
   372  			a = append(a, s[fieldStart:i])
   373  			i++
   374  		} else {
   375  			r, w := utf8.DecodeRuneInString(s[i:])
   376  			if !unicode.IsSpace(r) {
   377  				i += w
   378  				continue
   379  			}
   380  			a = append(a, s[fieldStart:i])
   381  			i += w
   382  		}
   383  		// Skip spaces in between fields.
   384  		for i < len(s) {
   385  			if c := s[i]; c < utf8.RuneSelf {
   386  				if asciiSpace[c] == 0 {
   387  					break
   388  				}
   389  				i++
   390  			} else {
   391  				r, w := utf8.DecodeRuneInString(s[i:])
   392  				if !unicode.IsSpace(r) {
   393  					break
   394  				}
   395  				i += w
   396  			}
   397  		}
   398  		fieldStart = i
   399  	}
   400  	if fieldStart < len(s) { // Last field might end at EOF.
   401  		a = append(a, s[fieldStart:])
   402  	}
   403  	return a
   404  }
   405  
   406  // FieldsFunc splits the string s at each run of Unicode code points c satisfying f(c)
   407  // and returns an array of slices of s. If all code points in s satisfy f(c) or the
   408  // string is empty, an empty slice is returned.
   409  // FieldsFunc makes no guarantees about the order in which it calls f(c).
   410  // If f does not return consistent results for a given c, FieldsFunc may crash.
   411  func FieldsFunc(s string, f func(rune) bool) []string {
   412  	// First count the fields.
   413  	n := 0
   414  	inField := false
   415  	for _, rune := range s {
   416  		wasInField := inField
   417  		inField = !f(rune)
   418  		if inField && !wasInField {
   419  			n++
   420  		}
   421  	}
   422  
   423  	// Now create them.
   424  	a := make([]string, n)
   425  	na := 0
   426  	fieldStart := -1 // Set to -1 when looking for start of field.
   427  	for i, rune := range s {
   428  		if f(rune) {
   429  			if fieldStart >= 0 {
   430  				a[na] = s[fieldStart:i]
   431  				na++
   432  				fieldStart = -1
   433  			}
   434  		} else if fieldStart == -1 {
   435  			fieldStart = i
   436  		}
   437  	}
   438  	if fieldStart >= 0 { // Last field might end at EOF.
   439  		a[na] = s[fieldStart:]
   440  	}
   441  	return a
   442  }
   443  
   444  // Join concatenates the elements of a to create a single string. The separator string
   445  // sep is placed between elements in the resulting string.
   446  func Join(a []string, sep string) string {
   447  	switch len(a) {
   448  	case 0:
   449  		return ""
   450  	case 1:
   451  		return a[0]
   452  	case 2:
   453  		// Special case for common small values.
   454  		// Remove if golang.org/issue/6714 is fixed
   455  		return a[0] + sep + a[1]
   456  	case 3:
   457  		// Special case for common small values.
   458  		// Remove if golang.org/issue/6714 is fixed
   459  		return a[0] + sep + a[1] + sep + a[2]
   460  	}
   461  	n := len(sep) * (len(a) - 1)
   462  	for i := 0; i < len(a); i++ {
   463  		n += len(a[i])
   464  	}
   465  
   466  	b := make([]byte, n)
   467  	bp := copy(b, a[0])
   468  	for _, s := range a[1:] {
   469  		bp += copy(b[bp:], sep)
   470  		bp += copy(b[bp:], s)
   471  	}
   472  	return string(b)
   473  }
   474  
   475  // HasPrefix tests whether the string s begins with prefix.
   476  func HasPrefix(s, prefix string) bool {
   477  	return len(s) >= len(prefix) && s[0:len(prefix)] == prefix
   478  }
   479  
   480  // HasSuffix tests whether the string s ends with suffix.
   481  func HasSuffix(s, suffix string) bool {
   482  	return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
   483  }
   484  
   485  // Map returns a copy of the string s with all its characters modified
   486  // according to the mapping function. If mapping returns a negative value, the character is
   487  // dropped from the string with no replacement.
   488  func Map(mapping func(rune) rune, s string) string {
   489  	// In the worst case, the string can grow when mapped, making
   490  	// things unpleasant. But it's so rare we barge in assuming it's
   491  	// fine. It could also shrink but that falls out naturally.
   492  
   493  	// The output buffer b is initialized on demand, the first
   494  	// time a character differs.
   495  	var b []byte
   496  	// nbytes is the number of bytes encoded in b.
   497  	var nbytes int
   498  
   499  	for i, c := range s {
   500  		r := mapping(c)
   501  		if r == c {
   502  			continue
   503  		}
   504  
   505  		b = make([]byte, len(s)+utf8.UTFMax)
   506  		nbytes = copy(b, s[:i])
   507  		if r >= 0 {
   508  			if r <= utf8.RuneSelf {
   509  				b[nbytes] = byte(r)
   510  				nbytes++
   511  			} else {
   512  				nbytes += utf8.EncodeRune(b[nbytes:], r)
   513  			}
   514  		}
   515  
   516  		if c == utf8.RuneError {
   517  			// RuneError is the result of either decoding
   518  			// an invalid sequence or '\uFFFD'. Determine
   519  			// the correct number of bytes we need to advance.
   520  			_, w := utf8.DecodeRuneInString(s[i:])
   521  			i += w
   522  		} else {
   523  			i += utf8.RuneLen(c)
   524  		}
   525  
   526  		s = s[i:]
   527  		break
   528  	}
   529  
   530  	if b == nil {
   531  		return s
   532  	}
   533  
   534  	for _, c := range s {
   535  		r := mapping(c)
   536  
   537  		// common case
   538  		if (0 <= r && r <= utf8.RuneSelf) && nbytes < len(b) {
   539  			b[nbytes] = byte(r)
   540  			nbytes++
   541  			continue
   542  		}
   543  
   544  		// b is not big enough or r is not a ASCII rune.
   545  		if r >= 0 {
   546  			if nbytes+utf8.UTFMax >= len(b) {
   547  				// Grow the buffer.
   548  				nb := make([]byte, 2*len(b))
   549  				copy(nb, b[:nbytes])
   550  				b = nb
   551  			}
   552  			nbytes += utf8.EncodeRune(b[nbytes:], r)
   553  		}
   554  	}
   555  
   556  	return string(b[:nbytes])
   557  }
   558  
   559  // Repeat returns a new string consisting of count copies of the string s.
   560  //
   561  // It panics if count is negative or if
   562  // the result of (len(s) * count) overflows.
   563  func Repeat(s string, count int) string {
   564  	// Since we cannot return an error on overflow,
   565  	// we should panic if the repeat will generate
   566  	// an overflow.
   567  	// See Issue golang.org/issue/16237
   568  	if count < 0 {
   569  		panic("strings: negative Repeat count")
   570  	} else if count > 0 && len(s)*count/count != len(s) {
   571  		panic("strings: Repeat count causes overflow")
   572  	}
   573  
   574  	b := make([]byte, len(s)*count)
   575  	bp := copy(b, s)
   576  	for bp < len(b) {
   577  		copy(b[bp:], b[:bp])
   578  		bp *= 2
   579  	}
   580  	return string(b)
   581  }
   582  
   583  // ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case.
   584  func ToUpper(s string) string { return Map(unicode.ToUpper, s) }
   585  
   586  // ToLower returns a copy of the string s with all Unicode letters mapped to their lower case.
   587  func ToLower(s string) string { return Map(unicode.ToLower, s) }
   588  
   589  // ToTitle returns a copy of the string s with all Unicode letters mapped to their title case.
   590  func ToTitle(s string) string { return Map(unicode.ToTitle, s) }
   591  
   592  // ToUpperSpecial returns a copy of the string s with all Unicode letters mapped to their
   593  // upper case, giving priority to the special casing rules.
   594  func ToUpperSpecial(c unicode.SpecialCase, s string) string {
   595  	return Map(func(r rune) rune { return c.ToUpper(r) }, s)
   596  }
   597  
   598  // ToLowerSpecial returns a copy of the string s with all Unicode letters mapped to their
   599  // lower case, giving priority to the special casing rules.
   600  func ToLowerSpecial(c unicode.SpecialCase, s string) string {
   601  	return Map(func(r rune) rune { return c.ToLower(r) }, s)
   602  }
   603  
   604  // ToTitleSpecial returns a copy of the string s with all Unicode letters mapped to their
   605  // title case, giving priority to the special casing rules.
   606  func ToTitleSpecial(c unicode.SpecialCase, s string) string {
   607  	return Map(func(r rune) rune { return c.ToTitle(r) }, s)
   608  }
   609  
   610  // isSeparator reports whether the rune could mark a word boundary.
   611  // TODO: update when package unicode captures more of the properties.
   612  func isSeparator(r rune) bool {
   613  	// ASCII alphanumerics and underscore are not separators
   614  	if r <= 0x7F {
   615  		switch {
   616  		case '0' <= r && r <= '9':
   617  			return false
   618  		case 'a' <= r && r <= 'z':
   619  			return false
   620  		case 'A' <= r && r <= 'Z':
   621  			return false
   622  		case r == '_':
   623  			return false
   624  		}
   625  		return true
   626  	}
   627  	// Letters and digits are not separators
   628  	if unicode.IsLetter(r) || unicode.IsDigit(r) {
   629  		return false
   630  	}
   631  	// Otherwise, all we can do for now is treat spaces as separators.
   632  	return unicode.IsSpace(r)
   633  }
   634  
   635  // Title returns a copy of the string s with all Unicode letters that begin words
   636  // mapped to their title case.
   637  //
   638  // BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly.
   639  func Title(s string) string {
   640  	// Use a closure here to remember state.
   641  	// Hackish but effective. Depends on Map scanning in order and calling
   642  	// the closure once per rune.
   643  	prev := ' '
   644  	return Map(
   645  		func(r rune) rune {
   646  			if isSeparator(prev) {
   647  				prev = r
   648  				return unicode.ToTitle(r)
   649  			}
   650  			prev = r
   651  			return r
   652  		},
   653  		s)
   654  }
   655  
   656  // TrimLeftFunc returns a slice of the string s with all leading
   657  // Unicode code points c satisfying f(c) removed.
   658  func TrimLeftFunc(s string, f func(rune) bool) string {
   659  	i := indexFunc(s, f, false)
   660  	if i == -1 {
   661  		return ""
   662  	}
   663  	return s[i:]
   664  }
   665  
   666  // TrimRightFunc returns a slice of the string s with all trailing
   667  // Unicode code points c satisfying f(c) removed.
   668  func TrimRightFunc(s string, f func(rune) bool) string {
   669  	i := lastIndexFunc(s, f, false)
   670  	if i >= 0 && s[i] >= utf8.RuneSelf {
   671  		_, wid := utf8.DecodeRuneInString(s[i:])
   672  		i += wid
   673  	} else {
   674  		i++
   675  	}
   676  	return s[0:i]
   677  }
   678  
   679  // TrimFunc returns a slice of the string s with all leading
   680  // and trailing Unicode code points c satisfying f(c) removed.
   681  func TrimFunc(s string, f func(rune) bool) string {
   682  	return TrimRightFunc(TrimLeftFunc(s, f), f)
   683  }
   684  
   685  // IndexFunc returns the index into s of the first Unicode
   686  // code point satisfying f(c), or -1 if none do.
   687  func IndexFunc(s string, f func(rune) bool) int {
   688  	return indexFunc(s, f, true)
   689  }
   690  
   691  // LastIndexFunc returns the index into s of the last
   692  // Unicode code point satisfying f(c), or -1 if none do.
   693  func LastIndexFunc(s string, f func(rune) bool) int {
   694  	return lastIndexFunc(s, f, true)
   695  }
   696  
   697  // indexFunc is the same as IndexFunc except that if
   698  // truth==false, the sense of the predicate function is
   699  // inverted.
   700  func indexFunc(s string, f func(rune) bool, truth bool) int {
   701  	start := 0
   702  	for start < len(s) {
   703  		wid := 1
   704  		r := rune(s[start])
   705  		if r >= utf8.RuneSelf {
   706  			r, wid = utf8.DecodeRuneInString(s[start:])
   707  		}
   708  		if f(r) == truth {
   709  			return start
   710  		}
   711  		start += wid
   712  	}
   713  	return -1
   714  }
   715  
   716  // lastIndexFunc is the same as LastIndexFunc except that if
   717  // truth==false, the sense of the predicate function is
   718  // inverted.
   719  func lastIndexFunc(s string, f func(rune) bool, truth bool) int {
   720  	for i := len(s); i > 0; {
   721  		r, size := utf8.DecodeLastRuneInString(s[0:i])
   722  		i -= size
   723  		if f(r) == truth {
   724  			return i
   725  		}
   726  	}
   727  	return -1
   728  }
   729  
   730  // asciiSet is a 32-byte value, where each bit represents the presence of a
   731  // given ASCII character in the set. The 128-bits of the lower 16 bytes,
   732  // starting with the least-significant bit of the lowest word to the
   733  // most-significant bit of the highest word, map to the full range of all
   734  // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
   735  // ensuring that any non-ASCII character will be reported as not in the set.
   736  type asciiSet [8]uint32
   737  
   738  // makeASCIISet creates a set of ASCII characters and reports whether all
   739  // characters in chars are ASCII.
   740  func makeASCIISet(chars string) (as asciiSet, ok bool) {
   741  	for i := 0; i < len(chars); i++ {
   742  		c := chars[i]
   743  		if c >= utf8.RuneSelf {
   744  			return as, false
   745  		}
   746  		as[c>>5] |= 1 << uint(c&31)
   747  	}
   748  	return as, true
   749  }
   750  
   751  // contains reports whether c is inside the set.
   752  func (as *asciiSet) contains(c byte) bool {
   753  	return (as[c>>5] & (1 << uint(c&31))) != 0
   754  }
   755  
   756  func makeCutsetFunc(cutset string) func(rune) bool {
   757  	if len(cutset) == 1 && cutset[0] < utf8.RuneSelf {
   758  		return func(r rune) bool {
   759  			return r == rune(cutset[0])
   760  		}
   761  	}
   762  	if as, isASCII := makeASCIISet(cutset); isASCII {
   763  		return func(r rune) bool {
   764  			return r < utf8.RuneSelf && as.contains(byte(r))
   765  		}
   766  	}
   767  	return func(r rune) bool { return IndexRune(cutset, r) >= 0 }
   768  }
   769  
   770  // Trim returns a slice of the string s with all leading and
   771  // trailing Unicode code points contained in cutset removed.
   772  func Trim(s string, cutset string) string {
   773  	if s == "" || cutset == "" {
   774  		return s
   775  	}
   776  	return TrimFunc(s, makeCutsetFunc(cutset))
   777  }
   778  
   779  // TrimLeft returns a slice of the string s with all leading
   780  // Unicode code points contained in cutset removed.
   781  func TrimLeft(s string, cutset string) string {
   782  	if s == "" || cutset == "" {
   783  		return s
   784  	}
   785  	return TrimLeftFunc(s, makeCutsetFunc(cutset))
   786  }
   787  
   788  // TrimRight returns a slice of the string s, with all trailing
   789  // Unicode code points contained in cutset removed.
   790  func TrimRight(s string, cutset string) string {
   791  	if s == "" || cutset == "" {
   792  		return s
   793  	}
   794  	return TrimRightFunc(s, makeCutsetFunc(cutset))
   795  }
   796  
   797  // TrimSpace returns a slice of the string s, with all leading
   798  // and trailing white space removed, as defined by Unicode.
   799  func TrimSpace(s string) string {
   800  	return TrimFunc(s, unicode.IsSpace)
   801  }
   802  
   803  // TrimPrefix returns s without the provided leading prefix string.
   804  // If s doesn't start with prefix, s is returned unchanged.
   805  func TrimPrefix(s, prefix string) string {
   806  	if HasPrefix(s, prefix) {
   807  		return s[len(prefix):]
   808  	}
   809  	return s
   810  }
   811  
   812  // TrimSuffix returns s without the provided trailing suffix string.
   813  // If s doesn't end with suffix, s is returned unchanged.
   814  func TrimSuffix(s, suffix string) string {
   815  	if HasSuffix(s, suffix) {
   816  		return s[:len(s)-len(suffix)]
   817  	}
   818  	return s
   819  }
   820  
   821  // Replace returns a copy of the string s with the first n
   822  // non-overlapping instances of old replaced by new.
   823  // If old is empty, it matches at the beginning of the string
   824  // and after each UTF-8 sequence, yielding up to k+1 replacements
   825  // for a k-rune string.
   826  // If n < 0, there is no limit on the number of replacements.
   827  func Replace(s, old, new string, n int) string {
   828  	if old == new || n == 0 {
   829  		return s // avoid allocation
   830  	}
   831  
   832  	// Compute number of replacements.
   833  	if m := Count(s, old); m == 0 {
   834  		return s // avoid allocation
   835  	} else if n < 0 || m < n {
   836  		n = m
   837  	}
   838  
   839  	// Apply replacements to buffer.
   840  	t := make([]byte, len(s)+n*(len(new)-len(old)))
   841  	w := 0
   842  	start := 0
   843  	for i := 0; i < n; i++ {
   844  		j := start
   845  		if len(old) == 0 {
   846  			if i > 0 {
   847  				_, wid := utf8.DecodeRuneInString(s[start:])
   848  				j += wid
   849  			}
   850  		} else {
   851  			j += Index(s[start:], old)
   852  		}
   853  		w += copy(t[w:], s[start:j])
   854  		w += copy(t[w:], new)
   855  		start = j + len(old)
   856  	}
   857  	w += copy(t[w:], s[start:])
   858  	return string(t[0:w])
   859  }
   860  
   861  // EqualFold reports whether s and t, interpreted as UTF-8 strings,
   862  // are equal under Unicode case-folding.
   863  func EqualFold(s, t string) bool {
   864  	for s != "" && t != "" {
   865  		// Extract first rune from each string.
   866  		var sr, tr rune
   867  		if s[0] < utf8.RuneSelf {
   868  			sr, s = rune(s[0]), s[1:]
   869  		} else {
   870  			r, size := utf8.DecodeRuneInString(s)
   871  			sr, s = r, s[size:]
   872  		}
   873  		if t[0] < utf8.RuneSelf {
   874  			tr, t = rune(t[0]), t[1:]
   875  		} else {
   876  			r, size := utf8.DecodeRuneInString(t)
   877  			tr, t = r, t[size:]
   878  		}
   879  
   880  		// If they match, keep going; if not, return false.
   881  
   882  		// Easy case.
   883  		if tr == sr {
   884  			continue
   885  		}
   886  
   887  		// Make sr < tr to simplify what follows.
   888  		if tr < sr {
   889  			tr, sr = sr, tr
   890  		}
   891  		// Fast check for ASCII.
   892  		if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' {
   893  			// ASCII, and sr is upper case.  tr must be lower case.
   894  			if tr == sr+'a'-'A' {
   895  				continue
   896  			}
   897  			return false
   898  		}
   899  
   900  		// General case. SimpleFold(x) returns the next equivalent rune > x
   901  		// or wraps around to smaller values.
   902  		r := unicode.SimpleFold(sr)
   903  		for r != sr && r < tr {
   904  			r = unicode.SimpleFold(r)
   905  		}
   906  		if r == tr {
   907  			continue
   908  		}
   909  		return false
   910  	}
   911  
   912  	// One string is empty. Are both?
   913  	return s == t
   914  }