1// Copyright 2011 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 5package bytes_test 6 7import ( 8 "bytes" 9 "encoding/base64" 10 "fmt" 11 "io" 12 "os" 13 "slices" 14 "strconv" 15 "unicode" 16) 17 18func ExampleBuffer() { 19 var b bytes.Buffer // A Buffer needs no initialization. 20 b.Write([]byte("Hello ")) 21 fmt.Fprintf(&b, "world!") 22 b.WriteTo(os.Stdout) 23 // Output: Hello world! 24} 25 26func ExampleBuffer_reader() { 27 // A Buffer can turn a string or a []byte into an io.Reader. 28 buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==") 29 dec := base64.NewDecoder(base64.StdEncoding, buf) 30 io.Copy(os.Stdout, dec) 31 // Output: Gophers rule! 32} 33 34func ExampleBuffer_Bytes() { 35 buf := bytes.Buffer{} 36 buf.Write([]byte{'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'}) 37 os.Stdout.Write(buf.Bytes()) 38 // Output: hello world 39} 40 41func ExampleBuffer_AvailableBuffer() { 42 var buf bytes.Buffer 43 for i := 0; i < 4; i++ { 44 b := buf.AvailableBuffer() 45 b = strconv.AppendInt(b, int64(i), 10) 46 b = append(b, ' ') 47 buf.Write(b) 48 } 49 os.Stdout.Write(buf.Bytes()) 50 // Output: 0 1 2 3 51} 52 53func ExampleBuffer_Cap() { 54 buf1 := bytes.NewBuffer(make([]byte, 10)) 55 buf2 := bytes.NewBuffer(make([]byte, 0, 10)) 56 fmt.Println(buf1.Cap()) 57 fmt.Println(buf2.Cap()) 58 // Output: 59 // 10 60 // 10 61} 62 63func ExampleBuffer_Grow() { 64 var b bytes.Buffer 65 b.Grow(64) 66 bb := b.Bytes() 67 b.Write([]byte("64 bytes or fewer")) 68 fmt.Printf("%q", bb[:b.Len()]) 69 // Output: "64 bytes or fewer" 70} 71 72func ExampleBuffer_Len() { 73 var b bytes.Buffer 74 b.Grow(64) 75 b.Write([]byte("abcde")) 76 fmt.Printf("%d", b.Len()) 77 // Output: 5 78} 79 80func ExampleBuffer_Next() { 81 var b bytes.Buffer 82 b.Grow(64) 83 b.Write([]byte("abcde")) 84 fmt.Printf("%s\n", b.Next(2)) 85 fmt.Printf("%s\n", b.Next(2)) 86 fmt.Printf("%s", b.Next(2)) 87 // Output: 88 // ab 89 // cd 90 // e 91} 92 93func ExampleBuffer_Read() { 94 var b bytes.Buffer 95 b.Grow(64) 96 b.Write([]byte("abcde")) 97 rdbuf := make([]byte, 1) 98 n, err := b.Read(rdbuf) 99 if err != nil { 100 panic(err) 101 } 102 fmt.Println(n) 103 fmt.Println(b.String()) 104 fmt.Println(string(rdbuf)) 105 // Output: 106 // 1 107 // bcde 108 // a 109} 110 111func ExampleBuffer_ReadByte() { 112 var b bytes.Buffer 113 b.Grow(64) 114 b.Write([]byte("abcde")) 115 c, err := b.ReadByte() 116 if err != nil { 117 panic(err) 118 } 119 fmt.Println(c) 120 fmt.Println(b.String()) 121 // Output: 122 // 97 123 // bcde 124} 125 126func ExampleClone() { 127 b := []byte("abc") 128 clone := bytes.Clone(b) 129 fmt.Printf("%s\n", clone) 130 clone[0] = 'd' 131 fmt.Printf("%s\n", b) 132 fmt.Printf("%s\n", clone) 133 // Output: 134 // abc 135 // abc 136 // dbc 137} 138 139func ExampleCompare() { 140 // Interpret Compare's result by comparing it to zero. 141 var a, b []byte 142 if bytes.Compare(a, b) < 0 { 143 // a less b 144 } 145 if bytes.Compare(a, b) <= 0 { 146 // a less or equal b 147 } 148 if bytes.Compare(a, b) > 0 { 149 // a greater b 150 } 151 if bytes.Compare(a, b) >= 0 { 152 // a greater or equal b 153 } 154 155 // Prefer Equal to Compare for equality comparisons. 156 if bytes.Equal(a, b) { 157 // a equal b 158 } 159 if !bytes.Equal(a, b) { 160 // a not equal b 161 } 162} 163 164func ExampleCompare_search() { 165 // Binary search to find a matching byte slice. 166 var needle []byte 167 var haystack [][]byte // Assume sorted 168 _, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare) 169 if found { 170 // Found it! 171 } 172} 173 174func ExampleContains() { 175 fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo"))) 176 fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar"))) 177 fmt.Println(bytes.Contains([]byte("seafood"), []byte(""))) 178 fmt.Println(bytes.Contains([]byte(""), []byte(""))) 179 // Output: 180 // true 181 // false 182 // true 183 // true 184} 185 186func ExampleContainsAny() { 187 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!")) 188 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的.")) 189 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "")) 190 fmt.Println(bytes.ContainsAny([]byte(""), "")) 191 // Output: 192 // true 193 // true 194 // false 195 // false 196} 197 198func ExampleContainsRune() { 199 fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f')) 200 fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö')) 201 fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大')) 202 fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!')) 203 fmt.Println(bytes.ContainsRune([]byte(""), '@')) 204 // Output: 205 // true 206 // false 207 // true 208 // true 209 // false 210} 211 212func ExampleContainsFunc() { 213 f := func(r rune) bool { 214 return r >= 'a' && r <= 'z' 215 } 216 fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f)) 217 fmt.Println(bytes.ContainsFunc([]byte("World"), f)) 218 // Output: 219 // false 220 // true 221} 222 223func ExampleCount() { 224 fmt.Println(bytes.Count([]byte("cheese"), []byte("e"))) 225 fmt.Println(bytes.Count([]byte("five"), []byte(""))) // before & after each rune 226 // Output: 227 // 3 228 // 5 229} 230 231func ExampleCut() { 232 show := func(s, sep string) { 233 before, after, found := bytes.Cut([]byte(s), []byte(sep)) 234 fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found) 235 } 236 show("Gopher", "Go") 237 show("Gopher", "ph") 238 show("Gopher", "er") 239 show("Gopher", "Badger") 240 // Output: 241 // Cut("Gopher", "Go") = "", "pher", true 242 // Cut("Gopher", "ph") = "Go", "er", true 243 // Cut("Gopher", "er") = "Goph", "", true 244 // Cut("Gopher", "Badger") = "Gopher", "", false 245} 246 247func ExampleCutPrefix() { 248 show := func(s, sep string) { 249 after, found := bytes.CutPrefix([]byte(s), []byte(sep)) 250 fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, sep, after, found) 251 } 252 show("Gopher", "Go") 253 show("Gopher", "ph") 254 // Output: 255 // CutPrefix("Gopher", "Go") = "pher", true 256 // CutPrefix("Gopher", "ph") = "Gopher", false 257} 258 259func ExampleCutSuffix() { 260 show := func(s, sep string) { 261 before, found := bytes.CutSuffix([]byte(s), []byte(sep)) 262 fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, sep, before, found) 263 } 264 show("Gopher", "Go") 265 show("Gopher", "er") 266 // Output: 267 // CutSuffix("Gopher", "Go") = "Gopher", false 268 // CutSuffix("Gopher", "er") = "Goph", true 269} 270 271func ExampleEqual() { 272 fmt.Println(bytes.Equal([]byte("Go"), []byte("Go"))) 273 fmt.Println(bytes.Equal([]byte("Go"), []byte("C++"))) 274 // Output: 275 // true 276 // false 277} 278 279func ExampleEqualFold() { 280 fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go"))) 281 // Output: true 282} 283 284func ExampleFields() { 285 fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz "))) 286 // Output: Fields are: ["foo" "bar" "baz"] 287} 288 289func ExampleFieldsFunc() { 290 f := func(c rune) bool { 291 return !unicode.IsLetter(c) && !unicode.IsNumber(c) 292 } 293 fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f)) 294 // Output: Fields are: ["foo1" "bar2" "baz3"] 295} 296 297func ExampleHasPrefix() { 298 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go"))) 299 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C"))) 300 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte(""))) 301 // Output: 302 // true 303 // false 304 // true 305} 306 307func ExampleHasSuffix() { 308 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go"))) 309 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O"))) 310 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami"))) 311 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte(""))) 312 // Output: 313 // true 314 // false 315 // false 316 // true 317} 318 319func ExampleIndex() { 320 fmt.Println(bytes.Index([]byte("chicken"), []byte("ken"))) 321 fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr"))) 322 // Output: 323 // 4 324 // -1 325} 326 327func ExampleIndexByte() { 328 fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k'))) 329 fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g'))) 330 // Output: 331 // 4 332 // -1 333} 334 335func ExampleIndexFunc() { 336 f := func(c rune) bool { 337 return unicode.Is(unicode.Han, c) 338 } 339 fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f)) 340 fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f)) 341 // Output: 342 // 7 343 // -1 344} 345 346func ExampleIndexAny() { 347 fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy")) 348 fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy")) 349 // Output: 350 // 2 351 // -1 352} 353 354func ExampleIndexRune() { 355 fmt.Println(bytes.IndexRune([]byte("chicken"), 'k')) 356 fmt.Println(bytes.IndexRune([]byte("chicken"), 'd')) 357 // Output: 358 // 4 359 // -1 360} 361 362func ExampleJoin() { 363 s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")} 364 fmt.Printf("%s", bytes.Join(s, []byte(", "))) 365 // Output: foo, bar, baz 366} 367 368func ExampleLastIndex() { 369 fmt.Println(bytes.Index([]byte("go gopher"), []byte("go"))) 370 fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go"))) 371 fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent"))) 372 // Output: 373 // 0 374 // 3 375 // -1 376} 377 378func ExampleLastIndexAny() { 379 fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp")) 380 fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大")) 381 fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!.")) 382 // Output: 383 // 5 384 // 3 385 // -1 386} 387 388func ExampleLastIndexByte() { 389 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g'))) 390 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r'))) 391 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z'))) 392 // Output: 393 // 3 394 // 8 395 // -1 396} 397 398func ExampleLastIndexFunc() { 399 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter)) 400 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct)) 401 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber)) 402 // Output: 403 // 8 404 // 9 405 // -1 406} 407 408func ExampleMap() { 409 rot13 := func(r rune) rune { 410 switch { 411 case r >= 'A' && r <= 'Z': 412 return 'A' + (r-'A'+13)%26 413 case r >= 'a' && r <= 'z': 414 return 'a' + (r-'a'+13)%26 415 } 416 return r 417 } 418 fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher..."))) 419 // Output: 420 // 'Gjnf oevyyvt naq gur fyvgul tbcure... 421} 422 423func ExampleReader_Len() { 424 fmt.Println(bytes.NewReader([]byte("Hi!")).Len()) 425 fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len()) 426 // Output: 427 // 3 428 // 16 429} 430 431func ExampleRepeat() { 432 fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2)) 433 // Output: banana 434} 435 436func ExampleReplace() { 437 fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2)) 438 fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1)) 439 // Output: 440 // oinky oinky oink 441 // moo moo moo 442} 443 444func ExampleReplaceAll() { 445 fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo"))) 446 // Output: 447 // moo moo moo 448} 449 450func ExampleRunes() { 451 rs := bytes.Runes([]byte("go gopher")) 452 for _, r := range rs { 453 fmt.Printf("%#U\n", r) 454 } 455 // Output: 456 // U+0067 'g' 457 // U+006F 'o' 458 // U+0020 ' ' 459 // U+0067 'g' 460 // U+006F 'o' 461 // U+0070 'p' 462 // U+0068 'h' 463 // U+0065 'e' 464 // U+0072 'r' 465} 466 467func ExampleSplit() { 468 fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(","))) 469 fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a "))) 470 fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte(""))) 471 fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins"))) 472 // Output: 473 // ["a" "b" "c"] 474 // ["" "man " "plan " "canal panama"] 475 // [" " "x" "y" "z" " "] 476 // [""] 477} 478 479func ExampleSplitN() { 480 fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2)) 481 z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0) 482 fmt.Printf("%q (nil = %v)\n", z, z == nil) 483 // Output: 484 // ["a" "b,c"] 485 // [] (nil = true) 486} 487 488func ExampleSplitAfter() { 489 fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(","))) 490 // Output: ["a," "b," "c"] 491} 492 493func ExampleSplitAfterN() { 494 fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2)) 495 // Output: ["a," "b,c"] 496} 497 498func ExampleTitle() { 499 fmt.Printf("%s", bytes.Title([]byte("her royal highness"))) 500 // Output: Her Royal Highness 501} 502 503func ExampleToTitle() { 504 fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises"))) 505 fmt.Printf("%s\n", bytes.ToTitle([]byte("хлеб"))) 506 // Output: 507 // LOUD NOISES 508 // ХЛЕБ 509} 510 511func ExampleToTitleSpecial() { 512 str := []byte("ahoj vývojári golang") 513 totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str) 514 fmt.Println("Original : " + string(str)) 515 fmt.Println("ToTitle : " + string(totitle)) 516 // Output: 517 // Original : ahoj vývojári golang 518 // ToTitle : AHOJ VÝVOJÁRİ GOLANG 519} 520 521func ExampleToValidUTF8() { 522 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD"))) 523 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte(""))) 524 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc"))) 525 // Output: 526 // abc 527 // abc 528 // abc 529} 530 531func ExampleTrim() { 532 fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! ")) 533 // Output: ["Achtung! Achtung"] 534} 535 536func ExampleTrimFunc() { 537 fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter))) 538 fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter))) 539 fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct))) 540 fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) 541 // Output: 542 // -gopher! 543 // "go-gopher!" 544 // go-gopher 545 // go-gopher! 546} 547 548func ExampleTrimLeft() { 549 fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789"))) 550 // Output: 551 // gopher8257 552} 553 554func ExampleTrimLeftFunc() { 555 fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter))) 556 fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct))) 557 fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) 558 // Output: 559 // -gopher 560 // go-gopher! 561 // go-gopher!567 562} 563 564func ExampleTrimPrefix() { 565 var b = []byte("Goodbye,, world!") 566 b = bytes.TrimPrefix(b, []byte("Goodbye,")) 567 b = bytes.TrimPrefix(b, []byte("See ya,")) 568 fmt.Printf("Hello%s", b) 569 // Output: Hello, world! 570} 571 572func ExampleTrimSpace() { 573 fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n"))) 574 // Output: a lone gopher 575} 576 577func ExampleTrimSuffix() { 578 var b = []byte("Hello, goodbye, etc!") 579 b = bytes.TrimSuffix(b, []byte("goodbye, etc!")) 580 b = bytes.TrimSuffix(b, []byte("gopher")) 581 b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...) 582 os.Stdout.Write(b) 583 // Output: Hello, world! 584} 585 586func ExampleTrimRight() { 587 fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789"))) 588 // Output: 589 // 453gopher 590} 591 592func ExampleTrimRightFunc() { 593 fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter))) 594 fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct))) 595 fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber))) 596 // Output: 597 // go- 598 // go-gopher 599 // 1234go-gopher! 600} 601 602func ExampleToLower() { 603 fmt.Printf("%s", bytes.ToLower([]byte("Gopher"))) 604 // Output: gopher 605} 606 607func ExampleToLowerSpecial() { 608 str := []byte("AHOJ VÝVOJÁRİ GOLANG") 609 totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str) 610 fmt.Println("Original : " + string(str)) 611 fmt.Println("ToLower : " + string(totitle)) 612 // Output: 613 // Original : AHOJ VÝVOJÁRİ GOLANG 614 // ToLower : ahoj vývojári golang 615} 616 617func ExampleToUpper() { 618 fmt.Printf("%s", bytes.ToUpper([]byte("Gopher"))) 619 // Output: GOPHER 620} 621 622func ExampleToUpperSpecial() { 623 str := []byte("ahoj vývojári golang") 624 totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str) 625 fmt.Println("Original : " + string(str)) 626 fmt.Println("ToUpper : " + string(totitle)) 627 // Output: 628 // Original : ahoj vývojári golang 629 // ToUpper : AHOJ VÝVOJÁRİ GOLANG 630} 631