Black Lives Matter. Support the Equal Justice Initiative.

Source file src/bytes/example_test.go

Documentation: bytes

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

View as plain text