Source file
src/bufio/bufio_test.go
1
2
3
4
5 package bufio_test
6
7 import (
8 . "bufio"
9 "bytes"
10 "errors"
11 "fmt"
12 "io"
13 "math/rand"
14 "strconv"
15 "strings"
16 "testing"
17 "testing/iotest"
18 "time"
19 "unicode/utf8"
20 )
21
22
23 type rot13Reader struct {
24 r io.Reader
25 }
26
27 func newRot13Reader(r io.Reader) *rot13Reader {
28 r13 := new(rot13Reader)
29 r13.r = r
30 return r13
31 }
32
33 func (r13 *rot13Reader) Read(p []byte) (int, error) {
34 n, err := r13.r.Read(p)
35 for i := 0; i < n; i++ {
36 c := p[i] | 0x20
37 if 'a' <= c && c <= 'm' {
38 p[i] += 13
39 } else if 'n' <= c && c <= 'z' {
40 p[i] -= 13
41 }
42 }
43 return n, err
44 }
45
46
47 func readBytes(buf *Reader) string {
48 var b [1000]byte
49 nb := 0
50 for {
51 c, err := buf.ReadByte()
52 if err == io.EOF {
53 break
54 }
55 if err == nil {
56 b[nb] = c
57 nb++
58 } else if err != iotest.ErrTimeout {
59 panic("Data: " + err.Error())
60 }
61 }
62 return string(b[0:nb])
63 }
64
65 func TestReaderSimple(t *testing.T) {
66 data := "hello world"
67 b := NewReader(strings.NewReader(data))
68 if s := readBytes(b); s != "hello world" {
69 t.Errorf("simple hello world test failed: got %q", s)
70 }
71
72 b = NewReader(newRot13Reader(strings.NewReader(data)))
73 if s := readBytes(b); s != "uryyb jbeyq" {
74 t.Errorf("rot13 hello world test failed: got %q", s)
75 }
76 }
77
78 type readMaker struct {
79 name string
80 fn func(io.Reader) io.Reader
81 }
82
83 var readMakers = []readMaker{
84 {"full", func(r io.Reader) io.Reader { return r }},
85 {"byte", iotest.OneByteReader},
86 {"half", iotest.HalfReader},
87 {"data+err", iotest.DataErrReader},
88 {"timeout", iotest.TimeoutReader},
89 }
90
91
92
93 func readLines(b *Reader) string {
94 s := ""
95 for {
96 s1, err := b.ReadString('\n')
97 if err == io.EOF {
98 break
99 }
100 if err != nil && err != iotest.ErrTimeout {
101 panic("GetLines: " + err.Error())
102 }
103 s += s1
104 }
105 return s
106 }
107
108
109 func reads(buf *Reader, m int) string {
110 var b [1000]byte
111 nb := 0
112 for {
113 n, err := buf.Read(b[nb : nb+m])
114 nb += n
115 if err == io.EOF {
116 break
117 }
118 }
119 return string(b[0:nb])
120 }
121
122 type bufReader struct {
123 name string
124 fn func(*Reader) string
125 }
126
127 var bufreaders = []bufReader{
128 {"1", func(b *Reader) string { return reads(b, 1) }},
129 {"2", func(b *Reader) string { return reads(b, 2) }},
130 {"3", func(b *Reader) string { return reads(b, 3) }},
131 {"4", func(b *Reader) string { return reads(b, 4) }},
132 {"5", func(b *Reader) string { return reads(b, 5) }},
133 {"7", func(b *Reader) string { return reads(b, 7) }},
134 {"bytes", readBytes},
135 {"lines", readLines},
136 }
137
138 const minReadBufferSize = 16
139
140 var bufsizes = []int{
141 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096,
142 }
143
144 func TestReader(t *testing.T) {
145 var texts [31]string
146 str := ""
147 all := ""
148 for i := 0; i < len(texts)-1; i++ {
149 texts[i] = str + "\n"
150 all += texts[i]
151 str += string(rune(i%26 + 'a'))
152 }
153 texts[len(texts)-1] = all
154
155 for h := 0; h < len(texts); h++ {
156 text := texts[h]
157 for i := 0; i < len(readMakers); i++ {
158 for j := 0; j < len(bufreaders); j++ {
159 for k := 0; k < len(bufsizes); k++ {
160 readmaker := readMakers[i]
161 bufreader := bufreaders[j]
162 bufsize := bufsizes[k]
163 read := readmaker.fn(strings.NewReader(text))
164 buf := NewReaderSize(read, bufsize)
165 s := bufreader.fn(buf)
166 if s != text {
167 t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q",
168 readmaker.name, bufreader.name, bufsize, text, s)
169 }
170 }
171 }
172 }
173 }
174 }
175
176 type zeroReader struct{}
177
178 func (zeroReader) Read(p []byte) (int, error) {
179 return 0, nil
180 }
181
182 func TestZeroReader(t *testing.T) {
183 var z zeroReader
184 r := NewReader(z)
185
186 c := make(chan error)
187 go func() {
188 _, err := r.ReadByte()
189 c <- err
190 }()
191
192 select {
193 case err := <-c:
194 if err == nil {
195 t.Error("error expected")
196 } else if err != io.ErrNoProgress {
197 t.Error("unexpected error:", err)
198 }
199 case <-time.After(time.Second):
200 t.Error("test timed out (endless loop in ReadByte?)")
201 }
202 }
203
204
205 type StringReader struct {
206 data []string
207 step int
208 }
209
210 func (r *StringReader) Read(p []byte) (n int, err error) {
211 if r.step < len(r.data) {
212 s := r.data[r.step]
213 n = copy(p, s)
214 r.step++
215 } else {
216 err = io.EOF
217 }
218 return
219 }
220
221 func readRuneSegments(t *testing.T, segments []string) {
222 got := ""
223 want := strings.Join(segments, "")
224 r := NewReader(&StringReader{data: segments})
225 for {
226 r, _, err := r.ReadRune()
227 if err != nil {
228 if err != io.EOF {
229 return
230 }
231 break
232 }
233 got += string(r)
234 }
235 if got != want {
236 t.Errorf("segments=%v got=%s want=%s", segments, got, want)
237 }
238 }
239
240 var segmentList = [][]string{
241 {},
242 {""},
243 {"日", "本語"},
244 {"\u65e5", "\u672c", "\u8a9e"},
245 {"\U000065e5", "\U0000672c", "\U00008a9e"},
246 {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"},
247 {"Hello", ", ", "World", "!"},
248 {"Hello", ", ", "", "World", "!"},
249 }
250
251 func TestReadRune(t *testing.T) {
252 for _, s := range segmentList {
253 readRuneSegments(t, s)
254 }
255 }
256
257 func TestUnreadRune(t *testing.T) {
258 segments := []string{"Hello, world:", "日本語"}
259 r := NewReader(&StringReader{data: segments})
260 got := ""
261 want := strings.Join(segments, "")
262
263 for {
264 r1, _, err := r.ReadRune()
265 if err != nil {
266 if err != io.EOF {
267 t.Error("unexpected error on ReadRune:", err)
268 }
269 break
270 }
271 got += string(r1)
272
273 if err = r.UnreadRune(); err != nil {
274 t.Fatal("unexpected error on UnreadRune:", err)
275 }
276 r2, _, err := r.ReadRune()
277 if err != nil {
278 t.Fatal("unexpected error reading after unreading:", err)
279 }
280 if r1 != r2 {
281 t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2)
282 }
283 }
284 if got != want {
285 t.Errorf("got %q, want %q", got, want)
286 }
287 }
288
289 func TestNoUnreadRuneAfterPeek(t *testing.T) {
290 br := NewReader(strings.NewReader("example"))
291 br.ReadRune()
292 br.Peek(1)
293 if err := br.UnreadRune(); err == nil {
294 t.Error("UnreadRune didn't fail after Peek")
295 }
296 }
297
298 func TestNoUnreadByteAfterPeek(t *testing.T) {
299 br := NewReader(strings.NewReader("example"))
300 br.ReadByte()
301 br.Peek(1)
302 if err := br.UnreadByte(); err == nil {
303 t.Error("UnreadByte didn't fail after Peek")
304 }
305 }
306
307 func TestNoUnreadRuneAfterDiscard(t *testing.T) {
308 br := NewReader(strings.NewReader("example"))
309 br.ReadRune()
310 br.Discard(1)
311 if err := br.UnreadRune(); err == nil {
312 t.Error("UnreadRune didn't fail after Discard")
313 }
314 }
315
316 func TestNoUnreadByteAfterDiscard(t *testing.T) {
317 br := NewReader(strings.NewReader("example"))
318 br.ReadByte()
319 br.Discard(1)
320 if err := br.UnreadByte(); err == nil {
321 t.Error("UnreadByte didn't fail after Discard")
322 }
323 }
324
325 func TestNoUnreadRuneAfterWriteTo(t *testing.T) {
326 br := NewReader(strings.NewReader("example"))
327 br.WriteTo(io.Discard)
328 if err := br.UnreadRune(); err == nil {
329 t.Error("UnreadRune didn't fail after WriteTo")
330 }
331 }
332
333 func TestNoUnreadByteAfterWriteTo(t *testing.T) {
334 br := NewReader(strings.NewReader("example"))
335 br.WriteTo(io.Discard)
336 if err := br.UnreadByte(); err == nil {
337 t.Error("UnreadByte didn't fail after WriteTo")
338 }
339 }
340
341 func TestUnreadByte(t *testing.T) {
342 segments := []string{"Hello, ", "world"}
343 r := NewReader(&StringReader{data: segments})
344 got := ""
345 want := strings.Join(segments, "")
346
347 for {
348 b1, err := r.ReadByte()
349 if err != nil {
350 if err != io.EOF {
351 t.Error("unexpected error on ReadByte:", err)
352 }
353 break
354 }
355 got += string(b1)
356
357 if err = r.UnreadByte(); err != nil {
358 t.Fatal("unexpected error on UnreadByte:", err)
359 }
360 b2, err := r.ReadByte()
361 if err != nil {
362 t.Fatal("unexpected error reading after unreading:", err)
363 }
364 if b1 != b2 {
365 t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2)
366 }
367 }
368 if got != want {
369 t.Errorf("got %q, want %q", got, want)
370 }
371 }
372
373 func TestUnreadByteMultiple(t *testing.T) {
374 segments := []string{"Hello, ", "world"}
375 data := strings.Join(segments, "")
376 for n := 0; n <= len(data); n++ {
377 r := NewReader(&StringReader{data: segments})
378
379 for i := 0; i < n; i++ {
380 b, err := r.ReadByte()
381 if err != nil {
382 t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err)
383 }
384 if b != data[i] {
385 t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i])
386 }
387 }
388
389 if n > 0 {
390 if err := r.UnreadByte(); err != nil {
391 t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err)
392 }
393 }
394
395 if err := r.UnreadByte(); err == nil {
396 t.Errorf("n = %d: expected error on UnreadByte", n)
397 }
398 }
399 }
400
401 func TestUnreadByteOthers(t *testing.T) {
402
403 var readers = []func(*Reader, byte) ([]byte, error){
404 (*Reader).ReadBytes,
405 (*Reader).ReadSlice,
406 func(r *Reader, delim byte) ([]byte, error) {
407 data, err := r.ReadString(delim)
408 return []byte(data), err
409 },
410
411
412
413
414
415 }
416
417
418 for rno, read := range readers {
419
420 const n = 10
421 var buf bytes.Buffer
422 for i := 0; i < n; i++ {
423 buf.WriteString("abcdefg")
424 }
425
426 r := NewReaderSize(&buf, minReadBufferSize)
427 readTo := func(delim byte, want string) {
428 data, err := read(r, delim)
429 if err != nil {
430 t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err)
431 }
432 if got := string(data); got != want {
433 t.Fatalf("#%d: got %q, want %q", rno, got, want)
434 }
435 }
436
437
438 for i := 0; i < n; i++ {
439 readTo('d', "abcd")
440 for j := 0; j < 3; j++ {
441 if err := r.UnreadByte(); err != nil {
442 t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err)
443 }
444 readTo('d', "d")
445 }
446 readTo('g', "efg")
447 }
448
449
450 _, err := r.ReadByte()
451 if err != io.EOF {
452 t.Errorf("#%d: got error %v; want EOF", rno, err)
453 }
454 }
455 }
456
457
458 func TestUnreadRuneError(t *testing.T) {
459 buf := make([]byte, 3)
460 r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}})
461 if r.UnreadRune() == nil {
462 t.Error("expected error on UnreadRune from fresh buffer")
463 }
464 _, _, err := r.ReadRune()
465 if err != nil {
466 t.Error("unexpected error on ReadRune (1):", err)
467 }
468 if err = r.UnreadRune(); err != nil {
469 t.Error("unexpected error on UnreadRune (1):", err)
470 }
471 if r.UnreadRune() == nil {
472 t.Error("expected error after UnreadRune (1)")
473 }
474
475 _, _, err = r.ReadRune()
476 if err != nil {
477 t.Error("unexpected error on ReadRune (2):", err)
478 }
479 _, err = r.Read(buf)
480 if err != nil {
481 t.Error("unexpected error on Read (2):", err)
482 }
483 if r.UnreadRune() == nil {
484 t.Error("expected error after Read (2)")
485 }
486
487 _, _, err = r.ReadRune()
488 if err != nil {
489 t.Error("unexpected error on ReadRune (2):", err)
490 }
491 for range buf {
492 _, err = r.ReadByte()
493 if err != nil {
494 t.Error("unexpected error on ReadByte (2):", err)
495 }
496 }
497 if r.UnreadRune() == nil {
498 t.Error("expected error after ReadByte")
499 }
500
501 _, _, err = r.ReadRune()
502 if err != nil {
503 t.Error("unexpected error on ReadRune (3):", err)
504 }
505 _, err = r.ReadByte()
506 if err != nil {
507 t.Error("unexpected error on ReadByte (3):", err)
508 }
509 err = r.UnreadByte()
510 if err != nil {
511 t.Error("unexpected error on UnreadByte (3):", err)
512 }
513 if r.UnreadRune() == nil {
514 t.Error("expected error after UnreadByte (3)")
515 }
516
517 _, _, err = r.ReadRune()
518 if err != nil {
519 t.Error("unexpected error on ReadRune (4):", err)
520 }
521 _, err = r.ReadSlice(0)
522 if err != io.EOF {
523 t.Error("unexpected error on ReadSlice (4):", err)
524 }
525 if r.UnreadRune() == nil {
526 t.Error("expected error after ReadSlice (4)")
527 }
528 }
529
530 func TestUnreadRuneAtEOF(t *testing.T) {
531
532 r := NewReader(strings.NewReader("x"))
533 r.ReadRune()
534 r.ReadRune()
535 r.UnreadRune()
536 _, _, err := r.ReadRune()
537 if err == nil {
538 t.Error("expected error at EOF")
539 } else if err != io.EOF {
540 t.Error("expected EOF; got", err)
541 }
542 }
543
544 func TestReadWriteRune(t *testing.T) {
545 const NRune = 1000
546 byteBuf := new(bytes.Buffer)
547 w := NewWriter(byteBuf)
548
549 buf := make([]byte, utf8.UTFMax)
550 for r := rune(0); r < NRune; r++ {
551 size := utf8.EncodeRune(buf, r)
552 nbytes, err := w.WriteRune(r)
553 if err != nil {
554 t.Fatalf("WriteRune(0x%x) error: %s", r, err)
555 }
556 if nbytes != size {
557 t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes)
558 }
559 }
560 w.Flush()
561
562 r := NewReader(byteBuf)
563
564 for r1 := rune(0); r1 < NRune; r1++ {
565 size := utf8.EncodeRune(buf, r1)
566 nr, nbytes, err := r.ReadRune()
567 if nr != r1 || nbytes != size || err != nil {
568 t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err)
569 }
570 }
571 }
572
573 func TestWriteInvalidRune(t *testing.T) {
574
575
576 for _, r := range []rune{-1, utf8.MaxRune + 1} {
577 var buf bytes.Buffer
578 w := NewWriter(&buf)
579 w.WriteRune(r)
580 w.Flush()
581 if s := buf.String(); s != "\uFFFD" {
582 t.Errorf("WriteRune(%d) wrote %q, not replacement character", r, s)
583 }
584 }
585 }
586
587 func TestReadStringAllocs(t *testing.T) {
588 r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
589 buf := NewReader(r)
590 allocs := testing.AllocsPerRun(100, func() {
591 r.Seek(0, io.SeekStart)
592 buf.Reset(r)
593
594 _, err := buf.ReadString('\n')
595 if err != nil {
596 t.Fatal(err)
597 }
598 })
599 if allocs != 1 {
600 t.Errorf("Unexpected number of allocations, got %f, want 1", allocs)
601 }
602 }
603
604 func TestWriter(t *testing.T) {
605 var data [8192]byte
606
607 for i := 0; i < len(data); i++ {
608 data[i] = byte(' ' + i%('~'-' '))
609 }
610 w := new(bytes.Buffer)
611 for i := 0; i < len(bufsizes); i++ {
612 for j := 0; j < len(bufsizes); j++ {
613 nwrite := bufsizes[i]
614 bs := bufsizes[j]
615
616
617
618
619
620 w.Reset()
621 buf := NewWriterSize(w, bs)
622 context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs)
623 n, e1 := buf.Write(data[0:nwrite])
624 if e1 != nil || n != nwrite {
625 t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1)
626 continue
627 }
628 if e := buf.Flush(); e != nil {
629 t.Errorf("%s: buf.Flush = %v", context, e)
630 }
631
632 written := w.Bytes()
633 if len(written) != nwrite {
634 t.Errorf("%s: %d bytes written", context, len(written))
635 }
636 for l := 0; l < len(written); l++ {
637 if written[l] != data[l] {
638 t.Errorf("wrong bytes written")
639 t.Errorf("want=%q", data[0:len(written)])
640 t.Errorf("have=%q", written)
641 }
642 }
643 }
644 }
645 }
646
647 func TestWriterAppend(t *testing.T) {
648 got := new(bytes.Buffer)
649 var want []byte
650 rn := rand.New(rand.NewSource(0))
651 w := NewWriterSize(got, 64)
652 for i := 0; i < 100; i++ {
653
654 b := w.AvailableBuffer()
655 if w.Available() != cap(b) {
656 t.Fatalf("Available() = %v, want %v", w.Available(), cap(b))
657 }
658
659
660
661 if rn.Intn(8) == 0 && cap(b) > 0 {
662 b = b[1:1:cap(b)]
663 }
664
665
666 n := int64(rn.Intn(1 << rn.Intn(30)))
667 want = append(strconv.AppendInt(want, n, 10), ' ')
668 b = append(strconv.AppendInt(b, n, 10), ' ')
669 w.Write(b)
670 }
671 w.Flush()
672
673 if !bytes.Equal(got.Bytes(), want) {
674 t.Errorf("output mismatch:\ngot %s\nwant %s", got.Bytes(), want)
675 }
676 }
677
678
679
680 type errorWriterTest struct {
681 n, m int
682 err error
683 expect error
684 }
685
686 func (w errorWriterTest) Write(p []byte) (int, error) {
687 return len(p) * w.n / w.m, w.err
688 }
689
690 var errorWriterTests = []errorWriterTest{
691 {0, 1, nil, io.ErrShortWrite},
692 {1, 2, nil, io.ErrShortWrite},
693 {1, 1, nil, nil},
694 {0, 1, io.ErrClosedPipe, io.ErrClosedPipe},
695 {1, 2, io.ErrClosedPipe, io.ErrClosedPipe},
696 {1, 1, io.ErrClosedPipe, io.ErrClosedPipe},
697 }
698
699 func TestWriteErrors(t *testing.T) {
700 for _, w := range errorWriterTests {
701 buf := NewWriter(w)
702 _, e := buf.Write([]byte("hello world"))
703 if e != nil {
704 t.Errorf("Write hello to %v: %v", w, e)
705 continue
706 }
707
708 for i := 0; i < 2; i++ {
709 e = buf.Flush()
710 if e != w.expect {
711 t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect)
712 }
713 }
714 }
715 }
716
717 func TestNewReaderSizeIdempotent(t *testing.T) {
718 const BufSize = 1000
719 b := NewReaderSize(strings.NewReader("hello world"), BufSize)
720
721 b1 := NewReaderSize(b, BufSize)
722 if b1 != b {
723 t.Error("NewReaderSize did not detect underlying Reader")
724 }
725
726 b2 := NewReaderSize(b, 2*BufSize)
727 if b2 == b {
728 t.Error("NewReaderSize did not enlarge buffer")
729 }
730 }
731
732 func TestNewWriterSizeIdempotent(t *testing.T) {
733 const BufSize = 1000
734 b := NewWriterSize(new(bytes.Buffer), BufSize)
735
736 b1 := NewWriterSize(b, BufSize)
737 if b1 != b {
738 t.Error("NewWriterSize did not detect underlying Writer")
739 }
740
741 b2 := NewWriterSize(b, 2*BufSize)
742 if b2 == b {
743 t.Error("NewWriterSize did not enlarge buffer")
744 }
745 }
746
747 func TestWriteString(t *testing.T) {
748 const BufSize = 8
749 buf := new(bytes.Buffer)
750 b := NewWriterSize(buf, BufSize)
751 b.WriteString("0")
752 b.WriteString("123456")
753 b.WriteString("7890")
754 b.WriteString("abcdefghijklmnopqrstuvwxy")
755 b.WriteString("z")
756 if err := b.Flush(); err != nil {
757 t.Error("WriteString", err)
758 }
759 s := "01234567890abcdefghijklmnopqrstuvwxyz"
760 if string(buf.Bytes()) != s {
761 t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes()))
762 }
763 }
764
765 func TestBufferFull(t *testing.T) {
766 const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party"
767 buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize)
768 line, err := buf.ReadSlice('!')
769 if string(line) != "And now, hello, " || err != ErrBufferFull {
770 t.Errorf("first ReadSlice(,) = %q, %v", line, err)
771 }
772 line, err = buf.ReadSlice('!')
773 if string(line) != "world!" || err != nil {
774 t.Errorf("second ReadSlice(,) = %q, %v", line, err)
775 }
776 }
777
778 func TestPeek(t *testing.T) {
779 p := make([]byte, 10)
780
781 buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize)
782 if s, err := buf.Peek(1); string(s) != "a" || err != nil {
783 t.Fatalf("want %q got %q, err=%v", "a", string(s), err)
784 }
785 if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
786 t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err)
787 }
788 if _, err := buf.Peek(-1); err != ErrNegativeCount {
789 t.Fatalf("want ErrNegativeCount got %v", err)
790 }
791 if s, err := buf.Peek(32); string(s) != "abcdefghijklmnop" || err != ErrBufferFull {
792 t.Fatalf("want %q, ErrBufFull got %q, err=%v", "abcdefghijklmnop", string(s), err)
793 }
794 if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil {
795 t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err)
796 }
797 if s, err := buf.Peek(1); string(s) != "d" || err != nil {
798 t.Fatalf("want %q got %q, err=%v", "d", string(s), err)
799 }
800 if s, err := buf.Peek(2); string(s) != "de" || err != nil {
801 t.Fatalf("want %q got %q, err=%v", "de", string(s), err)
802 }
803 if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil {
804 t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err)
805 }
806 if s, err := buf.Peek(4); string(s) != "ghij" || err != nil {
807 t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err)
808 }
809 if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil {
810 t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err)
811 }
812 if s, err := buf.Peek(0); string(s) != "" || err != nil {
813 t.Fatalf("want %q got %q, err=%v", "", string(s), err)
814 }
815 if _, err := buf.Peek(1); err != io.EOF {
816 t.Fatalf("want EOF got %v", err)
817 }
818
819
820 buf = NewReaderSize(dataAndEOFReader("abcd"), 32)
821 if s, err := buf.Peek(2); string(s) != "ab" || err != nil {
822 t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err)
823 }
824 if s, err := buf.Peek(4); string(s) != "abcd" || err != nil {
825 t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err)
826 }
827 if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil {
828 t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err)
829 }
830 if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF {
831 t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err)
832 }
833 }
834
835 type dataAndEOFReader string
836
837 func (r dataAndEOFReader) Read(p []byte) (int, error) {
838 return copy(p, r), io.EOF
839 }
840
841 func TestPeekThenUnreadRune(t *testing.T) {
842
843 r := NewReader(strings.NewReader("x"))
844 r.ReadRune()
845 r.Peek(1)
846 r.UnreadRune()
847 r.ReadRune()
848 }
849
850 var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy")
851 var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy")
852 var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n")
853
854
855 type testReader struct {
856 data []byte
857 stride int
858 }
859
860 func (t *testReader) Read(buf []byte) (n int, err error) {
861 n = t.stride
862 if n > len(t.data) {
863 n = len(t.data)
864 }
865 if n > len(buf) {
866 n = len(buf)
867 }
868 copy(buf, t.data)
869 t.data = t.data[n:]
870 if len(t.data) == 0 {
871 err = io.EOF
872 }
873 return
874 }
875
876 func testReadLine(t *testing.T, input []byte) {
877
878 for stride := 1; stride < 2; stride++ {
879 done := 0
880 reader := testReader{input, stride}
881 l := NewReaderSize(&reader, len(input)+1)
882 for {
883 line, isPrefix, err := l.ReadLine()
884 if len(line) > 0 && err != nil {
885 t.Errorf("ReadLine returned both data and error: %s", err)
886 }
887 if isPrefix {
888 t.Errorf("ReadLine returned prefix")
889 }
890 if err != nil {
891 if err != io.EOF {
892 t.Fatalf("Got unknown error: %s", err)
893 }
894 break
895 }
896 if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) {
897 t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line)
898 }
899 done += len(line)
900 }
901 if done != len(testOutput) {
902 t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride)
903 }
904 }
905 }
906
907 func TestReadLine(t *testing.T) {
908 testReadLine(t, testInput)
909 testReadLine(t, testInputrn)
910 }
911
912 func TestLineTooLong(t *testing.T) {
913 data := make([]byte, 0)
914 for i := 0; i < minReadBufferSize*5/2; i++ {
915 data = append(data, '0'+byte(i%10))
916 }
917 buf := bytes.NewReader(data)
918 l := NewReaderSize(buf, minReadBufferSize)
919 line, isPrefix, err := l.ReadLine()
920 if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
921 t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err)
922 }
923 data = data[len(line):]
924 line, isPrefix, err = l.ReadLine()
925 if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil {
926 t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err)
927 }
928 data = data[len(line):]
929 line, isPrefix, err = l.ReadLine()
930 if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil {
931 t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err)
932 }
933 line, isPrefix, err = l.ReadLine()
934 if isPrefix || err == nil {
935 t.Errorf("expected no more lines: %x %s", line, err)
936 }
937 }
938
939 func TestReadAfterLines(t *testing.T) {
940 line1 := "this is line1"
941 restData := "this is line2\nthis is line 3\n"
942 inbuf := bytes.NewReader([]byte(line1 + "\n" + restData))
943 outbuf := new(bytes.Buffer)
944 maxLineLength := len(line1) + len(restData)/2
945 l := NewReaderSize(inbuf, maxLineLength)
946 line, isPrefix, err := l.ReadLine()
947 if isPrefix || err != nil || string(line) != line1 {
948 t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line))
949 }
950 n, err := io.Copy(outbuf, l)
951 if int(n) != len(restData) || err != nil {
952 t.Errorf("bad result for Read: n=%d err=%v", n, err)
953 }
954 if outbuf.String() != restData {
955 t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData)
956 }
957 }
958
959 func TestReadEmptyBuffer(t *testing.T) {
960 l := NewReaderSize(new(bytes.Buffer), minReadBufferSize)
961 line, isPrefix, err := l.ReadLine()
962 if err != io.EOF {
963 t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
964 }
965 }
966
967 func TestLinesAfterRead(t *testing.T) {
968 l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize)
969 _, err := io.ReadAll(l)
970 if err != nil {
971 t.Error(err)
972 return
973 }
974
975 line, isPrefix, err := l.ReadLine()
976 if err != io.EOF {
977 t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err)
978 }
979 }
980
981 func TestReadLineNonNilLineOrError(t *testing.T) {
982 r := NewReader(strings.NewReader("line 1\n"))
983 for i := 0; i < 2; i++ {
984 l, _, err := r.ReadLine()
985 if l != nil && err != nil {
986 t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both",
987 i+1, l, err)
988 }
989 }
990 }
991
992 type readLineResult struct {
993 line []byte
994 isPrefix bool
995 err error
996 }
997
998 var readLineNewlinesTests = []struct {
999 input string
1000 expect []readLineResult
1001 }{
1002 {"012345678901234\r\n012345678901234\r\n", []readLineResult{
1003 {[]byte("012345678901234"), true, nil},
1004 {nil, false, nil},
1005 {[]byte("012345678901234"), true, nil},
1006 {nil, false, nil},
1007 {nil, false, io.EOF},
1008 }},
1009 {"0123456789012345\r012345678901234\r", []readLineResult{
1010 {[]byte("0123456789012345"), true, nil},
1011 {[]byte("\r012345678901234"), true, nil},
1012 {[]byte("\r"), false, nil},
1013 {nil, false, io.EOF},
1014 }},
1015 }
1016
1017 func TestReadLineNewlines(t *testing.T) {
1018 for _, e := range readLineNewlinesTests {
1019 testReadLineNewlines(t, e.input, e.expect)
1020 }
1021 }
1022
1023 func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) {
1024 b := NewReaderSize(strings.NewReader(input), minReadBufferSize)
1025 for i, e := range expect {
1026 line, isPrefix, err := b.ReadLine()
1027 if !bytes.Equal(line, e.line) {
1028 t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line)
1029 return
1030 }
1031 if isPrefix != e.isPrefix {
1032 t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix)
1033 return
1034 }
1035 if err != e.err {
1036 t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err)
1037 return
1038 }
1039 }
1040 }
1041
1042 func createTestInput(n int) []byte {
1043 input := make([]byte, n)
1044 for i := range input {
1045
1046
1047
1048 input[i] = byte(i % 251)
1049 if i%101 == 0 {
1050 input[i] ^= byte(i / 101)
1051 }
1052 }
1053 return input
1054 }
1055
1056 func TestReaderWriteTo(t *testing.T) {
1057 input := createTestInput(8192)
1058 r := NewReader(onlyReader{bytes.NewReader(input)})
1059 w := new(bytes.Buffer)
1060 if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) {
1061 t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input))
1062 }
1063
1064 for i, val := range w.Bytes() {
1065 if val != input[i] {
1066 t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i])
1067 }
1068 }
1069 }
1070
1071 type errorWriterToTest struct {
1072 rn, wn int
1073 rerr, werr error
1074 expected error
1075 }
1076
1077 func (r errorWriterToTest) Read(p []byte) (int, error) {
1078 return len(p) * r.rn, r.rerr
1079 }
1080
1081 func (w errorWriterToTest) Write(p []byte) (int, error) {
1082 return len(p) * w.wn, w.werr
1083 }
1084
1085 var errorWriterToTests = []errorWriterToTest{
1086 {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe},
1087 {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
1088 {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe},
1089 {0, 1, io.EOF, nil, nil},
1090 }
1091
1092 func TestReaderWriteToErrors(t *testing.T) {
1093 for i, rw := range errorWriterToTests {
1094 r := NewReader(rw)
1095 if _, err := r.WriteTo(rw); err != rw.expected {
1096 t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
1097 }
1098 }
1099 }
1100
1101 func TestWriterReadFrom(t *testing.T) {
1102 ws := []func(io.Writer) io.Writer{
1103 func(w io.Writer) io.Writer { return onlyWriter{w} },
1104 func(w io.Writer) io.Writer { return w },
1105 }
1106
1107 rs := []func(io.Reader) io.Reader{
1108 iotest.DataErrReader,
1109 func(r io.Reader) io.Reader { return r },
1110 }
1111
1112 for ri, rfunc := range rs {
1113 for wi, wfunc := range ws {
1114 input := createTestInput(8192)
1115 b := new(bytes.Buffer)
1116 w := NewWriter(wfunc(b))
1117 r := rfunc(bytes.NewReader(input))
1118 if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) {
1119 t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input))
1120 continue
1121 }
1122 if err := w.Flush(); err != nil {
1123 t.Errorf("Flush returned %v", err)
1124 continue
1125 }
1126 if got, want := b.String(), string(input); got != want {
1127 t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want)
1128 }
1129 }
1130 }
1131 }
1132
1133 type errorReaderFromTest struct {
1134 rn, wn int
1135 rerr, werr error
1136 expected error
1137 }
1138
1139 func (r errorReaderFromTest) Read(p []byte) (int, error) {
1140 return len(p) * r.rn, r.rerr
1141 }
1142
1143 func (w errorReaderFromTest) Write(p []byte) (int, error) {
1144 return len(p) * w.wn, w.werr
1145 }
1146
1147 var errorReaderFromTests = []errorReaderFromTest{
1148 {0, 1, io.EOF, nil, nil},
1149 {1, 1, io.EOF, nil, nil},
1150 {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe},
1151 {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe},
1152 {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite},
1153 }
1154
1155 func TestWriterReadFromErrors(t *testing.T) {
1156 for i, rw := range errorReaderFromTests {
1157 w := NewWriter(rw)
1158 if _, err := w.ReadFrom(rw); err != rw.expected {
1159 t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected)
1160 }
1161 }
1162 }
1163
1164
1165
1166
1167
1168 func TestWriterReadFromCounts(t *testing.T) {
1169 var w0 writeCountingDiscard
1170 b0 := NewWriterSize(&w0, 1234)
1171 b0.WriteString(strings.Repeat("x", 1000))
1172 if w0 != 0 {
1173 t.Fatalf("write 1000 'x's: got %d writes, want 0", w0)
1174 }
1175 b0.WriteString(strings.Repeat("x", 200))
1176 if w0 != 0 {
1177 t.Fatalf("write 1200 'x's: got %d writes, want 0", w0)
1178 }
1179 io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))})
1180 if w0 != 0 {
1181 t.Fatalf("write 1230 'x's: got %d writes, want 0", w0)
1182 }
1183 io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))})
1184 if w0 != 1 {
1185 t.Fatalf("write 1239 'x's: got %d writes, want 1", w0)
1186 }
1187
1188 var w1 writeCountingDiscard
1189 b1 := NewWriterSize(&w1, 1234)
1190 b1.WriteString(strings.Repeat("x", 1200))
1191 b1.Flush()
1192 if w1 != 1 {
1193 t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1)
1194 }
1195 b1.WriteString(strings.Repeat("x", 89))
1196 if w1 != 1 {
1197 t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1)
1198 }
1199 io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))})
1200 if w1 != 1 {
1201 t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1)
1202 }
1203 io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))})
1204 if w1 != 2 {
1205 t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1)
1206 }
1207 b1.Flush()
1208 if w1 != 3 {
1209 t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1)
1210 }
1211 }
1212
1213
1214
1215 type writeCountingDiscard int
1216
1217 func (w *writeCountingDiscard) Write(p []byte) (int, error) {
1218 *w++
1219 return len(p), nil
1220 }
1221
1222 type negativeReader int
1223
1224 func (r *negativeReader) Read([]byte) (int, error) { return -1, nil }
1225
1226 func TestNegativeRead(t *testing.T) {
1227
1228
1229 b := NewReader(new(negativeReader))
1230 defer func() {
1231 switch err := recover().(type) {
1232 case nil:
1233 t.Fatal("read did not panic")
1234 case error:
1235 if !strings.Contains(err.Error(), "reader returned negative count from Read") {
1236 t.Fatalf("wrong panic: %v", err)
1237 }
1238 default:
1239 t.Fatalf("unexpected panic value: %T(%v)", err, err)
1240 }
1241 }()
1242 b.Read(make([]byte, 100))
1243 }
1244
1245 var errFake = errors.New("fake error")
1246
1247 type errorThenGoodReader struct {
1248 didErr bool
1249 nread int
1250 }
1251
1252 func (r *errorThenGoodReader) Read(p []byte) (int, error) {
1253 r.nread++
1254 if !r.didErr {
1255 r.didErr = true
1256 return 0, errFake
1257 }
1258 return len(p), nil
1259 }
1260
1261 func TestReaderClearError(t *testing.T) {
1262 r := &errorThenGoodReader{}
1263 b := NewReader(r)
1264 buf := make([]byte, 1)
1265 if _, err := b.Read(nil); err != nil {
1266 t.Fatalf("1st nil Read = %v; want nil", err)
1267 }
1268 if _, err := b.Read(buf); err != errFake {
1269 t.Fatalf("1st Read = %v; want errFake", err)
1270 }
1271 if _, err := b.Read(nil); err != nil {
1272 t.Fatalf("2nd nil Read = %v; want nil", err)
1273 }
1274 if _, err := b.Read(buf); err != nil {
1275 t.Fatalf("3rd Read with buffer = %v; want nil", err)
1276 }
1277 if r.nread != 2 {
1278 t.Errorf("num reads = %d; want 2", r.nread)
1279 }
1280 }
1281
1282
1283 func TestWriterReadFromWhileFull(t *testing.T) {
1284 buf := new(bytes.Buffer)
1285 w := NewWriterSize(buf, 10)
1286
1287
1288 n, err := w.Write([]byte("0123456789"))
1289 if n != 10 || err != nil {
1290 t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err)
1291 }
1292
1293
1294 n2, err := w.ReadFrom(strings.NewReader("abcdef"))
1295 if n2 != 6 || err != nil {
1296 t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err)
1297 }
1298 }
1299
1300 type emptyThenNonEmptyReader struct {
1301 r io.Reader
1302 n int
1303 }
1304
1305 func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) {
1306 if r.n <= 0 {
1307 return r.r.Read(p)
1308 }
1309 r.n--
1310 return 0, nil
1311 }
1312
1313
1314 func TestWriterReadFromUntilEOF(t *testing.T) {
1315 buf := new(bytes.Buffer)
1316 w := NewWriterSize(buf, 5)
1317
1318
1319 n, err := w.Write([]byte("0123"))
1320 if n != 4 || err != nil {
1321 t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
1322 }
1323
1324
1325 r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3}
1326 n2, err := w.ReadFrom(r)
1327 if n2 != 4 || err != nil {
1328 t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err)
1329 }
1330 w.Flush()
1331 if got, want := string(buf.Bytes()), "0123abcd"; got != want {
1332 t.Fatalf("buf.Bytes() returned %q, want %q", got, want)
1333 }
1334 }
1335
1336 func TestWriterReadFromErrNoProgress(t *testing.T) {
1337 buf := new(bytes.Buffer)
1338 w := NewWriterSize(buf, 5)
1339
1340
1341 n, err := w.Write([]byte("0123"))
1342 if n != 4 || err != nil {
1343 t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err)
1344 }
1345
1346
1347 r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100}
1348 n2, err := w.ReadFrom(r)
1349 if n2 != 0 || err != io.ErrNoProgress {
1350 t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err)
1351 }
1352 }
1353
1354 type readFromWriter struct {
1355 buf []byte
1356 writeBytes int
1357 readFromBytes int
1358 }
1359
1360 func (w *readFromWriter) Write(p []byte) (int, error) {
1361 w.buf = append(w.buf, p...)
1362 w.writeBytes += len(p)
1363 return len(p), nil
1364 }
1365
1366 func (w *readFromWriter) ReadFrom(r io.Reader) (int64, error) {
1367 b, err := io.ReadAll(r)
1368 w.buf = append(w.buf, b...)
1369 w.readFromBytes += len(b)
1370 return int64(len(b)), err
1371 }
1372
1373
1374
1375 func TestWriterReadFromWithBufferedData(t *testing.T) {
1376 const bufsize = 16
1377
1378 input := createTestInput(64)
1379 rfw := &readFromWriter{}
1380 w := NewWriterSize(rfw, bufsize)
1381
1382 const writeSize = 8
1383 if n, err := w.Write(input[:writeSize]); n != writeSize || err != nil {
1384 t.Errorf("w.Write(%v bytes) = %v, %v; want %v, nil", writeSize, n, err, writeSize)
1385 }
1386 n, err := w.ReadFrom(bytes.NewReader(input[writeSize:]))
1387 if wantn := len(input[writeSize:]); int(n) != wantn || err != nil {
1388 t.Errorf("io.Copy(w, %v bytes) = %v, %v; want %v, nil", wantn, n, err, wantn)
1389 }
1390 if err := w.Flush(); err != nil {
1391 t.Errorf("w.Flush() = %v, want nil", err)
1392 }
1393
1394 if got, want := rfw.writeBytes, bufsize; got != want {
1395 t.Errorf("wrote %v bytes with Write, want %v", got, want)
1396 }
1397 if got, want := rfw.readFromBytes, len(input)-bufsize; got != want {
1398 t.Errorf("wrote %v bytes with ReadFrom, want %v", got, want)
1399 }
1400 }
1401
1402 func TestReadZero(t *testing.T) {
1403 for _, size := range []int{100, 2} {
1404 t.Run(fmt.Sprintf("bufsize=%d", size), func(t *testing.T) {
1405 r := io.MultiReader(strings.NewReader("abc"), &emptyThenNonEmptyReader{r: strings.NewReader("def"), n: 1})
1406 br := NewReaderSize(r, size)
1407 want := func(s string, wantErr error) {
1408 p := make([]byte, 50)
1409 n, err := br.Read(p)
1410 if err != wantErr || n != len(s) || string(p[:n]) != s {
1411 t.Fatalf("read(%d) = %q, %v, want %q, %v", len(p), string(p[:n]), err, s, wantErr)
1412 }
1413 t.Logf("read(%d) = %q, %v", len(p), string(p[:n]), err)
1414 }
1415 want("abc", nil)
1416 want("", nil)
1417 want("def", nil)
1418 want("", io.EOF)
1419 })
1420 }
1421 }
1422
1423 func TestReaderReset(t *testing.T) {
1424 r := NewReader(strings.NewReader("foo foo"))
1425 buf := make([]byte, 3)
1426 r.Read(buf)
1427 if string(buf) != "foo" {
1428 t.Errorf("buf = %q; want foo", buf)
1429 }
1430
1431 r.Reset(strings.NewReader("bar bar"))
1432 all, err := io.ReadAll(r)
1433 if err != nil {
1434 t.Fatal(err)
1435 }
1436 if string(all) != "bar bar" {
1437 t.Errorf("ReadAll = %q; want bar bar", all)
1438 }
1439
1440 *r = Reader{}
1441 r.Reset(strings.NewReader("bar bar"))
1442 all, err = io.ReadAll(r)
1443 if err != nil {
1444 t.Fatal(err)
1445 }
1446 if string(all) != "bar bar" {
1447 t.Errorf("ReadAll = %q; want bar bar", all)
1448 }
1449 }
1450
1451 func TestWriterReset(t *testing.T) {
1452 var buf1, buf2, buf3 bytes.Buffer
1453 w := NewWriter(&buf1)
1454 w.WriteString("foo")
1455
1456 w.Reset(&buf2)
1457 w.WriteString("bar")
1458 w.Flush()
1459 if buf1.String() != "" {
1460 t.Errorf("buf1 = %q; want empty", buf1.String())
1461 }
1462 if buf2.String() != "bar" {
1463 t.Errorf("buf2 = %q; want bar", buf2.String())
1464 }
1465
1466 *w = Writer{}
1467 w.Reset(&buf3)
1468 w.WriteString("bar")
1469 w.Flush()
1470 if buf1.String() != "" {
1471 t.Errorf("buf1 = %q; want empty", buf1.String())
1472 }
1473 if buf3.String() != "bar" {
1474 t.Errorf("buf3 = %q; want bar", buf3.String())
1475 }
1476 }
1477
1478 func TestReaderDiscard(t *testing.T) {
1479 tests := []struct {
1480 name string
1481 r io.Reader
1482 bufSize int
1483 peekSize int
1484
1485 n int
1486
1487 want int
1488 wantErr error
1489
1490 wantBuffered int
1491 }{
1492 {
1493 name: "normal case",
1494 r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1495 peekSize: 16,
1496 n: 6,
1497 want: 6,
1498 wantBuffered: 10,
1499 },
1500 {
1501 name: "discard causing read",
1502 r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1503 n: 6,
1504 want: 6,
1505 wantBuffered: 10,
1506 },
1507 {
1508 name: "discard all without peek",
1509 r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1510 n: 26,
1511 want: 26,
1512 wantBuffered: 0,
1513 },
1514 {
1515 name: "discard more than end",
1516 r: strings.NewReader("abcdefghijklmnopqrstuvwxyz"),
1517 n: 27,
1518 want: 26,
1519 wantErr: io.EOF,
1520 wantBuffered: 0,
1521 },
1522
1523
1524
1525 {
1526 name: "fill error, discard less",
1527 r: newScriptedReader(func(p []byte) (n int, err error) {
1528 if len(p) < 5 {
1529 panic("unexpected small read")
1530 }
1531 return 5, errors.New("5-then-error")
1532 }),
1533 n: 4,
1534 want: 4,
1535 wantErr: nil,
1536 wantBuffered: 1,
1537 },
1538 {
1539 name: "fill error, discard equal",
1540 r: newScriptedReader(func(p []byte) (n int, err error) {
1541 if len(p) < 5 {
1542 panic("unexpected small read")
1543 }
1544 return 5, errors.New("5-then-error")
1545 }),
1546 n: 5,
1547 want: 5,
1548 wantErr: nil,
1549 wantBuffered: 0,
1550 },
1551 {
1552 name: "fill error, discard more",
1553 r: newScriptedReader(func(p []byte) (n int, err error) {
1554 if len(p) < 5 {
1555 panic("unexpected small read")
1556 }
1557 return 5, errors.New("5-then-error")
1558 }),
1559 n: 6,
1560 want: 5,
1561 wantErr: errors.New("5-then-error"),
1562 wantBuffered: 0,
1563 },
1564
1565 {
1566 name: "discard zero",
1567 r: newScriptedReader(),
1568 n: 0,
1569 want: 0,
1570 wantErr: nil,
1571 wantBuffered: 0,
1572 },
1573 {
1574 name: "discard negative",
1575 r: newScriptedReader(),
1576 n: -1,
1577 want: 0,
1578 wantErr: ErrNegativeCount,
1579 wantBuffered: 0,
1580 },
1581 }
1582 for _, tt := range tests {
1583 br := NewReaderSize(tt.r, tt.bufSize)
1584 if tt.peekSize > 0 {
1585 peekBuf, err := br.Peek(tt.peekSize)
1586 if err != nil {
1587 t.Errorf("%s: Peek(%d): %v", tt.name, tt.peekSize, err)
1588 continue
1589 }
1590 if len(peekBuf) != tt.peekSize {
1591 t.Errorf("%s: len(Peek(%d)) = %v; want %v", tt.name, tt.peekSize, len(peekBuf), tt.peekSize)
1592 continue
1593 }
1594 }
1595 discarded, err := br.Discard(tt.n)
1596 if ge, we := fmt.Sprint(err), fmt.Sprint(tt.wantErr); discarded != tt.want || ge != we {
1597 t.Errorf("%s: Discard(%d) = (%v, %v); want (%v, %v)", tt.name, tt.n, discarded, ge, tt.want, we)
1598 continue
1599 }
1600 if bn := br.Buffered(); bn != tt.wantBuffered {
1601 t.Errorf("%s: after Discard, Buffered = %d; want %d", tt.name, bn, tt.wantBuffered)
1602 }
1603 }
1604
1605 }
1606
1607 func TestReaderSize(t *testing.T) {
1608 if got, want := NewReader(nil).Size(), DefaultBufSize; got != want {
1609 t.Errorf("NewReader's Reader.Size = %d; want %d", got, want)
1610 }
1611 if got, want := NewReaderSize(nil, 1234).Size(), 1234; got != want {
1612 t.Errorf("NewReaderSize's Reader.Size = %d; want %d", got, want)
1613 }
1614 }
1615
1616 func TestWriterSize(t *testing.T) {
1617 if got, want := NewWriter(nil).Size(), DefaultBufSize; got != want {
1618 t.Errorf("NewWriter's Writer.Size = %d; want %d", got, want)
1619 }
1620 if got, want := NewWriterSize(nil, 1234).Size(), 1234; got != want {
1621 t.Errorf("NewWriterSize's Writer.Size = %d; want %d", got, want)
1622 }
1623 }
1624
1625
1626 type onlyReader struct {
1627 io.Reader
1628 }
1629
1630
1631 type onlyWriter struct {
1632 io.Writer
1633 }
1634
1635
1636 type scriptedReader []func(p []byte) (n int, err error)
1637
1638 func (sr *scriptedReader) Read(p []byte) (n int, err error) {
1639 if len(*sr) == 0 {
1640 panic("too many Read calls on scripted Reader. No steps remain.")
1641 }
1642 step := (*sr)[0]
1643 *sr = (*sr)[1:]
1644 return step(p)
1645 }
1646
1647 func newScriptedReader(steps ...func(p []byte) (n int, err error)) io.Reader {
1648 sr := scriptedReader(steps)
1649 return &sr
1650 }
1651
1652
1653 type eofReader struct {
1654 buf []byte
1655 }
1656
1657 func (r *eofReader) Read(p []byte) (int, error) {
1658 read := copy(p, r.buf)
1659 r.buf = r.buf[read:]
1660
1661 switch read {
1662 case 0, len(r.buf):
1663
1664
1665
1666 return read, io.EOF
1667 }
1668
1669 return read, nil
1670 }
1671
1672 func TestPartialReadEOF(t *testing.T) {
1673 src := make([]byte, 10)
1674 eofR := &eofReader{buf: src}
1675 r := NewReader(eofR)
1676
1677
1678 dest := make([]byte, 5)
1679 read, err := r.Read(dest)
1680 if err != nil {
1681 t.Fatalf("unexpected error: %v", err)
1682 }
1683 if n := len(dest); read != n {
1684 t.Fatalf("read %d bytes; wanted %d bytes", read, n)
1685 }
1686
1687
1688 if n := len(eofR.buf); n != 0 {
1689 t.Fatalf("got %d bytes left in bufio.Reader source; want 0 bytes", n)
1690 }
1691
1692 if n := r.Buffered(); n != 5 {
1693 t.Fatalf("got %d bytes buffered in bufio.Reader; want 5 bytes", n)
1694 }
1695
1696
1697 read, err = r.Read([]byte{})
1698 if err != nil {
1699 t.Fatalf("unexpected error: %v", err)
1700 }
1701 if read != 0 {
1702 t.Fatalf("read %d bytes; want 0 bytes", read)
1703 }
1704 }
1705
1706 type writerWithReadFromError struct{}
1707
1708 func (w writerWithReadFromError) ReadFrom(r io.Reader) (int64, error) {
1709 return 0, errors.New("writerWithReadFromError error")
1710 }
1711
1712 func (w writerWithReadFromError) Write(b []byte) (n int, err error) {
1713 return 10, nil
1714 }
1715
1716 func TestWriterReadFromMustSetUnderlyingError(t *testing.T) {
1717 var wr = NewWriter(writerWithReadFromError{})
1718 if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
1719 t.Fatal("expected ReadFrom returns error, got nil")
1720 }
1721 if _, err := wr.Write([]byte("123")); err == nil {
1722 t.Fatal("expected Write returns error, got nil")
1723 }
1724 }
1725
1726 type writeErrorOnlyWriter struct{}
1727
1728 func (w writeErrorOnlyWriter) Write(p []byte) (n int, err error) {
1729 return 0, errors.New("writeErrorOnlyWriter error")
1730 }
1731
1732
1733
1734 func TestWriterReadFromMustReturnUnderlyingError(t *testing.T) {
1735 var wr = NewWriter(writeErrorOnlyWriter{})
1736 s := "test1"
1737 wantBuffered := len(s)
1738 if _, err := wr.WriteString(s); err != nil {
1739 t.Fatalf("unexpected error: %v", err)
1740 }
1741 if err := wr.Flush(); err == nil {
1742 t.Error("expected flush error, got nil")
1743 }
1744 if _, err := wr.ReadFrom(strings.NewReader("test2")); err == nil {
1745 t.Fatal("expected error, got nil")
1746 }
1747 if buffered := wr.Buffered(); buffered != wantBuffered {
1748 t.Fatalf("Buffered = %v; want %v", buffered, wantBuffered)
1749 }
1750 }
1751
1752 func BenchmarkReaderCopyOptimal(b *testing.B) {
1753
1754 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1755 src := NewReader(srcBuf)
1756 dstBuf := new(bytes.Buffer)
1757 dst := onlyWriter{dstBuf}
1758 for i := 0; i < b.N; i++ {
1759 srcBuf.Reset()
1760 src.Reset(srcBuf)
1761 dstBuf.Reset()
1762 io.Copy(dst, src)
1763 }
1764 }
1765
1766 func BenchmarkReaderCopyUnoptimal(b *testing.B) {
1767
1768 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1769 src := NewReader(onlyReader{srcBuf})
1770 dstBuf := new(bytes.Buffer)
1771 dst := onlyWriter{dstBuf}
1772 for i := 0; i < b.N; i++ {
1773 srcBuf.Reset()
1774 src.Reset(onlyReader{srcBuf})
1775 dstBuf.Reset()
1776 io.Copy(dst, src)
1777 }
1778 }
1779
1780 func BenchmarkReaderCopyNoWriteTo(b *testing.B) {
1781 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1782 srcReader := NewReader(srcBuf)
1783 src := onlyReader{srcReader}
1784 dstBuf := new(bytes.Buffer)
1785 dst := onlyWriter{dstBuf}
1786 for i := 0; i < b.N; i++ {
1787 srcBuf.Reset()
1788 srcReader.Reset(srcBuf)
1789 dstBuf.Reset()
1790 io.Copy(dst, src)
1791 }
1792 }
1793
1794 func BenchmarkReaderWriteToOptimal(b *testing.B) {
1795 const bufSize = 16 << 10
1796 buf := make([]byte, bufSize)
1797 r := bytes.NewReader(buf)
1798 srcReader := NewReaderSize(onlyReader{r}, 1<<10)
1799 if _, ok := io.Discard.(io.ReaderFrom); !ok {
1800 b.Fatal("io.Discard doesn't support ReaderFrom")
1801 }
1802 for i := 0; i < b.N; i++ {
1803 r.Seek(0, io.SeekStart)
1804 srcReader.Reset(onlyReader{r})
1805 n, err := srcReader.WriteTo(io.Discard)
1806 if err != nil {
1807 b.Fatal(err)
1808 }
1809 if n != bufSize {
1810 b.Fatalf("n = %d; want %d", n, bufSize)
1811 }
1812 }
1813 }
1814
1815 func BenchmarkReaderReadString(b *testing.B) {
1816 r := strings.NewReader(" foo foo 42 42 42 42 42 42 42 42 4.2 4.2 4.2 4.2\n")
1817 buf := NewReader(r)
1818 b.ReportAllocs()
1819 for i := 0; i < b.N; i++ {
1820 r.Seek(0, io.SeekStart)
1821 buf.Reset(r)
1822
1823 _, err := buf.ReadString('\n')
1824 if err != nil {
1825 b.Fatal(err)
1826 }
1827 }
1828 }
1829
1830 func BenchmarkWriterCopyOptimal(b *testing.B) {
1831
1832 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1833 src := onlyReader{srcBuf}
1834 dstBuf := new(bytes.Buffer)
1835 dst := NewWriter(dstBuf)
1836 for i := 0; i < b.N; i++ {
1837 srcBuf.Reset()
1838 dstBuf.Reset()
1839 dst.Reset(dstBuf)
1840 io.Copy(dst, src)
1841 }
1842 }
1843
1844 func BenchmarkWriterCopyUnoptimal(b *testing.B) {
1845 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1846 src := onlyReader{srcBuf}
1847 dstBuf := new(bytes.Buffer)
1848 dst := NewWriter(onlyWriter{dstBuf})
1849 for i := 0; i < b.N; i++ {
1850 srcBuf.Reset()
1851 dstBuf.Reset()
1852 dst.Reset(onlyWriter{dstBuf})
1853 io.Copy(dst, src)
1854 }
1855 }
1856
1857 func BenchmarkWriterCopyNoReadFrom(b *testing.B) {
1858 srcBuf := bytes.NewBuffer(make([]byte, 8192))
1859 src := onlyReader{srcBuf}
1860 dstBuf := new(bytes.Buffer)
1861 dstWriter := NewWriter(dstBuf)
1862 dst := onlyWriter{dstWriter}
1863 for i := 0; i < b.N; i++ {
1864 srcBuf.Reset()
1865 dstBuf.Reset()
1866 dstWriter.Reset(dstBuf)
1867 io.Copy(dst, src)
1868 }
1869 }
1870
1871 func BenchmarkReaderEmpty(b *testing.B) {
1872 b.ReportAllocs()
1873 str := strings.Repeat("x", 16<<10)
1874 for i := 0; i < b.N; i++ {
1875 br := NewReader(strings.NewReader(str))
1876 n, err := io.Copy(io.Discard, br)
1877 if err != nil {
1878 b.Fatal(err)
1879 }
1880 if n != int64(len(str)) {
1881 b.Fatal("wrong length")
1882 }
1883 }
1884 }
1885
1886 func BenchmarkWriterEmpty(b *testing.B) {
1887 b.ReportAllocs()
1888 str := strings.Repeat("x", 1<<10)
1889 bs := []byte(str)
1890 for i := 0; i < b.N; i++ {
1891 bw := NewWriter(io.Discard)
1892 bw.Flush()
1893 bw.WriteByte('a')
1894 bw.Flush()
1895 bw.WriteRune('B')
1896 bw.Flush()
1897 bw.Write(bs)
1898 bw.Flush()
1899 bw.WriteString(str)
1900 bw.Flush()
1901 }
1902 }
1903
1904 func BenchmarkWriterFlush(b *testing.B) {
1905 b.ReportAllocs()
1906 bw := NewWriter(io.Discard)
1907 str := strings.Repeat("x", 50)
1908 for i := 0; i < b.N; i++ {
1909 bw.WriteString(str)
1910 bw.Flush()
1911 }
1912 }
1913
View as plain text