Debian Codegraph @

bytcase/bytcase.go

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