Debian Codegraph @

libgo/go/bytes/bytes.go

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