1package moxio
2
3import (
4 "bufio"
5 "errors"
6 "fmt"
7 "io"
8 "strings"
9 "testing"
10
11 "github.com/mjl-/mox/mlog"
12)
13
14func TestBufpool(t *testing.T) {
15 bp := NewBufpool(1, 8)
16 a := bp.get()
17 b := bp.get()
18 for i := 0; i < len(a); i++ {
19 a[i] = 1
20 }
21 log := mlog.New("moxio", nil)
22 bp.put(log, a, len(a)) // Will be stored.
23 bp.put(log, b, 0) // Will be discarded.
24 na := bp.get()
25 if fmt.Sprintf("%p", a) != fmt.Sprintf("%p", na) {
26 t.Fatalf("received unexpected new buf %p != %p", a, na)
27 }
28 for _, c := range na {
29 if c != 0 {
30 t.Fatalf("reused buf not cleared")
31 }
32 }
33
34 if _, err := bp.Readline(log, bufio.NewReader(strings.NewReader("this is too long"))); !errors.Is(err, ErrLineTooLong) {
35 t.Fatalf("expected ErrLineTooLong, got error %v", err)
36 }
37 if _, err := bp.Readline(log, bufio.NewReader(strings.NewReader("short"))); !errors.Is(err, io.ErrUnexpectedEOF) {
38 t.Fatalf("expected ErrLineTooLong, got error %v", err)
39 }
40
41 er := errReader{fmt.Errorf("bad")}
42 if _, err := bp.Readline(log, bufio.NewReader(er)); err == nil || !errors.Is(err, er.err) {
43 t.Fatalf("got unexpected error %s", err)
44 }
45
46 if line, err := bp.Readline(log, bufio.NewReader(strings.NewReader("ok\r\n"))); line != "ok" {
47 t.Fatalf(`got %q, err %v, expected line "ok"`, line, err)
48 }
49 if line, err := bp.Readline(log, bufio.NewReader(strings.NewReader("ok\n"))); line != "ok" {
50 t.Fatalf(`got %q, err %v, expected line "ok"`, line, err)
51 }
52}
53
54type errReader struct {
55 err error
56}
57
58func (r errReader) Read(buf []byte) (int, error) {
59 return 0, r.err
60}
61