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.
5 // The bytes package implements functions for the manipulation of byte slices.
6 // Analogous to the facilities of the strings package.
14 // Compare returns an integer comparing the two byte arrays lexicographically.
15 // The result will be 0 if a==b, -1 if a < b, and +1 if a > b
16 func Compare(a, b []byte) int {
21 for i, ac := range a[0:m] {
39 // Equal returns a boolean reporting whether a == b.
40 func Equal(a, b []byte) bool {
52 // explode splits s into an array of UTF-8 sequences, one per Unicode character (still arrays of bytes),
53 // up to a maximum of n byte arrays. Invalid UTF-8 sequences are chopped into individual bytes.
54 func explode(s []byte, n int) [][]byte {
58 a := make([][]byte, n)
67 _, size = utf8.DecodeRune(s)
75 // Count counts the number of non-overlapping instances of sep in s.
76 func Count(s, sep []byte) int {
78 return utf8.RuneCount(s) + 1
82 for i := 0; i+len(sep) <= len(s); i++ {
83 if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) {
91 // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
92 func Index(s, sep []byte) int {
98 for i := 0; i+n <= len(s); i++ {
99 if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) {
106 func indexBytePortable(s []byte, c byte) int {
107 for i, b := range s {
115 // LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.
116 func LastIndex(s, sep []byte) int {
122 for i := len(s) - n; i >= 0; i-- {
123 if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) {
130 // IndexRune interprets s as a sequence of UTF-8-encoded Unicode code points.
131 // It returns the byte index of the first occurrence in s of the given rune.
132 // It returns -1 if rune is not present in s.
133 func IndexRune(s []byte, rune int) int {
134 for i := 0; i < len(s); {
135 r, size := utf8.DecodeRune(s[i:])
144 // IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points.
145 // It returns the byte index of the first occurrence in s of any of the Unicode
146 // code points in chars. It returns -1 if chars is empty or if there is no code
148 func IndexAny(s []byte, chars string) int {
151 for i := 0; i < len(s); i += width {
153 if rune < utf8.RuneSelf {
156 rune, width = utf8.DecodeRune(s[i:])
158 for _, r := range chars {
168 // LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code
169 // points. It returns the byte index of the last occurrence in s of any of
170 // the Unicode code points in chars. It returns -1 if chars is empty or if
171 // there is no code point in common.
172 func LastIndexAny(s []byte, chars string) int {
174 for i := len(s); i > 0; {
175 rune, size := utf8.DecodeLastRune(s[0:i])
177 for _, m := range chars {
187 // Generic split: splits after each instance of sep,
188 // including sepSave bytes of sep in the subarrays.
189 func genSplit(s, sep []byte, sepSave, n int) [][]byte {
197 n = Count(s, sep) + 1
201 a := make([][]byte, n)
203 for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
204 if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) {
205 a[na] = s[start : i+sepSave]
215 // Split slices s into subslices separated by sep and returns a slice of
216 // the subslices between those separators.
217 // If sep is empty, Split splits after each UTF-8 sequence.
218 // The count determines the number of subslices to return:
219 // n > 0: at most n subslices; the last subslice will be the unsplit remainder.
220 // n == 0: the result is nil (zero subslices)
221 // n < 0: all subslices
222 func Split(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) }
224 // SplitAfter slices s into subslices after each instance of sep and
225 // returns a slice of those subslices.
226 // If sep is empty, Split splits after each UTF-8 sequence.
227 // The count determines the number of subslices to return:
228 // n > 0: at most n subslices; the last subslice will be the unsplit remainder.
229 // n == 0: the result is nil (zero subslices)
230 // n < 0: all subslices
231 func SplitAfter(s, sep []byte, n int) [][]byte {
232 return genSplit(s, sep, len(sep), n)
235 // Fields splits the array s around each instance of one or more consecutive white space
236 // characters, returning a slice of subarrays of s or an empty list if s contains only white space.
237 func Fields(s []byte) [][]byte {
238 return FieldsFunc(s, unicode.IsSpace)
241 // FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode code points.
242 // It splits the array s at each run of code points c satisfying f(c) and
243 // returns a slice of subarrays of s. If no code points in s satisfy f(c), an
244 // empty slice is returned.
245 func FieldsFunc(s []byte, f func(int) bool) [][]byte {
248 for i := 0; i < len(s); {
249 rune, size := utf8.DecodeRune(s[i:])
250 wasInField := inField
252 if inField && !wasInField {
258 a := make([][]byte, n)
261 for i := 0; i <= len(s) && na < n; {
262 rune, size := utf8.DecodeRune(s[i:])
263 if fieldStart < 0 && size > 0 && !f(rune) {
268 if fieldStart >= 0 && (size == 0 || f(rune)) {
269 a[na] = s[fieldStart:i]
281 // Join concatenates the elements of a to create a single byte array. The separator
282 // sep is placed between elements in the resulting array.
283 func Join(a [][]byte, sep []byte) []byte {
290 n := len(sep) * (len(a) - 1)
291 for i := 0; i < len(a); i++ {
297 for i := 0; i < len(a); i++ {
299 for j := 0; j < len(s); j++ {
305 for j := 0; j < len(s); j++ {
314 // HasPrefix tests whether the byte array s begins with prefix.
315 func HasPrefix(s, prefix []byte) bool {
316 return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix)
319 // HasSuffix tests whether the byte array s ends with suffix.
320 func HasSuffix(s, suffix []byte) bool {
321 return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix)
324 // Map returns a copy of the byte array s with all its characters modified
325 // according to the mapping function. If mapping returns a negative value, the character is
326 // dropped from the string with no replacement. The characters in s and the
327 // output are interpreted as UTF-8-encoded Unicode code points.
328 func Map(mapping func(rune int) int, s []byte) []byte {
329 // In the worst case, the array can grow when mapped, making
330 // things unpleasant. But it's so rare we barge in assuming it's
331 // fine. It could also shrink but that falls out naturally.
332 maxbytes := len(s) // length of b
333 nbytes := 0 // number of bytes encoded in b
334 b := make([]byte, maxbytes)
335 for i := 0; i < len(s); {
338 if rune >= utf8.RuneSelf {
339 rune, wid = utf8.DecodeRune(s[i:])
343 if nbytes+utf8.RuneLen(rune) > maxbytes {
345 maxbytes = maxbytes*2 + utf8.UTFMax
346 nb := make([]byte, maxbytes)
347 copy(nb, b[0:nbytes])
350 nbytes += utf8.EncodeRune(b[nbytes:maxbytes], rune)
357 // Repeat returns a new byte slice consisting of count copies of b.
358 func Repeat(b []byte, count int) []byte {
359 nb := make([]byte, len(b)*count)
361 for i := 0; i < count; i++ {
362 for j := 0; j < len(b); j++ {
370 // ToUpper returns a copy of the byte array s with all Unicode letters mapped to their upper case.
371 func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) }
373 // ToUpper returns a copy of the byte array s with all Unicode letters mapped to their lower case.
374 func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) }
376 // ToTitle returns a copy of the byte array s with all Unicode letters mapped to their title case.
377 func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) }
379 // ToUpperSpecial returns a copy of the byte array s with all Unicode letters mapped to their
380 // upper case, giving priority to the special casing rules.
381 func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte {
382 return Map(func(r int) int { return _case.ToUpper(r) }, s)
385 // ToLowerSpecial returns a copy of the byte array s with all Unicode letters mapped to their
386 // lower case, giving priority to the special casing rules.
387 func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte {
388 return Map(func(r int) int { return _case.ToLower(r) }, s)
391 // ToTitleSpecial returns a copy of the byte array s with all Unicode letters mapped to their
392 // title case, giving priority to the special casing rules.
393 func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte {
394 return Map(func(r int) int { return _case.ToTitle(r) }, s)
398 // isSeparator reports whether the rune could mark a word boundary.
399 // TODO: update when package unicode captures more of the properties.
400 func isSeparator(rune int) bool {
401 // ASCII alphanumerics and underscore are not separators
404 case '0' <= rune && rune <= '9':
406 case 'a' <= rune && rune <= 'z':
408 case 'A' <= rune && rune <= 'Z':
415 // Letters and digits are not separators
416 if unicode.IsLetter(rune) || unicode.IsDigit(rune) {
419 // Otherwise, all we can do for now is treat spaces as separators.
420 return unicode.IsSpace(rune)
423 // BUG(r): The rule Title uses for word boundaries does not handle Unicode punctuation properly.
425 // Title returns a copy of s with all Unicode letters that begin words
426 // mapped to their title case.
427 func Title(s []byte) []byte {
428 // Use a closure here to remember state.
429 // Hackish but effective. Depends on Map scanning in order and calling
430 // the closure once per rune.
434 if isSeparator(prev) {
436 return unicode.ToTitle(r)
444 // TrimLeftFunc returns a subslice of s by slicing off all leading UTF-8-encoded
445 // Unicode code points c that satisfy f(c).
446 func TrimLeftFunc(s []byte, f func(r int) bool) []byte {
447 i := indexFunc(s, f, false)
454 // TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8
455 // encoded Unicode code points c that satisfy f(c).
456 func TrimRightFunc(s []byte, f func(r int) bool) []byte {
457 i := lastIndexFunc(s, f, false)
458 if i >= 0 && s[i] >= utf8.RuneSelf {
459 _, wid := utf8.DecodeRune(s[i:])
467 // TrimFunc returns a subslice of s by slicing off all leading and trailing
468 // UTF-8-encoded Unicode code points c that satisfy f(c).
469 func TrimFunc(s []byte, f func(r int) bool) []byte {
470 return TrimRightFunc(TrimLeftFunc(s, f), f)
473 // IndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points.
474 // It returns the byte index in s of the first Unicode
475 // code point satisfying f(c), or -1 if none do.
476 func IndexFunc(s []byte, f func(r int) bool) int {
477 return indexFunc(s, f, true)
480 // LastIndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points.
481 // It returns the byte index in s of the last Unicode
482 // code point satisfying f(c), or -1 if none do.
483 func LastIndexFunc(s []byte, f func(r int) bool) int {
484 return lastIndexFunc(s, f, true)
487 // indexFunc is the same as IndexFunc except that if
488 // truth==false, the sense of the predicate function is
490 func indexFunc(s []byte, f func(r int) bool, truth bool) int {
494 rune := int(s[start])
495 if rune >= utf8.RuneSelf {
496 rune, wid = utf8.DecodeRune(s[start:])
498 if f(rune) == truth {
506 // lastIndexFunc is the same as LastIndexFunc except that if
507 // truth==false, the sense of the predicate function is
509 func lastIndexFunc(s []byte, f func(r int) bool, truth bool) int {
510 for i := len(s); i > 0; {
511 rune, size := utf8.DecodeLastRune(s[0:i])
513 if f(rune) == truth {
520 func makeCutsetFunc(cutset string) func(rune int) bool {
521 return func(rune int) bool {
522 for _, c := range cutset {
531 // Trim returns a subslice of s by slicing off all leading and
532 // trailing UTF-8-encoded Unicode code points contained in cutset.
533 func Trim(s []byte, cutset string) []byte {
534 return TrimFunc(s, makeCutsetFunc(cutset))
537 // TrimLeft returns a subslice of s by slicing off all leading
538 // UTF-8-encoded Unicode code points contained in cutset.
539 func TrimLeft(s []byte, cutset string) []byte {
540 return TrimLeftFunc(s, makeCutsetFunc(cutset))
543 // TrimRight returns a subslice of s by slicing off all trailing
544 // UTF-8-encoded Unicode code points that are contained in cutset.
545 func TrimRight(s []byte, cutset string) []byte {
546 return TrimRightFunc(s, makeCutsetFunc(cutset))
549 // TrimSpace returns a subslice of s by slicing off all leading and
550 // trailing white space, as defined by Unicode.
551 func TrimSpace(s []byte) []byte {
552 return TrimFunc(s, unicode.IsSpace)
555 // Runes returns a slice of runes (Unicode code points) equivalent to s.
556 func Runes(s []byte) []int {
557 t := make([]int, utf8.RuneCount(s))
560 r, l := utf8.DecodeRune(s)
568 // Replace returns a copy of the slice s with the first n
569 // non-overlapping instances of old replaced by new.
570 // If n < 0, there is no limit on the number of replacements.
571 func Replace(s, old, new []byte, n int) []byte {
573 return s // avoid allocation
575 // Compute number of replacements.
576 if m := Count(s, old); m == 0 {
577 return s // avoid allocation
578 } else if n <= 0 || m < n {
582 // Apply replacements to buffer.
583 t := make([]byte, len(s)+n*(len(new)-len(old)))
586 for i := 0; i < n; i++ {
590 _, wid := utf8.DecodeRune(s[start:])
594 j += Index(s[start:], old)
596 w += copy(t[w:], s[start:j])
597 w += copy(t[w:], new)
600 w += copy(t[w:], s[start:])