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