Debian Codegraph @

strcase.go

raw
1 // Copyright 2023 Charlie Vieth. All rights reserved.
2 // Use of this source code is governed by the MIT license.
3
4 package strcase
5
6 import (
7 "strings"
8 "unicode/utf8"
9
10 "github.com/charlievieth/strcase/internal/bytealg"
11 "github.com/charlievieth/strcase/internal/tables"
12 )
13
14 const UnicodeVersion = tables.UnicodeVersion
15
16 const maxBruteForce = 16 // substring length
17 const maxLen = 32 // subject length
18
19 func clamp(n int) int {
20 if n < 0 {
21 return -1
22 }
23 if n > 0 {
24 return 1
25 }
26 return 0
27 }
28
29 // Compare returns an integer comparing two strings lexicographically
30 // ignoring case.
31 // The result will be 0 if a == b, -1 if a < b, and +1 if a > b.
32 func Compare(s, t string) int {
33 // TODO: move next to hasPrefixUnicode
34 i := 0
35 for ; i < len(s) && i < len(t); i++ {
36 sr := s[i]
37 tr := t[i]
38 if (sr|tr)&utf8.RuneSelf != 0 {
39 goto hasUnicode
40 }
41 if sr == tr || _lower[sr] == _lower[tr] {
42 continue
43 }
44 if _lower[sr] < _lower[tr] {
45 return -1
46 }
47 return 1
48 }
49 return clamp(len(s) - len(t))
50
51 hasUnicode:
52 s = s[i:]
53 t = t[i:]
54 for _, sr := range s {
55 // If t is exhausted the strings are not equal.
56 if len(t) == 0 {
57 return 1
58 }
59 // Extract first rune from second string.
60 var tr rune
61 if t[0] < utf8.RuneSelf {
62 tr, t = rune(_lower[t[0]]), t[1:]
63 } else {
64 r, size := utf8.DecodeRuneInString(t)
65 tr, t = tables.CaseFold(r), t[size:]
66 }
67 // Easy case.
68 if sr == tr || tables.CaseFold(sr) == tr {
69 continue
70 }
71 return clamp(int(tables.CaseFold(sr)) - int(tr))
72 }
73 if len(t) == 0 {
74 return 0
75 }
76 return -1
77 }
78
79 // EqualFold reports whether s and t, interpreted as UTF-8 strings,
80 // are equal under simple Unicode case-folding, which is a more general
81 // form of case-insensitivity.
82 //
83 // EqualFold is included for symmetry with the strings package and because
84 // our implementation is usually 2x faster than [strings.EqualFold].
85 func EqualFold(s, t string) bool {
86 return Compare(s, t) == 0
87 }
88
89 func isAlpha(c byte) bool {
90 return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
91 }
92
93 // NB: we previously used a table that only contained the 128 ASCII characters
94 // and a mask, but this is a about ~6% faster.
95 var _lower = [256]byte{
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
97 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, ' ', '!', '"', '#', '$', '%',
98 '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4',
99 '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'a', 'b', 'c',
100 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
101 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '[', '\\', ']', '^', '_', '`', 'a',
102 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
103 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', 127,
104 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
105 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
106 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172,
107 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
108 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202,
109 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217,
110 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232,
111 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
112 248, 249, 250, 251, 252, 253, 254, 255,
113 }
114
115 // containsKelvin returns true if string s contains rune 'K' (Kelvin).
116 func containsKelvin(s string) bool {
117 // TODO: it might be faster to check with IndexNonASCII first
118 // then with Count.
119 return len(s) > 0 && indexRuneCase(s, '\u212A') != -1
120 }
121
122 // HasPrefix tests whether the string s begins with prefix ignoring case.
123 func HasPrefix(s, prefix string) bool {
124 ok, _ := hasPrefixUnicode(s, prefix)
125 return ok
126 }
127
128 // hasPrefixUnicode returns if string s begins with prefix (ignoring case) and
129 // if all of s was consumed matching prefix (either before a match could be found
130 // or is prefix consumes all of s).
131 func hasPrefixUnicode(s, prefix string) (bool, bool) {
132 // TODO: return an enum instead of two bools
133
134 // The max difference in encoded lengths between cases is 2 bytes for
135 // [kK] (1 byte) and Kelvin 'K' (3 bytes).
136 n := len(s)
137 if len(prefix) > n*3 || (len(prefix) > n*2 && !containsKelvin(prefix)) {
138 return false, true
139 }
140
141 // ASCII fast path
142 i := 0
143 for ; i < len(s) && i < len(prefix); i++ {
144 sr := s[i]
145 tr := prefix[i]
146 if (sr|tr)&utf8.RuneSelf != 0 {
147 goto hasUnicode
148 }
149 if tr == sr || _lower[sr] == _lower[tr] {
150 continue
151 }
152 return false, i == len(s)-1
153 }
154 // Check if we've exhausted s
155 return i == len(prefix), i == len(s)
156
157 hasUnicode:
158 s = s[i:]
159 prefix = prefix[i:]
160 for _, tr := range prefix {
161 // If s is exhausted the strings are not equal.
162 if len(s) == 0 {
163 return false, true
164 }
165 var sr rune
166 if s[0] < utf8.RuneSelf {
167 sr, s = rune(_lower[s[0]]), s[1:]
168 } else {
169 r, size := utf8.DecodeRuneInString(s)
170 sr, s = r, s[size:]
171 }
172 if tr == sr || tables.CaseFold(tr) == tables.CaseFold(sr) {
173 continue
174 }
175 return false, len(s) == 0
176 }
177 return true, len(s) == 0 // s exhausted
178 }
179
180 // TrimPrefix returns s without the provided leading prefix string.
181 // If s doesn't start with prefix, s is returned unchanged.
182 func TrimPrefix(s, prefix string) string {
183 // The max difference in encoded lengths between cases is 2 bytes for
184 // [kK] (1 byte) and Kelvin 'K' (3 bytes).
185 n := len(s)
186 if n*3 < len(prefix) || (n*2 < len(prefix) && !containsKelvin(prefix)) {
187 return s
188 }
189
190 // ASCII fast path
191 i := 0
192 for ; i < len(s) && i < len(prefix); i++ {
193 sr := s[i]
194 tr := prefix[i]
195 if (sr|tr)&utf8.RuneSelf != 0 {
196 goto hasUnicode
197 }
198 if tr == sr || _lower[sr] == _lower[tr] {
199 continue
200 }
201 return s
202 }
203 return s[i:]
204
205 hasUnicode:
206 ss := s
207 s = s[i:]
208 prefix = prefix[i:]
209 for _, tr := range prefix {
210 // If s is exhausted the strings are not equal.
211 if len(s) == 0 {
212 return ss
213 }
214
215 var sr rune
216 if s[0] < utf8.RuneSelf {
217 sr, s = rune(_lower[s[0]]), s[1:]
218 } else {
219 r, size := utf8.DecodeRuneInString(s)
220 sr, s = tables.CaseFold(r), s[size:]
221 }
222 if tr == sr || tables.CaseFold(tr) == sr {
223 continue
224 }
225 return ss
226 }
227 return s
228 }
229
230 // HasSuffix tests whether the string s ends with suffix.
231 func HasSuffix(s, suffix string) bool {
232 ok, _ := hasSuffixUnicode(s, suffix)
233 return ok
234 }
235
236 // hasSuffixUnicode returns if string s ends with suffix and the starting index
237 // of the suffix in s (so that we can trim it).
238 func hasSuffixUnicode(s, suffix string) (bool, int) {
239 // TODO: if s and suffix have similar lengths it might be faster
240 // to trim the left side of s then use HasPrefix since that saves
241 // us from have to use utf8.DecodeLastRuneInString which is slow.
242
243 // The max difference in encoded lengths between cases is 2 bytes for
244 // [kK] (1 byte) and Kelvin 'K' (3 bytes).
245 nt := len(suffix)
246 ns := len(s)
247 if nt == 0 {
248 return true, ns
249 }
250 if ns*3 < nt || (ns*2 < nt && !containsKelvin(suffix)) {
251 return false, 0
252 }
253
254 t := suffix
255 i := ns - 1
256 j := nt - 1
257 for ; i >= 0 && j >= 0; i, j = i-1, j-1 {
258 sr := s[i]
259 tr := t[j]
260 if (sr|tr)&utf8.RuneSelf != 0 {
261 goto hasUnicode
262 }
263 if tr == sr || _lower[sr] == _lower[tr] {
264 continue
265 }
266 return false, 0
267 }
268 return j == -1, i + 1
269
270 hasUnicode:
271 s = s[:i+1]
272 t = t[:j+1]
273 for len(s) != 0 && len(t) != 0 {
274 var sr, tr rune
275 if n := len(s) - 1; s[n] < utf8.RuneSelf {
276 sr, s = rune(_lower[s[n]]), s[:n]
277 } else {
278 r, size := utf8.DecodeLastRuneInString(s)
279 sr, s = r, s[:len(s)-size]
280 }
281 if n := len(t) - 1; t[n] < utf8.RuneSelf {
282 tr, t = rune(_lower[t[n]]), t[:n]
283 } else {
284 r, size := utf8.DecodeLastRuneInString(t)
285 tr, t = r, t[:len(t)-size]
286 }
287 if sr == tr || tables.CaseFold(sr) == tables.CaseFold(tr) {
288 continue
289 }
290 return false, 0
291 }
292
293 return len(t) == 0, len(s)
294 }
295
296 // TrimSuffix returns s without the provided trailing suffix string.
297 // If s doesn't end with suffix, s is returned unchanged.
298 func TrimSuffix(s, suffix string) string {
299 if match, i := hasSuffixUnicode(s, suffix); match {
300 return s[:i]
301 }
302 return s
303 }
304
305 // bruteForceIndexUnicode performs a brute-force search for substr in s.
306 func bruteForceIndexUnicode(s, substr string) int {
307 var u0, u1 rune
308 var sz0, sz1 int
309 if substr[0] < utf8.RuneSelf {
310 u0, sz0 = rune(substr[0]), 1
311 } else {
312 u0, sz0 = utf8.DecodeRuneInString(substr)
313 }
314 if substr[sz0] < utf8.RuneSelf {
315 u1, sz1 = rune(substr[sz0]), 1
316 } else {
317 u1, sz1 = utf8.DecodeRuneInString(substr[sz0:])
318 }
319 folds0 := tables.FoldMapExcludingUpperLower(u0)
320 folds1 := tables.FoldMapExcludingUpperLower(u1)
321 hasFolds0 := folds0[0] != 0
322 hasFolds1 := folds1[0] != 0
323 needle := substr[sz0+sz1:]
324
325 // Ugly hack
326 var l0, l1 rune
327 switch u0 {
328 case 'İ':
329 l0 = 'İ'
330 case 'ı':
331 l0 = 'ı'
332 default:
333 u0, l0, _ = tables.ToUpperLower(u0)
334 }
335 switch u1 {
336 case 'İ':
337 l1 = 'İ'
338 case 'ı':
339 l1 = 'ı'
340 default:
341 u1, l1, _ = tables.ToUpperLower(u1)
342 }
343
344 // Limit search space.
345 t := len(s) - len(substr)/3 + 2
346 if t > len(s) {
347 t = len(s)
348 }
349 switch {
350 case !hasFolds0 && u0 == l0 && !hasFolds1 && u1 == l1:
351 i := 0
352 // Fast check for the first two runes.
353 if u0 != utf8.RuneError && u1 != utf8.RuneError {
354 i = strings.Index(s, substr[:sz0+sz1])
355 if i < 0 {
356 return -1
357 }
358 }
359 for i < t {
360 var n0 int
361 var r0 rune
362 if s[i] < utf8.RuneSelf {
363 r0, n0 = rune(s[i]), 1
364 } else {
365 r0, n0 = utf8.DecodeRuneInString(s[i:])
366 }
367 if r0 != u0 {
368 i += n0
369 continue
370 }
371 if i+n0 >= t {
372 break
373 }
374
375 var n1 int
376 var r1 rune
377 if s[i+n0] < utf8.RuneSelf {
378 r1, n1 = rune(s[i+n0]), 1
379 } else {
380 r1, n1 = utf8.DecodeRuneInString(s[i+n0:])
381 }
382 if r1 != u1 {
383 i += n0
384 if r1 != u0 {
385 i += n1 // Skip 2 runes when possible
386 }
387 continue
388 }
389
390 match, noMore := hasPrefixUnicode(s[i+n0+n1:], needle)
391 if match {
392 return i
393 }
394 if noMore {
395 break
396 }
397 i += n0
398 if r1 != u0 {
399 i += n1 // Skip 2 runes when possible
400 }
401 }
402 return -1
403 case !hasFolds0 && !hasFolds1:
404 // TODO: check is adding a fast check for l0 and u0 is faster
405 i := 0
406 for i < t {
407 var n0 int
408 var r0 rune
409 if s[i] < utf8.RuneSelf {
410 r0, n0 = rune(s[i]), 1
411 } else {
412 r0, n0 = utf8.DecodeRuneInString(s[i:])
413 }
414 if r0 != u0 && r0 != l0 {
415 i += n0
416 continue
417 }
418 if i+n0 >= t {
419 break
420 }
421
422 var n1 int
423 var r1 rune
424 if s[i+n0] < utf8.RuneSelf {
425 r1, n1 = rune(s[i+n0]), 1
426 } else {
427 r1, n1 = utf8.DecodeRuneInString(s[i+n0:])
428 }
429 if r1 != u1 && r1 != l1 {
430 i += n0
431 if r1 != u0 && r1 != l0 {
432 i += n1 // Skip 2 runes when possible
433 }
434 continue
435 }
436
437 match, noMore := hasPrefixUnicode(s[i+n0+n1:], needle)
438 if match {
439 return i
440 }
441 if noMore {
442 break
443 }
444 i += n0
445 if r1 != u0 && r1 != l0 {
446 i += n1 // Skip 2 runes when possible
447 }
448 }
449 return -1
450 default:
451 // TODO: see if there is a better cutoff to use
452 i := 0
453 for i < t {
454 var n0 int
455 var r0 rune
456 if s[i] < utf8.RuneSelf {
457 r0, n0 = rune(s[i]), 1
458 } else {
459 r0, n0 = utf8.DecodeRuneInString(s[i:])
460 }
461 if r0 != u0 && r0 != l0 {
462 if !hasFolds0 || (r0 != folds0[0] && r0 != folds0[1]) {
463 i += n0
464 continue
465 }
466 }
467 if i+n0 >= t {
468 break
469 }
470
471 var n1 int
472 var r1 rune
473 if s[i+n0] < utf8.RuneSelf {
474 r1, n1 = rune(s[i+n0]), 1
475 } else {
476 r1, n1 = utf8.DecodeRuneInString(s[i+n0:])
477 }
478 if r1 != u1 && r1 != l1 {
479 if !hasFolds1 || (r1 != folds1[0] && r1 != folds1[1]) {
480 i += n0
481 if !hasFolds0 && r1 != u0 && r1 != l0 {
482 i += n1 // Skip 2 runes when possible
483 }
484 continue
485 }
486 }
487
488 match, noMore := hasPrefixUnicode(s[i+n0+n1:], needle)
489 if match {
490 return i
491 }
492 if noMore {
493 break
494 }
495 i += n0
496 if !hasFolds0 && r1 != u0 && r1 != l0 {
497 i += n1 // Skip 2 runes when possible
498 }
499 }
500 return -1
501 }
502 }
503
504 // nonLetterASCII checks if the first 32 bytes of s consist only of
505 // non-letter ASCII characters. This is used to quickly check if we
506 // can use strings.Index.
507 func nonLetterASCII(s string) bool {
508 for i := 0; i < len(s); i++ {
509 // NB: this is faster than using a lookup table
510 c := s[i] | ' ' // simplify check for alpha
511 if c&utf8.RuneSelf != 0 || 'a' <= c && c <= 'z' {
512 return false
513 }
514 }
515 return true
516 }
517
518 // TODO: check substr for any folds - this should almost always be faster
519 // than our current search - especially since we end up having to scan it
520 // multiple times. Maybe: check first rune (and maybe second), then check
521 // if substr has any folds.
522 //
523 // That said this library is meant for dealing with text and this might
524 // only with languages that don't have any/few folds.
525 //
526 // One thing we could do is use the longest prefix that does not have any
527 // folds and use the fast string search for that.
528
529 // Index returns the index of the first instance of substr in s, or -1 if
530 // substr is not present in s. Both s and substr are interpreted as UTF-8
531 // strings and simple Unicode case-folding is used to check for equality.
532 // All invalid UTF-8 encoded runes are considered equal - this matches the
533 // behavior of [strings.EqualFold].
534 //
535 // If substr is a single byte and an invalid UTF-8 sequence (0x80-0xFF) the
536 // index of the first invalid rune is returned. This matches the behavior of
537 // [IndexRune], but does not match the behavior of [IndexByte], which will
538 // return the index of bytes in the range of 0x80-0xFF.
539 // This is required because we guarantee that the result of Index would equal
540 // if compared with [strings.EqualFold].
541 func Index(s, substr string) int {
542 n := len(substr)
543 var r rune
544 var size int
545 if n > 0 {
546 if substr[0] < utf8.RuneSelf {
547 r, size = rune(substr[0]), 1
548 } else {
549 r, size = utf8.DecodeRuneInString(substr)
550 }
551 }
552 switch {
553 case n == 0:
554 return 0
555 case n == 1 && r != utf8.RuneError:
556 return IndexByte(s, byte(r))
557 case n == size:
558 return IndexRune(s, r)
559 case n >= len(s):
560 if n > len(s)*3 {
561 return -1
562 }
563 // Match here is possible due to upper/lower case runes
564 // having different encoded sizes.
565 //
566 // Fast check to see if s contains the first character of substr.
567 i := IndexRune(s, r)
568 if i < 0 {
569 return -1
570 }
571 // Reduce the search space
572 s = s[i:]
573 // Kelvin K is three times the size of ASCII [Kk] so we need
574 // to check for it to see if the longer needle (substr) could
575 // possibly match the shorter haystack (s).
576 if n > len(s)*2 && !containsKelvin(substr) {
577 return -1
578 }
579 // NB: until disproven this is sufficiently fast (and maybe fastest)
580 if o := bruteForceIndexUnicode(s, substr); o != -1 {
581 return o + i
582 }
583 return -1
584 case n <= maxLen: // WARN: 32 is for arm64 (see: bytealg.MaxLen)
585 // WARN:
586 // * this does not take non-folding runes into account
587 // * figure out when this negatively impacts performance
588 // * consider skipping if s is small relative to substr
589 // * check if s contains the first char of substr first ???
590 // * check after the maxBruteForce check ???
591 //
592 // Fast path if the sub-string is all non-alpha ASCII chars
593 //
594 // NB: This only works because len(substr) <= 32
595 //
596 // TODO:
597 // * Are we just gaming benchmarks here and need a quicker
598 // cutover to Rabin-Karp?
599 // * We should skip this check if s is small
600 //
601 if bytealg.NativeIndex && n <= 32 && nonLetterASCII(substr) {
602 return bytealg.IndexString(s, substr)
603 }
604 // TODO: tune this
605 if len(s) <= maxBruteForce {
606 return bruteForceIndexUnicode(s, substr)
607 }
608 // fallthrough
609 }
610
611 var u0, u1 rune
612 var sz0, sz1 int
613 if substr[0] < utf8.RuneSelf {
614 u0, sz0 = rune(substr[0]), 1
615 } else {
616 u0, sz0 = utf8.DecodeRuneInString(substr)
617 }
618 if substr[sz0] < utf8.RuneSelf {
619 u1, sz1 = rune(substr[sz0]), 1
620 } else {
621 u1, sz1 = utf8.DecodeRuneInString(substr[sz0:])
622 }
623
624 // Use Rabin-Karp if either of the first two runes are invalid
625 // this is slower but simplifies the logic below.
626 if u0 == utf8.RuneError || u1 == utf8.RuneError {
627 return indexRabinKarpUnicode(s, substr)
628 }
629
630 // hasFolds{0,1} should be rare so consider optimizing
631 // the no folds case
632 folds0 := tables.FoldMapExcludingUpperLower(u0)
633 folds1 := tables.FoldMapExcludingUpperLower(u1)
634 needle := substr[sz0+sz1:]
635
636 // TODO: we can possibly get rid of the ToUpperLower function
637 // and table since it's not always on the critical path and it
638 // adds a a lot to the size of this package
639
640 // Ugly hack
641 var l0, l1 rune
642 switch u0 {
643 case 'İ':
644 l0 = 'İ'
645 case 'ı':
646 l0 = 'ı'
647 default:
648 u0, l0, _ = tables.ToUpperLower(u0)
649 }
650 switch u1 {
651 case 'İ':
652 l1 = 'İ'
653 case 'ı':
654 l1 = 'ı'
655 default:
656 u1, l1, _ = tables.ToUpperLower(u1)
657 }
658
659 fails := 0
660 // TODO: see if we can stop sooner.
661 t := len(s) - len(substr)/3 + 1
662 if t > len(s) {
663 t = len(s)
664 }
665 for i := 0; i < t; {
666 var r0 rune
667 var n0 int
668 if s[i] < utf8.RuneSelf {
669 r0, n0 = rune(s[i]), 1
670 } else {
671 r0, n0 = utf8.DecodeRuneInString(s[i:])
672 }
673
674 if r0 != u0 && r0 != l0 && (folds0[0] == 0 || (r0 != folds0[0] && r0 != folds0[1])) {
675 var o, sz int
676 if folds0[0] == 0 {
677 o, sz = indexRune2(s[i+n0:], l0, u0)
678 } else {
679 // TODO: pass folds to indexRune so that we don't have to
680 // look them up again.
681 o, sz = indexRune(s[i+n0:], l0)
682 }
683 if o < 0 {
684 return -1
685 }
686 i += o + n0
687 n0 = sz // The rune we matched on might not be the same size as c0
688 }
689
690 if i+n0 >= t {
691 return -1
692 }
693
694 var r1 rune
695 var n1 int
696 if s[i+n0] < utf8.RuneSelf {
697 r1, n1 = rune(s[i+n0]), 1
698 } else {
699 r1, n1 = utf8.DecodeRuneInString(s[i+n0:])
700 }
701
702 if r1 == u1 || r1 == l1 || (folds1[0] != 0 && (r1 == folds1[0] || r1 == folds1[1])) {
703 match, exhausted := hasPrefixUnicode(s[i+n0+n1:], needle)
704 if match {
705 return i
706 }
707 if exhausted {
708 return -1
709 }
710 }
711 fails++
712 i += n0
713
714 // NB: After tuning this appears to be ideal across platforms.
715 if fails >= 4+i>>4 && i < t {
716 // From bytes/bytes.go:
717 //
718 // Give up on IndexByte, it isn't skipping ahead
719 // far enough to be better than Rabin-Karp.
720 // Experiments (using IndexPeriodic) suggest
721 // the cutover is about 16 byte skips.
722 // TODO: if large prefixes of sep are matching
723 // we should cutover at even larger average skips,
724 // because Equal becomes that much more expensive.
725 // This code does not take that effect into account.
726 //
727 // NB(charlie): The above part about "Equal" being
728 // more expensive is particularly relevant us since
729 // our "Equal" is drastically more expensive than
730 // the stdlibs.
731 j := indexRabinKarpUnicode(s[i:], substr)
732 if j < 0 {
733 return -1
734 }
735 return i + j
736 }
737 }
738 return -1
739 }
740
741 // LastIndex returns the index of the last instance of substr in s, or -1 if
742 // substr is not present in s.
743 func LastIndex(s, substr string) int {
744 n := len(substr)
745 var r rune
746 var size int
747 if n > 0 {
748 if substr[n-1] < utf8.RuneSelf {
749 r, size = rune(substr[n-1]), 1
750 } else {
751 r, size = utf8.DecodeRuneInString(substr)
752 }
753 }
754 switch {
755 case n == 0:
756 return len(s)
757 // case n == 1 && r != utf8.RuneError:
758 case n == 1:
759 return LastIndexByte(s, substr[0])
760 case n == size:
761 // TODO: indexRabinKarpRevUnicode might be faster here
762 return lastIndexRune(s, r)
763 case n >= len(s):
764 if n > len(s)*3 {
765 return -1
766 }
767 if n > len(s)*2 && !containsKelvin(substr) {
768 return -1
769 }
770 // fallthrough
771 }
772 return indexRabinKarpRevUnicode(s, substr)
773 }
774
775 // IndexByte returns the index of the first instance of c (ignoring case) in s,
776 // or -1 if c is not present in s. Matching is case-insensitive and Unicode
777 // simple folding is used which means that ASCII bytes 'K' and 'k' match Kelvin
778 // 'K', and ASCII bytes 'S' and 's' match 'ſ' (Latin small letter long S).
779 // Therefore, string s may be scanned twice when c is in [KkSs]
780 // (because the optimized assembly is ASCII only).
781 //
782 // On amd64 and arm64 this is only ~20-25% slower than strings.IndexByte for
783 // small strings (<4M) and ~6% slower for larger strings.
784 // The slowdown for small strings is due to additional checks and function call
785 // overheard.
786 func IndexByte(s string, c byte) int {
787 // TODO: the below quick check is only to improve benchmark performance for
788 // small strings (where the overhead of this function and IndexByteString
789 // not being inlined becomes noticeable ~1ns).
790 // See if we can get this function inlined or reduce the overhead of
791 // indexByte.
792 //
793 // Fast check for bytes that can't be folded to from Unicode chars.
794 // This shaves one or two nanoseconds from IndexByte, which is
795 // meaningful when s is small.
796 switch c {
797 case 'K', 'S', 'k', 's':
798 i, _ := indexByte(s, c)
799 return i
800 default:
801 return bytealg.IndexByteString(s, c)
802 }
803 }
804
805 // IndexByte returns the index of the first instance of c (ignoring case) in s,
806 // or -1 if c is not present in s. Case matching is ASCII only, unlike
807 // [IndexByte] which is Unicode aware.
808 func IndexByteASCII(s string, c byte) int {
809 return bytealg.IndexByteString(s, c)
810 }
811
812 // indexByte returns the index of the first instance of c in s, or -1 if c is
813 // not present in s and the size (in bytes) of the character matched (this is
814 // needed to handle matching [Kk] and [Ss] to multibyte characters 'K' and 'ſ').
815 func indexByte(s string, c byte) (int, int) {
816 if len(s) == 0 {
817 return -1, 1
818 }
819
820 n := bytealg.IndexByteString(s, c)
821
822 // Special case for Unicode characters that map to ASCII.
823 var r rune
824 var sz int
825 switch c {
826 case 'K', 'k':
827 r = 'K' // Kelvin K
828 sz = 3
829 case 'S', 's':
830 r = 'ſ' // Latin small letter long S
831 sz = 2
832 default:
833 return n, 1
834 }
835
836 // Search for Unicode characters that map to ASCII byte 'c'
837 if n > 0 {
838 if n < sz {
839 return n, 1 // Matched c before a possible rune 'r'
840 }
841 s = s[:n] // Limit search space
842 }
843 if o := indexRuneCase(s, r); n == -1 || (o != -1 && o < n) {
844 return o, sz
845 }
846 return n, 1
847 }
848
849 // LastIndexByte returns the index of the last instance of c in s, or -1
850 // if c is not present in s.
851 func LastIndexByte(s string, c byte) int {
852 if len(s) == 0 {
853 return -1
854 }
855 if !isAlpha(c) {
856 return strings.LastIndexByte(s, c)
857 }
858
859 // Special case for Unicode characters that map to ASCII.
860 var r rune
861 switch c {
862 case 'K', 'k':
863 r = 'K'
864 case 'S', 's':
865 r = 'ſ'
866 default:
867 c |= ' ' // convert to lower case
868 for i := len(s) - 1; i >= 0; i-- {
869 if s[i]|' ' == c {
870 return i
871 }
872 }
873 return -1
874 }
875
876 // Handle ASCII characters with Unicode mappings
877 c |= ' ' // convert to lower case
878 for i := len(s); i > 0; {
879 if s[i-1] < utf8.RuneSelf {
880 i--
881 if s[i]|' ' == c {
882 return i
883 }
884 } else {
885 sr, size := utf8.DecodeLastRuneInString(s[:i])
886 i -= size
887 if sr == r {
888 return i
889 }
890 }
891 }
892 return -1
893 }
894
895 // IndexRune returns the index of the first instance of the Unicode code point
896 // r, or -1 if rune is not present in s.
897 // If r is utf8.RuneError, it returns the first instance of any
898 // invalid UTF-8 byte sequence.
899 func IndexRune(s string, r rune) int {
900 // TODO: This is faster than strings.IndexRune when r is not ASCII
901 // so make a PR to go/strings.
902
903 // TODO: consider checking if r is ASCII here so that it can be inlined
904 i, _ := indexRune(s, r)
905 return i
906 }
907
908 // indexRune returns the index of the first instance of the Unicode code point
909 // r and the size of the rune that matched.
910 func indexRune(s string, r rune) (int, int) {
911 // TODO: handle invalid runes
912 switch {
913 case 0 <= r && r < utf8.RuneSelf:
914 // TODO: Check if we can use bytealg.IndexByteString directly.
915 return indexByte(s, byte(r))
916 case r == utf8.RuneError:
917 for i, r := range s {
918 if r == utf8.RuneError {
919 return i, utf8.RuneLen(r)
920 }
921 }
922 return -1, 1
923 case !utf8.ValidRune(r):
924 return -1, 1
925 default:
926 // TODO: use a function for len(folds)
927 if folds := tables.FoldMap(r); folds != nil {
928 size := utf8.RuneLen(r)
929 n := indexRuneCase(s, r)
930 if n == 0 {
931 return 0, size
932 }
933 if n > 0 {
934 s = s[:n]
935 }
936 for i := 0; i < len(folds); i++ {
937 rr := rune(folds[i])
938 if rr == r {
939 continue
940 }
941 if rr == 0 {
942 break
943 }
944 o := indexRuneCase(s, rr)
945 if o != -1 && (n == -1 || o < n) {
946 n = o
947 s = s[:n]
948 size = utf8.RuneLen(rr)
949 }
950 }
951 return n, size
952 } else if u, l, ok := tables.ToUpperLower(r); ok {
953 return indexRune2(s, l, u)
954 }
955 return indexRuneCase(s, r), utf8.RuneLen(r)
956 }
957 }
958
959 // TODO: consider creating a version of this function for when we've already
960 // decoded the rune and know that it is valid and not-ASCII.
961 //
962 // indexRuneCase is a *case-sensitive* version of strings.IndexRune that is
963 // generally faster for Unicode characters since it searches for the rune's
964 // second byte, which is generally more unique, instead of the first byte,
965 // like strings.IndexRune.
966 func indexRuneCase(s string, r rune) int {
967 // TODO:
968 // * remove if my PR is ever merged
969 // * consider searching for the first byte if it is not one of:
970 // 240, 243, or 244 (which are the first byte of ~78% of multi-byte
971 // Unicode characters).
972 switch {
973 case 0 <= r && r < utf8.RuneSelf:
974 return strings.IndexByte(s, byte(r))
975 case r == utf8.RuneError:
976 for i, r := range s {
977 if r == utf8.RuneError {
978 return i
979 }
980 }
981 return -1
982 case !utf8.ValidRune(r):
983 return -1
984 default:
985 var n int
986 var c0, c1, c2, c3 byte
987 // Inlined version of utf8.EncodeRune. This is one of our hottest
988 // functions and EncodeRune or string(r) add significant overhead
989 // when the string being searched is small.
990 const (
991 tx = 0b10000000
992 t2 = 0b11000000
993 t3 = 0b11100000
994 t4 = 0b11110000
995 maskx = 0b00111111
996 rune2Max = 1<<11 - 1
997 rune3Max = 1<<16 - 1
998 )
999 switch i := uint32(r); {
1000 case i <= rune2Max:
1001 c0 = t2 | byte(r>>6)
1002 c1 = tx | byte(r)&maskx
1003 n = 2
1004 // NB: removed the invalid rune check since that is
1005 // performed above.
1006 case i <= rune3Max:
1007 c0 = t3 | byte(r>>12)
1008 c1 = tx | byte(r>>6)&maskx
1009 c2 = tx | byte(r)&maskx
1010 n = 3
1011 default:
1012 c0 = t4 | byte(r>>18)
1013 c1 = tx | byte(r>>12)&maskx
1014 c2 = tx | byte(r>>6)&maskx
1015 c3 = tx | byte(r)&maskx
1016 n = 4
1017 }
1018 // Search for r using the last byte of its UTF-8 encoded form
1019 // since it is more unique than the first byte. This 4-5x faster
1020 // when all the text is Unicode.
1021 var fails, i int
1022 switch n {
1023 case 2:
1024 i = 1
1025 for i < len(s) {
1026 if s[i] != c1 {
1027 o := strings.IndexByte(s[i+1:], c1)
1028 if o < 0 {
1029 return -1
1030 }
1031 i += o + 1
1032 }
1033 if s[i-1] == c0 {
1034 return i - 1
1035 }
1036 fails++
1037 i++
1038 // Switch to bytealg.IndexString, if implemented, when the needle
1039 // is small and IndexByte produces too many false positives.
1040 if (bytealg.NativeIndex && fails > bytealg.Cutover(i) && i < len(s)) ||
1041 (!bytealg.NativeIndex && fails >= 4+i>>4 && i < len(s)) {
1042 if bytealg.NativeIndex {
1043 // NB: Impossible to match in the middle of the two byte
1044 // rune so we don't need to search from: s[i-:].
1045 if j := bytealg.IndexString(s[i:], string(r)); j != -1 {
1046 return i + j
1047 }
1048 } else {
1049 // Elided on platforms with a native IndexString.
1050 // This is faster than calling strings.Index or
1051 // using Rabin-Karp.
1052 for ; i < len(s); i++ {
1053 if s[i] == c1 && s[i-1] == c0 {
1054 return i - 1
1055 }
1056 }
1057 }
1058 return -1
1059 }
1060 }
1061 case 3:
1062 i = 2
1063 for i < len(s) {
1064 if s[i] != c2 {
1065 o := strings.IndexByte(s[i+1:], c2)
1066 if o < 0 {
1067 return -1
1068 }
1069 i += o + 1
1070 }
1071 if s[i-2] == c0 && s[i-1] == c1 {
1072 return i - 2
1073 }
1074 fails++
1075 i++
1076 if (bytealg.NativeIndex && fails > bytealg.Cutover(i) && i < len(s)) ||
1077 (!bytealg.NativeIndex && fails >= 4+i>>4 && i < len(s)) {
1078 if bytealg.NativeIndex {
1079 // We might be in the middle of a rune so search: s[i-2:]
1080 if j := bytealg.IndexString(s[i-2:], string(r)); j != -1 {
1081 return i + j - 2
1082 }
1083 } else {
1084 for ; i < len(s); i++ {
1085 if s[i] == c2 && s[i-1] == c1 && s[i-2] == c0 {
1086 return i - 2
1087 }
1088 }
1089 }
1090 return -1
1091 }
1092 }
1093 case 4:
1094 i = 3
1095 for i < len(s) {
1096 if s[i] != c3 {
1097 o := strings.IndexByte(s[i+1:], c3)
1098 if o < 0 {
1099 return -1
1100 }
1101 i += o + 1
1102 }
1103 if s[i-3] == c0 && s[i-2] == c1 && s[i-1] == c2 {
1104 return i - 3
1105 }
1106 fails++
1107 i++
1108 if (bytealg.NativeIndex && fails > bytealg.Cutover(i) && i < len(s)) ||
1109 (!bytealg.NativeIndex && fails >= 4+i>>4 && i < len(s)) {
1110 if bytealg.NativeIndex {
1111 // We might be in the middle of a rune so search: s[i-3:]
1112 if j := bytealg.IndexString(s[i-3:], string(r)); j != -1 {
1113 return i + j - 3
1114 }
1115 } else {
1116 for ; i < len(s); i++ {
1117 if s[i] == c3 && s[i-1] == c2 && s[i-2] == c1 && s[i-3] == c0 {
1118 return i - 3
1119 }
1120 }
1121 }
1122 return -1
1123 }
1124 }
1125 }
1126 return -1
1127 }
1128 }
1129
1130 // indexRune2 returns the index of the first instance of the Unicode code point
1131 // lower or upper. The search is *case-sensitive*.
1132 func indexRune2(s string, lower, upper rune) (int, int) {
1133 // TODO:
1134 // - do we need this now that we don't search for the first byte?
1135 // - check if any of the rune bytes are equal and search by that
1136 // - NB: this ^^^ was slower when I tried that
1137 //
1138 // Percentage of uppper/lower case runes that share bytes (at index):
1139 //
1140 // 0: 80.65%
1141 // 1: 46.58%
1142 // 2: 11.57%
1143 // 3: 3.83%
1144 //
1145 // Based on the above we could combine searches using the second byte.
1146 if lower|upper < utf8.RuneSelf {
1147 return indexByte(s, byte(lower&0x7F))
1148 }
1149 n := indexRuneCase(s, lower)
1150 sz := utf8.RuneLen(lower)
1151 if n != 0 && lower != upper {
1152 if 0 <= n && n < len(s) {
1153 s = s[:n] // limit the search space
1154 }
1155 if o := indexRuneCase(s, upper); n == -1 || (0 <= o && o < n) {
1156 n = o
1157 sz = utf8.RuneLen(upper)
1158 }
1159 }
1160 return n, sz
1161 }
1162
1163 // lastIndexRune returns the last index of the first instance of the Unicode
1164 // code point r, or -1 if rune is not present in s.
1165 // If r is utf8.RuneError, it returns the last instance of any
1166 // invalid UTF-8 byte sequence.
1167 func lastIndexRune(s string, r rune) int {
1168 switch {
1169 case r == utf8.RuneError:
1170 for i := len(s); i > 0; {
1171 sr, size := utf8.DecodeLastRuneInString(s[:i])
1172 i -= size
1173 if sr == utf8.RuneError {
1174 return i
1175 }
1176 }
1177 return -1
1178 case !utf8.ValidRune(r):
1179 return -1
1180 default:
1181 if folds := tables.FoldMap(r); folds != nil {
1182 for i := len(s); i > 0; {
1183 var sr rune
1184 if sr = rune(s[i-1]); sr < utf8.RuneSelf {
1185 i--
1186 } else {
1187 var size int
1188 sr, size = utf8.DecodeLastRuneInString(s[:i])
1189 i -= size
1190 }
1191 for j := 0; j < len(folds) && folds[j] != 0; j++ {
1192 if sr == rune(folds[j]) {
1193 return i
1194 }
1195 }
1196 }
1197 } else {
1198 u, l, _ := tables.ToUpperLower(r)
1199 if u == l {
1200 rs := string(r)
1201 last := len(rs) - 1
1202 loop:
1203 for i := len(s) - 1; i >= last; i-- {
1204 // Step backwards comparing bytes.
1205 if s[i] == rs[last] {
1206 for j := 1; j < len(rs); j++ {
1207 if s[i-j] != rs[last-j] {
1208 continue loop
1209 }
1210 }
1211 return i - last
1212 }
1213 }
1214 } else {
1215 for i := len(s); i > 0; {
1216 var sr rune
1217 if sr = rune(s[i-1]); sr < utf8.RuneSelf {
1218 i--
1219 } else {
1220 var size int
1221 sr, size = utf8.DecodeLastRuneInString(s[:i])
1222 i -= size
1223 }
1224 if sr == u || sr == l {
1225 return i
1226 }
1227 }
1228 }
1229 }
1230 return -1
1231 }
1232 }
1233
1234 // primeRK is the prime base used in Rabin-Karp algorithm.
1235 const primeRK = 16777619
1236
1237 // hashStrUnicode returns the hash and the appropriate multiplicative
1238 // factor for use in Rabin-Karp algorithm, and the number of runes
1239 // in sep.
1240 func hashStrUnicode(sep string) (uint32, uint32, int) {
1241 hash := uint32(0)
1242 n := 0
1243 for _, r := range sep {
1244 if r < utf8.RuneSelf {
1245 r = rune(_lower[r])
1246 } else {
1247 r = tables.CaseFold(r)
1248 }
1249 hash = hash*primeRK + uint32(r)
1250 n++
1251 }
1252 var pow, sq uint32 = 1, primeRK
1253 for i := n; i > 0; i >>= 1 {
1254 if i&1 != 0 {
1255 pow *= sq
1256 }
1257 sq *= sq
1258 }
1259 return hash, pow, n
1260 }
1261
1262 // hashStrRevUnicode returns the hash of the reverse of sep and the
1263 // appropriate multiplicative factor for use in Rabin-Karp algorithm,
1264 // and the number of runes in sep.
1265 func hashStrRevUnicode(sep string) (uint32, uint32, int) {
1266 hash := uint32(0)
1267 n := 0
1268 for i := len(sep); i > 0; {
1269 var r rune
1270 var size int
1271 if sep[i-1] < utf8.RuneSelf {
1272 r, size = rune(_lower[sep[i-1]]), 1
1273 } else {
1274 r, size = utf8.DecodeLastRuneInString(sep[:i])
1275 r = tables.CaseFold(r)
1276 }
1277 hash = hash*primeRK + uint32(r)
1278 i -= size
1279 n++
1280 }
1281 var pow, sq uint32 = 1, primeRK
1282 for i := n; i > 0; i >>= 1 {
1283 if i&1 != 0 {
1284 pow *= sq
1285 }
1286 sq *= sq
1287 }
1288 return hash, pow, n
1289 }
1290
1291 // indexRabinKarpRevUnicode uses the Rabin-Karp search algorithm to return the
1292 // index of the last occurrence of substr in s, or -1 if not present.
1293 func indexRabinKarpRevUnicode(s, substr string) int {
1294 // Reverse Rabin-Karp search
1295 hashss, pow, n := hashStrRevUnicode(substr)
1296 var h uint32
1297 i := len(s)
1298 for i > 0 {
1299 var r rune
1300 var size int
1301 if s[i-1] < utf8.RuneSelf {
1302 r, size = rune(_lower[s[i-1]]), 1
1303 } else {
1304 r, size = utf8.DecodeLastRuneInString(s[:i])
1305 r = tables.CaseFold(r)
1306 }
1307 h = h*primeRK + uint32(r)
1308 i -= size
1309 n--
1310 if n == 0 {
1311 break
1312 }
1313 }
1314 if n > 0 {
1315 return -1
1316 }
1317 if h == hashss && HasSuffix(s, substr) {
1318 return i // WARN
1319 }
1320 j := len(s)
1321 for i > 0 {
1322 var r0 rune
1323 var n0 int
1324 if s[i-1] < utf8.RuneSelf {
1325 r0, n0 = rune(_lower[s[i-1]]), 1
1326 } else {
1327 r0, n0 = utf8.DecodeLastRuneInString(s[:i])
1328 r0 = tables.CaseFold(r0)
1329 }
1330 var r1 rune
1331 var n1 int
1332 if s[j-1] < utf8.RuneSelf {
1333 r1, n1 = rune(_lower[s[j-1]]), 1
1334 } else {
1335 r1, n1 = utf8.DecodeLastRuneInString(s[:j])
1336 r1 = tables.CaseFold(r1)
1337 }
1338 h *= primeRK
1339 h += uint32(r0)
1340 h -= pow * uint32(r1)
1341 i -= n0
1342 j -= n1
1343 if h == hashss && HasSuffix(s[i:j], substr) {
1344 return i
1345 }
1346 }
1347 return -1
1348 }
1349
1350 // indexRabinKarpUnicode uses the Rabin-Karp search algorithm to return the
1351 // index of the first occurrence of substr in s, or -1 if not present.
1352 func indexRabinKarpUnicode(s, substr string) int {
1353 // Rabin-Karp search
1354 hashss, pow, n := hashStrUnicode(substr)
1355 var h uint32
1356 sz := 0 // byte size of 'n' runes
1357 for i, r := range s {
1358 orig := r
1359 if r < utf8.RuneSelf {
1360 r = rune(_lower[r])
1361 } else {
1362 r = tables.CaseFold(r)
1363 }
1364 h = h*primeRK + uint32(r)
1365 n--
1366 if n == 0 {
1367 sz = i + utf8.RuneLen(orig)
1368 break
1369 }
1370 }
1371 if h == hashss && HasPrefix(s, substr) {
1372 return 0
1373 }
1374 i := 0 // start of rolling hash
1375 for j := sz; j < len(s); {
1376 h *= primeRK
1377 var s0, s1 rune
1378 var n0, n1 int
1379 if s[j] < utf8.RuneSelf {
1380 s0, n0 = rune(_lower[s[j]]), 1
1381 } else {
1382 s0, n0 = utf8.DecodeRuneInString(s[j:])
1383 s0 = tables.CaseFold(s0)
1384 }
1385 if s[i] < utf8.RuneSelf {
1386 s1, n1 = rune(_lower[s[i]]), 1
1387 } else {
1388 s1, n1 = utf8.DecodeRuneInString(s[i:])
1389 s1 = tables.CaseFold(s1)
1390 }
1391 h += uint32(s0)
1392 h -= pow * uint32(s1)
1393 j += n0
1394 i += n1
1395 if h == hashss && HasPrefix(s[i:j], substr) {
1396 return i
1397 }
1398 }
1399 return -1
1400 }
1401
1402 func countRune(s string, r rune) (n int) {
1403 sz := utf8.RuneLen(r)
1404 for {
1405 i := indexRuneCase(s, r)
1406 if i == -1 {
1407 return n
1408 }
1409 n++
1410 s = s[i+sz:]
1411 }
1412 }
1413
1414 // Count counts the number of non-overlapping instances of substr in s.
1415 // If substr is an empty string, Count returns 1 + the number of Unicode
1416 // code points in s.
1417 func Count(s, substr string) int {
1418 // special case
1419 if len(substr) == 0 {
1420 return utf8.RuneCountInString(s) + 1
1421 }
1422 if len(substr) == 1 {
1423 c := substr[0]
1424 n := bytealg.CountString(s, c)
1425 switch c {
1426 case 'K', 'k':
1427 n += countRune(s, 'K')
1428 case 'S', 's':
1429 n += countRune(s, 'ſ')
1430 }
1431 return n
1432 }
1433 n := 0
1434 runeCount := -1 // Lazily calculated after the first match
1435 for {
1436 i := Index(s, substr)
1437 if i == -1 {
1438 return n
1439 }
1440 n++
1441 if runeCount < 0 {
1442 runeCount = utf8.RuneCountInString(substr)
1443 }
1444 o := runeCount
1445 s = s[i:]
1446 // Trim substr prefix from s.
1447 for j, r := range s {
1448 o--
1449 if o == 0 {
1450 s = s[j+utf8.RuneLen(r):]
1451 break
1452 }
1453 }
1454 }
1455 }
1456
1457 // Contains reports whether substr is within s.
1458 func Contains(s, substr string) bool {
1459 return Index(s, substr) >= 0
1460 }
1461
1462 // ContainsAny reports whether any Unicode code points in chars are within s.
1463 func ContainsAny(s, chars string) bool {
1464 return IndexAny(s, chars) >= 0
1465 }
1466
1467 // ContainsRune reports whether the Unicode code point r is within s.
1468 func ContainsRune(s string, r rune) bool {
1469 return IndexRune(s, r) >= 0
1470 }
1471
1472 // asciiSet is a 32-byte value, where each bit represents the presence of a
1473 // given ASCII character in the set. The 128-bits of the lower 16 bytes,
1474 // starting with the least-significant bit of the lowest word to the
1475 // most-significant bit of the highest word, map to the full range of all
1476 // 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,
1477 // ensuring that any non-ASCII character will be reported as not in the set.
1478 // This allocates a total of 32 bytes even though the upper half
1479 // is unused to avoid bounds checks in asciiSet.contains.
1480 type asciiSet [8]uint32
1481
1482 // makeASCIISet creates a set of ASCII characters and reports whether all
1483 // characters in chars are ASCII.
1484 func makeASCIISet(s, chars string) (as asciiSet, ok bool) {
1485 i := 0
1486 for ; i < len(chars); i++ {
1487 c := chars[i]
1488 if c >= utf8.RuneSelf {
1489 return as, false
1490 }
1491 as[c/32] |= 1 << (c % 32)
1492 if isAlpha(c) {
1493 c ^= ' ' // swap case
1494 as[c/32] |= 1 << (c % 32)
1495 // Can't use ASCII when non-ASCII chars fold to ASCII chars.
1496 switch c {
1497 case 'K', 'k', 'S', 's':
1498 // Checking if s contains only ASCII and using asciiSet is
1499 // faster than falling back to the Unicode aware search.
1500 // This holds true even on systems where ContainsNonASCII
1501 // does not use SIMD (tested on arm).
1502 if !ContainsNonASCII(s) {
1503 i++
1504 goto ascii // ASCII fast path that elides this check
1505 }
1506 return as, false
1507 }
1508 }
1509 }
1510
1511 ascii:
1512 // ASCII fast path for when we know s does not contain Unicode.
1513 for ; i < len(chars); i++ {
1514 c := chars[i]
1515 if c >= utf8.RuneSelf {
1516 return as, false
1517 }
1518 as[c/32] |= 1 << (c % 32)
1519 if isAlpha(c) {
1520 c ^= ' ' // swap case
1521 as[c/32] |= 1 << (c % 32)
1522 }
1523 }
1524 return as, true
1525 }
1526
1527 // contains reports whether c is inside the set.
1528 func (as *asciiSet) contains(c byte) bool {
1529 return (as[c/32] & (1 << (c % 32))) != 0
1530 }
1531
1532 // IndexAny returns the index of the first instance of any Unicode code point
1533 // from chars in s, or -1 if no Unicode code point from chars is present in s.
1534 func IndexAny(s, chars string) int {
1535 if len(chars) == 0 {
1536 // Avoid scanning all of s.
1537 return -1
1538 }
1539 if len(chars) == 1 {
1540 // Avoid scanning all of s.
1541 r := rune(chars[0])
1542 if r >= utf8.RuneSelf {
1543 r = utf8.RuneError
1544 }
1545 return IndexRune(s, r)
1546 }
1547 if len(s) > 8 {
1548 if as, isASCII := makeASCIISet(s, chars); isASCII {
1549 // TODO: should we convert Kelvin and Small Long S to ASCII here?
1550 for i := 0; i < len(s); i++ {
1551 if as.contains(s[i]) {
1552 return i
1553 }
1554 }
1555 return -1
1556 }
1557 }
1558 if len(s) > len(chars)*2 {
1559 // Avoid the overhead of repeatedly calling IndexRune
1560 // if s significantly longer than chars (IndexRune is
1561 // also quite fast for long strings).
1562 //
1563 // This cutover was empirically found via internal/benchtest.
1564 n := -1
1565 for _, r := range chars {
1566 i := IndexRune(s, r)
1567 if i != -1 && (n == -1 || i < n) {
1568 n = i
1569 if n == 0 {
1570 break
1571 }
1572 s = s[:n]
1573 }
1574 }
1575 return n
1576 }
1577 for i, c := range s {
1578 if IndexRune(chars, c) >= 0 {
1579 return i
1580 }
1581 }
1582 return -1
1583 }
1584
1585 // LastIndexAny returns the index of the last instance of any Unicode code
1586 // point from chars in s, or -1 if no Unicode code point from chars is
1587 // present in s.
1588 func LastIndexAny(s, chars string) int {
1589 if len(chars) == 0 {
1590 return -1
1591 }
1592 if len(s) == 1 {
1593 rc := rune(s[0])
1594 if rc >= utf8.RuneSelf {
1595 rc = utf8.RuneError
1596 }
1597 if IndexRune(chars, rc) >= 0 {
1598 return 0
1599 }
1600 return -1
1601 }
1602 if len(s) > 8 {
1603 if as, isASCII := makeASCIISet(s, chars); isASCII {
1604 for i := len(s) - 1; i >= 0; i-- {
1605 if as.contains(s[i]) {
1606 return i
1607 }
1608 }
1609 return -1
1610 }
1611 }
1612 if len(chars) == 1 {
1613 if c := chars[0]; c < utf8.RuneSelf {
1614 return LastIndexByte(s, c)
1615 }
1616 for i := len(s); i > 0; {
1617 r, size := utf8.DecodeLastRuneInString(s[:i])
1618 i -= size
1619 if r == utf8.RuneError {
1620 return i
1621 }
1622 }
1623 return -1
1624 }
1625 for i := len(s); i > 0; {
1626 r, size := utf8.DecodeLastRuneInString(s[:i])
1627 i -= size
1628 if IndexRune(chars, r) >= 0 {
1629 return i
1630 }
1631 }
1632 return -1
1633 }
1634
1635 // Cut slices s around the first instance of sep,
1636 // returning the text before and after sep.
1637 // The found result reports whether sep appears in s.
1638 // If sep does not appear in s, cut returns s, "", false.
1639 func Cut(s, sep string) (before, after string, found bool) {
1640 // TODO: both Cut and Count would benefit from Index returning the
1641 // number of bytes consumed from sep - consider adding this.
1642 if i := Index(s, sep); i >= 0 {
1643 after = s[i:]
1644 // trim sep from s
1645 for range sep {
1646 if after[0] < utf8.RuneSelf {
1647 after = after[1:]
1648 } else {
1649 _, n := utf8.DecodeRuneInString(after)
1650 after = after[n:]
1651 }
1652 }
1653 return s[:i], after, true
1654 }
1655 return s, "", false
1656 }
1657
1658 // CutPrefix returns s without the provided leading prefix string
1659 // and reports whether it found the prefix.
1660 // If s doesn't start with prefix, CutPrefix returns s, false.
1661 // If prefix is the empty string, CutPrefix returns s, true.
1662 func CutPrefix(s, prefix string) (after string, found bool) {
1663 if len(prefix) == 0 {
1664 return s, true
1665 }
1666 if ss := TrimPrefix(s, prefix); len(ss) != len(s) {
1667 return ss, true
1668 }
1669 return s, false
1670 }
1671
1672 // CutSuffix returns s without theI provided ending suffix string
1673 // and reports whether it found the suffix.
1674 // If s doesn't end with suffix, CutSuffix returns s, false.
1675 // If suffix is the empty string, CutSuffix returns s, true.
1676 func CutSuffix(s, suffix string) (before string, found bool) {
1677 if len(suffix) == 0 {
1678 return s, true
1679 }
1680 if match, i := hasSuffixUnicode(s, suffix); match {
1681 return s[:i], true
1682 }
1683 return s, false
1684 }
1685
1686 // IndexNonASCII returns the index of first non-ASCII rune in s, or -1 if s
1687 // consists only of ASCII characters.
1688 //
1689 // On arm64 and amd64, IndexNonASCII is an order of magnitude faster than
1690 // using a for loop and checking each byte of s and should be close to that
1691 // of strings.IndexByte (54GBi/s on arm64).
1692 //
1693 // IndexNonASCII is up to 17 times faster on arm64 and 12 times faster on
1694 // amd64 compared to using a for loop and checking each byte of s.
1695 func IndexNonASCII(s string) int {
1696 return bytealg.IndexNonASCII(s)
1697 }
1698
1699 // ContainsNonASCII returns true if s contains any non-ASCII characters.
1700 func ContainsNonASCII(s string) bool {
1701 return bytealg.IndexNonASCII(s) >= 0
1702 }