aboutsummaryrefslogtreecommitdiff
path: root/io.go
blob: d9b59eb9558e11de63f25bad32272ae25cb69cbc (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
package gemini

import (
	"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
}