Source file
src/bytes/example_test.go
1
2
3
4
5 package bytes_test
6
7 import (
8 "bytes"
9 "encoding/base64"
10 "fmt"
11 "io"
12 "os"
13 "slices"
14 "strconv"
15 "unicode"
16 )
17
18 func ExampleBuffer() {
19 var b bytes.Buffer
20 b.Write([]byte("Hello "))
21 fmt.Fprintf(&b, "world!")
22 b.WriteTo(os.Stdout)
23
24 }
25
26 func ExampleBuffer_reader() {
27
28 buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==")
29 dec := base64.NewDecoder(base64.StdEncoding, buf)
30 io.Copy(os.Stdout, dec)
31
32 }
33
34 func 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
39 }
40
41 func 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
51 }
52
53 func 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
59
60
61 }
62
63 func 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
70 }
71
72 func ExampleBuffer_Len() {
73 var b bytes.Buffer
74 b.Grow(64)
75 b.Write([]byte("abcde"))
76 fmt.Printf("%d", b.Len())
77
78 }
79
80 func 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
88
89
90
91 }
92
93 func 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
106
107
108
109 }
110
111 func 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
122
123
124 }
125
126 func ExampleBuffer_Peek() {
127 var b bytes.Buffer
128 b.WriteString("Hello, Gophers!")
129
130 data, err := b.Peek(5)
131 if err != nil {
132 panic(err)
133 }
134 fmt.Printf("First peek: %s\n", data)
135
136 fmt.Printf("Buffer: %s\n", b.String())
137
138
139 if _, err := b.Read(make([]byte, 7)); err != nil {
140 panic(err)
141 }
142
143 data, err = b.Peek(7)
144 if err != nil {
145 panic(err)
146 }
147 fmt.Printf("Second peek: %s\n", data)
148
149
150
151
152
153 }
154
155 func ExampleClone() {
156 b := []byte("abc")
157 clone := bytes.Clone(b)
158 fmt.Printf("%s\n", clone)
159 clone[0] = 'd'
160 fmt.Printf("%s\n", b)
161 fmt.Printf("%s\n", clone)
162
163
164
165
166 }
167
168 func ExampleCompare() {
169
170 var a, b []byte
171 if bytes.Compare(a, b) < 0 {
172
173 }
174 if bytes.Compare(a, b) <= 0 {
175
176 }
177 if bytes.Compare(a, b) > 0 {
178
179 }
180 if bytes.Compare(a, b) >= 0 {
181
182 }
183
184
185 if bytes.Equal(a, b) {
186
187 }
188 if !bytes.Equal(a, b) {
189
190 }
191 }
192
193 func ExampleCompare_search() {
194
195 var needle []byte
196 var haystack [][]byte
197 _, found := slices.BinarySearchFunc(haystack, needle, bytes.Compare)
198 if found {
199
200 }
201 }
202
203 func ExampleContains() {
204 fmt.Println(bytes.Contains([]byte("seafood"), []byte("foo")))
205 fmt.Println(bytes.Contains([]byte("seafood"), []byte("bar")))
206 fmt.Println(bytes.Contains([]byte("seafood"), []byte("")))
207 fmt.Println(bytes.Contains([]byte(""), []byte("")))
208
209
210
211
212
213 }
214
215 func ExampleContainsAny() {
216 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "fÄo!"))
217 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), "去是伟大的."))
218 fmt.Println(bytes.ContainsAny([]byte("I like seafood."), ""))
219 fmt.Println(bytes.ContainsAny([]byte(""), ""))
220
221
222
223
224
225 }
226
227 func ExampleContainsRune() {
228 fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'f'))
229 fmt.Println(bytes.ContainsRune([]byte("I like seafood."), 'ö'))
230 fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '大'))
231 fmt.Println(bytes.ContainsRune([]byte("去是伟大的!"), '!'))
232 fmt.Println(bytes.ContainsRune([]byte(""), '@'))
233
234
235
236
237
238
239 }
240
241 func ExampleContainsFunc() {
242 f := func(r rune) bool {
243 return r >= 'a' && r <= 'z'
244 }
245 fmt.Println(bytes.ContainsFunc([]byte("HELLO"), f))
246 fmt.Println(bytes.ContainsFunc([]byte("World"), f))
247
248
249
250 }
251
252 func ExampleCount() {
253 fmt.Println(bytes.Count([]byte("cheese"), []byte("e")))
254 fmt.Println(bytes.Count([]byte("five"), []byte("")))
255
256
257
258 }
259
260 func ExampleCut() {
261 show := func(s, sep string) {
262 before, after, found := bytes.Cut([]byte(s), []byte(sep))
263 fmt.Printf("Cut(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
264 }
265 show("Gopher", "Go")
266 show("Gopher", "ph")
267 show("Gopher", "er")
268 show("Gopher", "Badger")
269
270
271
272
273
274 }
275
276 func ExampleCutLast() {
277 show := func(s, sep string) {
278 before, after, found := bytes.CutLast([]byte(s), []byte(sep))
279 fmt.Printf("CutLast(%q, %q) = %q, %q, %v\n", s, sep, before, after, found)
280 }
281 show("root/user/docs", "/")
282 show("Gopher", "/")
283
284
285
286 }
287
288 func ExampleCutPrefix() {
289 show := func(s, prefix string) {
290 after, found := bytes.CutPrefix([]byte(s), []byte(prefix))
291 fmt.Printf("CutPrefix(%q, %q) = %q, %v\n", s, prefix, after, found)
292 }
293 show("Gopher", "Go")
294 show("Gopher", "ph")
295
296
297
298 }
299
300 func ExampleCutSuffix() {
301 show := func(s, suffix string) {
302 before, found := bytes.CutSuffix([]byte(s), []byte(suffix))
303 fmt.Printf("CutSuffix(%q, %q) = %q, %v\n", s, suffix, before, found)
304 }
305 show("Gopher", "Go")
306 show("Gopher", "er")
307
308
309
310 }
311
312 func ExampleEqual() {
313 fmt.Println(bytes.Equal([]byte("Go"), []byte("Go")))
314 fmt.Println(bytes.Equal([]byte("Go"), []byte("C++")))
315
316
317
318 }
319
320 func ExampleEqualFold() {
321 fmt.Println(bytes.EqualFold([]byte("Go"), []byte("go")))
322
323 }
324
325 func ExampleFields() {
326 fmt.Printf("Fields are: %q", bytes.Fields([]byte(" foo bar baz ")))
327
328 }
329
330 func ExampleFieldsFunc() {
331 f := func(c rune) bool {
332 return !unicode.IsLetter(c) && !unicode.IsNumber(c)
333 }
334 fmt.Printf("Fields are: %q", bytes.FieldsFunc([]byte(" foo1;bar2,baz3..."), f))
335
336 }
337
338 func ExampleHasPrefix() {
339 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
340 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
341 fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
342
343
344
345
346 }
347
348 func ExampleHasSuffix() {
349 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("go")))
350 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("O")))
351 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("Ami")))
352 fmt.Println(bytes.HasSuffix([]byte("Amigo"), []byte("")))
353
354
355
356
357
358 }
359
360 func ExampleIndex() {
361 fmt.Println(bytes.Index([]byte("chicken"), []byte("ken")))
362 fmt.Println(bytes.Index([]byte("chicken"), []byte("dmr")))
363
364
365
366 }
367
368 func ExampleIndexByte() {
369 fmt.Println(bytes.IndexByte([]byte("chicken"), byte('k')))
370 fmt.Println(bytes.IndexByte([]byte("chicken"), byte('g')))
371
372
373
374 }
375
376 func ExampleIndexFunc() {
377 f := func(c rune) bool {
378 return unicode.Is(unicode.Han, c)
379 }
380 fmt.Println(bytes.IndexFunc([]byte("Hello, 世界"), f))
381 fmt.Println(bytes.IndexFunc([]byte("Hello, world"), f))
382
383
384
385 }
386
387 func ExampleIndexAny() {
388 fmt.Println(bytes.IndexAny([]byte("chicken"), "aeiouy"))
389 fmt.Println(bytes.IndexAny([]byte("crwth"), "aeiouy"))
390
391
392
393 }
394
395 func ExampleIndexRune() {
396 fmt.Println(bytes.IndexRune([]byte("chicken"), 'k'))
397 fmt.Println(bytes.IndexRune([]byte("chicken"), 'd'))
398
399
400
401 }
402
403 func ExampleJoin() {
404 s := [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")}
405 fmt.Printf("%s", bytes.Join(s, []byte(", ")))
406
407 }
408
409 func ExampleLastIndex() {
410 fmt.Println(bytes.Index([]byte("go gopher"), []byte("go")))
411 fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("go")))
412 fmt.Println(bytes.LastIndex([]byte("go gopher"), []byte("rodent")))
413
414
415
416
417 }
418
419 func ExampleLastIndexAny() {
420 fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "MüQp"))
421 fmt.Println(bytes.LastIndexAny([]byte("go 地鼠"), "地大"))
422 fmt.Println(bytes.LastIndexAny([]byte("go gopher"), "z,!."))
423
424
425
426
427 }
428
429 func ExampleLastIndexByte() {
430 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('g')))
431 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('r')))
432 fmt.Println(bytes.LastIndexByte([]byte("go gopher"), byte('z')))
433
434
435
436
437 }
438
439 func ExampleLastIndexFunc() {
440 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsLetter))
441 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsPunct))
442 fmt.Println(bytes.LastIndexFunc([]byte("go gopher!"), unicode.IsNumber))
443
444
445
446
447 }
448
449 func ExampleMap() {
450 rot13 := func(r rune) rune {
451 switch {
452 case r >= 'A' && r <= 'Z':
453 return 'A' + (r-'A'+13)%26
454 case r >= 'a' && r <= 'z':
455 return 'a' + (r-'a'+13)%26
456 }
457 return r
458 }
459 fmt.Printf("%s\n", bytes.Map(rot13, []byte("'Twas brillig and the slithy gopher...")))
460
461
462 }
463
464 func ExampleReader_Len() {
465 fmt.Println(bytes.NewReader([]byte("Hi!")).Len())
466 fmt.Println(bytes.NewReader([]byte("こんにちは!")).Len())
467
468
469
470 }
471
472 func ExampleRepeat() {
473 fmt.Printf("ba%s", bytes.Repeat([]byte("na"), 2))
474
475 }
476
477 func ExampleReplace() {
478 fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("k"), []byte("ky"), 2))
479 fmt.Printf("%s\n", bytes.Replace([]byte("oink oink oink"), []byte("oink"), []byte("moo"), -1))
480
481
482
483 }
484
485 func ExampleReplaceAll() {
486 fmt.Printf("%s\n", bytes.ReplaceAll([]byte("oink oink oink"), []byte("oink"), []byte("moo")))
487
488
489 }
490
491 func ExampleRunes() {
492 rs := bytes.Runes([]byte("go gopher"))
493 for _, r := range rs {
494 fmt.Printf("%#U\n", r)
495 }
496
497
498
499
500
501
502
503
504
505
506 }
507
508 func ExampleSplit() {
509 fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
510 fmt.Printf("%q\n", bytes.Split([]byte("a man a plan a canal panama"), []byte("a ")))
511 fmt.Printf("%q\n", bytes.Split([]byte(" xyz "), []byte("")))
512 fmt.Printf("%q\n", bytes.Split([]byte(""), []byte("Bernardo O'Higgins")))
513
514
515
516
517
518 }
519
520 func ExampleSplitN() {
521 fmt.Printf("%q\n", bytes.SplitN([]byte("a,b,c"), []byte(","), 2))
522 z := bytes.SplitN([]byte("a,b,c"), []byte(","), 0)
523 fmt.Printf("%q (nil = %v)\n", z, z == nil)
524
525
526
527 }
528
529 func ExampleSplitAfter() {
530 fmt.Printf("%q\n", bytes.SplitAfter([]byte("a,b,c"), []byte(",")))
531
532 }
533
534 func ExampleSplitAfterN() {
535 fmt.Printf("%q\n", bytes.SplitAfterN([]byte("a,b,c"), []byte(","), 2))
536
537 }
538
539 func ExampleTitle() {
540 fmt.Printf("%s", bytes.Title([]byte("her royal highness")))
541
542 }
543
544 func ExampleToTitle() {
545 fmt.Printf("%s\n", bytes.ToTitle([]byte("loud noises")))
546 fmt.Printf("%s\n", bytes.ToTitle([]byte("брат")))
547
548
549
550 }
551
552 func ExampleToTitleSpecial() {
553 str := []byte("ahoj vývojári golang")
554 totitle := bytes.ToTitleSpecial(unicode.AzeriCase, str)
555 fmt.Println("Original : " + string(str))
556 fmt.Println("ToTitle : " + string(totitle))
557
558
559
560 }
561
562 func ExampleToValidUTF8() {
563 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("abc"), []byte("\uFFFD")))
564 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("a\xffb\xC0\xAFc\xff"), []byte("")))
565 fmt.Printf("%s\n", bytes.ToValidUTF8([]byte("\xed\xa0\x80"), []byte("abc")))
566
567
568
569
570 }
571
572 func ExampleTrim() {
573 fmt.Printf("[%q]", bytes.Trim([]byte(" !!! Achtung! Achtung! !!! "), "! "))
574
575 }
576
577 func ExampleTrimFunc() {
578 fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsLetter)))
579 fmt.Println(string(bytes.TrimFunc([]byte("\"go-gopher!\""), unicode.IsLetter)))
580 fmt.Println(string(bytes.TrimFunc([]byte("go-gopher!"), unicode.IsPunct)))
581 fmt.Println(string(bytes.TrimFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
582
583
584
585
586
587 }
588
589 func ExampleTrimLeft() {
590 fmt.Print(string(bytes.TrimLeft([]byte("453gopher8257"), "0123456789")))
591
592
593 }
594
595 func ExampleTrimLeftFunc() {
596 fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher"), unicode.IsLetter)))
597 fmt.Println(string(bytes.TrimLeftFunc([]byte("go-gopher!"), unicode.IsPunct)))
598 fmt.Println(string(bytes.TrimLeftFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
599
600
601
602
603 }
604
605 func ExampleTrimPrefix() {
606 var b = []byte("Goodbye,, world!")
607 b = bytes.TrimPrefix(b, []byte("Goodbye,"))
608 b = bytes.TrimPrefix(b, []byte("See ya,"))
609 fmt.Printf("Hello%s", b)
610
611 }
612
613 func ExampleTrimSpace() {
614 fmt.Printf("%s", bytes.TrimSpace([]byte(" \t\n a lone gopher \n\t\r\n")))
615
616 }
617
618 func ExampleTrimSuffix() {
619 var b = []byte("Hello, goodbye, etc!")
620 b = bytes.TrimSuffix(b, []byte("goodbye, etc!"))
621 b = bytes.TrimSuffix(b, []byte("gopher"))
622 b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...)
623 os.Stdout.Write(b)
624
625 }
626
627 func ExampleTrimRight() {
628 fmt.Print(string(bytes.TrimRight([]byte("453gopher8257"), "0123456789")))
629
630
631 }
632
633 func ExampleTrimRightFunc() {
634 fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher"), unicode.IsLetter)))
635 fmt.Println(string(bytes.TrimRightFunc([]byte("go-gopher!"), unicode.IsPunct)))
636 fmt.Println(string(bytes.TrimRightFunc([]byte("1234go-gopher!567"), unicode.IsNumber)))
637
638
639
640
641 }
642
643 func ExampleToLower() {
644 fmt.Printf("%s", bytes.ToLower([]byte("Gopher")))
645
646 }
647
648 func ExampleToLowerSpecial() {
649 str := []byte("AHOJ VÝVOJÁRİ GOLANG")
650 totitle := bytes.ToLowerSpecial(unicode.AzeriCase, str)
651 fmt.Println("Original : " + string(str))
652 fmt.Println("ToLower : " + string(totitle))
653
654
655
656 }
657
658 func ExampleToUpper() {
659 fmt.Printf("%s", bytes.ToUpper([]byte("Gopher")))
660
661 }
662
663 func ExampleToUpperSpecial() {
664 str := []byte("ahoj vývojári golang")
665 totitle := bytes.ToUpperSpecial(unicode.AzeriCase, str)
666 fmt.Println("Original : " + string(str))
667 fmt.Println("ToUpper : " + string(totitle))
668
669
670
671 }
672
673 func ExampleLines() {
674 text := []byte("Hello\nWorld\nGo Programming\n")
675 for line := range bytes.Lines(text) {
676 fmt.Printf("%q\n", line)
677 }
678
679
680
681
682
683 }
684
685 func ExampleSplitSeq() {
686 s := []byte("a,b,c,d")
687 for part := range bytes.SplitSeq(s, []byte(",")) {
688 fmt.Printf("%q\n", part)
689 }
690
691
692
693
694
695
696 }
697
698 func ExampleSplitAfterSeq() {
699 s := []byte("a,b,c,d")
700 for part := range bytes.SplitAfterSeq(s, []byte(",")) {
701 fmt.Printf("%q\n", part)
702 }
703
704
705
706
707
708
709 }
710
711 func ExampleFieldsSeq() {
712 text := []byte("The quick brown fox")
713 fmt.Println("Split byte slice into fields:")
714 for word := range bytes.FieldsSeq(text) {
715 fmt.Printf("%q\n", word)
716 }
717
718 textWithSpaces := []byte(" lots of spaces ")
719 fmt.Println("\nSplit byte slice with multiple spaces:")
720 for word := range bytes.FieldsSeq(textWithSpaces) {
721 fmt.Printf("%q\n", word)
722 }
723
724
725
726
727
728
729
730
731
732
733
734
735 }
736
737 func ExampleFieldsFuncSeq() {
738 text := []byte("The quick brown fox")
739 fmt.Println("Split on whitespace(similar to FieldsSeq):")
740 for word := range bytes.FieldsFuncSeq(text, unicode.IsSpace) {
741 fmt.Printf("%q\n", word)
742 }
743
744 mixedText := []byte("abc123def456ghi")
745 fmt.Println("\nSplit on digits:")
746 for word := range bytes.FieldsFuncSeq(mixedText, unicode.IsDigit) {
747 fmt.Printf("%q\n", word)
748 }
749
750
751
752
753
754
755
756
757
758
759
760
761 }
762
View as plain text