-
Notifications
You must be signed in to change notification settings - Fork 20
/
readerwriter.go
92 lines (74 loc) · 2.21 KB
/
readerwriter.go
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
package iotools
import (
"io"
"github.com/mandelsoft/goutils/errors"
"github.com/mandelsoft/goutils/generics"
"github.com/mandelsoft/goutils/sliceutils"
)
////////////////////////////////////////////////////////////////////////////////
type additionalCloser[T any] struct {
msg []interface{}
wrapped T
additionalCloser io.Closer
}
func (c *additionalCloser[T]) Close() error {
var list *errors.ErrorList
if len(c.msg) == 0 {
list = errors.ErrListf("close")
} else {
if s, ok := c.msg[0].(string); ok && len(c.msg) > 1 {
list = errors.ErrListf(s, c.msg[1:]...)
} else {
list = errors.ErrList(c.msg...)
}
}
if cl, ok := generics.TryCast[io.Closer](c.wrapped); ok {
list.Add(cl.Close())
}
if c.additionalCloser != nil {
list.Add(c.additionalCloser.Close())
}
return list.Result()
}
func newAdditionalCloser[T any](w T, closer io.Closer, msg ...interface{}) additionalCloser[T] {
return additionalCloser[T]{
wrapped: w,
msg: msg,
additionalCloser: closer,
}
}
////////////////////////////////////////////////////////////////////////////////
type readCloser struct {
additionalCloser[io.Reader]
}
var _ io.ReadCloser = (*readCloser)(nil)
// Deprecated: use AddReaderCloser .
func AddCloser(reader io.ReadCloser, closer io.Closer, msg ...string) io.ReadCloser {
return AddReaderCloser(reader, closer, sliceutils.Convert[any](msg)...)
}
func ReadCloser(r io.Reader) io.ReadCloser {
return AddReaderCloser(r, nil)
}
func AddReaderCloser(reader io.Reader, closer io.Closer, msg ...interface{}) io.ReadCloser {
return &readCloser{
additionalCloser: newAdditionalCloser[io.Reader](reader, closer, msg...),
}
}
func (c *readCloser) Read(p []byte) (n int, err error) {
return c.wrapped.Read(p)
}
type writeCloser struct {
additionalCloser[io.Writer]
}
var _ io.WriteCloser = (*writeCloser)(nil)
func WriteCloser(w io.Writer) io.WriteCloser {
return AddWriterCloser(w, nil)
}
func AddWriterCloser(writer io.Writer, closer io.Closer, msg ...interface{}) io.WriteCloser {
return &writeCloser{
additionalCloser: newAdditionalCloser[io.Writer](writer, closer, msg...),
}
}
func (c *writeCloser) Write(p []byte) (n int, err error) {
return c.wrapped.Write(p)
}