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

View as plain text