Merged revisions 195034,195219,195245,195357,195374,195428,195599,195673,195809 via...
[official-gcc.git] / main / libgo / go / bytes / example_test.go
blobdc66b6a40f67b73c24bd9c158bb82bded3f8d064
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.
5 package bytes_test
7 import (
8 "bytes"
9 "encoding/base64"
10 "fmt"
11 "io"
12 "os"
13 "sort"
16 func ExampleBuffer() {
17 var b bytes.Buffer // A Buffer needs no initialization.
18 b.Write([]byte("Hello "))
19 fmt.Fprintf(&b, "world!")
20 b.WriteTo(os.Stdout)
21 // Output: Hello world!
24 func ExampleBuffer_reader() {
25 // A Buffer can turn a string or a []byte into an io.Reader.
26 buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
27 dec := base64.NewDecoder(base64.StdEncoding, buf)
28 io.Copy(os.Stdout, dec)
29 // Output: Gophers rule!
32 func ExampleCompare() {
33 // Interpret Compare's result by comparing it to zero.
34 var a, b []byte
35 if bytes.Compare(a, b) < 0 {
36 // a less b
38 if bytes.Compare(a, b) <= 0 {
39 // a less or equal b
41 if bytes.Compare(a, b) > 0 {
42 // a greater b
44 if bytes.Compare(a, b) >= 0 {
45 // a greater or equal b
48 // Prefer Equal to Compare for equality comparisons.
49 if bytes.Equal(a, b) {
50 // a equal b
52 if !bytes.Equal(a, b) {
53 // a not equal b
57 func ExampleCompare_search() {
58 // Binary search to find a matching byte slice.
59 var needle []byte
60 var haystack [][]byte // Assume sorted
61 i := sort.Search(len(haystack), func(i int) bool {
62 // Return haystack[i] >= needle.
63 return bytes.Compare(haystack[i], needle) >= 0
65 if i < len(haystack) && bytes.Equal(haystack[i], needle) {
66 // Found it!