github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/bytes/bytes.go (about) 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 "unicode" 11 "unicode/utf8" 12 ) 13 14 func equalPortable(a, b []byte) bool { 15 if len(a) != len(b) { 16 return false 17 } 18 for i, c := range a { 19 if c != b[i] { 20 return false 21 } 22 } 23 return true 24 } 25 26 // explode splits s into a slice of UTF-8 sequences, one per Unicode code point (still slices of bytes), 27 // up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes. 28 func explode(s []byte, n int) [][]byte { 29 if n <= 0 { 30 n = len(s) 31 } 32 a := make([][]byte, n) 33 var size int 34 na := 0 35 for len(s) > 0 { 36 if na+1 >= n { 37 a[na] = s 38 na++ 39 break 40 } 41 _, size = utf8.DecodeRune(s) 42 a[na] = s[0:size] 43 s = s[size:] 44 na++ 45 } 46 return a[0:na] 47 } 48 49 // Count counts the number of non-overlapping instances of sep in s. 50 // If sep is an empty slice, Count returns 1 + the number of Unicode code points in s. 51 func Count(s, sep []byte) int { 52 n := len(sep) 53 if n == 0 { 54 return utf8.RuneCount(s) + 1 55 } 56 if n > len(s) { 57 return 0 58 } 59 count := 0 60 c := sep[0] 61 i := 0 62 t := s[:len(s)-n+1] 63 for i < len(t) { 64 if t[i] != c { 65 o := IndexByte(t[i:], c) 66 if o < 0 { 67 break 68 } 69 i += o 70 } 71 if n == 1 || Equal(s[i:i+n], sep) { 72 count++ 73 i += n 74 continue 75 } 76 i++ 77 } 78 return count 79 } 80 81 // Contains reports whether subslice is within b. 82 func Contains(b, subslice []byte) bool { 83 return Index(b, subslice) != -1 84 } 85 86 // Index returns the index of the first instance of sep in s, or -1 if sep is not present in s. 87 func Index(s, sep []byte) int { 88 n := len(sep) 89 if n == 0 { 90 return 0 91 } 92 if n > len(s) { 93 return -1 94 } 95 c := sep[0] 96 if n == 1 { 97 return IndexByte(s, c) 98 } 99 i := 0 100 t := s[:len(s)-n+1] 101 for i < len(t) { 102 if t[i] != c { 103 o := IndexByte(t[i:], c) 104 if o < 0 { 105 break 106 } 107 i += o 108 } 109 if Equal(s[i:i+n], sep) { 110 return i 111 } 112 i++ 113 } 114 return -1 115 } 116 117 func indexBytePortable(s []byte, c byte) int { 118 for i, b := range s { 119 if b == c { 120 return i 121 } 122 } 123 return -1 124 } 125 126 // LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s. 127 func LastIndex(s, sep []byte) int { 128 n := len(sep) 129 if n == 0 { 130 return len(s) 131 } 132 c := sep[0] 133 for i := len(s) - n; i >= 0; i-- { 134 if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) { 135 return i 136 } 137 } 138 return -1 139 } 140 141 // IndexRune interprets s as a sequence of UTF-8-encoded Unicode code points. 142 // It returns the byte index of the first occurrence in s of the given rune. 143 // It returns -1 if rune is not present in s. 144 func IndexRune(s []byte, r rune) int { 145 for i := 0; i < len(s); { 146 r1, size := utf8.DecodeRune(s[i:]) 147 if r == r1 { 148 return i 149 } 150 i += size 151 } 152 return -1 153 } 154 155 // IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. 156 // It returns the byte index of the first occurrence in s of any of the Unicode 157 // code points in chars. It returns -1 if chars is empty or if there is no code 158 // point in common. 159 func IndexAny(s []byte, chars string) int { 160 if len(chars) > 0 { 161 var r rune 162 var width int 163 for i := 0; i < len(s); i += width { 164 r = rune(s[i]) 165 if r < utf8.RuneSelf { 166 width = 1 167 } else { 168 r, width = utf8.DecodeRune(s[i:]) 169 } 170 for _, ch := range chars { 171 if r == ch { 172 return i 173 } 174 } 175 } 176 } 177 return -1 178 } 179 180 // LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code 181 // points. It returns the byte index of the last occurrence in s of any of 182 // the Unicode code points in chars. It returns -1 if chars is empty or if 183 // there is no code point in common. 184 func LastIndexAny(s []byte, chars string) int { 185 if len(chars) > 0 { 186 for i := len(s); i > 0; { 187 r, size := utf8.DecodeLastRune(s[0:i]) 188 i -= size 189 for _, ch := range chars { 190 if r == ch { 191 return i 192 } 193 } 194 } 195 } 196 return -1 197 } 198 199 // Generic split: splits after each instance of sep, 200 // including sepSave bytes of sep in the subslices. 201 func genSplit(s, sep []byte, sepSave, n int) [][]byte { 202 if n == 0 { 203 return nil 204 } 205 if len(sep) == 0 { 206 return explode(s, n) 207 } 208 if n < 0 { 209 n = Count(s, sep) + 1 210 } 211 c := sep[0] 212 start := 0 213 a := make([][]byte, n) 214 na := 0 215 for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { 216 if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) { 217 a[na] = s[start : i+sepSave] 218 na++ 219 start = i + len(sep) 220 i += len(sep) - 1 221 } 222 } 223 a[na] = s[start:] 224 return a[0 : na+1] 225 } 226 227 // SplitN slices s into subslices separated by sep and returns a slice of 228 // the subslices between those separators. 229 // If sep is empty, SplitN splits after each UTF-8 sequence. 230 // The count determines the number of subslices to return: 231 // n > 0: at most n subslices; the last subslice will be the unsplit remainder. 232 // n == 0: the result is nil (zero subslices) 233 // n < 0: all subslices 234 func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) } 235 236 // SplitAfterN slices s into subslices after each instance of sep and 237 // returns a slice of those subslices. 238 // If sep is empty, SplitAfterN splits after each UTF-8 sequence. 239 // The count determines the number of subslices to return: 240 // n > 0: at most n subslices; the last subslice will be the unsplit remainder. 241 // n == 0: the result is nil (zero subslices) 242 // n < 0: all subslices 243 func SplitAfterN(s, sep []byte, n int) [][]byte { 244 return genSplit(s, sep, len(sep), n) 245 } 246 247 // Split slices s into all subslices separated by sep and returns a slice of 248 // the subslices between those separators. 249 // If sep is empty, Split splits after each UTF-8 sequence. 250 // It is equivalent to SplitN with a count of -1. 251 func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) } 252 253 // SplitAfter slices s into all subslices after each instance of sep and 254 // returns a slice of those subslices. 255 // If sep is empty, SplitAfter splits after each UTF-8 sequence. 256 // It is equivalent to SplitAfterN with a count of -1. 257 func SplitAfter(s, sep []byte) [][]byte { 258 return genSplit(s, sep, len(sep), -1) 259 } 260 261 // Fields splits the slice s around each instance of one or more consecutive white space 262 // characters, returning a slice of subslices of s or an empty list if s contains only white space. 263 func Fields(s []byte) [][]byte { 264 return FieldsFunc(s, unicode.IsSpace) 265 } 266 267 // FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode code points. 268 // It splits the slice s at each run of code points c satisfying f(c) and 269 // returns a slice of subslices of s. If all code points in s satisfy f(c), or 270 // len(s) == 0, an empty slice is returned. 271 // FieldsFunc makes no guarantees about the order in which it calls f(c). 272 // If f does not return consistent results for a given c, FieldsFunc may crash. 273 func FieldsFunc(s []byte, f func(rune) bool) [][]byte { 274 n := 0 275 inField := false 276 for i := 0; i < len(s); { 277 r, size := utf8.DecodeRune(s[i:]) 278 wasInField := inField 279 inField = !f(r) 280 if inField && !wasInField { 281 n++ 282 } 283 i += size 284 } 285 286 a := make([][]byte, n) 287 na := 0 288 fieldStart := -1 289 for i := 0; i <= len(s) && na < n; { 290 r, size := utf8.DecodeRune(s[i:]) 291 if fieldStart < 0 && size > 0 && !f(r) { 292 fieldStart = i 293 i += size 294 continue 295 } 296 if fieldStart >= 0 && (size == 0 || f(r)) { 297 a[na] = s[fieldStart:i] 298 na++ 299 fieldStart = -1 300 } 301 if size == 0 { 302 break 303 } 304 i += size 305 } 306 return a[0:na] 307 } 308 309 // Join concatenates the elements of s to create a new byte slice. The separator 310 // sep is placed between elements in the resulting slice. 311 func Join(s [][]byte, sep []byte) []byte { 312 if len(s) == 0 { 313 return []byte{} 314 } 315 if len(s) == 1 { 316 // Just return a copy. 317 return append([]byte(nil), s[0]...) 318 } 319 n := len(sep) * (len(s) - 1) 320 for _, v := range s { 321 n += len(v) 322 } 323 324 b := make([]byte, n) 325 bp := copy(b, s[0]) 326 for _, v := range s[1:] { 327 bp += copy(b[bp:], sep) 328 bp += copy(b[bp:], v) 329 } 330 return b 331 } 332 333 // HasPrefix tests whether the byte slice s begins with prefix. 334 func HasPrefix(s, prefix []byte) bool { 335 return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix) 336 } 337 338 // HasSuffix tests whether the byte slice s ends with suffix. 339 func HasSuffix(s, suffix []byte) bool { 340 return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix) 341 } 342 343 // Map returns a copy of the byte slice s with all its characters modified 344 // according to the mapping function. If mapping returns a negative value, the character is 345 // dropped from the string with no replacement. The characters in s and the 346 // output are interpreted as UTF-8-encoded Unicode code points. 347 func Map(mapping func(r rune) rune, s []byte) []byte { 348 // In the worst case, the slice can grow when mapped, making 349 // things unpleasant. But it's so rare we barge in assuming it's 350 // fine. It could also shrink but that falls out naturally. 351 maxbytes := len(s) // length of b 352 nbytes := 0 // number of bytes encoded in b 353 b := make([]byte, maxbytes) 354 for i := 0; i < len(s); { 355 wid := 1 356 r := rune(s[i]) 357 if r >= utf8.RuneSelf { 358 r, wid = utf8.DecodeRune(s[i:]) 359 } 360 r = mapping(r) 361 if r >= 0 { 362 rl := utf8.RuneLen(r) 363 if rl < 0 { 364 rl = len(string(utf8.RuneError)) 365 } 366 if nbytes+rl > maxbytes { 367 // Grow the buffer. 368 maxbytes = maxbytes*2 + utf8.UTFMax 369 nb := make([]byte, maxbytes) 370 copy(nb, b[0:nbytes]) 371 b = nb 372 } 373 nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r) 374 } 375 i += wid 376 } 377 return b[0:nbytes] 378 } 379 380 // Repeat returns a new byte slice consisting of count copies of b. 381 func Repeat(b []byte, count int) []byte { 382 nb := make([]byte, len(b)*count) 383 bp := copy(nb, b) 384 for bp < len(nb) { 385 copy(nb[bp:], nb[:bp]) 386 bp *= 2 387 } 388 return nb 389 } 390 391 // ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case. 392 func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) } 393 394 // ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case. 395 func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) } 396 397 // ToTitle returns a copy of the byte slice s with all Unicode letters mapped to their title case. 398 func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) } 399 400 // ToUpperSpecial returns a copy of the byte slice s with all Unicode letters mapped to their 401 // upper case, giving priority to the special casing rules. 402 func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte { 403 return Map(func(r rune) rune { return _case.ToUpper(r) }, s) 404 } 405 406 // ToLowerSpecial returns a copy of the byte slice s with all Unicode letters mapped to their 407 // lower case, giving priority to the special casing rules. 408 func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte { 409 return Map(func(r rune) rune { return _case.ToLower(r) }, s) 410 } 411 412 // ToTitleSpecial returns a copy of the byte slice s with all Unicode letters mapped to their 413 // title case, giving priority to the special casing rules. 414 func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte { 415 return Map(func(r rune) rune { return _case.ToTitle(r) }, s) 416 } 417 418 // isSeparator reports whether the rune could mark a word boundary. 419 // TODO: update when package unicode captures more of the properties. 420 func isSeparator(r rune) bool { 421 // ASCII alphanumerics and underscore are not separators 422 if r <= 0x7F { 423 switch { 424 case '0' <= r && r <= '9': 425 return false 426 case 'a' <= r && r <= 'z': 427 return false 428 case 'A' <= r && r <= 'Z': 429 return false 430 case r == '_': 431 return false 432 } 433 return true 434 } 435 // Letters and digits are not separators 436 if unicode.IsLetter(r) || unicode.IsDigit(r) { 437 return false 438 } 439 // Otherwise, all we can do for now is treat spaces as separators. 440 return unicode.IsSpace(r) 441 } 442 443 // Title returns a copy of s with all Unicode letters that begin words 444 // mapped to their title case. 445 // 446 // BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly. 447 func Title(s []byte) []byte { 448 // Use a closure here to remember state. 449 // Hackish but effective. Depends on Map scanning in order and calling 450 // the closure once per rune. 451 prev := ' ' 452 return Map( 453 func(r rune) rune { 454 if isSeparator(prev) { 455 prev = r 456 return unicode.ToTitle(r) 457 } 458 prev = r 459 return r 460 }, 461 s) 462 } 463 464 // TrimLeftFunc returns a subslice of s by slicing off all leading UTF-8-encoded 465 // Unicode code points c that satisfy f(c). 466 func TrimLeftFunc(s []byte, f func(r rune) bool) []byte { 467 i := indexFunc(s, f, false) 468 if i == -1 { 469 return nil 470 } 471 return s[i:] 472 } 473 474 // TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8 475 // encoded Unicode code points c that satisfy f(c). 476 func TrimRightFunc(s []byte, f func(r rune) bool) []byte { 477 i := lastIndexFunc(s, f, false) 478 if i >= 0 && s[i] >= utf8.RuneSelf { 479 _, wid := utf8.DecodeRune(s[i:]) 480 i += wid 481 } else { 482 i++ 483 } 484 return s[0:i] 485 } 486 487 // TrimFunc returns a subslice of s by slicing off all leading and trailing 488 // UTF-8-encoded Unicode code points c that satisfy f(c). 489 func TrimFunc(s []byte, f func(r rune) bool) []byte { 490 return TrimRightFunc(TrimLeftFunc(s, f), f) 491 } 492 493 // TrimPrefix returns s without the provided leading prefix string. 494 // If s doesn't start with prefix, s is returned unchanged. 495 func TrimPrefix(s, prefix []byte) []byte { 496 if HasPrefix(s, prefix) { 497 return s[len(prefix):] 498 } 499 return s 500 } 501 502 // TrimSuffix returns s without the provided trailing suffix string. 503 // If s doesn't end with suffix, s is returned unchanged. 504 func TrimSuffix(s, suffix []byte) []byte { 505 if HasSuffix(s, suffix) { 506 return s[:len(s)-len(suffix)] 507 } 508 return s 509 } 510 511 // IndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points. 512 // It returns the byte index in s of the first Unicode 513 // code point satisfying f(c), or -1 if none do. 514 func IndexFunc(s []byte, f func(r rune) bool) int { 515 return indexFunc(s, f, true) 516 } 517 518 // LastIndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points. 519 // It returns the byte index in s of the last Unicode 520 // code point satisfying f(c), or -1 if none do. 521 func LastIndexFunc(s []byte, f func(r rune) bool) int { 522 return lastIndexFunc(s, f, true) 523 } 524 525 // indexFunc is the same as IndexFunc except that if 526 // truth==false, the sense of the predicate function is 527 // inverted. 528 func indexFunc(s []byte, f func(r rune) bool, truth bool) int { 529 start := 0 530 for start < len(s) { 531 wid := 1 532 r := rune(s[start]) 533 if r >= utf8.RuneSelf { 534 r, wid = utf8.DecodeRune(s[start:]) 535 } 536 if f(r) == truth { 537 return start 538 } 539 start += wid 540 } 541 return -1 542 } 543 544 // lastIndexFunc is the same as LastIndexFunc except that if 545 // truth==false, the sense of the predicate function is 546 // inverted. 547 func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int { 548 for i := len(s); i > 0; { 549 r, size := rune(s[i-1]), 1 550 if r >= utf8.RuneSelf { 551 r, size = utf8.DecodeLastRune(s[0:i]) 552 } 553 i -= size 554 if f(r) == truth { 555 return i 556 } 557 } 558 return -1 559 } 560 561 func makeCutsetFunc(cutset string) func(r rune) bool { 562 return func(r rune) bool { 563 for _, c := range cutset { 564 if c == r { 565 return true 566 } 567 } 568 return false 569 } 570 } 571 572 // Trim returns a subslice of s by slicing off all leading and 573 // trailing UTF-8-encoded Unicode code points contained in cutset. 574 func Trim(s []byte, cutset string) []byte { 575 return TrimFunc(s, makeCutsetFunc(cutset)) 576 } 577 578 // TrimLeft returns a subslice of s by slicing off all leading 579 // UTF-8-encoded Unicode code points contained in cutset. 580 func TrimLeft(s []byte, cutset string) []byte { 581 return TrimLeftFunc(s, makeCutsetFunc(cutset)) 582 } 583 584 // TrimRight returns a subslice of s by slicing off all trailing 585 // UTF-8-encoded Unicode code points that are contained in cutset. 586 func TrimRight(s []byte, cutset string) []byte { 587 return TrimRightFunc(s, makeCutsetFunc(cutset)) 588 } 589 590 // TrimSpace returns a subslice of s by slicing off all leading and 591 // trailing white space, as defined by Unicode. 592 func TrimSpace(s []byte) []byte { 593 return TrimFunc(s, unicode.IsSpace) 594 } 595 596 // Runes returns a slice of runes (Unicode code points) equivalent to s. 597 func Runes(s []byte) []rune { 598 t := make([]rune, utf8.RuneCount(s)) 599 i := 0 600 for len(s) > 0 { 601 r, l := utf8.DecodeRune(s) 602 t[i] = r 603 i++ 604 s = s[l:] 605 } 606 return t 607 } 608 609 // Replace returns a copy of the slice s with the first n 610 // non-overlapping instances of old replaced by new. 611 // If old is empty, it matches at the beginning of the slice 612 // and after each UTF-8 sequence, yielding up to k+1 replacements 613 // for a k-rune slice. 614 // If n < 0, there is no limit on the number of replacements. 615 func Replace(s, old, new []byte, n int) []byte { 616 m := 0 617 if n != 0 { 618 // Compute number of replacements. 619 m = Count(s, old) 620 } 621 if m == 0 { 622 // Just return a copy. 623 return append([]byte(nil), s...) 624 } 625 if n < 0 || m < n { 626 n = m 627 } 628 629 // Apply replacements to buffer. 630 t := make([]byte, len(s)+n*(len(new)-len(old))) 631 w := 0 632 start := 0 633 for i := 0; i < n; i++ { 634 j := start 635 if len(old) == 0 { 636 if i > 0 { 637 _, wid := utf8.DecodeRune(s[start:]) 638 j += wid 639 } 640 } else { 641 j += Index(s[start:], old) 642 } 643 w += copy(t[w:], s[start:j]) 644 w += copy(t[w:], new) 645 start = j + len(old) 646 } 647 w += copy(t[w:], s[start:]) 648 return t[0:w] 649 } 650 651 // EqualFold reports whether s and t, interpreted as UTF-8 strings, 652 // are equal under Unicode case-folding. 653 func EqualFold(s, t []byte) bool { 654 for len(s) != 0 && len(t) != 0 { 655 // Extract first rune from each. 656 var sr, tr rune 657 if s[0] < utf8.RuneSelf { 658 sr, s = rune(s[0]), s[1:] 659 } else { 660 r, size := utf8.DecodeRune(s) 661 sr, s = r, s[size:] 662 } 663 if t[0] < utf8.RuneSelf { 664 tr, t = rune(t[0]), t[1:] 665 } else { 666 r, size := utf8.DecodeRune(t) 667 tr, t = r, t[size:] 668 } 669 670 // If they match, keep going; if not, return false. 671 672 // Easy case. 673 if tr == sr { 674 continue 675 } 676 677 // Make sr < tr to simplify what follows. 678 if tr < sr { 679 tr, sr = sr, tr 680 } 681 // Fast check for ASCII. 682 if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { 683 // ASCII, and sr is upper case. tr must be lower case. 684 if tr == sr+'a'-'A' { 685 continue 686 } 687 return false 688 } 689 690 // General case. SimpleFold(x) returns the next equivalent rune > x 691 // or wraps around to smaller values. 692 r := unicode.SimpleFold(sr) 693 for r != sr && r < tr { 694 r = unicode.SimpleFold(r) 695 } 696 if r == tr { 697 continue 698 } 699 return false 700 } 701 702 // One string is empty. Are both? 703 return len(s) == len(t) 704 }