aboutsummaryrefslogtreecommitdiff
path: root/io.go
blob: 3b9e540236bffda5cf09760aa1e108e3723f2ee8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gemini

import (
	"bufio"
	"context"
	"io"
)

type contextReader struct {
	ctx    context.Context
	done   <-chan struct{}
	cancel func()
	rc     io.ReadCloser
}

func (r *contextReader) Read(p []byte) (int, error) {
	select {
	case <-r.done:
		r.rc.Close()
		return 0, r.ctx.Err()
	default:
	}
	n, err := r.rc.Read(p)
	if err != nil {
		r.cancel()
	}
	return n, err
}

func (r *contextReader) Close() error {
	r.cancel()
	return r.rc.Close()
}

type contextWriter struct {
	ctx    context.Context
	done   <-chan struct{}
	cancel func()
	wc     io.WriteCloser
}

func (w *contextWriter) Write(b []byte) (int, error) {
	select {
	case <-w.done:
		w.wc.Close()
		return 0, w.ctx.Err()
	default:
	}
	n, err := w.wc.Write(b)
	if err != nil {
		w.cancel()
	}
	return n, err
}

func (w *contextWriter) Close() error {
	w.cancel()
	return w.wc.Close()
}

type nopCloser struct {
	io.Writer
}

func (nopCloser) Close() error {
	return nil
}

type nopReadCloser struct{}

func (nopReadCloser) Read(p []byte) (int, error) {
	return 0, io.EOF
}

func (nopReadCloser) Close() error {
	return nil
}

type bufReadCloser struct {
	br *bufio.Reader // used until empty
	io.ReadCloser
}

func newBufReadCloser(br *bufio.Reader, rc io.ReadCloser) io.ReadCloser {
	body := &bufReadCloser{ReadCloser: rc}
	if br.Buffered() != 0 {
		body.br = br
	}
	return body
}

func (b *bufReadCloser) Read(p []byte) (n int, err error) {
	if b.br != nil {
		if n := b.br.Buffered(); len(p) > n {
			p = p[:n]
		}
		n, err = b.br.Read(p)
		if b.br.Buffered() == 0 {
			b.br = nil
		}
		return n, err
	}
	return b.ReadCloser.Read(p)
}