example_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. package bytes_test
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "fmt"
  9. "io"
  10. "os"
  11. "sort"
  12. )
  13. func ExampleBuffer() {
  14. var b bytes.Buffer // A Buffer needs no initialization.
  15. b.Write([]byte("Hello "))
  16. fmt.Fprintf(&b, "world!")
  17. b.WriteTo(os.Stdout)
  18. // Output: Hello world!
  19. }
  20. func ExampleBuffer_reader() {
  21. // A Buffer can turn a string or a []byte into an io.Reader.
  22. buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
  23. dec := base64.NewDecoder(base64.StdEncoding, buf)
  24. io.Copy(os.Stdout, dec)
  25. // Output: Gophers rule!
  26. }
  27. func ExampleCompare() {
  28. // Interpret Compare's result by comparing it to zero.
  29. var a, b []byte
  30. if bytes.Compare(a, b) < 0 {
  31. // a less b
  32. }
  33. if bytes.Compare(a, b) <= 0 {
  34. // a less or equal b
  35. }
  36. if bytes.Compare(a, b) > 0 {
  37. // a greater b
  38. }
  39. if bytes.Compare(a, b) >= 0 {
  40. // a greater or equal b
  41. }
  42. // Prefer Equal to Compare for equality comparisons.
  43. if bytes.Equal(a, b) {
  44. // a equal b
  45. }
  46. if !bytes.Equal(a, b) {
  47. // a not equal b
  48. }
  49. }
  50. func ExampleCompare_search() {
  51. // Binary search to find a matching byte slice.
  52. var needle []byte
  53. var haystack [][]byte // Assume sorted
  54. i := sort.Search(len(haystack), func(i int) bool {
  55. // Return haystack[i] >= needle.
  56. return bytes.Compare(haystack[i], needle) >= 0
  57. })
  58. if i < len(haystack) && bytes.Equal(haystack[i], needle) {
  59. // Found it!
  60. }
  61. }
  62. func ExampleTrimSuffix() {
  63. var b = []byte("Hello, goodbye, etc!")
  64. b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
  65. b = bytes.TrimSuffix(b, []byte("gopher"))
  66. b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
  67. os.Stdout.Write(b)
  68. // Output: Hello, world!
  69. }
  70. func ExampleTrimPrefix() {
  71. var b = []byte("Goodbye,, world!")
  72. b = bytes.TrimPrefix(b, []byte("Goodbye,"))
  73. b = bytes.TrimPrefix(b, []byte("See ya,"))
  74. fmt.Printf("Hello%s", b)
  75. // Output: Hello, world!
  76. }