Debian Codegraph @

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